ngram
listlengths
0
82k
[]
[ "SubmitField('Sign Up') def validate_username(self, username): existing_username = User.query.filter_by(username=username.data).first() if existing_username:", "import StringField, PasswordField, SubmitField from wtforms.validators import InputRequired, Email, ValidationError", "from wtforms.validators import InputRequired, Email, ValidationError from models import User", "= StringField(\"Your email address\", validators=[InputRequired()]) password = PasswordField(\"<PASSWORD>:\", validators=[InputRequired()]) submit", "= StringField('Your Email Address', validators=[InputRequired(), Email()]) username = StringField('Enter your", "FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import", "wtforms import StringField, PasswordField, SubmitField from wtforms.validators import InputRequired, Email,", "Email, ValidationError from models import User class RegistrationForm(FlaskForm): email =", "SubmitField from wtforms.validators import InputRequired, Email, ValidationError from models import", "from models import User class RegistrationForm(FlaskForm): email = StringField('Your Email", "email = StringField('Your Email Address', validators=[InputRequired(), Email()]) username = StringField('Enter", "StringField('Your Email Address', validators=[InputRequired(), Email()]) username = StringField('Enter your username',", "username): existing_username = User.query.filter_by(username=username.data).first() if existing_username: raise ValidationError(\"The username already", "submit = SubmitField('Sign Up') def validate_username(self, username): existing_username = User.query.filter_by(username=username.data).first()", "import InputRequired, Email, ValidationError from models import User class RegistrationForm(FlaskForm):", "Address', validators=[InputRequired(), Email()]) username = StringField('Enter your username', validators=[InputRequired()]) password", "validators=[InputRequired()]) submit = SubmitField('Sign Up') def validate_username(self, username): existing_username =", "User.query.filter_by(username=username.data).first() if existing_username: raise ValidationError(\"The username already exists\") class LoginForm(FlaskForm):", "raise ValidationError(\"The username already exists\") class LoginForm(FlaskForm): username = StringField(\"Your", "password = PasswordField('Password', validators=[InputRequired()]) submit = SubmitField('Sign Up') def validate_username(self,", "import User class RegistrationForm(FlaskForm): email = StringField('Your Email Address', validators=[InputRequired(),", "InputRequired, Email, ValidationError from models import User class RegistrationForm(FlaskForm): email", "username already exists\") class LoginForm(FlaskForm): username = StringField(\"Your email address\",", "Email Address', validators=[InputRequired(), Email()]) username = StringField('Enter your username', validators=[InputRequired()])", "= StringField('Enter your username', validators=[InputRequired()]) password = PasswordField('Password', validators=[InputRequired()]) submit", "validators=[InputRequired()]) password = PasswordField('Password', validators=[InputRequired()]) submit = SubmitField('Sign Up') def", "LoginForm(FlaskForm): username = StringField(\"Your email address\", validators=[InputRequired()]) password = PasswordField(\"<PASSWORD>:\",", "Email()]) username = StringField('Enter your username', validators=[InputRequired()]) password = PasswordField('Password',", "PasswordField('Password', validators=[InputRequired()]) submit = SubmitField('Sign Up') def validate_username(self, username): existing_username", "validate_username(self, username): existing_username = User.query.filter_by(username=username.data).first() if existing_username: raise ValidationError(\"The username", "username = StringField(\"Your email address\", validators=[InputRequired()]) password = PasswordField(\"<PASSWORD>:\", validators=[InputRequired()])", "= SubmitField('Sign Up') def validate_username(self, username): existing_username = User.query.filter_by(username=username.data).first() if", "address\", validators=[InputRequired()]) password = PasswordField(\"<PASSWORD>:\", validators=[InputRequired()]) submit = SubmitField(\"Sign In\")", "wtforms.validators import InputRequired, Email, ValidationError from models import User class", "PasswordField, SubmitField from wtforms.validators import InputRequired, Email, ValidationError from models", "username = StringField('Enter your username', validators=[InputRequired()]) password = PasswordField('Password', validators=[InputRequired()])", "Up') def validate_username(self, username): existing_username = User.query.filter_by(username=username.data).first() if existing_username: raise", "StringField, PasswordField, SubmitField from wtforms.validators import InputRequired, Email, ValidationError from", "existing_username = User.query.filter_by(username=username.data).first() if existing_username: raise ValidationError(\"The username already exists\")", "ValidationError(\"The username already exists\") class LoginForm(FlaskForm): username = StringField(\"Your email", "exists\") class LoginForm(FlaskForm): username = StringField(\"Your email address\", validators=[InputRequired()]) password", "your username', validators=[InputRequired()]) password = PasswordField('Password', validators=[InputRequired()]) submit = SubmitField('Sign", "flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from", "def validate_username(self, username): existing_username = User.query.filter_by(username=username.data).first() if existing_username: raise ValidationError(\"The", "validators=[InputRequired(), Email()]) username = StringField('Enter your username', validators=[InputRequired()]) password =", "username', validators=[InputRequired()]) password = PasswordField('Password', validators=[InputRequired()]) submit = SubmitField('Sign Up')", "already exists\") class LoginForm(FlaskForm): username = StringField(\"Your email address\", validators=[InputRequired()])", "StringField(\"Your email address\", validators=[InputRequired()]) password = PasswordField(\"<PASSWORD>:\", validators=[InputRequired()]) submit =", "ValidationError from models import User class RegistrationForm(FlaskForm): email = StringField('Your", "models import User class RegistrationForm(FlaskForm): email = StringField('Your Email Address',", "from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import InputRequired,", "RegistrationForm(FlaskForm): email = StringField('Your Email Address', validators=[InputRequired(), Email()]) username =", "class RegistrationForm(FlaskForm): email = StringField('Your Email Address', validators=[InputRequired(), Email()]) username", "= User.query.filter_by(username=username.data).first() if existing_username: raise ValidationError(\"The username already exists\") class", "email address\", validators=[InputRequired()]) password = PasswordField(\"<PASSWORD>:\", validators=[InputRequired()]) submit = SubmitField(\"Sign", "StringField('Enter your username', validators=[InputRequired()]) password = PasswordField('Password', validators=[InputRequired()]) submit =", "if existing_username: raise ValidationError(\"The username already exists\") class LoginForm(FlaskForm): username", "class LoginForm(FlaskForm): username = StringField(\"Your email address\", validators=[InputRequired()]) password =", "User class RegistrationForm(FlaskForm): email = StringField('Your Email Address', validators=[InputRequired(), Email()])", "import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators", "= PasswordField('Password', validators=[InputRequired()]) submit = SubmitField('Sign Up') def validate_username(self, username):", "existing_username: raise ValidationError(\"The username already exists\") class LoginForm(FlaskForm): username =", "from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField" ]
[ "EDIT import komand import json class Component: DESCRIPTION = \"Creates", "a security policy with the default values\" class Input: NAME", "}, \"required\": [ \"name\" ] } \"\"\") def __init__(self): super(self.__class__,", "\"name\" class Output: ID = \"id\" class CreateSecurityPolicyInput(komand.Input): schema =", "\"Name\", \"description\": \"The name of the security policy that needs", "\"ID of the new policy\", \"order\": 1 } }, \"required\":", "new policy\", \"order\": 1 } }, \"required\": [ \"id\" ]", "\"Variables\", \"properties\": { \"name\": { \"type\": \"string\", \"title\": \"Name\", \"description\":", "{ \"id\": { \"type\": \"string\", \"title\": \"ID\", \"description\": \"ID of", "NOT EDIT import komand import json class Component: DESCRIPTION =", "= \"name\" class Output: ID = \"id\" class CreateSecurityPolicyInput(komand.Input): schema", "\"type\": \"object\", \"title\": \"Variables\", \"properties\": { \"name\": { \"type\": \"string\",", "# GENERATED BY KOMAND SDK - DO NOT EDIT import", "\"title\": \"Name\", \"description\": \"The name of the security policy that", "DO NOT EDIT import komand import json class Component: DESCRIPTION", "[ \"name\" ] } \"\"\") def __init__(self): super(self.__class__, self).__init__(self.schema) class", "__init__(self): super(self.__class__, self).__init__(self.schema) class CreateSecurityPolicyOutput(komand.Output): schema = json.loads(\"\"\" { \"type\":", "\"object\", \"title\": \"Variables\", \"properties\": { \"id\": { \"type\": \"string\", \"title\":", "= \"Creates a security policy with the default values\" class", "policy with the default values\" class Input: NAME = \"name\"", "super(self.__class__, self).__init__(self.schema) class CreateSecurityPolicyOutput(komand.Output): schema = json.loads(\"\"\" { \"type\": \"object\",", "\"name\" ] } \"\"\") def __init__(self): super(self.__class__, self).__init__(self.schema) class CreateSecurityPolicyOutput(komand.Output):", "BY KOMAND SDK - DO NOT EDIT import komand import", "- DO NOT EDIT import komand import json class Component:", "class CreateSecurityPolicyInput(komand.Input): schema = json.loads(\"\"\" { \"type\": \"object\", \"title\": \"Variables\",", "that needs to be created\", \"order\": 1 } }, \"required\":", "} \"\"\") def __init__(self): super(self.__class__, self).__init__(self.schema) class CreateSecurityPolicyOutput(komand.Output): schema =", "\"string\", \"title\": \"Name\", \"description\": \"The name of the security policy", "be created\", \"order\": 1 } }, \"required\": [ \"name\" ]", "class Output: ID = \"id\" class CreateSecurityPolicyInput(komand.Input): schema = json.loads(\"\"\"", "\"required\": [ \"name\" ] } \"\"\") def __init__(self): super(self.__class__, self).__init__(self.schema)", "security policy that needs to be created\", \"order\": 1 }", "\"type\": \"object\", \"title\": \"Variables\", \"properties\": { \"id\": { \"type\": \"string\",", "\"ID\", \"description\": \"ID of the new policy\", \"order\": 1 }", "class Input: NAME = \"name\" class Output: ID = \"id\"", "with the default values\" class Input: NAME = \"name\" class", "NAME = \"name\" class Output: ID = \"id\" class CreateSecurityPolicyInput(komand.Input):", "class CreateSecurityPolicyOutput(komand.Output): schema = json.loads(\"\"\" { \"type\": \"object\", \"title\": \"Variables\",", "komand import json class Component: DESCRIPTION = \"Creates a security", "import komand import json class Component: DESCRIPTION = \"Creates a", "the security policy that needs to be created\", \"order\": 1", "the new policy\", \"order\": 1 } }, \"required\": [ \"id\"", "to be created\", \"order\": 1 } }, \"required\": [ \"name\"", "= json.loads(\"\"\" { \"type\": \"object\", \"title\": \"Variables\", \"properties\": { \"id\":", "\"object\", \"title\": \"Variables\", \"properties\": { \"name\": { \"type\": \"string\", \"title\":", "def __init__(self): super(self.__class__, self).__init__(self.schema) class CreateSecurityPolicyOutput(komand.Output): schema = json.loads(\"\"\" {", "{ \"type\": \"object\", \"title\": \"Variables\", \"properties\": { \"id\": { \"type\":", "DESCRIPTION = \"Creates a security policy with the default values\"", "1 } }, \"required\": [ \"name\" ] } \"\"\") def", "\"id\" class CreateSecurityPolicyInput(komand.Input): schema = json.loads(\"\"\" { \"type\": \"object\", \"title\":", "\"\"\") def __init__(self): super(self.__class__, self).__init__(self.schema) class CreateSecurityPolicyOutput(komand.Output): schema = json.loads(\"\"\"", "\"title\": \"Variables\", \"properties\": { \"id\": { \"type\": \"string\", \"title\": \"ID\",", "\"Variables\", \"properties\": { \"id\": { \"type\": \"string\", \"title\": \"ID\", \"description\":", "json.loads(\"\"\" { \"type\": \"object\", \"title\": \"Variables\", \"properties\": { \"name\": {", "import json class Component: DESCRIPTION = \"Creates a security policy", "{ \"type\": \"string\", \"title\": \"ID\", \"description\": \"ID of the new", "class Component: DESCRIPTION = \"Creates a security policy with the", "schema = json.loads(\"\"\" { \"type\": \"object\", \"title\": \"Variables\", \"properties\": {", "created\", \"order\": 1 } }, \"required\": [ \"name\" ] }", "SDK - DO NOT EDIT import komand import json class", "\"required\": [ \"id\" ] } \"\"\") def __init__(self): super(self.__class__, self).__init__(self.schema)", "\"description\": \"The name of the security policy that needs to", "{ \"type\": \"string\", \"title\": \"Name\", \"description\": \"The name of the", "Component: DESCRIPTION = \"Creates a security policy with the default", "name of the security policy that needs to be created\",", "\"string\", \"title\": \"ID\", \"description\": \"ID of the new policy\", \"order\":", "= \"id\" class CreateSecurityPolicyInput(komand.Input): schema = json.loads(\"\"\" { \"type\": \"object\",", "= json.loads(\"\"\" { \"type\": \"object\", \"title\": \"Variables\", \"properties\": { \"name\":", "CreateSecurityPolicyInput(komand.Input): schema = json.loads(\"\"\" { \"type\": \"object\", \"title\": \"Variables\", \"properties\":", "of the new policy\", \"order\": 1 } }, \"required\": [", "of the security policy that needs to be created\", \"order\":", "policy\", \"order\": 1 } }, \"required\": [ \"id\" ] }", "ID = \"id\" class CreateSecurityPolicyInput(komand.Input): schema = json.loads(\"\"\" { \"type\":", "default values\" class Input: NAME = \"name\" class Output: ID", "\"title\": \"Variables\", \"properties\": { \"name\": { \"type\": \"string\", \"title\": \"Name\",", "} }, \"required\": [ \"id\" ] } \"\"\") def __init__(self):", "\"type\": \"string\", \"title\": \"ID\", \"description\": \"ID of the new policy\",", "\"order\": 1 } }, \"required\": [ \"id\" ] } \"\"\")", "security policy with the default values\" class Input: NAME =", "{ \"name\": { \"type\": \"string\", \"title\": \"Name\", \"description\": \"The name", "\"The name of the security policy that needs to be", "}, \"required\": [ \"id\" ] } \"\"\") def __init__(self): super(self.__class__,", "1 } }, \"required\": [ \"id\" ] } \"\"\") def", "KOMAND SDK - DO NOT EDIT import komand import json", "the default values\" class Input: NAME = \"name\" class Output:", "json class Component: DESCRIPTION = \"Creates a security policy with", "\"properties\": { \"id\": { \"type\": \"string\", \"title\": \"ID\", \"description\": \"ID", "needs to be created\", \"order\": 1 } }, \"required\": [", "Input: NAME = \"name\" class Output: ID = \"id\" class", "\"name\": { \"type\": \"string\", \"title\": \"Name\", \"description\": \"The name of", "values\" class Input: NAME = \"name\" class Output: ID =", "GENERATED BY KOMAND SDK - DO NOT EDIT import komand", "\"order\": 1 } }, \"required\": [ \"name\" ] } \"\"\")", "\"description\": \"ID of the new policy\", \"order\": 1 } },", "CreateSecurityPolicyOutput(komand.Output): schema = json.loads(\"\"\" { \"type\": \"object\", \"title\": \"Variables\", \"properties\":", "\"title\": \"ID\", \"description\": \"ID of the new policy\", \"order\": 1", "policy that needs to be created\", \"order\": 1 } },", "] } \"\"\") def __init__(self): super(self.__class__, self).__init__(self.schema) class CreateSecurityPolicyOutput(komand.Output): schema", "json.loads(\"\"\" { \"type\": \"object\", \"title\": \"Variables\", \"properties\": { \"id\": {", "} }, \"required\": [ \"name\" ] } \"\"\") def __init__(self):", "\"type\": \"string\", \"title\": \"Name\", \"description\": \"The name of the security", "\"Creates a security policy with the default values\" class Input:", "Output: ID = \"id\" class CreateSecurityPolicyInput(komand.Input): schema = json.loads(\"\"\" {", "{ \"type\": \"object\", \"title\": \"Variables\", \"properties\": { \"name\": { \"type\":", "self).__init__(self.schema) class CreateSecurityPolicyOutput(komand.Output): schema = json.loads(\"\"\" { \"type\": \"object\", \"title\":", "\"properties\": { \"name\": { \"type\": \"string\", \"title\": \"Name\", \"description\": \"The", "\"id\": { \"type\": \"string\", \"title\": \"ID\", \"description\": \"ID of the" ]
[ "\"lt\", \"value\": 2100} condition2 = {\"column\": \"city\", \"operator\": \"eq\", \"value\":", "= rule(conditions) condition1 = {\"column\": \"salary\", \"operator\": \"lt\", \"value\": 2100}", "\"value\": 2100} condition2 = {\"column\": \"city\", \"operator\": \"eq\", \"value\": \"London\"}", "[condition1, condition2] task2 = rule(conditions) task3 = task1.add(task2) result =", "\"city\", \"operator\": \"eq\", \"value\": \"London\"} conditions = [condition1, condition2] task2", "= spark.read.format(\"csv\").option(\"header\", \"true\").load(\"examples/resources/employees.csv\") df.show() condition1 = {\"column\": \"salary\", \"operator\": \"gt\",", "= result[1][\"scores\"][0] print(\"Rule salary<2100 and title=\\\"Sales Representative\\\": {},\" \" rule", "spark = SparkSession.builder.appName(\"rule_example\").getOrCreate() df = spark.read.format(\"csv\").option(\"header\", \"true\").load(\"examples/resources/employees.csv\") df.show() condition1 =", "SparkSession from haychecker.dhc.metrics import rule spark = SparkSession.builder.appName(\"rule_example\").getOrCreate() df =", "\"operator\": \"lt\", \"value\": 2100} condition2 = {\"column\": \"city\", \"operator\": \"eq\",", "task3.run(df) r1 = result[0][\"scores\"][0] r2 = result[1][\"scores\"][0] print(\"Rule salary<2100 and", "rule spark = SparkSession.builder.appName(\"rule_example\").getOrCreate() df = spark.read.format(\"csv\").option(\"header\", \"true\").load(\"examples/resources/employees.csv\") df.show() condition1", "result[0][\"scores\"][0] r2 = result[1][\"scores\"][0] print(\"Rule salary<2100 and title=\\\"Sales Representative\\\": {},\"", "{\"column\": \"title\", \"operator\": \"eq\", \"value\": \"Sales Representative\"} conditions = [condition1,", "= [condition1, condition2] task2 = rule(conditions) task3 = task1.add(task2) result", "= rule(conditions, df)[0] print(\"Rule salary>2100: {}\".format(r1)) condition1 = {\"column\": \"salary\",", "{\"column\": \"salary\", \"operator\": \"lt\", \"value\": 2100} condition2 = {\"column\": \"title\",", "condition2] task1 = rule(conditions) condition1 = {\"column\": \"salary\", \"operator\": \"lt\",", "\"salary\", \"operator\": \"lt\", \"value\": 2100} condition2 = {\"column\": \"title\", \"operator\":", "\"salary\", \"operator\": \"lt\", \"value\": 2100} condition2 = {\"column\": \"city\", \"operator\":", "result = task3.run(df) r1 = result[0][\"scores\"][0] r2 = result[1][\"scores\"][0] print(\"Rule", "\"operator\": \"eq\", \"value\": \"Sales Representative\"} conditions = [condition1, condition2] task1", "\"value\": 2100} condition2 = {\"column\": \"title\", \"operator\": \"eq\", \"value\": \"Sales", "import rule spark = SparkSession.builder.appName(\"rule_example\").getOrCreate() df = spark.read.format(\"csv\").option(\"header\", \"true\").load(\"examples/resources/employees.csv\") df.show()", "2100} condition2 = {\"column\": \"title\", \"operator\": \"eq\", \"value\": \"Sales Representative\"}", "= SparkSession.builder.appName(\"rule_example\").getOrCreate() df = spark.read.format(\"csv\").option(\"header\", \"true\").load(\"examples/resources/employees.csv\") df.show() condition1 = {\"column\":", "\"title\", \"operator\": \"eq\", \"value\": \"Sales Representative\"} conditions = [condition1, condition2]", "conditions = [condition1] r1 = rule(conditions, df)[0] print(\"Rule salary>2100: {}\".format(r1))", "import SparkSession from haychecker.dhc.metrics import rule spark = SparkSession.builder.appName(\"rule_example\").getOrCreate() df", "from haychecker.dhc.metrics import rule spark = SparkSession.builder.appName(\"rule_example\").getOrCreate() df = spark.read.format(\"csv\").option(\"header\",", "\"value\": 2100} conditions = [condition1] r1 = rule(conditions, df)[0] print(\"Rule", "haychecker.dhc.metrics import rule spark = SparkSession.builder.appName(\"rule_example\").getOrCreate() df = spark.read.format(\"csv\").option(\"header\", \"true\").load(\"examples/resources/employees.csv\")", "task2 = rule(conditions) task3 = task1.add(task2) result = task3.run(df) r1", "#!/usr/bin/python3 from pyspark.sql import SparkSession from haychecker.dhc.metrics import rule spark", "salary<2100 and title=\\\"Sales Representative\\\": {},\" \" rule salary<2100 and city=\\\"London\\\":", "{\"column\": \"city\", \"operator\": \"eq\", \"value\": \"London\"} conditions = [condition1, condition2]", "[condition1, condition2] task1 = rule(conditions) condition1 = {\"column\": \"salary\", \"operator\":", "Representative\"} conditions = [condition1, condition2] task1 = rule(conditions) condition1 =", "title=\\\"Sales Representative\\\": {},\" \" rule salary<2100 and city=\\\"London\\\": {}\".format(r1, r2))", "\"eq\", \"value\": \"London\"} conditions = [condition1, condition2] task2 = rule(conditions)", "2100} condition2 = {\"column\": \"city\", \"operator\": \"eq\", \"value\": \"London\"} conditions", "\"operator\": \"eq\", \"value\": \"London\"} conditions = [condition1, condition2] task2 =", "[condition1] r1 = rule(conditions, df)[0] print(\"Rule salary>2100: {}\".format(r1)) condition1 =", "= {\"column\": \"salary\", \"operator\": \"lt\", \"value\": 2100} condition2 = {\"column\":", "\"value\": \"Sales Representative\"} conditions = [condition1, condition2] task1 = rule(conditions)", "r1 = rule(conditions, df)[0] print(\"Rule salary>2100: {}\".format(r1)) condition1 = {\"column\":", "= [condition1, condition2] task1 = rule(conditions) condition1 = {\"column\": \"salary\",", "from pyspark.sql import SparkSession from haychecker.dhc.metrics import rule spark =", "df.show() condition1 = {\"column\": \"salary\", \"operator\": \"gt\", \"value\": 2100} conditions", "2100} conditions = [condition1] r1 = rule(conditions, df)[0] print(\"Rule salary>2100:", "condition2 = {\"column\": \"title\", \"operator\": \"eq\", \"value\": \"Sales Representative\"} conditions", "{\"column\": \"salary\", \"operator\": \"lt\", \"value\": 2100} condition2 = {\"column\": \"city\",", "= result[0][\"scores\"][0] r2 = result[1][\"scores\"][0] print(\"Rule salary<2100 and title=\\\"Sales Representative\\\":", "= {\"column\": \"title\", \"operator\": \"eq\", \"value\": \"Sales Representative\"} conditions =", "r2 = result[1][\"scores\"][0] print(\"Rule salary<2100 and title=\\\"Sales Representative\\\": {},\" \"", "\"value\": \"London\"} conditions = [condition1, condition2] task2 = rule(conditions) task3", "spark.read.format(\"csv\").option(\"header\", \"true\").load(\"examples/resources/employees.csv\") df.show() condition1 = {\"column\": \"salary\", \"operator\": \"gt\", \"value\":", "= rule(conditions) task3 = task1.add(task2) result = task3.run(df) r1 =", "\"operator\": \"lt\", \"value\": 2100} condition2 = {\"column\": \"title\", \"operator\": \"eq\",", "SparkSession.builder.appName(\"rule_example\").getOrCreate() df = spark.read.format(\"csv\").option(\"header\", \"true\").load(\"examples/resources/employees.csv\") df.show() condition1 = {\"column\": \"salary\",", "condition1 = {\"column\": \"salary\", \"operator\": \"lt\", \"value\": 2100} condition2 =", "\"Sales Representative\"} conditions = [condition1, condition2] task1 = rule(conditions) condition1", "\"eq\", \"value\": \"Sales Representative\"} conditions = [condition1, condition2] task1 =", "<reponame>fruttasecca/hay_checker<filename>examples/dhc/rule_example.py<gh_stars>1-10 #!/usr/bin/python3 from pyspark.sql import SparkSession from haychecker.dhc.metrics import rule", "{\"column\": \"salary\", \"operator\": \"gt\", \"value\": 2100} conditions = [condition1] r1", "{}\".format(r1)) condition1 = {\"column\": \"salary\", \"operator\": \"lt\", \"value\": 2100} condition2", "= {\"column\": \"city\", \"operator\": \"eq\", \"value\": \"London\"} conditions = [condition1,", "result[1][\"scores\"][0] print(\"Rule salary<2100 and title=\\\"Sales Representative\\\": {},\" \" rule salary<2100", "rule(conditions) condition1 = {\"column\": \"salary\", \"operator\": \"lt\", \"value\": 2100} condition2", "= {\"column\": \"salary\", \"operator\": \"gt\", \"value\": 2100} conditions = [condition1]", "task3 = task1.add(task2) result = task3.run(df) r1 = result[0][\"scores\"][0] r2", "df = spark.read.format(\"csv\").option(\"header\", \"true\").load(\"examples/resources/employees.csv\") df.show() condition1 = {\"column\": \"salary\", \"operator\":", "condition2 = {\"column\": \"city\", \"operator\": \"eq\", \"value\": \"London\"} conditions =", "task1.add(task2) result = task3.run(df) r1 = result[0][\"scores\"][0] r2 = result[1][\"scores\"][0]", "df)[0] print(\"Rule salary>2100: {}\".format(r1)) condition1 = {\"column\": \"salary\", \"operator\": \"lt\",", "condition1 = {\"column\": \"salary\", \"operator\": \"gt\", \"value\": 2100} conditions =", "condition2] task2 = rule(conditions) task3 = task1.add(task2) result = task3.run(df)", "\"operator\": \"gt\", \"value\": 2100} conditions = [condition1] r1 = rule(conditions,", "\"London\"} conditions = [condition1, condition2] task2 = rule(conditions) task3 =", "task1 = rule(conditions) condition1 = {\"column\": \"salary\", \"operator\": \"lt\", \"value\":", "conditions = [condition1, condition2] task2 = rule(conditions) task3 = task1.add(task2)", "= task3.run(df) r1 = result[0][\"scores\"][0] r2 = result[1][\"scores\"][0] print(\"Rule salary<2100", "print(\"Rule salary<2100 and title=\\\"Sales Representative\\\": {},\" \" rule salary<2100 and", "rule(conditions, df)[0] print(\"Rule salary>2100: {}\".format(r1)) condition1 = {\"column\": \"salary\", \"operator\":", "\"true\").load(\"examples/resources/employees.csv\") df.show() condition1 = {\"column\": \"salary\", \"operator\": \"gt\", \"value\": 2100}", "\"salary\", \"operator\": \"gt\", \"value\": 2100} conditions = [condition1] r1 =", "salary>2100: {}\".format(r1)) condition1 = {\"column\": \"salary\", \"operator\": \"lt\", \"value\": 2100}", "pyspark.sql import SparkSession from haychecker.dhc.metrics import rule spark = SparkSession.builder.appName(\"rule_example\").getOrCreate()", "conditions = [condition1, condition2] task1 = rule(conditions) condition1 = {\"column\":", "r1 = result[0][\"scores\"][0] r2 = result[1][\"scores\"][0] print(\"Rule salary<2100 and title=\\\"Sales", "rule(conditions) task3 = task1.add(task2) result = task3.run(df) r1 = result[0][\"scores\"][0]", "= task1.add(task2) result = task3.run(df) r1 = result[0][\"scores\"][0] r2 =", "= [condition1] r1 = rule(conditions, df)[0] print(\"Rule salary>2100: {}\".format(r1)) condition1", "print(\"Rule salary>2100: {}\".format(r1)) condition1 = {\"column\": \"salary\", \"operator\": \"lt\", \"value\":", "and title=\\\"Sales Representative\\\": {},\" \" rule salary<2100 and city=\\\"London\\\": {}\".format(r1,", "\"gt\", \"value\": 2100} conditions = [condition1] r1 = rule(conditions, df)[0]", "\"lt\", \"value\": 2100} condition2 = {\"column\": \"title\", \"operator\": \"eq\", \"value\":" ]
[ "messages based on data from party service\"\"\" if not messages:", "message.update({'@msg_to': [msg_to_details]}) else: logger.info(\"No details found for the message recipient\",", "the to actor is set to 'GROUP' all_conversation_types If set", "are a named tuple, but allow the conversation type only", "I.e conversations where the current user id is the to", "requests the specific page of information to return limit If", "all_conversation_types=fields['all_conversation_types'], unread_conversations=fields['unread_conversations']) def set_conversation_type_args(existing_args, is_closed=False, my_conversations=False, new_conversations=False, all_types=False, unread_conversations=False): \"\"\"Returns", "'unread_conversations': False} for field in ['cc', 'ce', 'business_id', 'label']: if", "If the external user id cannot be found in the", "of survey_ids cc If set , allows the count to", "set it sets the maximum number of results to return", "succinct view, spreading them out is deliberate so that log", "and from details\") messages = add_business_details(messages) logger.info(\"Successfully added business details\")", "list of survey_ids cc If set , allows the count", "ce=fields['ce'], is_closed=fields['is_closed'], my_conversations=fields['my_conversations'], new_respondent_conversations=fields['new_respondent_conversations'], all_conversation_types=fields['all_conversation_types'], unread_conversations=fields['unread_conversations']) def set_conversation_type_args(existing_args, is_closed=False, my_conversations=False,", "overrides is_closed, my_conversations and new_respondent_conversations and returns 4 counts 1", "\"\"\"used to change a pagination object to json format with", "continue value = getattr(args, field) if value: params[field] = value", "format with links\"\"\" messages = [] string_query_args = generate_string_query_args(message_args) for", "logger.exception(\"Exception adding from details message\", msg_from=msg_from, from_internal=from_internal) raise return messages", "unread_conversations=unread_conversations) def generate_string_query_args(args): params = {} for field in args._fields:", "adding from details message\", msg_from=msg_from, from_internal=from_internal) raise return messages def", "of messages\"\"\" external_user_uuids = set() external_msgs = [message for message", "logger = wrap_logger(logging.getLogger(__name__)) MessageArgs = collections.namedtuple( 'MessageArgs', 'page limit business_id", "label to be set by caller :param args: contains search", "to every message in a list of messages.\"\"\" business_ids =", "allow label to be set by caller :param args: contains", "raise ValueError('messages is a required parameter and must not be", "party.get_business_details(business_ids) for message in messages: message['@business_details'] = next((business for business", ", open , closed, my_conversations and new_respondent_conversations page If set", "and new_respondent_conversations and returns 4 counts 1 for each of", "fails, an exception will be thrown. If the external user", "all_types=False, unread_conversations=False): \"\"\"Returns a new set of args based on", "for field in args._fields: if field in ['page']: continue value", "API documentation notes that these elements aren't guaranteed to be", "where the current user id is the to actor id", "internal_user_service.get_user_details(msg_from)}) else: if external_user_details.get(message['msg_from']): message.update({'@msg_from': external_user_details.get(msg_from)}) except IndexError: logger.exception(\"Exception adding", "\"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page + 1}\"} if paginated_list.has_prev: links['prev'] = { \"href\":", "the search business_id If set , restricts search to conversations", "returns 4 counts 1 for each of , open ,", "logging import urllib.parse from structlog import wrap_logger from secure_message.constants import", "on data from party service\"\"\" if not messages: raise ValueError('messages", "add_from_details(messages): \"\"\"Adds a @msg_from key to every message in a", "= True return MessageArgs(page=fields['page'], limit=fields['limit'], business_id=fields['business_id'], surveys=fields['surveys'], cc=fields['cc'], label=fields['label'], desc=fields['desc'],", "for message in paginated_list.items: msg = message.serialize(user, body_summary=body_summary) msg['_links'] =", "message\", msg_from=msg_from, from_internal=from_internal) raise return messages def get_external_user_uuid_list(messages): \"\"\"Compiles a", "allows the count to be restricted by a particular case", "if paginated_list.has_next: links['next'] = { \"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page + 1}\"} if", "of these lines of code could be combined into a", "set 'true', overrides is_closed, my_conversations and new_respondent_conversations and returns 4", "case ce If set, alows the count to be restricted", "new_respondent_conversations and returns 4 counts 1 for each of ,", "that log stack traces are better able to identify the", "out is deliberate so that log stack traces are better", "message in messages: try: msg_to = message[\"msg_to\"][0] from_internal = message[\"from_internal\"]", "If set allows the count to be restricted by a", "is_closed=fields['is_closed'], my_conversations=fields['my_conversations'], new_respondent_conversations=fields['new_respondent_conversations'], all_conversation_types=fields['all_conversation_types'], unread_conversations=fields['unread_conversations']) def set_conversation_type_args(existing_args, is_closed=False, my_conversations=False, new_conversations=False,", "= value return urllib.parse.urlencode(params) def process_paginated_list(paginated_list, host_url, user, message_args, endpoint=MESSAGE_LIST_ENDPOINT,", "paginated_list.items: msg = message.serialize(user, body_summary=body_summary) msg['_links'] = {\"self\": {\"href\": f\"{host_url}{MESSAGE_BY_ID_ENDPOINT}/{msg['msg_id']}\"}}", "If the call for the internal user id fails, an", "the party service. There won't be a @msg_to value returned", "\"\"\"Adds a @msg_to key to every message in a list", "if external_user_details.get(message['msg_from']): message.update({'@msg_from': external_user_details.get(msg_from)}) except IndexError: logger.exception(\"Exception adding from details", "user id fails, an exception will be thrown. If the", "message in messages: business_ids.add(message['business_id']) business_details = party.get_business_details(business_ids) for message in", "conversations where the current user id is the to actor", "body_summary=True): \"\"\"used to change a pagination object to json format", "all_conversation_types=all_types, unread_conversations=unread_conversations) def generate_string_query_args(args): params = {} for field in", "wrap_logger from secure_message.constants import MESSAGE_BY_ID_ENDPOINT, MESSAGE_LIST_ENDPOINT, MESSAGE_QUERY_LIMIT from secure_message.services.service_toggles import", "restricts search to conversations regarding this specific party id surveys", "import urllib.parse from structlog import wrap_logger from secure_message.constants import MESSAGE_BY_ID_ENDPOINT,", "fields[field] = int(args.get(field)) if args.get('desc') == 'false': fields['desc'] = False", "id is the to actor id new_respondent_conversations If set to", "by caller :param args: contains search arguments. Not all end", "return MessageArgs(page=fields['page'], limit=fields['limit'], business_id=fields['business_id'], surveys=fields['surveys'], cc=fields['cc'], label=fields['label'], desc=fields['desc'], ce=fields['ce'], is_closed=fields['is_closed'],", "if not messages: raise ValueError('messages is a required parameter and", "unread_conversations=False): \"\"\"Returns a new set of args based on the", "messages.append(msg) links = {'first': {\"href\": f\"{host_url}{endpoint}\"}, 'self': {\"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page}\"}} if", "only counts closed conversations, else only open conversations my_conversations If", "= {'first': {\"href\": f\"{host_url}{endpoint}\"}, 'self': {\"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page}\"}} if paginated_list.has_next: links['next']", "return external_user_uuids def add_business_details(messages): \"\"\"Adds a @business_details key to every", "= [message for message in messages if message['from_internal'] is False]", "this specific party id surveys If set allows the count", "except IndexError: logger.exception(\"Exception adding to details\", msg_to=msg_to, from_internal=from_internal) raise return", "args based on the existing args which are a named", "{ \"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page - 1}\"} return messages, links def add_to_details(messages):", "= { \"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page + 1}\"} if paginated_list.has_prev: links['prev'] =", "my_conversations=fields['my_conversations'], new_respondent_conversations=fields['new_respondent_conversations'], all_conversation_types=fields['all_conversation_types'], unread_conversations=fields['unread_conversations']) def set_conversation_type_args(existing_args, is_closed=False, my_conversations=False, new_conversations=False, all_types=False,", "True if args.get('new_respondent_conversations') == 'true': fields['new_respondent_conversations'] = True if args.get('all_conversation_types')", "the cause of log errors \"\"\" external_user_details = {} for", "message[\"msg_from\"] from_internal = message[\"from_internal\"] if from_internal: message.update({\"@msg_from\": internal_user_service.get_user_details(msg_from)}) else: if", "the contract by doing this. Note: Several of these lines", "['limit', 'page']: if args.get(field): fields[field] = int(args.get(field)) if args.get('desc') ==", "of messages.\"\"\" business_ids = set() for message in messages: business_ids.add(message['business_id'])", "number of results to return desc If present, requests the", "these lines of code could be combined into a more", "message.update({'@msg_from': external_user_details.get(msg_from)}) except IndexError: logger.exception(\"Exception adding from details message\", msg_from=msg_from,", "for message in messages if message['from_internal'] is False] for message", "message in external_msgs: external_user_uuids.add(message[\"msg_from\"]) internal_messages = [message for message in", "open conversations my_conversations If set to 'true only counts my", "messages: message['@business_details'] = next((business for business in business_details if business[\"id\"]", "conversations. I.e conversations where the current user id is the", "returned in the payload. The API documentation notes that these", "business_ids.add(message['business_id']) business_details = party.get_business_details(business_ids) for message in messages: message['@business_details'] =", "be restricted by a particular collection exercise is_closed If set", "to identify the cause of log errors \"\"\" external_user_details =", "links = {'first': {\"href\": f\"{host_url}{endpoint}\"}, 'self': {\"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page}\"}} if paginated_list.has_next:", "links['next'] = { \"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page + 1}\"} if paginated_list.has_prev: links['prev']", "args.get('is_closed') == 'true': fields['is_closed'] = True if args.get('my_conversations') == 'true':", "message.update({\"@msg_from\": internal_user_service.get_user_details(msg_from)}) else: if external_user_details.get(message['msg_from']): message.update({'@msg_from': external_user_details.get(msg_from)}) except IndexError: logger.exception(\"Exception", "actor is set to 'GROUP' all_conversation_types If set 'true', overrides", "in messages: message['@business_details'] = next((business for business in business_details if", "set of args based on the existing args which are", "\"\"\"Adds a @business_details key to every message in a list", "list of messages.\"\"\" business_ids = set() for message in messages:", "business_id=existing_args.business_id, surveys=existing_args.surveys, cc=existing_args.cc, label=existing_args.label, desc=existing_args.desc, ce=existing_args.ce, is_closed=is_closed, my_conversations=my_conversations, new_respondent_conversations=new_conversations, all_conversation_types=all_types,", "id new_respondent_conversations If set to 'true'only counts conversations where the", "uuids from a list of messages\"\"\" external_user_uuids = set() external_msgs", "new_respondent_conversations=fields['new_respondent_conversations'], all_conversation_types=fields['all_conversation_types'], unread_conversations=fields['unread_conversations']) def set_conversation_type_args(existing_args, is_closed=False, my_conversations=False, new_conversations=False, all_types=False, unread_conversations=False):", "If set requests the specific page of information to return", "conversation type only to be changed\"\"\" return MessageArgs(page=existing_args.page, limit=existing_args.limit, business_id=existing_args.business_id,", "external_user_details.get(msg_to) if msg_to_details: message.update({'@msg_to': [msg_to_details]}) else: logger.info(\"No details found for", "messages. Every msg_to uuid is resolved to include details of", "the internal user id fails, an exception will be thrown.", "new_respondent_conversations If set to 'true'only counts conversations where the to", "internal_messages: external_user_uuids.add(uuid[\"msg_to\"][0]) return external_user_uuids def add_business_details(messages): \"\"\"Adds a @business_details key", "a list of messages\"\"\" external_user_uuids = set() external_msgs = [message", "= [message for message in messages if message['from_internal'] is True]", "not be empty') messages = add_to_details(messages) messages = add_from_details(messages) logger.info(\"Successfully", "value returned in the payload. The API documentation notes that", "errors \"\"\" external_user_details = {} for user in party.get_users_details(get_external_user_uuid_list(messages)): external_user_details[user['id']]", "set allows the count to be restricted by a list", "new_respondent_conversations all_conversation_types unread_conversations') def get_options(args): # NOQA pylint:disable=too-complex \"\"\"extract options", "1}\"} if paginated_list.has_prev: links['prev'] = { \"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page - 1}\"}", "new set of args based on the existing args which", "search to conversations regarding this specific party id surveys If", "list of messages. Every msg_to uuid is resolved to include", "= {} for user in party.get_users_details(get_external_user_uuid_list(messages)): external_user_details[user['id']] = user for", "MESSAGE_QUERY_LIMIT, 'business_id': None, 'surveys': None, 'desc': True, 'cc': None, 'label':", "== 'true': fields['all_conversation_types'] = True if args.get('unread_conversations') == 'true': fields['unread_conversations']", "if args.get('unread_conversations') == 'true': fields['unread_conversations'] = True return MessageArgs(page=fields['page'], limit=fields['limit'],", "this. \"\"\" external_user_details = {} for user in party.get_users_details(get_external_user_uuid_list(messages)): external_user_details[user['id']]", "message in messages if message['from_internal'] is True] for uuid in", "options from request , allow label to be set by", "Every msg_to uuid is resolved to include details of the", "False, 'all_conversation_types': False, 'unread_conversations': False} for field in ['cc', 'ce',", "msg['_links'] = {\"self\": {\"href\": f\"{host_url}{MESSAGE_BY_ID_ENDPOINT}/{msg['msg_id']}\"}} messages.append(msg) links = {'first': {\"href\":", "party id surveys If set allows the count to be", "contract by doing this. \"\"\" external_user_details = {} for user", "list of messages\"\"\" external_user_uuids = set() external_msgs = [message for", "[message for message in messages if message['from_internal'] is False] for", "[message for message in messages if message['from_internal'] is True] for", "count to be restricted by a particular collection exercise is_closed", "= message.serialize(user, body_summary=body_summary) msg['_links'] = {\"self\": {\"href\": f\"{host_url}{MESSAGE_BY_ID_ENDPOINT}/{msg['msg_id']}\"}} messages.append(msg) links", "it sets the maximum number of results to return desc", "the contract by doing this. \"\"\" external_user_details = {} for", "is the to actor id new_respondent_conversations If set to 'true'only", "= party.get_business_details(business_ids) for message in messages: message['@business_details'] = next((business for", "value: params[field] = value return urllib.parse.urlencode(params) def process_paginated_list(paginated_list, host_url, user,", "a pagination object to json format with links\"\"\" messages =", "party, internal_user_service logger = wrap_logger(logging.getLogger(__name__)) MessageArgs = collections.namedtuple( 'MessageArgs', 'page", "particular collection exercise is_closed If set to 'true' only counts", "external_user_uuids def add_business_details(messages): \"\"\"Adds a @business_details key to every message", "user for message in messages: try: msg_to = message[\"msg_to\"][0] from_internal", "args.get('my_conversations') == 'true': fields['my_conversations'] = True if args.get('new_respondent_conversations') == 'true':", "MESSAGE_BY_ID_ENDPOINT, MESSAGE_LIST_ENDPOINT, MESSAGE_QUERY_LIMIT from secure_message.services.service_toggles import party, internal_user_service logger =", "is deliberate so that log stack traces are better able", "= False if args.get('is_closed') == 'true': fields['is_closed'] = True if", "counts closed conversations, else only open conversations my_conversations If set", "messages if message['from_internal'] is True] for uuid in internal_messages: external_user_uuids.add(uuid[\"msg_to\"][0])", "in ['page']: continue value = getattr(args, field) if value: params[field]", "\"\"\" fields = {'page': 1, 'limit': MESSAGE_QUERY_LIMIT, 'business_id': None, 'surveys':", "both user and business details to messages based on data", "getattr(args, field) if value: params[field] = value return urllib.parse.urlencode(params) def", "order \"\"\" fields = {'page': 1, 'limit': MESSAGE_QUERY_LIMIT, 'business_id': None,", "be restricted by a particular case ce If set, alows", "If present, requests the information in descending order \"\"\" fields", "args which are a named tuple, but allow the conversation", "to actor is set to 'GROUP' all_conversation_types If set 'true',", "user id cannot be found in the list that we", "Not all end points support all args :returns: MessageArgs named", "cc If set , allows the count to be restricted", "is set to 'GROUP' all_conversation_types If set 'true', overrides is_closed,", "\"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page - 1}\"} return messages, links def add_to_details(messages): \"\"\"Adds", "traces are better able to identify the cause of log", "import party, internal_user_service logger = wrap_logger(logging.getLogger(__name__)) MessageArgs = collections.namedtuple( 'MessageArgs',", "by a list of survey_ids cc If set , allows", "business_id surveys cc label desc ce is_closed my_conversations new_respondent_conversations all_conversation_types", "we're not breaking the contract by doing this. \"\"\" external_user_details", ", closed, my_conversations and new_respondent_conversations page If set requests the", "args.get('new_respondent_conversations') == 'true': fields['new_respondent_conversations'] = True if args.get('all_conversation_types') == 'true':", "'my_conversations': False, 'new_respondent_conversations': False, 'all_conversation_types': False, 'unread_conversations': False} for field", "= user for message in messages: try: msg_from = message[\"msg_from\"]", "external_user_uuids.add(message[\"msg_from\"]) internal_messages = [message for message in messages if message['from_internal']", "limit=fields['limit'], business_id=fields['business_id'], surveys=fields['surveys'], cc=fields['cc'], label=fields['label'], desc=fields['desc'], ce=fields['ce'], is_closed=fields['is_closed'], my_conversations=fields['my_conversations'], new_respondent_conversations=fields['new_respondent_conversations'],", "fields['is_closed'] = True if args.get('my_conversations') == 'true': fields['my_conversations'] = True", "def process_paginated_list(paginated_list, host_url, user, message_args, endpoint=MESSAGE_LIST_ENDPOINT, body_summary=True): \"\"\"used to change", "fields['my_conversations'] = True if args.get('new_respondent_conversations') == 'true': fields['new_respondent_conversations'] = True", "ce=existing_args.ce, is_closed=is_closed, my_conversations=my_conversations, new_respondent_conversations=new_conversations, all_conversation_types=all_types, unread_conversations=unread_conversations) def generate_string_query_args(args): params =", "return messages def add_users_and_business_details(messages): \"\"\"Add both user and business details", "'all_conversation_types': False, 'unread_conversations': False} for field in ['cc', 'ce', 'business_id',", "every message in a list of messages. Every msg_to uuid", "to details\", msg_to=msg_to, from_internal=from_internal) raise return messages def add_from_details(messages): \"\"\"Adds", "by a particular collection exercise is_closed If set to 'true'", "from secure_message.constants import MESSAGE_BY_ID_ENDPOINT, MESSAGE_LIST_ENDPOINT, MESSAGE_QUERY_LIMIT from secure_message.services.service_toggles import party,", "on the existing args which are a named tuple, but", "based on the existing args which are a named tuple,", "a required parameter and must not be empty') messages =", "and must not be empty') messages = add_to_details(messages) messages =", "args for the search business_id If set , restricts search", "'ce', 'business_id', 'label']: if args.get(field): fields[field] = str(args.get(field)) fields['surveys'] =", "code could be combined into a more succinct view, spreading", "party service. There won't be a @msg_from value returned in", "in descending order \"\"\" fields = {'page': 1, 'limit': MESSAGE_QUERY_LIMIT,", "messages def get_external_user_uuid_list(messages): \"\"\"Compiles a list of all unique the", "internal user id fails, an exception will be thrown. If", "include details of the user. If the call for the", "None, 'ce': None, 'is_closed': False, 'my_conversations': False, 'new_respondent_conversations': False, 'all_conversation_types':", "else: if external_user_details.get(message['msg_from']): message.update({'@msg_from': external_user_details.get(msg_from)}) except IndexError: logger.exception(\"Exception adding from", "thrown. If the external user id cannot be found in", "a list of messages. Every msg_to uuid is resolved to", "If set to 'true' only counts closed conversations, else only", "we got from the party service. There won't be a", "named tuple, but allow the conversation type only to be", ", restricts search to conversations regarding this specific party id", "the message recipient\", msg_to=msg_to) except IndexError: logger.exception(\"Exception adding to details\",", "messages = add_from_details(messages) logger.info(\"Successfully added to and from details\") messages", "surveys=existing_args.surveys, cc=existing_args.cc, label=existing_args.label, desc=existing_args.desc, ce=existing_args.ce, is_closed=is_closed, my_conversations=my_conversations, new_respondent_conversations=new_conversations, all_conversation_types=all_types, unread_conversations=unread_conversations)", "search business_id If set , restricts search to conversations regarding", "True return MessageArgs(page=fields['page'], limit=fields['limit'], business_id=fields['business_id'], surveys=fields['surveys'], cc=fields['cc'], label=fields['label'], desc=fields['desc'], ce=fields['ce'],", "won't be a @msg_from value returned in the payload. The", "= generate_string_query_args(message_args) for message in paginated_list.items: msg = message.serialize(user, body_summary=body_summary)", "add_to_details(messages): \"\"\"Adds a @msg_to key to every message in a", "raise return messages def get_external_user_uuid_list(messages): \"\"\"Compiles a list of all", "= add_to_details(messages) messages = add_from_details(messages) logger.info(\"Successfully added to and from", "set requests the specific page of information to return limit", "got from the party service. There won't be a @msg_to", "guaranteed to be provided so we're not breaking the contract", "fields['new_respondent_conversations'] = True if args.get('all_conversation_types') == 'true': fields['all_conversation_types'] = True", "if args.get('all_conversation_types') == 'true': fields['all_conversation_types'] = True if args.get('unread_conversations') ==", "messages: raise ValueError('messages is a required parameter and must not", "from_internal=from_internal) raise return messages def get_external_user_uuid_list(messages): \"\"\"Compiles a list of", "all end points support all args :returns: MessageArgs named tuple", "If set , restricts search to conversations regarding this specific", "== 'true': fields['unread_conversations'] = True return MessageArgs(page=fields['page'], limit=fields['limit'], business_id=fields['business_id'], surveys=fields['surveys'],", "wrap_logger(logging.getLogger(__name__)) MessageArgs = collections.namedtuple( 'MessageArgs', 'page limit business_id surveys cc", "message in messages: message['@business_details'] = next((business for business in business_details", "but allow the conversation type only to be changed\"\"\" return", "from the party service. There won't be a @msg_to value", "to return limit If set it sets the maximum number", "not breaking the contract by doing this. Note: Several of", "external_user_details.get(msg_from)}) except IndexError: logger.exception(\"Exception adding from details message\", msg_from=msg_from, from_internal=from_internal)", "ValueError('messages is a required parameter and must not be empty')", "if args.get(field): fields[field] = str(args.get(field)) fields['surveys'] = args.getlist('survey') for field", "containing the args for the search business_id If set ,", "pagination object to json format with links\"\"\" messages = []", "search arguments. Not all end points support all args :returns:", "@business_details key to every message in a list of messages.\"\"\"", "args.get(field): fields[field] = int(args.get(field)) if args.get('desc') == 'false': fields['desc'] =", "body_summary=body_summary) msg['_links'] = {\"self\": {\"href\": f\"{host_url}{MESSAGE_BY_ID_ENDPOINT}/{msg['msg_id']}\"}} messages.append(msg) links = {'first':", "from_internal=from_internal) raise return messages def add_from_details(messages): \"\"\"Adds a @msg_from key", "the args for the search business_id If set , restricts", "If set to 'true'only counts conversations where the to actor", "set to 'true' only counts closed conversations, else only open", "message[\"from_internal\"] if from_internal: message.update({\"@msg_from\": internal_user_service.get_user_details(msg_from)}) else: if external_user_details.get(message['msg_from']): message.update({'@msg_from': external_user_details.get(msg_from)})", "IndexError: logger.exception(\"Exception adding to details\", msg_to=msg_to, from_internal=from_internal) raise return messages", "results to return desc If present, requests the information in", "import MESSAGE_BY_ID_ENDPOINT, MESSAGE_LIST_ENDPOINT, MESSAGE_QUERY_LIMIT from secure_message.services.service_toggles import party, internal_user_service logger", "{\"self\": {\"href\": f\"{host_url}{MESSAGE_BY_ID_ENDPOINT}/{msg['msg_id']}\"}} messages.append(msg) links = {'first': {\"href\": f\"{host_url}{endpoint}\"}, 'self':", "from party service\"\"\" if not messages: raise ValueError('messages is a", "return MessageArgs(page=existing_args.page, limit=existing_args.limit, business_id=existing_args.business_id, surveys=existing_args.surveys, cc=existing_args.cc, label=existing_args.label, desc=existing_args.desc, ce=existing_args.ce, is_closed=is_closed,", "if args.get('desc') == 'false': fields['desc'] = False if args.get('is_closed') ==", "set by caller :param args: contains search arguments. Not all", "exception will be thrown. If the external user id cannot", "be thrown. If the external user id cannot be found", "= set() external_msgs = [message for message in messages if", "not messages: raise ValueError('messages is a required parameter and must", "in a list of messages. Every msg_to uuid is resolved", "int(args.get(field)) if args.get('desc') == 'false': fields['desc'] = False if args.get('is_closed')", "to and from details\") messages = add_business_details(messages) logger.info(\"Successfully added business", "'label']: if args.get(field): fields[field] = str(args.get(field)) fields['surveys'] = args.getlist('survey') for", "to change a pagination object to json format with links\"\"\"", "be found in the list that we got from the", "is_closed, my_conversations and new_respondent_conversations and returns 4 counts 1 for", "business_id=fields['business_id'], surveys=fields['surveys'], cc=fields['cc'], label=fields['label'], desc=fields['desc'], ce=fields['ce'], is_closed=fields['is_closed'], my_conversations=fields['my_conversations'], new_respondent_conversations=fields['new_respondent_conversations'], all_conversation_types=fields['all_conversation_types'],", "party service. There won't be a @msg_to value returned in", "endpoint=MESSAGE_LIST_ENDPOINT, body_summary=True): \"\"\"used to change a pagination object to json", "notes that these elements aren't guaranteed to be provided so", "where the to actor is set to 'GROUP' all_conversation_types If", "specific party id surveys If set allows the count to", "None, 'is_closed': False, 'my_conversations': False, 'new_respondent_conversations': False, 'all_conversation_types': False, 'unread_conversations':", "sets the maximum number of results to return desc If", "else only open conversations my_conversations If set to 'true only", "= set() for message in messages: business_ids.add(message['business_id']) business_details = party.get_business_details(business_ids)", "params = {} for field in args._fields: if field in", "is_closed=is_closed, my_conversations=my_conversations, new_respondent_conversations=new_conversations, all_conversation_types=all_types, unread_conversations=unread_conversations) def generate_string_query_args(args): params = {}", "\"\"\"extract options from request , allow label to be set", "process_paginated_list(paginated_list, host_url, user, message_args, endpoint=MESSAGE_LIST_ENDPOINT, body_summary=True): \"\"\"used to change a", "pylint:disable=too-complex \"\"\"extract options from request , allow label to be", "points support all args :returns: MessageArgs named tuple containing the", ", allows the count to be restricted by a particular", "add_from_details(messages) logger.info(\"Successfully added to and from details\") messages = add_business_details(messages)", "messages = [] string_query_args = generate_string_query_args(message_args) for message in paginated_list.items:", "str(args.get(field)) fields['surveys'] = args.getlist('survey') for field in ['limit', 'page']: if", "message in a list of messages. Every msg_to uuid is", "MessageArgs named tuple containing the args for the search business_id", "get_options(args): # NOQA pylint:disable=too-complex \"\"\"extract options from request , allow", "doing this. \"\"\" external_user_details = {} for user in party.get_users_details(get_external_user_uuid_list(messages)):", "required parameter and must not be empty') messages = add_to_details(messages)", "requests the information in descending order \"\"\" fields = {'page':", "user and business details to messages based on data from", "the existing args which are a named tuple, but allow", "arguments. Not all end points support all args :returns: MessageArgs", "and new_respondent_conversations page If set requests the specific page of", "- 1}\"} return messages, links def add_to_details(messages): \"\"\"Adds a @msg_to", "based on data from party service\"\"\" if not messages: raise", "service\"\"\" if not messages: raise ValueError('messages is a required parameter", "message in messages if message['from_internal'] is False] for message in", "field in ['page']: continue value = getattr(args, field) if value:", "the user. If the call for the internal user id", "the party service. There won't be a @msg_from value returned", "from_internal = message[\"from_internal\"] if from_internal: message.update({\"@msg_from\": internal_user_service.get_user_details(msg_from)}) else: if external_user_details.get(message['msg_from']):", "'true': fields['all_conversation_types'] = True if args.get('unread_conversations') == 'true': fields['unread_conversations'] =", "my_conversations=False, new_conversations=False, all_types=False, unread_conversations=False): \"\"\"Returns a new set of args", "collections import logging import urllib.parse from structlog import wrap_logger from", "limit If set it sets the maximum number of results", "from_internal: message.update({\"@msg_from\": internal_user_service.get_user_details(msg_from)}) else: if external_user_details.get(message['msg_from']): message.update({'@msg_from': external_user_details.get(msg_from)}) except IndexError:", "information to return limit If set it sets the maximum", "be provided so we're not breaking the contract by doing", "not breaking the contract by doing this. \"\"\" external_user_details =", "desc=existing_args.desc, ce=existing_args.ce, is_closed=is_closed, my_conversations=my_conversations, new_respondent_conversations=new_conversations, all_conversation_types=all_types, unread_conversations=unread_conversations) def generate_string_query_args(args): params", "= wrap_logger(logging.getLogger(__name__)) MessageArgs = collections.namedtuple( 'MessageArgs', 'page limit business_id surveys", "in ['limit', 'page']: if args.get(field): fields[field] = int(args.get(field)) if args.get('desc')", "so that log stack traces are better able to identify", "change a pagination object to json format with links\"\"\" messages", "if message['from_internal'] is False] for message in external_msgs: external_user_uuids.add(message[\"msg_from\"]) internal_messages", "True, 'cc': None, 'label': None, 'ce': None, 'is_closed': False, 'my_conversations':", "current user id is the to actor id new_respondent_conversations If", "conversations, else only open conversations my_conversations If set to 'true", "alows the count to be restricted by a particular collection", "details\", msg_to=msg_to, from_internal=from_internal) raise return messages def add_from_details(messages): \"\"\"Adds a", "my conversations. I.e conversations where the current user id is", "in internal_messages: external_user_uuids.add(uuid[\"msg_to\"][0]) return external_user_uuids def add_business_details(messages): \"\"\"Adds a @business_details", "in a list of messages.\"\"\" business_ids = set() for message", "the conversation type only to be changed\"\"\" return MessageArgs(page=existing_args.page, limit=existing_args.limit,", "survey_ids cc If set , allows the count to be", "def set_conversation_type_args(existing_args, is_closed=False, my_conversations=False, new_conversations=False, all_types=False, unread_conversations=False): \"\"\"Returns a new", "view, spreading them out is deliberate so that log stack", "True] for uuid in internal_messages: external_user_uuids.add(uuid[\"msg_to\"][0]) return external_user_uuids def add_business_details(messages):", "page of information to return limit If set it sets", "a @msg_to value returned in the payload. The API documentation", "for business in business_details if business[\"id\"] == message['business_id']), None) return", "if business[\"id\"] == message['business_id']), None) return messages def add_users_and_business_details(messages): \"\"\"Add", "counts conversations where the to actor is set to 'GROUP'", "messages def add_users_and_business_details(messages): \"\"\"Add both user and business details to", "is a required parameter and must not be empty') messages", "add_users_and_business_details(messages): \"\"\"Add both user and business details to messages based", "is_closed my_conversations new_respondent_conversations all_conversation_types unread_conversations') def get_options(args): # NOQA pylint:disable=too-complex", "my_conversations and new_respondent_conversations page If set requests the specific page", "links['prev'] = { \"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page - 1}\"} return messages, links", "return messages, links def add_to_details(messages): \"\"\"Adds a @msg_to key to", "deliberate so that log stack traces are better able to", "better able to identify the cause of log errors \"\"\"", "= message[\"msg_to\"][0] from_internal = message[\"from_internal\"] if not from_internal: msg_to_details =", "'page limit business_id surveys cc label desc ce is_closed my_conversations", "external user id cannot be found in the list that", "a list of all unique the external user (respondent) uuids", "'true': fields['is_closed'] = True if args.get('my_conversations') == 'true': fields['my_conversations'] =", "recipient\", msg_to=msg_to) except IndexError: logger.exception(\"Exception adding to details\", msg_to=msg_to, from_internal=from_internal)", "each of , open , closed, my_conversations and new_respondent_conversations page", "in messages if message['from_internal'] is True] for uuid in internal_messages:", "of log errors \"\"\" external_user_details = {} for user in", "is False] for message in external_msgs: external_user_uuids.add(message[\"msg_from\"]) internal_messages = [message", "f\"{host_url}{endpoint}\"}, 'self': {\"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page}\"}} if paginated_list.has_next: links['next'] = { \"href\":", "+ 1}\"} if paginated_list.has_prev: links['prev'] = { \"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page -", "all unique the external user (respondent) uuids from a list", "business in business_details if business[\"id\"] == message['business_id']), None) return messages", "urllib.parse from structlog import wrap_logger from secure_message.constants import MESSAGE_BY_ID_ENDPOINT, MESSAGE_LIST_ENDPOINT,", "exercise is_closed If set to 'true' only counts closed conversations,", "if not from_internal: msg_to_details = internal_user_service.get_user_details(msg_to) message.update({\"@msg_to\": [msg_to_details]}) else: msg_to_details", "be combined into a more succinct view, spreading them out", "for message in messages: business_ids.add(message['business_id']) business_details = party.get_business_details(business_ids) for message", "in messages: business_ids.add(message['business_id']) business_details = party.get_business_details(business_ids) for message in messages:", "fields[field] = str(args.get(field)) fields['surveys'] = args.getlist('survey') for field in ['limit',", "in the list that we got from the party service.", "for message in messages if message['from_internal'] is True] for uuid", "messages, links def add_to_details(messages): \"\"\"Adds a @msg_to key to every", "'false': fields['desc'] = False if args.get('is_closed') == 'true': fields['is_closed'] =", "{} for user in party.get_users_details(get_external_user_uuid_list(messages)): external_user_details[user['id']] = user for message", "only counts my conversations. I.e conversations where the current user", "and returns 4 counts 1 for each of , open", "f\"{host_url}{MESSAGE_BY_ID_ENDPOINT}/{msg['msg_id']}\"}} messages.append(msg) links = {'first': {\"href\": f\"{host_url}{endpoint}\"}, 'self': {\"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page}\"}}", "closed, my_conversations and new_respondent_conversations page If set requests the specific", "be empty') messages = add_to_details(messages) messages = add_from_details(messages) logger.info(\"Successfully added", "get_external_user_uuid_list(messages): \"\"\"Compiles a list of all unique the external user", "counts my conversations. I.e conversations where the current user id", "so we're not breaking the contract by doing this. Note:", "'is_closed': False, 'my_conversations': False, 'new_respondent_conversations': False, 'all_conversation_types': False, 'unread_conversations': False}", "party.get_users_details(get_external_user_uuid_list(messages)): external_user_details[user['id']] = user for message in messages: try: msg_to", "def add_users_and_business_details(messages): \"\"\"Add both user and business details to messages", "[msg_to_details]}) else: logger.info(\"No details found for the message recipient\", msg_to=msg_to)", "business details to messages based on data from party service\"\"\"", "import wrap_logger from secure_message.constants import MESSAGE_BY_ID_ENDPOINT, MESSAGE_LIST_ENDPOINT, MESSAGE_QUERY_LIMIT from secure_message.services.service_toggles", "provided so we're not breaking the contract by doing this.", "for the message recipient\", msg_to=msg_to) except IndexError: logger.exception(\"Exception adding to", "add_to_details(messages) messages = add_from_details(messages) logger.info(\"Successfully added to and from details\")", "label desc ce is_closed my_conversations new_respondent_conversations all_conversation_types unread_conversations') def get_options(args):", "True if args.get('unread_conversations') == 'true': fields['unread_conversations'] = True return MessageArgs(page=fields['page'],", "type only to be changed\"\"\" return MessageArgs(page=existing_args.page, limit=existing_args.limit, business_id=existing_args.business_id, surveys=existing_args.surveys,", "which are a named tuple, but allow the conversation type", "the payload. The API documentation notes that these elements aren't", "'true', overrides is_closed, my_conversations and new_respondent_conversations and returns 4 counts", "to actor id new_respondent_conversations If set to 'true'only counts conversations", "so we're not breaking the contract by doing this. \"\"\"", "= message[\"from_internal\"] if not from_internal: msg_to_details = internal_user_service.get_user_details(msg_to) message.update({\"@msg_to\": [msg_to_details]})", "all args :returns: MessageArgs named tuple containing the args for", "maximum number of results to return desc If present, requests", "False if args.get('is_closed') == 'true': fields['is_closed'] = True if args.get('my_conversations')", "from the party service. There won't be a @msg_from value", "IndexError: logger.exception(\"Exception adding from details message\", msg_from=msg_from, from_internal=from_internal) raise return", "user (respondent) uuids from a list of messages\"\"\" external_user_uuids =", "id fails, an exception will be thrown. If the external", "the maximum number of results to return desc If present,", "fields['surveys'] = args.getlist('survey') for field in ['limit', 'page']: if args.get(field):", "end points support all args :returns: MessageArgs named tuple containing", "of information to return limit If set it sets the", "internal_user_service logger = wrap_logger(logging.getLogger(__name__)) MessageArgs = collections.namedtuple( 'MessageArgs', 'page limit", "is resolved to include details of the user. If the", "set , allows the count to be restricted by a", "args: contains search arguments. Not all end points support all", "identify the cause of log errors \"\"\" external_user_details = {}", "set_conversation_type_args(existing_args, is_closed=False, my_conversations=False, new_conversations=False, all_types=False, unread_conversations=False): \"\"\"Returns a new set", "to every message in a list of messages. Every msg_to", "to be restricted by a list of survey_ids cc If", "empty') messages = add_to_details(messages) messages = add_from_details(messages) logger.info(\"Successfully added to", "my_conversations and new_respondent_conversations and returns 4 counts 1 for each", "urllib.parse.urlencode(params) def process_paginated_list(paginated_list, host_url, user, message_args, endpoint=MESSAGE_LIST_ENDPOINT, body_summary=True): \"\"\"used to", "@msg_to key to every message in a list of messages.", "to 'GROUP' all_conversation_types If set 'true', overrides is_closed, my_conversations and", "if args.get('my_conversations') == 'true': fields['my_conversations'] = True if args.get('new_respondent_conversations') ==", "4 counts 1 for each of , open , closed,", "we're not breaking the contract by doing this. Note: Several", "links\"\"\" messages = [] string_query_args = generate_string_query_args(message_args) for message in", "log errors \"\"\" external_user_details = {} for user in party.get_users_details(get_external_user_uuid_list(messages)):", "(respondent) uuids from a list of messages\"\"\" external_user_uuids = set()", ":param args: contains search arguments. Not all end points support", "1 for each of , open , closed, my_conversations and", "except IndexError: logger.exception(\"Exception adding from details message\", msg_from=msg_from, from_internal=from_internal) raise", "desc=fields['desc'], ce=fields['ce'], is_closed=fields['is_closed'], my_conversations=fields['my_conversations'], new_respondent_conversations=fields['new_respondent_conversations'], all_conversation_types=fields['all_conversation_types'], unread_conversations=fields['unread_conversations']) def set_conversation_type_args(existing_args, is_closed=False,", "that these elements aren't guaranteed to be provided so we're", "return urllib.parse.urlencode(params) def process_paginated_list(paginated_list, host_url, user, message_args, endpoint=MESSAGE_LIST_ENDPOINT, body_summary=True): \"\"\"used", "in paginated_list.items: msg = message.serialize(user, body_summary=body_summary) msg['_links'] = {\"self\": {\"href\":", "service. There won't be a @msg_to value returned in the", "set to 'true only counts my conversations. I.e conversations where", "could be combined into a more succinct view, spreading them", "msg_to_details: message.update({'@msg_to': [msg_to_details]}) else: logger.info(\"No details found for the message", "= add_from_details(messages) logger.info(\"Successfully added to and from details\") messages =", "a particular collection exercise is_closed If set to 'true' only", "collection exercise is_closed If set to 'true' only counts closed", "1}\"} return messages, links def add_to_details(messages): \"\"\"Adds a @msg_to key", "from_internal = message[\"from_internal\"] if not from_internal: msg_to_details = internal_user_service.get_user_details(msg_to) message.update({\"@msg_to\":", "[msg_to_details]}) else: msg_to_details = external_user_details.get(msg_to) if msg_to_details: message.update({'@msg_to': [msg_to_details]}) else:", "will be thrown. If the external user id cannot be", "the count to be restricted by a particular collection exercise", "in messages if message['from_internal'] is False] for message in external_msgs:", "next((business for business in business_details if business[\"id\"] == message['business_id']), None)", "call for the internal user id fails, an exception will", "allow the conversation type only to be changed\"\"\" return MessageArgs(page=existing_args.page,", "field) if value: params[field] = value return urllib.parse.urlencode(params) def process_paginated_list(paginated_list,", ":returns: MessageArgs named tuple containing the args for the search", "business_id If set , restricts search to conversations regarding this", "regarding this specific party id surveys If set allows the", "lines of code could be combined into a more succinct", "messages.\"\"\" business_ids = set() for message in messages: business_ids.add(message['business_id']) business_details", "user. If the call for the internal user id fails,", "args.get('unread_conversations') == 'true': fields['unread_conversations'] = True return MessageArgs(page=fields['page'], limit=fields['limit'], business_id=fields['business_id'],", "found for the message recipient\", msg_to=msg_to) except IndexError: logger.exception(\"Exception adding", "new_respondent_conversations page If set requests the specific page of information", "user, message_args, endpoint=MESSAGE_LIST_ENDPOINT, body_summary=True): \"\"\"used to change a pagination object", "by doing this. \"\"\" external_user_details = {} for user in", "only to be changed\"\"\" return MessageArgs(page=existing_args.page, limit=existing_args.limit, business_id=existing_args.business_id, surveys=existing_args.surveys, cc=existing_args.cc,", "named tuple containing the args for the search business_id If", "{ \"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page + 1}\"} if paginated_list.has_prev: links['prev'] = {", "{\"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page}\"}} if paginated_list.has_next: links['next'] = { \"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page +", "to be set by caller :param args: contains search arguments.", "information in descending order \"\"\" fields = {'page': 1, 'limit':", "changed\"\"\" return MessageArgs(page=existing_args.page, limit=existing_args.limit, business_id=existing_args.business_id, surveys=existing_args.surveys, cc=existing_args.cc, label=existing_args.label, desc=existing_args.desc, ce=existing_args.ce,", "ce is_closed my_conversations new_respondent_conversations all_conversation_types unread_conversations') def get_options(args): # NOQA", "a named tuple, but allow the conversation type only to", "MESSAGE_LIST_ENDPOINT, MESSAGE_QUERY_LIMIT from secure_message.services.service_toggles import party, internal_user_service logger = wrap_logger(logging.getLogger(__name__))", "logger.exception(\"Exception adding to details\", msg_to=msg_to, from_internal=from_internal) raise return messages def", "message recipient\", msg_to=msg_to) except IndexError: logger.exception(\"Exception adding to details\", msg_to=msg_to,", "in messages: try: msg_from = message[\"msg_from\"] from_internal = message[\"from_internal\"] if", "of , open , closed, my_conversations and new_respondent_conversations page If", "in external_msgs: external_user_uuids.add(message[\"msg_from\"]) internal_messages = [message for message in messages", "cc=fields['cc'], label=fields['label'], desc=fields['desc'], ce=fields['ce'], is_closed=fields['is_closed'], my_conversations=fields['my_conversations'], new_respondent_conversations=fields['new_respondent_conversations'], all_conversation_types=fields['all_conversation_types'], unread_conversations=fields['unread_conversations']) def", "to 'true only counts my conversations. I.e conversations where the", "False, 'new_respondent_conversations': False, 'all_conversation_types': False, 'unread_conversations': False} for field in", "external_user_details[user['id']] = user for message in messages: try: msg_to =", "= True if args.get('my_conversations') == 'true': fields['my_conversations'] = True if", "field in args._fields: if field in ['page']: continue value =", "{\"href\": f\"{host_url}{endpoint}\"}, 'self': {\"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page}\"}} if paginated_list.has_next: links['next'] = {", "payload. The API documentation notes that these elements aren't guaranteed", "conversations regarding this specific party id surveys If set allows", "must not be empty') messages = add_to_details(messages) messages = add_from_details(messages)", "'true': fields['new_respondent_conversations'] = True if args.get('all_conversation_types') == 'true': fields['all_conversation_types'] =", "restricted by a particular case ce If set, alows the", "the list that we got from the party service. There", "\"\"\" external_user_details = {} for user in party.get_users_details(get_external_user_uuid_list(messages)): external_user_details[user['id']] =", "to be restricted by a particular collection exercise is_closed If", "in the payload. The API documentation notes that these elements", "documentation notes that these elements aren't guaranteed to be provided", "tuple, but allow the conversation type only to be changed\"\"\"", "raise return messages def add_from_details(messages): \"\"\"Adds a @msg_from key to", "= message[\"from_internal\"] if from_internal: message.update({\"@msg_from\": internal_user_service.get_user_details(msg_from)}) else: if external_user_details.get(message['msg_from']): message.update({'@msg_from':", "label=existing_args.label, desc=existing_args.desc, ce=existing_args.ce, is_closed=is_closed, my_conversations=my_conversations, new_respondent_conversations=new_conversations, all_conversation_types=all_types, unread_conversations=unread_conversations) def generate_string_query_args(args):", "to 'true'only counts conversations where the to actor is set", "limit business_id surveys cc label desc ce is_closed my_conversations new_respondent_conversations", "field in ['cc', 'ce', 'business_id', 'label']: if args.get(field): fields[field] =", "all_conversation_types If set 'true', overrides is_closed, my_conversations and new_respondent_conversations and", "paginated_list.has_prev: links['prev'] = { \"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page - 1}\"} return messages,", "field in ['limit', 'page']: if args.get(field): fields[field] = int(args.get(field)) if", "conversations where the to actor is set to 'GROUP' all_conversation_types", "'true': fields['unread_conversations'] = True return MessageArgs(page=fields['page'], limit=fields['limit'], business_id=fields['business_id'], surveys=fields['surveys'], cc=fields['cc'],", "MessageArgs(page=fields['page'], limit=fields['limit'], business_id=fields['business_id'], surveys=fields['surveys'], cc=fields['cc'], label=fields['label'], desc=fields['desc'], ce=fields['ce'], is_closed=fields['is_closed'], my_conversations=fields['my_conversations'],", "msg_to_details = internal_user_service.get_user_details(msg_to) message.update({\"@msg_to\": [msg_to_details]}) else: msg_to_details = external_user_details.get(msg_to) if", "details message\", msg_from=msg_from, from_internal=from_internal) raise return messages def get_external_user_uuid_list(messages): \"\"\"Compiles", "internal_messages = [message for message in messages if message['from_internal'] is", "request , allow label to be set by caller :param", "list that we got from the party service. There won't", "adding to details\", msg_to=msg_to, from_internal=from_internal) raise return messages def add_from_details(messages):", "to be changed\"\"\" return MessageArgs(page=existing_args.page, limit=existing_args.limit, business_id=existing_args.business_id, surveys=existing_args.surveys, cc=existing_args.cc, label=existing_args.label,", "msg_to=msg_to) except IndexError: logger.exception(\"Exception adding to details\", msg_to=msg_to, from_internal=from_internal) raise", "False, 'my_conversations': False, 'new_respondent_conversations': False, 'all_conversation_types': False, 'unread_conversations': False} for", "'true'only counts conversations where the to actor is set to", "of the user. If the call for the internal user", "are better able to identify the cause of log errors", "key to every message in a list of messages. Every", "= True if args.get('all_conversation_types') == 'true': fields['all_conversation_types'] = True if", "msg_to = message[\"msg_to\"][0] from_internal = message[\"from_internal\"] if not from_internal: msg_to_details", "external_user_details.get(message['msg_from']): message.update({'@msg_from': external_user_details.get(msg_from)}) except IndexError: logger.exception(\"Exception adding from details message\",", "surveys If set allows the count to be restricted by", "f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page}\"}} if paginated_list.has_next: links['next'] = { \"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page + 1}\"}", "== message['business_id']), None) return messages def add_users_and_business_details(messages): \"\"\"Add both user", "from details\") messages = add_business_details(messages) logger.info(\"Successfully added business details\") return", "the information in descending order \"\"\" fields = {'page': 1,", "for the internal user id fails, an exception will be", "breaking the contract by doing this. Note: Several of these", "message[\"from_internal\"] if not from_internal: msg_to_details = internal_user_service.get_user_details(msg_to) message.update({\"@msg_to\": [msg_to_details]}) else:", "from_internal: msg_to_details = internal_user_service.get_user_details(msg_to) message.update({\"@msg_to\": [msg_to_details]}) else: msg_to_details = external_user_details.get(msg_to)", "True if args.get('my_conversations') == 'true': fields['my_conversations'] = True if args.get('new_respondent_conversations')", "message[\"msg_to\"][0] from_internal = message[\"from_internal\"] if not from_internal: msg_to_details = internal_user_service.get_user_details(msg_to)", "combined into a more succinct view, spreading them out is", "'page']: if args.get(field): fields[field] = int(args.get(field)) if args.get('desc') == 'false':", "business_details if business[\"id\"] == message['business_id']), None) return messages def add_users_and_business_details(messages):", "If set it sets the maximum number of results to", "the count to be restricted by a particular case ce", "a list of survey_ids cc If set , allows the", "== 'true': fields['is_closed'] = True if args.get('my_conversations') == 'true': fields['my_conversations']", "a @msg_to key to every message in a list of", "details\") messages = add_business_details(messages) logger.info(\"Successfully added business details\") return messages", "= collections.namedtuple( 'MessageArgs', 'page limit business_id surveys cc label desc", "tuple containing the args for the search business_id If set", "actor id new_respondent_conversations If set to 'true'only counts conversations where", "into a more succinct view, spreading them out is deliberate", "\"\"\"Adds a @msg_from key to every message in a list", "set , restricts search to conversations regarding this specific party", "= [] string_query_args = generate_string_query_args(message_args) for message in paginated_list.items: msg", "messages def add_from_details(messages): \"\"\"Adds a @msg_from key to every message", "fields['desc'] = False if args.get('is_closed') == 'true': fields['is_closed'] = True", "@msg_from key to every message in a list of messages.", "def get_options(args): # NOQA pylint:disable=too-complex \"\"\"extract options from request ,", "doing this. Note: Several of these lines of code could", "breaking the contract by doing this. \"\"\" external_user_details = {}", "args :returns: MessageArgs named tuple containing the args for the", "by a particular case ce If set, alows the count", "= external_user_details.get(msg_to) if msg_to_details: message.update({'@msg_to': [msg_to_details]}) else: logger.info(\"No details found", "import collections import logging import urllib.parse from structlog import wrap_logger", "generate_string_query_args(message_args) for message in paginated_list.items: msg = message.serialize(user, body_summary=body_summary) msg['_links']", "messages: business_ids.add(message['business_id']) business_details = party.get_business_details(business_ids) for message in messages: message['@business_details']", "secure_message.services.service_toggles import party, internal_user_service logger = wrap_logger(logging.getLogger(__name__)) MessageArgs = collections.namedtuple(", "label=fields['label'], desc=fields['desc'], ce=fields['ce'], is_closed=fields['is_closed'], my_conversations=fields['my_conversations'], new_respondent_conversations=fields['new_respondent_conversations'], all_conversation_types=fields['all_conversation_types'], unread_conversations=fields['unread_conversations']) def set_conversation_type_args(existing_args,", "= message[\"msg_from\"] from_internal = message[\"from_internal\"] if from_internal: message.update({\"@msg_from\": internal_user_service.get_user_details(msg_from)}) else:", "from details message\", msg_from=msg_from, from_internal=from_internal) raise return messages def get_external_user_uuid_list(messages):", "party.get_users_details(get_external_user_uuid_list(messages)): external_user_details[user['id']] = user for message in messages: try: msg_from", "paginated_list.has_next: links['next'] = { \"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page + 1}\"} if paginated_list.has_prev:", "in args._fields: if field in ['page']: continue value = getattr(args,", "set to 'GROUP' all_conversation_types If set 'true', overrides is_closed, my_conversations", "user for message in messages: try: msg_from = message[\"msg_from\"] from_internal", "service. There won't be a @msg_from value returned in the", "won't be a @msg_to value returned in the payload. The", "args.get('desc') == 'false': fields['desc'] = False if args.get('is_closed') == 'true':", "elements aren't guaranteed to be provided so we're not breaking", "log stack traces are better able to identify the cause", "else: logger.info(\"No details found for the message recipient\", msg_to=msg_to) except", "to return desc If present, requests the information in descending", "[] string_query_args = generate_string_query_args(message_args) for message in paginated_list.items: msg =", "If set , allows the count to be restricted by", "the to actor id new_respondent_conversations If set to 'true'only counts", "a new set of args based on the existing args", "if from_internal: message.update({\"@msg_from\": internal_user_service.get_user_details(msg_from)}) else: if external_user_details.get(message['msg_from']): message.update({'@msg_from': external_user_details.get(msg_from)}) except", "False] for message in external_msgs: external_user_uuids.add(message[\"msg_from\"]) internal_messages = [message for", "msg_to=msg_to, from_internal=from_internal) raise return messages def add_from_details(messages): \"\"\"Adds a @msg_from", "False, 'unread_conversations': False} for field in ['cc', 'ce', 'business_id', 'label']:", "@msg_to value returned in the payload. The API documentation notes", "= str(args.get(field)) fields['surveys'] = args.getlist('survey') for field in ['limit', 'page']:", "desc If present, requests the information in descending order \"\"\"", "aren't guaranteed to be provided so we're not breaking the", "to 'true' only counts closed conversations, else only open conversations", "msg_from=msg_from, from_internal=from_internal) raise return messages def get_external_user_uuid_list(messages): \"\"\"Compiles a list", "# NOQA pylint:disable=too-complex \"\"\"extract options from request , allow label", "'cc': None, 'label': None, 'ce': None, 'is_closed': False, 'my_conversations': False,", "present, requests the information in descending order \"\"\" fields =", "'business_id': None, 'surveys': None, 'desc': True, 'cc': None, 'label': None,", "= internal_user_service.get_user_details(msg_to) message.update({\"@msg_to\": [msg_to_details]}) else: msg_to_details = external_user_details.get(msg_to) if msg_to_details:", "messages\"\"\" external_user_uuids = set() external_msgs = [message for message in", "args.get(field): fields[field] = str(args.get(field)) fields['surveys'] = args.getlist('survey') for field in", "from secure_message.services.service_toggles import party, internal_user_service logger = wrap_logger(logging.getLogger(__name__)) MessageArgs =", "{'first': {\"href\": f\"{host_url}{endpoint}\"}, 'self': {\"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page}\"}} if paginated_list.has_next: links['next'] =", "a @msg_from key to every message in a list of", "if args.get('new_respondent_conversations') == 'true': fields['new_respondent_conversations'] = True if args.get('all_conversation_types') ==", "business_details = party.get_business_details(business_ids) for message in messages: message['@business_details'] = next((business", "'GROUP' all_conversation_types If set 'true', overrides is_closed, my_conversations and new_respondent_conversations", "add_business_details(messages): \"\"\"Adds a @business_details key to every message in a", "There won't be a @msg_to value returned in the payload.", "in messages: try: msg_to = message[\"msg_to\"][0] from_internal = message[\"from_internal\"] if", "for uuid in internal_messages: external_user_uuids.add(uuid[\"msg_to\"][0]) return external_user_uuids def add_business_details(messages): \"\"\"Adds", "counts 1 for each of , open , closed, my_conversations", "be a @msg_to value returned in the payload. The API", "my_conversations=my_conversations, new_respondent_conversations=new_conversations, all_conversation_types=all_types, unread_conversations=unread_conversations) def generate_string_query_args(args): params = {} for", "If set 'true', overrides is_closed, my_conversations and new_respondent_conversations and returns", "not from_internal: msg_to_details = internal_user_service.get_user_details(msg_to) message.update({\"@msg_to\": [msg_to_details]}) else: msg_to_details =", "new_conversations=False, all_types=False, unread_conversations=False): \"\"\"Returns a new set of args based", "message.serialize(user, body_summary=body_summary) msg['_links'] = {\"self\": {\"href\": f\"{host_url}{MESSAGE_BY_ID_ENDPOINT}/{msg['msg_id']}\"}} messages.append(msg) links =", "with links\"\"\" messages = [] string_query_args = generate_string_query_args(message_args) for message", "'true' only counts closed conversations, else only open conversations my_conversations", "= int(args.get(field)) if args.get('desc') == 'false': fields['desc'] = False if", "caller :param args: contains search arguments. Not all end points", "set to 'true'only counts conversations where the to actor is", "unread_conversations=fields['unread_conversations']) def set_conversation_type_args(existing_args, is_closed=False, my_conversations=False, new_conversations=False, all_types=False, unread_conversations=False): \"\"\"Returns a", "logger.info(\"No details found for the message recipient\", msg_to=msg_to) except IndexError:", "True if args.get('all_conversation_types') == 'true': fields['all_conversation_types'] = True if args.get('unread_conversations')", "messages: try: msg_to = message[\"msg_to\"][0] from_internal = message[\"from_internal\"] if not", "json format with links\"\"\" messages = [] string_query_args = generate_string_query_args(message_args)", "party service\"\"\" if not messages: raise ValueError('messages is a required", "to be restricted by a particular case ce If set,", "every message in a list of messages.\"\"\" business_ids = set()", "specific page of information to return limit If set it", "try: msg_from = message[\"msg_from\"] from_internal = message[\"from_internal\"] if from_internal: message.update({\"@msg_from\":", "existing args which are a named tuple, but allow the", "a @msg_from value returned in the payload. The API documentation", "object to json format with links\"\"\" messages = [] string_query_args", "if args.get(field): fields[field] = int(args.get(field)) if args.get('desc') == 'false': fields['desc']", "links def add_to_details(messages): \"\"\"Adds a @msg_to key to every message", "list of all unique the external user (respondent) uuids from", "to be provided so we're not breaking the contract by", "page If set requests the specific page of information to", "message.update({\"@msg_to\": [msg_to_details]}) else: msg_to_details = external_user_details.get(msg_to) if msg_to_details: message.update({'@msg_to': [msg_to_details]})", "messages = add_to_details(messages) messages = add_from_details(messages) logger.info(\"Successfully added to and", "is True] for uuid in internal_messages: external_user_uuids.add(uuid[\"msg_to\"][0]) return external_user_uuids def", "for the search business_id If set , restricts search to", "def add_to_details(messages): \"\"\"Adds a @msg_to key to every message in", "Note: Several of these lines of code could be combined", "to conversations regarding this specific party id surveys If set", "= next((business for business in business_details if business[\"id\"] == message['business_id']),", "def generate_string_query_args(args): params = {} for field in args._fields: if", "'ce': None, 'is_closed': False, 'my_conversations': False, 'new_respondent_conversations': False, 'all_conversation_types': False,", "cc=existing_args.cc, label=existing_args.label, desc=existing_args.desc, ce=existing_args.ce, is_closed=is_closed, my_conversations=my_conversations, new_respondent_conversations=new_conversations, all_conversation_types=all_types, unread_conversations=unread_conversations) def", "return desc If present, requests the information in descending order", "in party.get_users_details(get_external_user_uuid_list(messages)): external_user_details[user['id']] = user for message in messages: try:", "if message['from_internal'] is True] for uuid in internal_messages: external_user_uuids.add(uuid[\"msg_to\"][0]) return", "msg = message.serialize(user, body_summary=body_summary) msg['_links'] = {\"self\": {\"href\": f\"{host_url}{MESSAGE_BY_ID_ENDPOINT}/{msg['msg_id']}\"}} messages.append(msg)", "a more succinct view, spreading them out is deliberate so", "allows the count to be restricted by a list of", "user id is the to actor id new_respondent_conversations If set", "= { \"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page - 1}\"} return messages, links def", "@msg_from value returned in the payload. The API documentation notes", "= user for message in messages: try: msg_to = message[\"msg_to\"][0]", "args.get('all_conversation_types') == 'true': fields['all_conversation_types'] = True if args.get('unread_conversations') == 'true':", "fields['unread_conversations'] = True return MessageArgs(page=fields['page'], limit=fields['limit'], business_id=fields['business_id'], surveys=fields['surveys'], cc=fields['cc'], label=fields['label'],", "of results to return desc If present, requests the information", "MessageArgs = collections.namedtuple( 'MessageArgs', 'page limit business_id surveys cc label", "= True if args.get('new_respondent_conversations') == 'true': fields['new_respondent_conversations'] = True if", "= True if args.get('unread_conversations') == 'true': fields['unread_conversations'] = True return", "them out is deliberate so that log stack traces are", "message in messages: try: msg_from = message[\"msg_from\"] from_internal = message[\"from_internal\"]", "business[\"id\"] == message['business_id']), None) return messages def add_users_and_business_details(messages): \"\"\"Add both", "to messages based on data from party service\"\"\" if not", "a list of messages.\"\"\" business_ids = set() for message in", "to json format with links\"\"\" messages = [] string_query_args =", "'self': {\"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page}\"}} if paginated_list.has_next: links['next'] = { \"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page", "secure_message.constants import MESSAGE_BY_ID_ENDPOINT, MESSAGE_LIST_ENDPOINT, MESSAGE_QUERY_LIMIT from secure_message.services.service_toggles import party, internal_user_service", "message['from_internal'] is True] for uuid in internal_messages: external_user_uuids.add(uuid[\"msg_to\"][0]) return external_user_uuids", "uuid in internal_messages: external_user_uuids.add(uuid[\"msg_to\"][0]) return external_user_uuids def add_business_details(messages): \"\"\"Adds a", "msg_to uuid is resolved to include details of the user.", "def add_business_details(messages): \"\"\"Adds a @business_details key to every message in", "None, 'surveys': None, 'desc': True, 'cc': None, 'label': None, 'ce':", "if field in ['page']: continue value = getattr(args, field) if", "args._fields: if field in ['page']: continue value = getattr(args, field)", "message in a list of messages.\"\"\" business_ids = set() for", "only open conversations my_conversations If set to 'true only counts", "= {} for field in args._fields: if field in ['page']:", "more succinct view, spreading them out is deliberate so that", "for message in messages: try: msg_from = message[\"msg_from\"] from_internal =", "and business details to messages based on data from party", "for user in party.get_users_details(get_external_user_uuid_list(messages)): external_user_details[user['id']] = user for message in", "contract by doing this. Note: Several of these lines of", "external_user_uuids = set() external_msgs = [message for message in messages", "conversations my_conversations If set to 'true only counts my conversations.", "message['from_internal'] is False] for message in external_msgs: external_user_uuids.add(message[\"msg_from\"]) internal_messages =", "msg_to_details = external_user_details.get(msg_to) if msg_to_details: message.update({'@msg_to': [msg_to_details]}) else: logger.info(\"No details", "found in the list that we got from the party", "Several of these lines of code could be combined into", "1, 'limit': MESSAGE_QUERY_LIMIT, 'business_id': None, 'surveys': None, 'desc': True, 'cc':", "message in paginated_list.items: msg = message.serialize(user, body_summary=body_summary) msg['_links'] = {\"self\":", "for field in ['cc', 'ce', 'business_id', 'label']: if args.get(field): fields[field]", "messages if message['from_internal'] is False] for message in external_msgs: external_user_uuids.add(message[\"msg_from\"])", "external_user_details = {} for user in party.get_users_details(get_external_user_uuid_list(messages)): external_user_details[user['id']] = user", "{\"href\": f\"{host_url}{MESSAGE_BY_ID_ENDPOINT}/{msg['msg_id']}\"}} messages.append(msg) links = {'first': {\"href\": f\"{host_url}{endpoint}\"}, 'self': {\"href\":", "surveys cc label desc ce is_closed my_conversations new_respondent_conversations all_conversation_types unread_conversations')", "'surveys': None, 'desc': True, 'cc': None, 'label': None, 'ce': None,", "NOQA pylint:disable=too-complex \"\"\"extract options from request , allow label to", "the count to be restricted by a list of survey_ids", "able to identify the cause of log errors \"\"\" external_user_details", "added to and from details\") messages = add_business_details(messages) logger.info(\"Successfully added", "cannot be found in the list that we got from", "ce If set, alows the count to be restricted by", "'true': fields['my_conversations'] = True if args.get('new_respondent_conversations') == 'true': fields['new_respondent_conversations'] =", "False} for field in ['cc', 'ce', 'business_id', 'label']: if args.get(field):", "host_url, user, message_args, endpoint=MESSAGE_LIST_ENDPOINT, body_summary=True): \"\"\"used to change a pagination", "try: msg_to = message[\"msg_to\"][0] from_internal = message[\"from_internal\"] if not from_internal:", "uuid is resolved to include details of the user. If", "of args based on the existing args which are a", "MESSAGE_QUERY_LIMIT from secure_message.services.service_toggles import party, internal_user_service logger = wrap_logger(logging.getLogger(__name__)) MessageArgs", "be changed\"\"\" return MessageArgs(page=existing_args.page, limit=existing_args.limit, business_id=existing_args.business_id, surveys=existing_args.surveys, cc=existing_args.cc, label=existing_args.label, desc=existing_args.desc,", "{'page': 1, 'limit': MESSAGE_QUERY_LIMIT, 'business_id': None, 'surveys': None, 'desc': True,", "if value: params[field] = value return urllib.parse.urlencode(params) def process_paginated_list(paginated_list, host_url,", ", allow label to be set by caller :param args:", "if paginated_list.has_prev: links['prev'] = { \"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page - 1}\"} return", "= args.getlist('survey') for field in ['limit', 'page']: if args.get(field): fields[field]", "params[field] = value return urllib.parse.urlencode(params) def process_paginated_list(paginated_list, host_url, user, message_args,", "'business_id', 'label']: if args.get(field): fields[field] = str(args.get(field)) fields['surveys'] = args.getlist('survey')", "msg_from = message[\"msg_from\"] from_internal = message[\"from_internal\"] if from_internal: message.update({\"@msg_from\": internal_user_service.get_user_details(msg_from)})", "\"\"\"Compiles a list of all unique the external user (respondent)", "user in party.get_users_details(get_external_user_uuid_list(messages)): external_user_details[user['id']] = user for message in messages:", "from request , allow label to be set by caller", "['page']: continue value = getattr(args, field) if value: params[field] =", "details found for the message recipient\", msg_to=msg_to) except IndexError: logger.exception(\"Exception", "for field in ['limit', 'page']: if args.get(field): fields[field] = int(args.get(field))", "particular case ce If set, alows the count to be", "desc ce is_closed my_conversations new_respondent_conversations all_conversation_types unread_conversations') def get_options(args): #", "surveys=fields['surveys'], cc=fields['cc'], label=fields['label'], desc=fields['desc'], ce=fields['ce'], is_closed=fields['is_closed'], my_conversations=fields['my_conversations'], new_respondent_conversations=fields['new_respondent_conversations'], all_conversation_types=fields['all_conversation_types'], unread_conversations=fields['unread_conversations'])", "cause of log errors \"\"\" external_user_details = {} for user", "for message in external_msgs: external_user_uuids.add(message[\"msg_from\"]) internal_messages = [message for message", "'MessageArgs', 'page limit business_id surveys cc label desc ce is_closed", "resolved to include details of the user. If the call", "else: msg_to_details = external_user_details.get(msg_to) if msg_to_details: message.update({'@msg_to': [msg_to_details]}) else: logger.info(\"No", "structlog import wrap_logger from secure_message.constants import MESSAGE_BY_ID_ENDPOINT, MESSAGE_LIST_ENDPOINT, MESSAGE_QUERY_LIMIT from", "the current user id is the to actor id new_respondent_conversations", "set() external_msgs = [message for message in messages if message['from_internal']", "external_user_details[user['id']] = user for message in messages: try: msg_from =", "value = getattr(args, field) if value: params[field] = value return", "internal_user_service.get_user_details(msg_to) message.update({\"@msg_to\": [msg_to_details]}) else: msg_to_details = external_user_details.get(msg_to) if msg_to_details: message.update({'@msg_to':", "in business_details if business[\"id\"] == message['business_id']), None) return messages def", "all_conversation_types unread_conversations') def get_options(args): # NOQA pylint:disable=too-complex \"\"\"extract options from", "my_conversations new_respondent_conversations all_conversation_types unread_conversations') def get_options(args): # NOQA pylint:disable=too-complex \"\"\"extract", "\"\"\"Returns a new set of args based on the existing", "count to be restricted by a list of survey_ids cc", "my_conversations If set to 'true only counts my conversations. I.e", "def add_from_details(messages): \"\"\"Adds a @msg_from key to every message in", "the external user (respondent) uuids from a list of messages\"\"\"", "{} for field in args._fields: if field in ['page']: continue", "from a list of messages\"\"\" external_user_uuids = set() external_msgs =", "is_closed If set to 'true' only counts closed conversations, else", "data from party service\"\"\" if not messages: raise ValueError('messages is", "message_args, endpoint=MESSAGE_LIST_ENDPOINT, body_summary=True): \"\"\"used to change a pagination object to", "for message in messages: try: msg_to = message[\"msg_to\"][0] from_internal =", "if msg_to_details: message.update({'@msg_to': [msg_to_details]}) else: logger.info(\"No details found for the", "logger.info(\"Successfully added to and from details\") messages = add_business_details(messages) logger.info(\"Successfully", "There won't be a @msg_from value returned in the payload.", "open , closed, my_conversations and new_respondent_conversations page If set requests", "contains search arguments. Not all end points support all args", "message['business_id']), None) return messages def add_users_and_business_details(messages): \"\"\"Add both user and", "details to messages based on data from party service\"\"\" if", "cc label desc ce is_closed my_conversations new_respondent_conversations all_conversation_types unread_conversations') def", "id surveys If set allows the count to be restricted", "these elements aren't guaranteed to be provided so we're not", "return messages def get_external_user_uuid_list(messages): \"\"\"Compiles a list of all unique", "return limit If set it sets the maximum number of", "import logging import urllib.parse from structlog import wrap_logger from secure_message.constants", "of code could be combined into a more succinct view,", "external_user_uuids.add(uuid[\"msg_to\"][0]) return external_user_uuids def add_business_details(messages): \"\"\"Adds a @business_details key to", "restricted by a list of survey_ids cc If set ,", "parameter and must not be empty') messages = add_to_details(messages) messages", "= getattr(args, field) if value: params[field] = value return urllib.parse.urlencode(params)", "to include details of the user. If the call for", "an exception will be thrown. If the external user id", "that we got from the party service. There won't be", "restricted by a particular collection exercise is_closed If set to", "fields = {'page': 1, 'limit': MESSAGE_QUERY_LIMIT, 'business_id': None, 'surveys': None,", "spreading them out is deliberate so that log stack traces", "messages: try: msg_from = message[\"msg_from\"] from_internal = message[\"from_internal\"] if from_internal:", "collections.namedtuple( 'MessageArgs', 'page limit business_id surveys cc label desc ce", "of all unique the external user (respondent) uuids from a", "a @business_details key to every message in a list of", "= {'page': 1, 'limit': MESSAGE_QUERY_LIMIT, 'business_id': None, 'surveys': None, 'desc':", "'new_respondent_conversations': False, 'all_conversation_types': False, 'unread_conversations': False} for field in ['cc',", "the specific page of information to return limit If set", "args.getlist('survey') for field in ['limit', 'page']: if args.get(field): fields[field] =", "of messages. Every msg_to uuid is resolved to include details", "id cannot be found in the list that we got", "external_msgs: external_user_uuids.add(message[\"msg_from\"]) internal_messages = [message for message in messages if", "external_msgs = [message for message in messages if message['from_internal'] is", "== 'true': fields['new_respondent_conversations'] = True if args.get('all_conversation_types') == 'true': fields['all_conversation_types']", "from structlog import wrap_logger from secure_message.constants import MESSAGE_BY_ID_ENDPOINT, MESSAGE_LIST_ENDPOINT, MESSAGE_QUERY_LIMIT", "['cc', 'ce', 'business_id', 'label']: if args.get(field): fields[field] = str(args.get(field)) fields['surveys']", "for message in messages: message['@business_details'] = next((business for business in", "= {\"self\": {\"href\": f\"{host_url}{MESSAGE_BY_ID_ENDPOINT}/{msg['msg_id']}\"}} messages.append(msg) links = {'first': {\"href\": f\"{host_url}{endpoint}\"},", "\"\"\"Add both user and business details to messages based on", "The API documentation notes that these elements aren't guaranteed to", "None, 'desc': True, 'cc': None, 'label': None, 'ce': None, 'is_closed':", "new_respondent_conversations=new_conversations, all_conversation_types=all_types, unread_conversations=unread_conversations) def generate_string_query_args(args): params = {} for field", "stack traces are better able to identify the cause of", "descending order \"\"\" fields = {'page': 1, 'limit': MESSAGE_QUERY_LIMIT, 'business_id':", "set, alows the count to be restricted by a particular", "string_query_args = generate_string_query_args(message_args) for message in paginated_list.items: msg = message.serialize(user,", "If set, alows the count to be restricted by a", "fields['all_conversation_types'] = True if args.get('unread_conversations') == 'true': fields['unread_conversations'] = True", "a particular case ce If set, alows the count to", "closed conversations, else only open conversations my_conversations If set to", "If set to 'true only counts my conversations. I.e conversations", "None, 'label': None, 'ce': None, 'is_closed': False, 'my_conversations': False, 'new_respondent_conversations':", "be restricted by a list of survey_ids cc If set", "key to every message in a list of messages.\"\"\" business_ids", "if args.get('is_closed') == 'true': fields['is_closed'] = True if args.get('my_conversations') ==", "this. Note: Several of these lines of code could be", "count to be restricted by a particular case ce If", "f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page - 1}\"} return messages, links def add_to_details(messages): \"\"\"Adds a", "the external user id cannot be found in the list", "'label': None, 'ce': None, 'is_closed': False, 'my_conversations': False, 'new_respondent_conversations': False,", "be set by caller :param args: contains search arguments. Not", "'desc': True, 'cc': None, 'label': None, 'ce': None, 'is_closed': False,", "in ['cc', 'ce', 'business_id', 'label']: if args.get(field): fields[field] = str(args.get(field))", "'true only counts my conversations. I.e conversations where the current", "for each of , open , closed, my_conversations and new_respondent_conversations", "value return urllib.parse.urlencode(params) def process_paginated_list(paginated_list, host_url, user, message_args, endpoint=MESSAGE_LIST_ENDPOINT, body_summary=True):", "generate_string_query_args(args): params = {} for field in args._fields: if field", "f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page + 1}\"} if paginated_list.has_prev: links['prev'] = { \"href\": f\"{host_url}{endpoint}?{string_query_args}&page={message_args.page", "details of the user. If the call for the internal", "set() for message in messages: business_ids.add(message['business_id']) business_details = party.get_business_details(business_ids) for", "unique the external user (respondent) uuids from a list of", "None) return messages def add_users_and_business_details(messages): \"\"\"Add both user and business", "return messages def add_from_details(messages): \"\"\"Adds a @msg_from key to every", "== 'true': fields['my_conversations'] = True if args.get('new_respondent_conversations') == 'true': fields['new_respondent_conversations']", "got from the party service. There won't be a @msg_from", "the call for the internal user id fails, an exception", "support all args :returns: MessageArgs named tuple containing the args", "by doing this. Note: Several of these lines of code", "MessageArgs(page=existing_args.page, limit=existing_args.limit, business_id=existing_args.business_id, surveys=existing_args.surveys, cc=existing_args.cc, label=existing_args.label, desc=existing_args.desc, ce=existing_args.ce, is_closed=is_closed, my_conversations=my_conversations,", "'limit': MESSAGE_QUERY_LIMIT, 'business_id': None, 'surveys': None, 'desc': True, 'cc': None,", "def get_external_user_uuid_list(messages): \"\"\"Compiles a list of all unique the external", "external user (respondent) uuids from a list of messages\"\"\" external_user_uuids", "== 'false': fields['desc'] = False if args.get('is_closed') == 'true': fields['is_closed']", "be a @msg_from value returned in the payload. The API", "limit=existing_args.limit, business_id=existing_args.business_id, surveys=existing_args.surveys, cc=existing_args.cc, label=existing_args.label, desc=existing_args.desc, ce=existing_args.ce, is_closed=is_closed, my_conversations=my_conversations, new_respondent_conversations=new_conversations,", "unread_conversations') def get_options(args): # NOQA pylint:disable=too-complex \"\"\"extract options from request", "message['@business_details'] = next((business for business in business_details if business[\"id\"] ==", "business_ids = set() for message in messages: business_ids.add(message['business_id']) business_details =", "is_closed=False, my_conversations=False, new_conversations=False, all_types=False, unread_conversations=False): \"\"\"Returns a new set of" ]
[ "icons[self.value] if len(value) == 1: value = value[0] else: #", "rend_j = j + self.side_width if not col: col =", "= ' ' def __init__(self, icon=None): self.icon = icon or", "\"\"\" return cell.ascii_icon() def render(self): for row in self.cells: res", "%sx%s', self.full_width, self.full_width) self.cells = [[Cell()] * self.full_width for _", "self.board: return # already initialized, do nothing board = _DummyBoard()", "is_list_like(value): self.value, self.color = value else: self.value, self.color = value,", "from sys import stdout from notetool.tool.log import logger from six", "if icons is None: icons = dict(self.DEFAULT_ICONS) self.icons = icons", "drawn on the top and on the left. \"\"\" BLOTTED_SYMBOL", "to draw columns descriptions \"\"\" raise NotImplementedError() def draw_side(self): \"\"\"", "sys import stdout from notetool.tool.log import logger from six import", "\"\"\" Represent cell that is part of description (clue). They", "for row in self.cells: res = [] for index, cell", "of a cell given its state and predefined table `icons`", "draws\"\"\" if board: logger.info('Init %r renderer with board %r', self.__class__.__name__,", "usually drawn). \"\"\" DEFAULT_ICON = '#' class ClueCell(Cell): \"\"\" Represent", "hasattr(obj, '__rend_name__'): res[obj.__rend_name__] = obj return res RENDERERS = _register_renderers()", "Get a symbolic representation of a cell given its state", "cell_icon(self, cell): \"\"\" Get a symbolic representation of a cell", "full_height(self): \"\"\"The full visual height of a board\"\"\" return self.header_height", "notetool.tool.log import logger from six import integer_types, itervalues, text_type from", "self.value icons = self.renderer.icons if not self.colored: return icons[self.value] if", "if isinstance(self.value, integer_types): return text_type(self.value) if self.value == BlottedBlock: return", "in range(self.full_height)] def cell_icon(self, cell): \"\"\" Get a symbolic representation", "a board\"\"\" return self.header_height + self.board.height @property def full_width(self): \"\"\"The", "self.DEFAULT_ICON def __repr__(self): return '{}(({}, {}))'.format( self.__class__.__name__, self.value, self.color) class", "isinstance(obj, type): if issubclass(obj, StreamRenderer) and hasattr(obj, '__rend_name__'): res[obj.__rend_name__] =", "self.color = value, None def ascii_icon(self): \"\"\" Gets a symbolic", "be able to draw rows descriptions \"\"\" raise NotImplementedError() def", "in row] rend_row = pad(rend_row, self.side_width, Cell()) self.cells[rend_i][:self.side_width] = rend_row", "for i, row in enumerate(self.board.rows_descriptions): rend_i = i + self.header_height", "col = [0] rend_column = [ClueCell(val) for val in col]", "self.is_colored for i, row in enumerate(cells): rend_i = i +", "be printed as a text\"\"\" return self.DEFAULT_ICON def __repr__(self): return", "self.renderer = renderer self.colored = colored if self.colored: self.value =", "self.side_width + self.board.width @property def header_height(self): \"\"\"The size of the", "render(self): \"\"\"Actually print out the board\"\"\" raise NotImplementedError() def draw(self,", "= self.renderer.board.symbol_for_color_id(value) if symbol is not None: return symbol return", "symbol return icons.get(value, self.DEFAULT_ICON) def __repr__(self): return '{}({})'.format( self.__class__.__name__, self.value)", "+= ' ' res.append(ico) self._print(''.join(res)) def draw_header(self): for i in", "of a board\"\"\" return self.header_height + self.board.height @property def full_width(self):", "col: col = [0] rend_column = [ClueCell(val) for val in", "full visual width of a board\"\"\" return self.side_width + self.board.width", "pad from ..utils.other import two_powers from .common import BOX, SPACE,", "a simple text table (without grid) \"\"\" __rend_name__ = 'text'", "renderer for a nonogram board\"\"\" def __init__(self, board=None): self.cells =", "import BOX, SPACE, UNKNOWN, BlottedBlock, is_list_like class Cell(object): \"\"\"Represent basic", "..utils.iter import max_safe, pad from ..utils.other import two_powers from .common", "\"\"\"Calculate all the cells and draw an image of the", "draw_side(self): \"\"\" Changes the internal state to be able to", "as a text\"\"\" return self.DEFAULT_ICON def __repr__(self): return '{}()'.format(self.__class__.__name__) class", "in enumerate(cells): rend_i = i + self.header_height for j, val", "from six import integer_types, itervalues, text_type from ..utils.iter import max_safe,", "a line if len(ico) == 1: if index < len(row)", "and predefined table `icons` \"\"\" return cell.ascii_icon() def render(self): for", "a text\"\"\" return self.DEFAULT_ICON def __repr__(self): return '{}()'.format(self.__class__.__name__) class ThumbnailCell(Cell):", "= UNKNOWN symbol = self.renderer.board.symbol_for_color_id(value) if symbol is not None:", "class GridCell(Cell): \"\"\"Represent the main area cell\"\"\" def __init__(self, value,", "+ self.board.width @property def header_height(self): \"\"\"The size of the header", "i in range(self.header_height): for j in range(self.side_width): self.cells[i][j] = ThumbnailCell()", "in range(self.side_width): self.cells[i][j] = ThumbnailCell() for j, col in enumerate(self.board.columns_descriptions):", "width of the side block with rows descriptions\"\"\" return max_safe(map(len,", "renderers for the game of nonogram \"\"\" from abc import", "draw an image of the board\"\"\" self.draw_header() self.draw_side() self.draw_grid(cells=cells) self.render()", "as a simple text table (without grid) \"\"\" __rend_name__ =", "that is part of description (clue). They are usually drawn", "' def __init__(self, icon=None): self.icon = icon or self.DEFAULT_ICON def", "is None: icons = dict(self.DEFAULT_ICONS) self.icons = icons super(StreamRenderer, self).__init__(board)", "row in self.cells: res = [] for index, cell in", "= value def ascii_icon(self): value = self.value icons = self.renderer.icons", "Renders a board as a simple text table (without grid)", "for j, col in enumerate(self.board.columns_descriptions): rend_j = j + self.side_width", "two_powers from .common import BOX, SPACE, UNKNOWN, BlottedBlock, is_list_like class", "self.color) class GridCell(Cell): \"\"\"Represent the main area cell\"\"\" def __init__(self,", "stream=stdout, icons=None): self.stream = stream if icons is None: icons", "def __repr__(self): return '{}()'.format(self.__class__.__name__) class ThumbnailCell(Cell): \"\"\" Represent upper-left cell", "\"\"\" Defines various renderers for the game of nonogram \"\"\"", "icon=None): self.icon = icon or self.DEFAULT_ICON def ascii_icon(self): \"\"\"How the", "corresponding board \"\"\" rows_descriptions = columns_descriptions = () width =", "max_safe(map(len, self.board.rows_descriptions), default=0) def render(self): \"\"\"Actually print out the board\"\"\"", "the internal state to be able to draw columns descriptions", "be able to draw columns descriptions \"\"\" raise NotImplementedError() def", "'text' def board_init(self, board=None): super(BaseAsciiRenderer, self).board_init(board) logger.info('init cells: %sx%s', self.full_width,", "j, col in enumerate(self.board.columns_descriptions): rend_j = j + self.side_width if", "the abstract renderer for a nonogram board\"\"\" def __init__(self, board=None):", "self.cells[:self.header_height, rend_j] = rend_column for i, cell in enumerate(rend_column): self.cells[i][rend_j]", "tuple(two_powers(value)) else: self.value = value def ascii_icon(self): value = self.value", "raise NotImplementedError() def draw(self, cells=None): \"\"\"Calculate all the cells and", "renderer initialization when it created before the corresponding board \"\"\"", "game of nonogram \"\"\" from abc import ABC from sys", "if is_list_like(value): self.value, self.color = value else: self.value, self.color =", "len(row) - 1: ico += ' ' res.append(ico) self._print(''.join(res)) def", "return '{}({})'.format( self.__class__.__name__, self.value) class _DummyBoard(object): \"\"\" Stub for renderer", "width of a board\"\"\" return self.side_width + self.board.width @property def", "col] rend_column = pad(rend_column, self.header_height, Cell()) # self.cells[:self.header_height, rend_j] =", "i + self.header_height for j, val in enumerate(row): rend_j =", "def cell_icon(self, cell): \"\"\" Get a symbolic representation of a", "`icons` \"\"\" if isinstance(self.value, integer_types): return text_type(self.value) if self.value ==", "NotImplementedError() def draw(self, cells=None): \"\"\"Calculate all the cells and draw", "part of description (clue). They are usually drawn on the", "%r', self.__class__.__name__, board) else: if self.board: return # already initialized,", "= icons super(StreamRenderer, self).__init__(board) def _print(self, *args): return print(*args, file=self.stream)", "'#' class ClueCell(Cell): \"\"\" Represent cell that is part of", "return '{}(({}, {}))'.format( self.__class__.__name__, self.value, self.color) class GridCell(Cell): \"\"\"Represent the", "def __init__(self, board=None, stream=stdout, icons=None): self.stream = stream if icons", "abstract renderer for a nonogram board\"\"\" def __init__(self, board=None): self.cells", "by default) \"\"\" DEFAULT_ICONS = { UNKNOWN: '_', BOX: 'X',", "the top and on the left. \"\"\" BLOTTED_SYMBOL = '?'", "-*- \"\"\" Defines various renderers for the game of nonogram", "return text_type(self.value) if self.value == BlottedBlock: return self.BLOTTED_SYMBOL return self.DEFAULT_ICON", "self.cells[rend_i][rend_j] = GridCell( val, self, colored=is_colored) def _register_renderers(): res =", "__init__(self, board=None, stream=stdout, icons=None): self.stream = stream if icons is", "a board as a simple text table (without grid) \"\"\"", "rend_column for i, cell in enumerate(rend_column): self.cells[i][rend_j] = cell def", "self._print(''.join(res)) def draw_header(self): for i in range(self.header_height): for j in", "the board\"\"\" self.draw_header() self.draw_side() self.draw_grid(cells=cells) self.render() def draw_header(self): \"\"\" Changes", "width = height = 0 class Renderer(object): \"\"\"Defines the abstract", "@property def side_width(self): \"\"\"The width of the side block with", "is_colored(self): \"\"\"Whether the linked board is colored board\"\"\" return self.board.is_colored", "description (clue). They are usually drawn on the top and", "\"\"\"Whether the linked board is colored board\"\"\" return self.board.is_colored class", "res = dict() for obj in itervalues(globals()): if isinstance(obj, type):", "multiple colors value = UNKNOWN symbol = self.renderer.board.symbol_for_color_id(value) if symbol", "to be able to draw a main grid \"\"\" raise", "None self.board_init(board) def board_init(self, board=None): \"\"\"Initialize renderer's properties dependent on", "import stdout from notetool.tool.log import logger from six import integer_types,", "self.board.columns_descriptions), default=0) @property def side_width(self): \"\"\"The width of the side", "obj in itervalues(globals()): if isinstance(obj, type): if issubclass(obj, StreamRenderer) and", "_register_renderers(): res = dict() for obj in itervalues(globals()): if isinstance(obj,", "len(value) == 1: value = value[0] else: # multiple colors", "not col: col = [0] rend_column = [ClueCell(val) for val", "\"\"\"The size of the header block with columns descriptions\"\"\" return", "before the corresponding board \"\"\" rows_descriptions = columns_descriptions = ()", "Changes the internal state to be able to draw rows", "enumerate(self.board.rows_descriptions): rend_i = i + self.header_height # row = list(row)", "' ' res.append(ico) self._print(''.join(res)) def draw_header(self): for i in range(self.header_height):", "rendered cell\"\"\" DEFAULT_ICON = ' ' def __init__(self, icon=None): self.icon", "initialization when it created before the corresponding board \"\"\" rows_descriptions", "[0] rend_row = [ClueCell(val) for val in row] rend_row =", "block with columns descriptions\"\"\" return max_safe(map(len, self.board.columns_descriptions), default=0) @property def", "side_width(self): \"\"\"The width of the side block with rows descriptions\"\"\"", "return self.board.is_colored class StreamRenderer(Renderer, ABC): \"\"\" Simplify textual rendering of", "SPACE, UNKNOWN, BlottedBlock, is_list_like class Cell(object): \"\"\"Represent basic rendered cell\"\"\"", "super(StreamRenderer, self).__init__(board) def _print(self, *args): return print(*args, file=self.stream) class BaseAsciiRenderer(StreamRenderer):", "if not self.colored: return icons[self.value] if len(value) == 1: value", "self.DEFAULT_ICON) def __repr__(self): return '{}({})'.format( self.__class__.__name__, self.value) class _DummyBoard(object): \"\"\"", "of the side block with rows descriptions\"\"\" return max_safe(map(len, self.board.rows_descriptions),", "BaseAsciiRenderer(StreamRenderer): \"\"\" Renders a board as a simple text table", "StreamRenderer) and hasattr(obj, '__rend_name__'): res[obj.__rend_name__] = obj return res RENDERERS", "itervalues(globals()): if isinstance(obj, type): if issubclass(obj, StreamRenderer) and hasattr(obj, '__rend_name__'):", "# -*- coding: utf-8 -*- \"\"\" Defines various renderers for", "cell given its state and predefined table `icons` \"\"\" if", "cells=None): \"\"\" Changes the internal state to be able to", "board) else: if self.board: return # already initialized, do nothing", "self.__class__.__name__, self.value) class _DummyBoard(object): \"\"\" Stub for renderer initialization when", "isinstance(self.value, integer_types): return text_type(self.value) if self.value == BlottedBlock: return self.BLOTTED_SYMBOL", "self.render() def draw_header(self): \"\"\" Changes the internal state to be", "columns descriptions\"\"\" return max_safe(map(len, self.board.columns_descriptions), default=0) @property def side_width(self): \"\"\"The", "row = [0] rend_row = [ClueCell(val) for val in row]", "j, val in enumerate(row): rend_j = j + self.side_width self.cells[rend_i][rend_j]", "def __init__(self, value, renderer, colored=False): super(GridCell, self).__init__() self.renderer = renderer", "on the top and on the left. \"\"\" BLOTTED_SYMBOL =", "value = self.value icons = self.renderer.icons if not self.colored: return", "\"\"\" Changes the internal state to be able to draw", "cells=None): \"\"\"Calculate all the cells and draw an image of", "= 'text' def board_init(self, board=None): super(BaseAsciiRenderer, self).board_init(board) logger.info('init cells: %sx%s',", "for the game of nonogram \"\"\" from abc import ABC", "= self.value icons = self.renderer.icons if not self.colored: return icons[self.value]", "{}))'.format( self.__class__.__name__, self.value, self.color) class GridCell(Cell): \"\"\"Represent the main area", "with columns descriptions\"\"\" return max_safe(map(len, self.board.columns_descriptions), default=0) @property def side_width(self):", "return self.DEFAULT_ICON def __repr__(self): return '{}(({}, {}))'.format( self.__class__.__name__, self.value, self.color)", "cells=None): if cells is None: cells = self.board.cells is_colored =", "cell def draw_side(self): for i, row in enumerate(self.board.rows_descriptions): rend_i =", "self.header_height for j, val in enumerate(row): rend_j = j +", "on board it draws\"\"\" if board: logger.info('Init %r renderer with", "class ThumbnailCell(Cell): \"\"\" Represent upper-left cell (where the thumbnail of", "text table (without grid) \"\"\" __rend_name__ = 'text' def board_init(self,", "draw_side(self): for i, row in enumerate(self.board.rows_descriptions): rend_i = i +", "upper-left cell (where the thumbnail of the puzzle usually drawn).", "default=0) @property def side_width(self): \"\"\"The width of the side block", "and on the left. \"\"\" BLOTTED_SYMBOL = '?' def __init__(self,", "\"\"\" __rend_name__ = 'text' def board_init(self, board=None): super(BaseAsciiRenderer, self).board_init(board) logger.info('init", "for renderer initialization when it created before the corresponding board", "predefined table `icons` \"\"\" return cell.ascii_icon() def render(self): for row", "def ascii_icon(self): value = self.value icons = self.renderer.icons if not", "= renderer self.colored = colored if self.colored: self.value = tuple(two_powers(value))", "symbol = self.renderer.board.symbol_for_color_id(value) if symbol is not None: return symbol", "print out the board\"\"\" raise NotImplementedError() def draw(self, cells=None): \"\"\"Calculate", "the last symbol in a line if len(ico) == 1:", "- 1: ico += ' ' res.append(ico) self._print(''.join(res)) def draw_header(self):", "() width = height = 0 class Renderer(object): \"\"\"Defines the", "for j, val in enumerate(row): rend_j = j + self.side_width", "StreamRenderer(Renderer, ABC): \"\"\" Simplify textual rendering of a board to", "= self.is_colored for i, row in enumerate(cells): rend_i = i", "rend_i = i + self.header_height for j, val in enumerate(row):", "main area cell\"\"\" def __init__(self, value, renderer, colored=False): super(GridCell, self).__init__()", "in itervalues(globals()): if isinstance(obj, type): if issubclass(obj, StreamRenderer) and hasattr(obj,", "\"\"\" raise NotImplementedError() @property def is_colored(self): \"\"\"Whether the linked board", "= value, None def ascii_icon(self): \"\"\" Gets a symbolic representation", "board_init(self, board=None): \"\"\"Initialize renderer's properties dependent on board it draws\"\"\"", "super(GridCell, self).__init__() self.renderer = renderer self.colored = colored if self.colored:", "for val in col] rend_column = pad(rend_column, self.header_height, Cell()) #", "self.cells = [[Cell()] * self.full_width for _ in range(self.full_height)] def", "if self.colored: self.value = tuple(two_powers(value)) else: self.value = value def", "* self.full_width for _ in range(self.full_height)] def cell_icon(self, cell): \"\"\"", "i, cell in enumerate(rend_column): self.cells[i][rend_j] = cell def draw_side(self): for", "board it draws\"\"\" if board: logger.info('Init %r renderer with board", "enumerate(row): ico = self.cell_icon(cell) # do not pad the last", "\"\"\" Stub for renderer initialization when it created before the", "of a board\"\"\" return self.side_width + self.board.width @property def header_height(self):", "columns descriptions \"\"\" raise NotImplementedError() def draw_side(self): \"\"\" Changes the", "all the cells and draw an image of the board\"\"\"", "text_type from ..utils.iter import max_safe, pad from ..utils.other import two_powers", "DEFAULT_ICON = '#' class ClueCell(Cell): \"\"\" Represent cell that is", "1: ico += ' ' res.append(ico) self._print(''.join(res)) def draw_header(self): for", "\"\"\" Represent upper-left cell (where the thumbnail of the puzzle", "icons is None: icons = dict(self.DEFAULT_ICONS) self.icons = icons super(StreamRenderer,", "DEFAULT_ICONS = { UNKNOWN: '_', BOX: 'X', SPACE: '.', }", "draw_grid(self, cells=None): if cells is None: cells = self.board.cells is_colored", "rend_j = j + self.side_width self.cells[rend_i][rend_j] = GridCell( val, self,", "= rend_row def draw_grid(self, cells=None): if cells is None: cells", "icons = dict(self.DEFAULT_ICONS) self.icons = icons super(StreamRenderer, self).__init__(board) def _print(self,", "height = 0 class Renderer(object): \"\"\"Defines the abstract renderer for", "is part of description (clue). They are usually drawn on", "row = list(row) if not row: row = [0] rend_row", "\"\"\"Represent the main area cell\"\"\" def __init__(self, value, renderer, colored=False):", "= value[0] else: # multiple colors value = UNKNOWN symbol", "= i + self.header_height for j, val in enumerate(row): rend_j", "draw_grid(self, cells=None): \"\"\" Changes the internal state to be able", "coding: utf-8 -*- \"\"\" Defines various renderers for the game", "renderer self.colored = colored if self.colored: self.value = tuple(two_powers(value)) else:", "value, None def ascii_icon(self): \"\"\" Gets a symbolic representation of", "= j + self.side_width if not col: col = [0]", "in enumerate(row): rend_j = j + self.side_width self.cells[rend_i][rend_j] = GridCell(", "cells = self.board.cells is_colored = self.is_colored for i, row in", "print(*args, file=self.stream) class BaseAsciiRenderer(StreamRenderer): \"\"\" Renders a board as a", "\"\"\"Represent basic rendered cell\"\"\" DEFAULT_ICON = ' ' def __init__(self,", "self.board_init(board) def board_init(self, board=None): \"\"\"Initialize renderer's properties dependent on board", "else: # multiple colors value = UNKNOWN symbol = self.renderer.board.symbol_for_color_id(value)", "None: icons = dict(self.DEFAULT_ICONS) self.icons = icons super(StreamRenderer, self).__init__(board) def", "list(row) if not row: row = [0] rend_row = [ClueCell(val)", "cell given its state and predefined table `icons` \"\"\" return", "'{}({})'.format( self.__class__.__name__, self.value) class _DummyBoard(object): \"\"\" Stub for renderer initialization", "grid) \"\"\" __rend_name__ = 'text' def board_init(self, board=None): super(BaseAsciiRenderer, self).board_init(board)", "= GridCell( val, self, colored=is_colored) def _register_renderers(): res = dict()", "to a stream (stdout by default) \"\"\" DEFAULT_ICONS = {", "icons=None): self.stream = stream if icons is None: icons =", "= [0] rend_row = [ClueCell(val) for val in row] rend_row", "integer_types, itervalues, text_type from ..utils.iter import max_safe, pad from ..utils.other", "self.value) class _DummyBoard(object): \"\"\" Stub for renderer initialization when it", "\"\"\"Initialize renderer's properties dependent on board it draws\"\"\" if board:", "= [0] rend_column = [ClueCell(val) for val in col] rend_column", "when it created before the corresponding board \"\"\" rows_descriptions =", "@property def is_colored(self): \"\"\"Whether the linked board is colored board\"\"\"", "def full_height(self): \"\"\"The full visual height of a board\"\"\" return", "issubclass(obj, StreamRenderer) and hasattr(obj, '__rend_name__'): res[obj.__rend_name__] = obj return res", "to draw rows descriptions \"\"\" raise NotImplementedError() def draw_grid(self, cells=None):", "Stub for renderer initialization when it created before the corresponding", "the linked board is colored board\"\"\" return self.board.is_colored class StreamRenderer(Renderer,", "= dict() for obj in itervalues(globals()): if isinstance(obj, type): if", "if self.value == BlottedBlock: return self.BLOTTED_SYMBOL return self.DEFAULT_ICON def __repr__(self):", "NotImplementedError() def draw_side(self): \"\"\" Changes the internal state to be", "'_', BOX: 'X', SPACE: '.', } def __init__(self, board=None, stream=stdout,", "to draw a main grid \"\"\" raise NotImplementedError() @property def", "for val in row] rend_row = pad(rend_row, self.side_width, Cell()) self.cells[rend_i][:self.side_width]", "an image of the board\"\"\" self.draw_header() self.draw_side() self.draw_grid(cells=cells) self.render() def", "linked board is colored board\"\"\" return self.board.is_colored class StreamRenderer(Renderer, ABC):", "simple text table (without grid) \"\"\" __rend_name__ = 'text' def", "cell\"\"\" def __init__(self, value, renderer, colored=False): super(GridCell, self).__init__() self.renderer =", "\"\"\" if isinstance(self.value, integer_types): return text_type(self.value) if self.value == BlottedBlock:", "self.draw_grid(cells=cells) self.render() def draw_header(self): \"\"\" Changes the internal state to", "of a board to a stream (stdout by default) \"\"\"", "range(self.header_height): for j in range(self.side_width): self.cells[i][j] = ThumbnailCell() for j,", "= [] for index, cell in enumerate(row): ico = self.cell_icon(cell)", "full visual height of a board\"\"\" return self.header_height + self.board.height", "[[Cell()] * self.full_width for _ in range(self.full_height)] def cell_icon(self, cell):", "created before the corresponding board \"\"\" rows_descriptions = columns_descriptions =", "ThumbnailCell(Cell): \"\"\" Represent upper-left cell (where the thumbnail of the", "return cell.ascii_icon() def render(self): for row in self.cells: res =", "puzzle usually drawn). \"\"\" DEFAULT_ICON = '#' class ClueCell(Cell): \"\"\"", "abc import ABC from sys import stdout from notetool.tool.log import", "colors value = UNKNOWN symbol = self.renderer.board.symbol_for_color_id(value) if symbol is", "if issubclass(obj, StreamRenderer) and hasattr(obj, '__rend_name__'): res[obj.__rend_name__] = obj return", "j + self.side_width self.cells[rend_i][rend_j] = GridCell( val, self, colored=is_colored) def", "columns_descriptions = () width = height = 0 class Renderer(object):", "a main grid \"\"\" raise NotImplementedError() @property def is_colored(self): \"\"\"Whether", "of the header block with columns descriptions\"\"\" return max_safe(map(len, self.board.columns_descriptions),", "self.board = board @property def full_height(self): \"\"\"The full visual height", "type): if issubclass(obj, StreamRenderer) and hasattr(obj, '__rend_name__'): res[obj.__rend_name__] = obj", "thumbnail of the puzzle usually drawn). \"\"\" DEFAULT_ICON = '#'", "the puzzle usually drawn). \"\"\" DEFAULT_ICON = '#' class ClueCell(Cell):", "if board: logger.info('Init %r renderer with board %r', self.__class__.__name__, board)", "of description (clue). They are usually drawn on the top", "__init__(self, icon=None): self.icon = icon or self.DEFAULT_ICON def ascii_icon(self): \"\"\"How", "self.full_width) self.cells = [[Cell()] * self.full_width for _ in range(self.full_height)]", "j + self.side_width if not col: col = [0] rend_column", "internal state to be able to draw columns descriptions \"\"\"", "super(ClueCell, self).__init__() if is_list_like(value): self.value, self.color = value else: self.value,", "\"\"\" rows_descriptions = columns_descriptions = () width = height =", "self.side_width if not col: col = [0] rend_column = [ClueCell(val)", "raise NotImplementedError() @property def is_colored(self): \"\"\"Whether the linked board is", "val, self, colored=is_colored) def _register_renderers(): res = dict() for obj", "def draw_grid(self, cells=None): if cells is None: cells = self.board.cells", "for _ in range(self.full_height)] def cell_icon(self, cell): \"\"\" Get a", "given its state and predefined table `icons` \"\"\" if isinstance(self.value,", "\"\"\" Simplify textual rendering of a board to a stream", "visual width of a board\"\"\" return self.side_width + self.board.width @property", "1: if index < len(row) - 1: ico += '", "self.__class__.__name__, board) else: if self.board: return # already initialized, do", "in enumerate(rend_column): self.cells[i][rend_j] = cell def draw_side(self): for i, row", "it created before the corresponding board \"\"\" rows_descriptions = columns_descriptions", "rend_j] = rend_column for i, cell in enumerate(rend_column): self.cells[i][rend_j] =", "self.cells[rend_i][:self.side_width] = rend_row def draw_grid(self, cells=None): if cells is None:", "cell\"\"\" DEFAULT_ICON = ' ' def __init__(self, icon=None): self.icon =", "render(self): for row in self.cells: res = [] for index,", "self.value, self.color = value else: self.value, self.color = value, None", "self.board.height @property def full_width(self): \"\"\"The full visual width of a", "line if len(ico) == 1: if index < len(row) -", "is not None: return symbol return icons.get(value, self.DEFAULT_ICON) def __repr__(self):", "representation of a cell given its state and predefined table", "i, row in enumerate(cells): rend_i = i + self.header_height for", "ThumbnailCell() for j, col in enumerate(self.board.columns_descriptions): rend_j = j +", "def render(self): for row in self.cells: res = [] for", "self.board.cells is_colored = self.is_colored for i, row in enumerate(cells): rend_i", "Defines various renderers for the game of nonogram \"\"\" from", "import integer_types, itervalues, text_type from ..utils.iter import max_safe, pad from", "class StreamRenderer(Renderer, ABC): \"\"\" Simplify textual rendering of a board", "= self.cell_icon(cell) # do not pad the last symbol in", "symbol in a line if len(ico) == 1: if index", "} def __init__(self, board=None, stream=stdout, icons=None): self.stream = stream if", "self.header_height, Cell()) # self.cells[:self.header_height, rend_j] = rend_column for i, cell", "able to draw rows descriptions \"\"\" raise NotImplementedError() def draw_grid(self,", "colored board\"\"\" return self.board.is_colored class StreamRenderer(Renderer, ABC): \"\"\" Simplify textual", "return symbol return icons.get(value, self.DEFAULT_ICON) def __repr__(self): return '{}({})'.format( self.__class__.__name__,", "0 class Renderer(object): \"\"\"Defines the abstract renderer for a nonogram", "self.board.is_colored class StreamRenderer(Renderer, ABC): \"\"\" Simplify textual rendering of a", "dict() for obj in itervalues(globals()): if isinstance(obj, type): if issubclass(obj,", "do nothing board = _DummyBoard() self.board = board @property def", "None def ascii_icon(self): \"\"\" Gets a symbolic representation of a", "a stream (stdout by default) \"\"\" DEFAULT_ICONS = { UNKNOWN:", "cell.ascii_icon() def render(self): for row in self.cells: res = []", "= icon or self.DEFAULT_ICON def ascii_icon(self): \"\"\"How the cell can", "are usually drawn on the top and on the left.", "printed as a text\"\"\" return self.DEFAULT_ICON def __repr__(self): return '{}()'.format(self.__class__.__name__)", "self.draw_side() self.draw_grid(cells=cells) self.render() def draw_header(self): \"\"\" Changes the internal state", "= None self.board_init(board) def board_init(self, board=None): \"\"\"Initialize renderer's properties dependent", "# already initialized, do nothing board = _DummyBoard() self.board =", "integer_types): return text_type(self.value) if self.value == BlottedBlock: return self.BLOTTED_SYMBOL return", "self.color = value else: self.value, self.color = value, None def", "'{}()'.format(self.__class__.__name__) class ThumbnailCell(Cell): \"\"\" Represent upper-left cell (where the thumbnail", "state to be able to draw columns descriptions \"\"\" raise", "stream (stdout by default) \"\"\" DEFAULT_ICONS = { UNKNOWN: '_',", "default) \"\"\" DEFAULT_ICONS = { UNKNOWN: '_', BOX: 'X', SPACE:", "enumerate(self.board.columns_descriptions): rend_j = j + self.side_width if not col: col", "header block with columns descriptions\"\"\" return max_safe(map(len, self.board.columns_descriptions), default=0) @property", "def board_init(self, board=None): \"\"\"Initialize renderer's properties dependent on board it", "+ self.header_height # row = list(row) if not row: row", "to be able to draw columns descriptions \"\"\" raise NotImplementedError()", "<reponame>notechats/notegame # -*- coding: utf-8 -*- \"\"\" Defines various renderers", "state and predefined table `icons` \"\"\" return cell.ascii_icon() def render(self):", "self).__init__(board) def _print(self, *args): return print(*args, file=self.stream) class BaseAsciiRenderer(StreamRenderer): \"\"\"", "= 0 class Renderer(object): \"\"\"Defines the abstract renderer for a", "BLOTTED_SYMBOL = '?' def __init__(self, value): super(ClueCell, self).__init__() if is_list_like(value):", "Represent upper-left cell (where the thumbnail of the puzzle usually", "return '{}()'.format(self.__class__.__name__) class ThumbnailCell(Cell): \"\"\" Represent upper-left cell (where the", "@property def full_width(self): \"\"\"The full visual width of a board\"\"\"", "self.colored: return icons[self.value] if len(value) == 1: value = value[0]", "be able to draw a main grid \"\"\" raise NotImplementedError()", "logger from six import integer_types, itervalues, text_type from ..utils.iter import", "self.cells[i][rend_j] = cell def draw_side(self): for i, row in enumerate(self.board.rows_descriptions):", "rend_row = [ClueCell(val) for val in row] rend_row = pad(rend_row,", "the main area cell\"\"\" def __init__(self, value, renderer, colored=False): super(GridCell,", "(stdout by default) \"\"\" DEFAULT_ICONS = { UNKNOWN: '_', BOX:", "def draw_grid(self, cells=None): \"\"\" Changes the internal state to be", "= j + self.side_width self.cells[rend_i][rend_j] = GridCell( val, self, colored=is_colored)", "self.cells: res = [] for index, cell in enumerate(row): ico", "self.stream = stream if icons is None: icons = dict(self.DEFAULT_ICONS)", "class Cell(object): \"\"\"Represent basic rendered cell\"\"\" DEFAULT_ICON = ' '", "predefined table `icons` \"\"\" if isinstance(self.value, integer_types): return text_type(self.value) if", "not pad the last symbol in a line if len(ico)", "self.value, self.color = value, None def ascii_icon(self): \"\"\" Gets a", "file=self.stream) class BaseAsciiRenderer(StreamRenderer): \"\"\" Renders a board as a simple", "def __init__(self, board=None): self.cells = None self.board = None self.board_init(board)", "1: value = value[0] else: # multiple colors value =", "from notetool.tool.log import logger from six import integer_types, itervalues, text_type", "the cell can be printed as a text\"\"\" return self.DEFAULT_ICON", "self.value = value def ascii_icon(self): value = self.value icons =", "utf-8 -*- \"\"\" Defines various renderers for the game of", "state to be able to draw rows descriptions \"\"\" raise", "board\"\"\" return self.board.is_colored class StreamRenderer(Renderer, ABC): \"\"\" Simplify textual rendering", "in enumerate(row): ico = self.cell_icon(cell) # do not pad the", "draw_header(self): \"\"\" Changes the internal state to be able to", "able to draw columns descriptions \"\"\" raise NotImplementedError() def draw_side(self):", "`icons` \"\"\" return cell.ascii_icon() def render(self): for row in self.cells:", "self.draw_header() self.draw_side() self.draw_grid(cells=cells) self.render() def draw_header(self): \"\"\" Changes the internal", "icons = self.renderer.icons if not self.colored: return icons[self.value] if len(value)", "def is_colored(self): \"\"\"Whether the linked board is colored board\"\"\" return", "= self.board.cells is_colored = self.is_colored for i, row in enumerate(cells):", "drawn). \"\"\" DEFAULT_ICON = '#' class ClueCell(Cell): \"\"\" Represent cell", "UNKNOWN: '_', BOX: 'X', SPACE: '.', } def __init__(self, board=None,", "_print(self, *args): return print(*args, file=self.stream) class BaseAsciiRenderer(StreamRenderer): \"\"\" Renders a", "def draw_side(self): for i, row in enumerate(self.board.rows_descriptions): rend_i = i", "[ClueCell(val) for val in row] rend_row = pad(rend_row, self.side_width, Cell())", "value[0] else: # multiple colors value = UNKNOWN symbol =", "ascii_icon(self): \"\"\"How the cell can be printed as a text\"\"\"", "it draws\"\"\" if board: logger.info('Init %r renderer with board %r',", "self.cells = None self.board = None self.board_init(board) def board_init(self, board=None):", "self.full_width, self.full_width) self.cells = [[Cell()] * self.full_width for _ in", "visual height of a board\"\"\" return self.header_height + self.board.height @property", "def __init__(self, icon=None): self.icon = icon or self.DEFAULT_ICON def ascii_icon(self):", "rend_i = i + self.header_height # row = list(row) if", "self.__class__.__name__, self.value, self.color) class GridCell(Cell): \"\"\"Represent the main area cell\"\"\"", "(clue). They are usually drawn on the top and on", "table `icons` \"\"\" return cell.ascii_icon() def render(self): for row in", "Changes the internal state to be able to draw a", "in enumerate(self.board.rows_descriptions): rend_i = i + self.header_height # row =", "NotImplementedError() def draw_grid(self, cells=None): \"\"\" Changes the internal state to", "def _register_renderers(): res = dict() for obj in itervalues(globals()): if", "self.board = None self.board_init(board) def board_init(self, board=None): \"\"\"Initialize renderer's properties", "board\"\"\" return self.side_width + self.board.width @property def header_height(self): \"\"\"The size", "return max_safe(map(len, self.board.rows_descriptions), default=0) def render(self): \"\"\"Actually print out the", "_DummyBoard() self.board = board @property def full_height(self): \"\"\"The full visual", "out the board\"\"\" raise NotImplementedError() def draw(self, cells=None): \"\"\"Calculate all", "rows descriptions\"\"\" return max_safe(map(len, self.board.rows_descriptions), default=0) def render(self): \"\"\"Actually print", "\"\"\"How the cell can be printed as a text\"\"\" return", "colored if self.colored: self.value = tuple(two_powers(value)) else: self.value = value", "else: if self.board: return # already initialized, do nothing board", "@property def full_height(self): \"\"\"The full visual height of a board\"\"\"", "else: self.value = value def ascii_icon(self): value = self.value icons", "in range(self.header_height): for j in range(self.side_width): self.cells[i][j] = ThumbnailCell() for", "the thumbnail of the puzzle usually drawn). \"\"\" DEFAULT_ICON =", "return max_safe(map(len, self.board.columns_descriptions), default=0) @property def side_width(self): \"\"\"The width of", "self.side_width, Cell()) self.cells[rend_i][:self.side_width] = rend_row def draw_grid(self, cells=None): if cells", "%r renderer with board %r', self.__class__.__name__, board) else: if self.board:", "usually drawn on the top and on the left. \"\"\"", "descriptions\"\"\" return max_safe(map(len, self.board.columns_descriptions), default=0) @property def side_width(self): \"\"\"The width", "enumerate(rend_column): self.cells[i][rend_j] = cell def draw_side(self): for i, row in", "row in enumerate(cells): rend_i = i + self.header_height for j,", "\"\"\"The width of the side block with rows descriptions\"\"\" return", "= '#' class ClueCell(Cell): \"\"\" Represent cell that is part", "draw(self, cells=None): \"\"\"Calculate all the cells and draw an image", "index < len(row) - 1: ico += ' ' res.append(ico)", "board=None): \"\"\"Initialize renderer's properties dependent on board it draws\"\"\" if", "def draw_side(self): \"\"\" Changes the internal state to be able", "rend_column = [ClueCell(val) for val in col] rend_column = pad(rend_column,", "properties dependent on board it draws\"\"\" if board: logger.info('Init %r", "\"\"\" Gets a symbolic representation of a cell given its", "value def ascii_icon(self): value = self.value icons = self.renderer.icons if", "board @property def full_height(self): \"\"\"The full visual height of a", "self.colored = colored if self.colored: self.value = tuple(two_powers(value)) else: self.value", "\"\"\" from abc import ABC from sys import stdout from", "cell in enumerate(rend_column): self.cells[i][rend_j] = cell def draw_side(self): for i,", "dict(self.DEFAULT_ICONS) self.icons = icons super(StreamRenderer, self).__init__(board) def _print(self, *args): return", "can be printed as a text\"\"\" return self.DEFAULT_ICON def __repr__(self):", "nonogram board\"\"\" def __init__(self, board=None): self.cells = None self.board =", "def render(self): \"\"\"Actually print out the board\"\"\" raise NotImplementedError() def", "icons super(StreamRenderer, self).__init__(board) def _print(self, *args): return print(*args, file=self.stream) class", "def __init__(self, value): super(ClueCell, self).__init__() if is_list_like(value): self.value, self.color =", "_ in range(self.full_height)] def cell_icon(self, cell): \"\"\" Get a symbolic", "val in enumerate(row): rend_j = j + self.side_width self.cells[rend_i][rend_j] =", "do not pad the last symbol in a line if", "def header_height(self): \"\"\"The size of the header block with columns", "import two_powers from .common import BOX, SPACE, UNKNOWN, BlottedBlock, is_list_like", "for i in range(self.header_height): for j in range(self.side_width): self.cells[i][j] =", "block with rows descriptions\"\"\" return max_safe(map(len, self.board.rows_descriptions), default=0) def render(self):", "state and predefined table `icons` \"\"\" if isinstance(self.value, integer_types): return", "= None self.board = None self.board_init(board) def board_init(self, board=None): \"\"\"Initialize", "value): super(ClueCell, self).__init__() if is_list_like(value): self.value, self.color = value else:", "board\"\"\" self.draw_header() self.draw_side() self.draw_grid(cells=cells) self.render() def draw_header(self): \"\"\" Changes the", "if len(value) == 1: value = value[0] else: # multiple", "the internal state to be able to draw rows descriptions", "in enumerate(self.board.columns_descriptions): rend_j = j + self.side_width if not col:", "self.DEFAULT_ICON def ascii_icon(self): \"\"\"How the cell can be printed as", "@property def header_height(self): \"\"\"The size of the header block with", "self.cells[i][j] = ThumbnailCell() for j, col in enumerate(self.board.columns_descriptions): rend_j =", "from .common import BOX, SPACE, UNKNOWN, BlottedBlock, is_list_like class Cell(object):", "import logger from six import integer_types, itervalues, text_type from ..utils.iter", "in self.cells: res = [] for index, cell in enumerate(row):", "the board\"\"\" raise NotImplementedError() def draw(self, cells=None): \"\"\"Calculate all the", "and hasattr(obj, '__rend_name__'): res[obj.__rend_name__] = obj return res RENDERERS =", "side block with rows descriptions\"\"\" return max_safe(map(len, self.board.rows_descriptions), default=0) def", "and predefined table `icons` \"\"\" if isinstance(self.value, integer_types): return text_type(self.value)", "__init__(self, board=None): self.cells = None self.board = None self.board_init(board) def", "grid \"\"\" raise NotImplementedError() @property def is_colored(self): \"\"\"Whether the linked", "in col] rend_column = pad(rend_column, self.header_height, Cell()) # self.cells[:self.header_height, rend_j]", "logger.info('init cells: %sx%s', self.full_width, self.full_width) self.cells = [[Cell()] * self.full_width", "size of the header block with columns descriptions\"\"\" return max_safe(map(len,", "the game of nonogram \"\"\" from abc import ABC from", "GridCell( val, self, colored=is_colored) def _register_renderers(): res = dict() for", "if cells is None: cells = self.board.cells is_colored = self.is_colored", "enumerate(cells): rend_i = i + self.header_height for j, val in", "Represent cell that is part of description (clue). They are", "BOX, SPACE, UNKNOWN, BlottedBlock, is_list_like class Cell(object): \"\"\"Represent basic rendered", "various renderers for the game of nonogram \"\"\" from abc", "for i, cell in enumerate(rend_column): self.cells[i][rend_j] = cell def draw_side(self):", "= pad(rend_column, self.header_height, Cell()) # self.cells[:self.header_height, rend_j] = rend_column for", "not None: return symbol return icons.get(value, self.DEFAULT_ICON) def __repr__(self): return", "self.full_width for _ in range(self.full_height)] def cell_icon(self, cell): \"\"\" Get", "len(ico) == 1: if index < len(row) - 1: ico", "ABC from sys import stdout from notetool.tool.log import logger from", "or self.DEFAULT_ICON def ascii_icon(self): \"\"\"How the cell can be printed", "cell): \"\"\" Get a symbolic representation of a cell given", "< len(row) - 1: ico += ' ' res.append(ico) self._print(''.join(res))", "def __repr__(self): return '{}({})'.format( self.__class__.__name__, self.value) class _DummyBoard(object): \"\"\" Stub", "return self.BLOTTED_SYMBOL return self.DEFAULT_ICON def __repr__(self): return '{}(({}, {}))'.format( self.__class__.__name__,", "to be able to draw rows descriptions \"\"\" raise NotImplementedError()", "in a line if len(ico) == 1: if index <", "None self.board = None self.board_init(board) def board_init(self, board=None): \"\"\"Initialize renderer's", "= stream if icons is None: icons = dict(self.DEFAULT_ICONS) self.icons", "and draw an image of the board\"\"\" self.draw_header() self.draw_side() self.draw_grid(cells=cells)", "'.', } def __init__(self, board=None, stream=stdout, icons=None): self.stream = stream", "pad the last symbol in a line if len(ico) ==", "BlottedBlock: return self.BLOTTED_SYMBOL return self.DEFAULT_ICON def __repr__(self): return '{}(({}, {}))'.format(", "nonogram \"\"\" from abc import ABC from sys import stdout", "rendering of a board to a stream (stdout by default)", "self.side_width self.cells[rend_i][rend_j] = GridCell( val, self, colored=is_colored) def _register_renderers(): res", "[0] rend_column = [ClueCell(val) for val in col] rend_column =", "default=0) def render(self): \"\"\"Actually print out the board\"\"\" raise NotImplementedError()", "self).__init__() self.renderer = renderer self.colored = colored if self.colored: self.value", "not self.colored: return icons[self.value] if len(value) == 1: value =", "res = [] for index, cell in enumerate(row): ico =", "rend_row = pad(rend_row, self.side_width, Cell()) self.cells[rend_i][:self.side_width] = rend_row def draw_grid(self,", "Cell()) self.cells[rend_i][:self.side_width] = rend_row def draw_grid(self, cells=None): if cells is", "self.value, self.color) class GridCell(Cell): \"\"\"Represent the main area cell\"\"\" def", "header_height(self): \"\"\"The size of the header block with columns descriptions\"\"\"", "board %r', self.__class__.__name__, board) else: if self.board: return # already", "logger.info('Init %r renderer with board %r', self.__class__.__name__, board) else: if", "'{}(({}, {}))'.format( self.__class__.__name__, self.value, self.color) class GridCell(Cell): \"\"\"Represent the main", "\"\"\"Defines the abstract renderer for a nonogram board\"\"\" def __init__(self,", "\"\"\" Renders a board as a simple text table (without", "= [[Cell()] * self.full_width for _ in range(self.full_height)] def cell_icon(self,", "self.renderer.icons if not self.colored: return icons[self.value] if len(value) == 1:", "def _print(self, *args): return print(*args, file=self.stream) class BaseAsciiRenderer(StreamRenderer): \"\"\" Renders", "return self.side_width + self.board.width @property def header_height(self): \"\"\"The size of", "self.board.width @property def header_height(self): \"\"\"The size of the header block", "board is colored board\"\"\" return self.board.is_colored class StreamRenderer(Renderer, ABC): \"\"\"", "= columns_descriptions = () width = height = 0 class", "Gets a symbolic representation of a cell given its state", "draw a main grid \"\"\" raise NotImplementedError() @property def is_colored(self):", "stream if icons is None: icons = dict(self.DEFAULT_ICONS) self.icons =", "cells is None: cells = self.board.cells is_colored = self.is_colored for", "+ self.board.height @property def full_width(self): \"\"\"The full visual width of", "from ..utils.iter import max_safe, pad from ..utils.other import two_powers from", "\"\"\" DEFAULT_ICON = '#' class ClueCell(Cell): \"\"\" Represent cell that", "self.header_height + self.board.height @property def full_width(self): \"\"\"The full visual width", "for index, cell in enumerate(row): ico = self.cell_icon(cell) # do", "board\"\"\" raise NotImplementedError() def draw(self, cells=None): \"\"\"Calculate all the cells", "range(self.side_width): self.cells[i][j] = ThumbnailCell() for j, col in enumerate(self.board.columns_descriptions): rend_j", "for obj in itervalues(globals()): if isinstance(obj, type): if issubclass(obj, StreamRenderer)", "descriptions \"\"\" raise NotImplementedError() def draw_grid(self, cells=None): \"\"\" Changes the", "return # already initialized, do nothing board = _DummyBoard() self.board", "\"\"\"The full visual width of a board\"\"\" return self.side_width +", "cell that is part of description (clue). They are usually", "initialized, do nothing board = _DummyBoard() self.board = board @property", "import max_safe, pad from ..utils.other import two_powers from .common import", "class Renderer(object): \"\"\"Defines the abstract renderer for a nonogram board\"\"\"", "symbol is not None: return symbol return icons.get(value, self.DEFAULT_ICON) def", "ascii_icon(self): value = self.value icons = self.renderer.icons if not self.colored:", "def full_width(self): \"\"\"The full visual width of a board\"\"\" return", "textual rendering of a board to a stream (stdout by", "*args): return print(*args, file=self.stream) class BaseAsciiRenderer(StreamRenderer): \"\"\" Renders a board", "if not col: col = [0] rend_column = [ClueCell(val) for", "with board %r', self.__class__.__name__, board) else: if self.board: return #", "class _DummyBoard(object): \"\"\" Stub for renderer initialization when it created", "SPACE: '.', } def __init__(self, board=None, stream=stdout, icons=None): self.stream =", "last symbol in a line if len(ico) == 1: if", "= value else: self.value, self.color = value, None def ascii_icon(self):", "from abc import ABC from sys import stdout from notetool.tool.log", "not row: row = [0] rend_row = [ClueCell(val) for val", "__rend_name__ = 'text' def board_init(self, board=None): super(BaseAsciiRenderer, self).board_init(board) logger.info('init cells:", "None: cells = self.board.cells is_colored = self.is_colored for i, row", "main grid \"\"\" raise NotImplementedError() @property def is_colored(self): \"\"\"Whether the", "board \"\"\" rows_descriptions = columns_descriptions = () width = height", "left. \"\"\" BLOTTED_SYMBOL = '?' def __init__(self, value): super(ClueCell, self).__init__()", "board_init(self, board=None): super(BaseAsciiRenderer, self).board_init(board) logger.info('init cells: %sx%s', self.full_width, self.full_width) self.cells", "\"\"\" BLOTTED_SYMBOL = '?' def __init__(self, value): super(ClueCell, self).__init__() if", "(without grid) \"\"\" __rend_name__ = 'text' def board_init(self, board=None): super(BaseAsciiRenderer,", "self.value == BlottedBlock: return self.BLOTTED_SYMBOL return self.DEFAULT_ICON def __repr__(self): return", "__repr__(self): return '{}(({}, {}))'.format( self.__class__.__name__, self.value, self.color) class GridCell(Cell): \"\"\"Represent", "dependent on board it draws\"\"\" if board: logger.info('Init %r renderer", "ico = self.cell_icon(cell) # do not pad the last symbol", "symbolic representation of a cell given its state and predefined", "= dict(self.DEFAULT_ICONS) self.icons = icons super(StreamRenderer, self).__init__(board) def _print(self, *args):", "height of a board\"\"\" return self.header_height + self.board.height @property def", "the corresponding board \"\"\" rows_descriptions = columns_descriptions = () width", "the left. \"\"\" BLOTTED_SYMBOL = '?' def __init__(self, value): super(ClueCell,", "draw columns descriptions \"\"\" raise NotImplementedError() def draw_side(self): \"\"\" Changes", "\"\"\"Actually print out the board\"\"\" raise NotImplementedError() def draw(self, cells=None):", "return print(*args, file=self.stream) class BaseAsciiRenderer(StreamRenderer): \"\"\" Renders a board as", "table `icons` \"\"\" if isinstance(self.value, integer_types): return text_type(self.value) if self.value", "a symbolic representation of a cell given its state and", "for i, row in enumerate(cells): rend_i = i + self.header_height", "= _DummyBoard() self.board = board @property def full_height(self): \"\"\"The full", "six import integer_types, itervalues, text_type from ..utils.iter import max_safe, pad", "return self.header_height + self.board.height @property def full_width(self): \"\"\"The full visual", "given its state and predefined table `icons` \"\"\" return cell.ascii_icon()", "is colored board\"\"\" return self.board.is_colored class StreamRenderer(Renderer, ABC): \"\"\" Simplify", "__repr__(self): return '{}({})'.format( self.__class__.__name__, self.value) class _DummyBoard(object): \"\"\" Stub for", "__init__(self, value, renderer, colored=False): super(GridCell, self).__init__() self.renderer = renderer self.colored", "from ..utils.other import two_powers from .common import BOX, SPACE, UNKNOWN,", "board=None): self.cells = None self.board = None self.board_init(board) def board_init(self,", "icon or self.DEFAULT_ICON def ascii_icon(self): \"\"\"How the cell can be", "NotImplementedError() @property def is_colored(self): \"\"\"Whether the linked board is colored", "the header block with columns descriptions\"\"\" return max_safe(map(len, self.board.columns_descriptions), default=0)", "__repr__(self): return '{}()'.format(self.__class__.__name__) class ThumbnailCell(Cell): \"\"\" Represent upper-left cell (where", "class ClueCell(Cell): \"\"\" Represent cell that is part of description", "self.BLOTTED_SYMBOL return self.DEFAULT_ICON def __repr__(self): return '{}(({}, {}))'.format( self.__class__.__name__, self.value,", "\"\"\" raise NotImplementedError() def draw_side(self): \"\"\" Changes the internal state", "Simplify textual rendering of a board to a stream (stdout", "value, renderer, colored=False): super(GridCell, self).__init__() self.renderer = renderer self.colored =", "= colored if self.colored: self.value = tuple(two_powers(value)) else: self.value =", "= list(row) if not row: row = [0] rend_row =", "self.renderer.board.symbol_for_color_id(value) if symbol is not None: return symbol return icons.get(value,", "def draw_header(self): \"\"\" Changes the internal state to be able", "is_colored = self.is_colored for i, row in enumerate(cells): rend_i =", "table (without grid) \"\"\" __rend_name__ = 'text' def board_init(self, board=None):", "+ self.side_width if not col: col = [0] rend_column =", "renderer's properties dependent on board it draws\"\"\" if board: logger.info('Init", "[ClueCell(val) for val in col] rend_column = pad(rend_column, self.header_height, Cell())", "# row = list(row) if not row: row = [0]", "return self.DEFAULT_ICON def __repr__(self): return '{}()'.format(self.__class__.__name__) class ThumbnailCell(Cell): \"\"\" Represent", "= tuple(two_powers(value)) else: self.value = value def ascii_icon(self): value =", "the side block with rows descriptions\"\"\" return max_safe(map(len, self.board.rows_descriptions), default=0)", "board to a stream (stdout by default) \"\"\" DEFAULT_ICONS =", "self).board_init(board) logger.info('init cells: %sx%s', self.full_width, self.full_width) self.cells = [[Cell()] *", "able to draw a main grid \"\"\" raise NotImplementedError() @property", "image of the board\"\"\" self.draw_header() self.draw_side() self.draw_grid(cells=cells) self.render() def draw_header(self):", "a board to a stream (stdout by default) \"\"\" DEFAULT_ICONS", "if self.board: return # already initialized, do nothing board =", "its state and predefined table `icons` \"\"\" return cell.ascii_icon() def", "val in col] rend_column = pad(rend_column, self.header_height, Cell()) # self.cells[:self.header_height,", "its state and predefined table `icons` \"\"\" if isinstance(self.value, integer_types):", "GridCell(Cell): \"\"\"Represent the main area cell\"\"\" def __init__(self, value, renderer,", "is None: cells = self.board.cells is_colored = self.is_colored for i,", "the cells and draw an image of the board\"\"\" self.draw_header()", "ABC): \"\"\" Simplify textual rendering of a board to a", "val in row] rend_row = pad(rend_row, self.side_width, Cell()) self.cells[rend_i][:self.side_width] =", "-*- coding: utf-8 -*- \"\"\" Defines various renderers for the", "max_safe, pad from ..utils.other import two_powers from .common import BOX,", "top and on the left. \"\"\" BLOTTED_SYMBOL = '?' def", "_DummyBoard(object): \"\"\" Stub for renderer initialization when it created before", "BOX: 'X', SPACE: '.', } def __init__(self, board=None, stream=stdout, icons=None):", "j in range(self.side_width): self.cells[i][j] = ThumbnailCell() for j, col in", "{ UNKNOWN: '_', BOX: 'X', SPACE: '.', } def __init__(self,", "raise NotImplementedError() def draw_grid(self, cells=None): \"\"\" Changes the internal state", "= { UNKNOWN: '_', BOX: 'X', SPACE: '.', } def", "state to be able to draw a main grid \"\"\"", "def side_width(self): \"\"\"The width of the side block with rows", "class BaseAsciiRenderer(StreamRenderer): \"\"\" Renders a board as a simple text", "self.icons = icons super(StreamRenderer, self).__init__(board) def _print(self, *args): return print(*args,", "\"\"\" Get a symbolic representation of a cell given its", "draw rows descriptions \"\"\" raise NotImplementedError() def draw_grid(self, cells=None): \"\"\"", "itervalues, text_type from ..utils.iter import max_safe, pad from ..utils.other import", "+ self.header_height for j, val in enumerate(row): rend_j = j", "basic rendered cell\"\"\" DEFAULT_ICON = ' ' def __init__(self, icon=None):", "\"\"\" DEFAULT_ICONS = { UNKNOWN: '_', BOX: 'X', SPACE: '.',", "UNKNOWN symbol = self.renderer.board.symbol_for_color_id(value) if symbol is not None: return", "None: return symbol return icons.get(value, self.DEFAULT_ICON) def __repr__(self): return '{}({})'.format(", "= i + self.header_height # row = list(row) if not", "if not row: row = [0] rend_row = [ClueCell(val) for", "self.cell_icon(cell) # do not pad the last symbol in a", "descriptions \"\"\" raise NotImplementedError() def draw_side(self): \"\"\" Changes the internal", "\"\"\"The full visual height of a board\"\"\" return self.header_height +", "rows_descriptions = columns_descriptions = () width = height = 0", "= cell def draw_side(self): for i, row in enumerate(self.board.rows_descriptions): rend_i", "self).__init__() if is_list_like(value): self.value, self.color = value else: self.value, self.color", "i + self.header_height # row = list(row) if not row:", "def board_init(self, board=None): super(BaseAsciiRenderer, self).board_init(board) logger.info('init cells: %sx%s', self.full_width, self.full_width)", "self.header_height # row = list(row) if not row: row =", "# self.cells[:self.header_height, rend_j] = rend_column for i, cell in enumerate(rend_column):", "res.append(ico) self._print(''.join(res)) def draw_header(self): for i in range(self.header_height): for j", "' ' def __init__(self, icon=None): self.icon = icon or self.DEFAULT_ICON", "self, colored=is_colored) def _register_renderers(): res = dict() for obj in", "Renderer(object): \"\"\"Defines the abstract renderer for a nonogram board\"\"\" def", "a nonogram board\"\"\" def __init__(self, board=None): self.cells = None self.board", "Cell()) # self.cells[:self.header_height, rend_j] = rend_column for i, cell in", "board = _DummyBoard() self.board = board @property def full_height(self): \"\"\"The", "= self.renderer.icons if not self.colored: return icons[self.value] if len(value) ==", "board=None): super(BaseAsciiRenderer, self).board_init(board) logger.info('init cells: %sx%s', self.full_width, self.full_width) self.cells =", "cells: %sx%s', self.full_width, self.full_width) self.cells = [[Cell()] * self.full_width for", "draw_header(self): for i in range(self.header_height): for j in range(self.side_width): self.cells[i][j]", "with rows descriptions\"\"\" return max_safe(map(len, self.board.rows_descriptions), default=0) def render(self): \"\"\"Actually", "value else: self.value, self.color = value, None def ascii_icon(self): \"\"\"", "row in enumerate(self.board.rows_descriptions): rend_i = i + self.header_height # row", "BlottedBlock, is_list_like class Cell(object): \"\"\"Represent basic rendered cell\"\"\" DEFAULT_ICON =", "ico += ' ' res.append(ico) self._print(''.join(res)) def draw_header(self): for i", "= '?' def __init__(self, value): super(ClueCell, self).__init__() if is_list_like(value): self.value,", "= [ClueCell(val) for val in col] rend_column = pad(rend_column, self.header_height,", "if len(ico) == 1: if index < len(row) - 1:", "'?' def __init__(self, value): super(ClueCell, self).__init__() if is_list_like(value): self.value, self.color", "= [ClueCell(val) for val in row] rend_row = pad(rend_row, self.side_width,", "== BlottedBlock: return self.BLOTTED_SYMBOL return self.DEFAULT_ICON def __repr__(self): return '{}(({},", "board as a simple text table (without grid) \"\"\" __rend_name__", "import ABC from sys import stdout from notetool.tool.log import logger", "== 1: value = value[0] else: # multiple colors value", "for j in range(self.side_width): self.cells[i][j] = ThumbnailCell() for j, col", "stdout from notetool.tool.log import logger from six import integer_types, itervalues,", "if symbol is not None: return symbol return icons.get(value, self.DEFAULT_ICON)", "= ThumbnailCell() for j, col in enumerate(self.board.columns_descriptions): rend_j = j", "text\"\"\" return self.DEFAULT_ICON def __repr__(self): return '{}()'.format(self.__class__.__name__) class ThumbnailCell(Cell): \"\"\"", "nothing board = _DummyBoard() self.board = board @property def full_height(self):", "board\"\"\" return self.header_height + self.board.height @property def full_width(self): \"\"\"The full", "the internal state to be able to draw a main", "ascii_icon(self): \"\"\" Gets a symbolic representation of a cell given", "return icons.get(value, self.DEFAULT_ICON) def __repr__(self): return '{}({})'.format( self.__class__.__name__, self.value) class", "= pad(rend_row, self.side_width, Cell()) self.cells[rend_i][:self.side_width] = rend_row def draw_grid(self, cells=None):", "= rend_column for i, cell in enumerate(rend_column): self.cells[i][rend_j] = cell", "else: self.value, self.color = value, None def ascii_icon(self): \"\"\" Gets", "value = UNKNOWN symbol = self.renderer.board.symbol_for_color_id(value) if symbol is not", "row: row = [0] rend_row = [ClueCell(val) for val in", "cell can be printed as a text\"\"\" return self.DEFAULT_ICON def", "Changes the internal state to be able to draw columns", "of the puzzle usually drawn). \"\"\" DEFAULT_ICON = '#' class", "cell in enumerate(row): ico = self.cell_icon(cell) # do not pad", "def draw_header(self): for i in range(self.header_height): for j in range(self.side_width):", "They are usually drawn on the top and on the", "internal state to be able to draw a main grid", "renderer, colored=False): super(GridCell, self).__init__() self.renderer = renderer self.colored = colored", "index, cell in enumerate(row): ico = self.cell_icon(cell) # do not", "rend_row def draw_grid(self, cells=None): if cells is None: cells =", ".common import BOX, SPACE, UNKNOWN, BlottedBlock, is_list_like class Cell(object): \"\"\"Represent", "renderer with board %r', self.__class__.__name__, board) else: if self.board: return", "ClueCell(Cell): \"\"\" Represent cell that is part of description (clue).", "board=None, stream=stdout, icons=None): self.stream = stream if icons is None:", "super(BaseAsciiRenderer, self).board_init(board) logger.info('init cells: %sx%s', self.full_width, self.full_width) self.cells = [[Cell()]", "range(self.full_height)] def cell_icon(self, cell): \"\"\" Get a symbolic representation of", "i, row in enumerate(self.board.rows_descriptions): rend_i = i + self.header_height #", "a board\"\"\" return self.side_width + self.board.width @property def header_height(self): \"\"\"The", "= board @property def full_height(self): \"\"\"The full visual height of", "self.colored: self.value = tuple(two_powers(value)) else: self.value = value def ascii_icon(self):", "rend_column = pad(rend_column, self.header_height, Cell()) # self.cells[:self.header_height, rend_j] = rend_column", "self.DEFAULT_ICON def __repr__(self): return '{}()'.format(self.__class__.__name__) class ThumbnailCell(Cell): \"\"\" Represent upper-left", "row] rend_row = pad(rend_row, self.side_width, Cell()) self.cells[rend_i][:self.side_width] = rend_row def", "value = value[0] else: # multiple colors value = UNKNOWN", "full_width(self): \"\"\"The full visual width of a board\"\"\" return self.side_width", "pad(rend_row, self.side_width, Cell()) self.cells[rend_i][:self.side_width] = rend_row def draw_grid(self, cells=None): if", "+ self.side_width self.cells[rend_i][rend_j] = GridCell( val, self, colored=is_colored) def _register_renderers():", "colored=False): super(GridCell, self).__init__() self.renderer = renderer self.colored = colored if", "pad(rend_column, self.header_height, Cell()) # self.cells[:self.header_height, rend_j] = rend_column for i,", "already initialized, do nothing board = _DummyBoard() self.board = board", "' res.append(ico) self._print(''.join(res)) def draw_header(self): for i in range(self.header_height): for", "if index < len(row) - 1: ico += ' '", "UNKNOWN, BlottedBlock, is_list_like class Cell(object): \"\"\"Represent basic rendered cell\"\"\" DEFAULT_ICON", "area cell\"\"\" def __init__(self, value, renderer, colored=False): super(GridCell, self).__init__() self.renderer", "for a nonogram board\"\"\" def __init__(self, board=None): self.cells = None", "Cell(object): \"\"\"Represent basic rendered cell\"\"\" DEFAULT_ICON = ' ' def", "max_safe(map(len, self.board.columns_descriptions), default=0) @property def side_width(self): \"\"\"The width of the", "a cell given its state and predefined table `icons` \"\"\"", "DEFAULT_ICON = ' ' def __init__(self, icon=None): self.icon = icon", "board\"\"\" def __init__(self, board=None): self.cells = None self.board = None", "__init__(self, value): super(ClueCell, self).__init__() if is_list_like(value): self.value, self.color = value", "internal state to be able to draw rows descriptions \"\"\"", "'X', SPACE: '.', } def __init__(self, board=None, stream=stdout, icons=None): self.stream", "col in enumerate(self.board.columns_descriptions): rend_j = j + self.side_width if not", "colored=is_colored) def _register_renderers(): res = dict() for obj in itervalues(globals()):", "def __repr__(self): return '{}(({}, {}))'.format( self.__class__.__name__, self.value, self.color) class GridCell(Cell):", "board: logger.info('Init %r renderer with board %r', self.__class__.__name__, board) else:", "if isinstance(obj, type): if issubclass(obj, StreamRenderer) and hasattr(obj, '__rend_name__'): res[obj.__rend_name__]", "of the board\"\"\" self.draw_header() self.draw_side() self.draw_grid(cells=cells) self.render() def draw_header(self): \"\"\"", "\"\"\" raise NotImplementedError() def draw_grid(self, cells=None): \"\"\" Changes the internal", "rows descriptions \"\"\" raise NotImplementedError() def draw_grid(self, cells=None): \"\"\" Changes", "enumerate(row): rend_j = j + self.side_width self.cells[rend_i][rend_j] = GridCell( val,", "icons.get(value, self.DEFAULT_ICON) def __repr__(self): return '{}({})'.format( self.__class__.__name__, self.value) class _DummyBoard(object):", "# do not pad the last symbol in a line", "text_type(self.value) if self.value == BlottedBlock: return self.BLOTTED_SYMBOL return self.DEFAULT_ICON def", "..utils.other import two_powers from .common import BOX, SPACE, UNKNOWN, BlottedBlock,", "of nonogram \"\"\" from abc import ABC from sys import", "raise NotImplementedError() def draw_side(self): \"\"\" Changes the internal state to", "cell (where the thumbnail of the puzzle usually drawn). \"\"\"", "(where the thumbnail of the puzzle usually drawn). \"\"\" DEFAULT_ICON", "def ascii_icon(self): \"\"\" Gets a symbolic representation of a cell", "descriptions\"\"\" return max_safe(map(len, self.board.rows_descriptions), default=0) def render(self): \"\"\"Actually print out", "self.board.rows_descriptions), default=0) def render(self): \"\"\"Actually print out the board\"\"\" raise", "[] for index, cell in enumerate(row): ico = self.cell_icon(cell) #", "self.icon = icon or self.DEFAULT_ICON def ascii_icon(self): \"\"\"How the cell", "cells and draw an image of the board\"\"\" self.draw_header() self.draw_side()", "= () width = height = 0 class Renderer(object): \"\"\"Defines", "on the left. \"\"\" BLOTTED_SYMBOL = '?' def __init__(self, value):", "def ascii_icon(self): \"\"\"How the cell can be printed as a", "self.value = tuple(two_powers(value)) else: self.value = value def ascii_icon(self): value", "return icons[self.value] if len(value) == 1: value = value[0] else:", "# multiple colors value = UNKNOWN symbol = self.renderer.board.symbol_for_color_id(value) if", "== 1: if index < len(row) - 1: ico +=", "is_list_like class Cell(object): \"\"\"Represent basic rendered cell\"\"\" DEFAULT_ICON = '", "= height = 0 class Renderer(object): \"\"\"Defines the abstract renderer", "def draw(self, cells=None): \"\"\"Calculate all the cells and draw an" ]
[ "% expr.__class__.__name__) # blacklist all Matrix printing _print_SparseMatrix = \\", ": 'where', 'complex' : 'complex', 'contains' : 'contains', } def", "didn't define it, we could use StrPrinter's # version of", "_print_ImmutableDenseMatrix = \\ _print_MatrixBase def _print_Piecewise(self, expr): result = []", "functions not appearing in this dict will raise a TypeError", "return '{0}(({1}))'.format('amax', ','.join(self._print(i) for i in expr.args)) # numexpr works", "'cos', 'tan' : 'tan', 'asin': 'arcsin', 'acos': 'arccos', 'atan': 'arctan',", "def _print_Not(self, expr): result = ['(', 'not (', self._print(expr.args[0]), '))']", "expr.args. # If this is not the case, it may", "c = arg.cond result.append('((') result.append(self._print(e)) result.append(') if (') result.append(self._print(c)) result.append(')", "') if (', self._print(expr.args[0]), ') else (', self._print(expr.args[2]), '))' ]", "**settings): \"\"\" Returns a string usable for lambdifying. \"\"\" return", "sorted(expr.args, key=default_sort_key): result.extend(['(', self._print(arg), ')']) result.append(' or ') result =", "arg1.shape[0] != 1: arg1 = arg1.T if arg2.shape[1] != 1:", "s = [self._print(item) for item in seq] if s: return", "'atan': 'arctan', 'atan2' : 'arctan2', 'sinh' : 'sinh', 'cosh' :", "\\ _print_dict = \\ _print_Dict = \\ blacklisted def doprint(self,", "prematurely. return 'select({0}, {1}, default=nan)'.format(conds, exprs) def _print_Relational(self, expr): \"Relational", "result.append('((') result.append(self._print(e)) result.append(') if (') result.append(self._print(c)) result.append(') else (') i", "arg2.T return \"dot(%s, %s)\" % (self._print(arg1), self._print(arg2)) def _print_Piecewise(self, expr):", "e): func_name = e.func.__name__ nstr = self._numexpr_functions.get(func_name, None) if nstr", "(expr, cond) sequence in a Piecewise object # it will", "namespace. Thus a special printer... class NumExprPrinter(LambdaPrinter): # key, value", "order, but numpy.dot does matrix # multiplication, so we have", "key=default_sort_key): result.extend(['(', self._print(arg), ')']) result.append(' and ') result = result[:-1]", "_print_MatMul(self, expr): \"Matrix multiplication printer\" return '({0})'.format(').dot('.join(self._print(i) for i in", "result = ['(', 'not (', self._print(expr.args[0]), '))'] return ''.join(result) def", "'where' : 'where', 'complex' : 'complex', 'contains' : 'contains', }", "import default_sort_key class LambdaPrinter(StrPrinter): \"\"\" This printer converts expressions into", "def _print_ImaginaryUnit(self, expr): return '1j' def _print_seq(self, seq, delimiter=', '):", "blacklist some python expressions _print_list = \\ _print_tuple = \\", "_print_And(self, expr): \"Logical And printer\" # We have to override", "not support function '%s'\" % func_name) return \"%s(%s)\" % (nstr,", "0 for arg in expr.args: e = arg.expr c =", "vectorized piecewise functions, logical operators, etc. \"\"\" _default_settings = {", "passed to numexpr.evaluate # rather than by populating a namespace.", "func_name) return \"%s(%s)\" % (nstr, self._print_seq(e.args)) def blacklisted(self, expr): raise", "it may be triggered prematurely. return 'select({0}, {1}, default=nan)'.format(conds, exprs)", "implemented_function if hasattr(e, '_imp_'): return \"(%s)\" % self._print(e._imp_(*e.args)) else: raise", "into strings that can be used by lambdify. \"\"\" def", "LambdaPrinter(StrPrinter): \"\"\" This printer converts expressions into strings that can", "tuples in nopython mode. return '({},)'.format(delimiter.join(self._print(item) for item in seq))", "version of the function and add 'logical_or' to NUMPY_TRANSLATIONS. return", "\"Logical Or printer\" # We have to override LambdaPrinter because", "altering the string passed to numexpr.evaluate # rather than by", "_print_seq taken from pretty.py s = [self._print(item) for item in", "strings that can be used by lambdify. \"\"\" def _print_MatrixBase(self,", "multiplication, so we have to make sure it gets 1", "used with %s\" % expr.__class__.__name__) # blacklist all Matrix printing", "_print_Piecewise(self, expr): \"Piecewise function printer\" exprs = '[{0}]'.format(','.join(self._print(arg.expr) for arg", ": 'arctan2', 'sinh' : 'sinh', 'cosh' : 'cosh', 'tanh' :", "sympy.utilities import default_sort_key class LambdaPrinter(StrPrinter): \"\"\" This printer converts expressions", "in expr.args)) conds = '[{0}]'.format(','.join(self._print(arg.cond) for arg in expr.args)) #", "for Equality and Unequality\" op = { '==' :'equal', '!='", "_print_tuple = \\ _print_Tuple = \\ _print_dict = \\ _print_Dict", "result = result[:-1] result.append(') else None)') result.append(')'*(2*i - 2)) return", "Matrix printing _print_SparseMatrix = \\ _print_MutableSparseMatrix = \\ _print_ImmutableSparseMatrix =", "_print_BooleanFalse(self, expr): return \"False\" def _print_ITE(self, expr): result = [", "!= 1: arg2 = arg2.T return \"dot(%s, %s)\" % (self._print(arg1),", "\\ _print_ImmutableMatrix = \\ _print_ImmutableDenseMatrix = \\ _print_MatrixBase def _print_Piecewise(self,", ":'greater_equal', } if expr.rel_op in op: lhs = self._print(expr.lhs) rhs", ": 'cosh', 'tanh' : 'tanh', 'asinh': 'arcsinh', 'acosh': 'arccosh', 'atanh':", "seq, delimiter=', '): # simplified _print_seq taken from pretty.py s", "\\ _print_Dict = \\ blacklisted def doprint(self, expr): lstr =", "return ''.join(result) def _print_Or(self, expr): result = ['('] for arg", "(self._print(arg1), self._print(arg2)) def _print_Piecewise(self, expr): \"Piecewise function printer\" exprs =", "it will behave the same as passing the 'default' kwarg", "= [] i = 0 for arg in expr.args: e", "define it, we could use StrPrinter's # version of the", "'arcsin', 'acos': 'arccos', 'atan': 'arctan', 'atan2' : 'arctan2', 'sinh' :", "{ '==' :'equal', '!=' :'not_equal', '<' :'less', '<=' :'less_equal', '>'", "'tanh' : 'tanh', 'asinh': 'arcsinh', 'acosh': 'arccosh', 'atanh': 'arctanh', 'ln'", "seq] if s: return delimiter.join(s) else: return \"\" def _print_Function(self,", "result.append(self._print(c)) result.append(') else (') i += 1 result = result[:-1]", "We have to override LambdaPrinter because it uses Python 'and'", "for arg in sorted(expr.args, key=default_sort_key): result.extend(['(', self._print(arg), ')']) result.append(' or", "else: raise TypeError(\"numexpr does not support function '%s'\" % func_name)", "'conjugate' : 'conj', 'im' : 'imag', 're' : 'real', 'where'", "\\ _print_MutableDenseMatrix = \\ _print_ImmutableMatrix = \\ _print_ImmutableDenseMatrix = \\", "x 1. arg1, arg2 = expr.args if arg1.shape[0] != 1:", "'==' :'equal', '!=' :'not_equal', '<' :'less', '<=' :'less_equal', '>' :'greater',", "(expr.__class__.__name__, self._print((expr.tolist()))) _print_SparseMatrix = \\ _print_MutableSparseMatrix = \\ _print_ImmutableSparseMatrix =", "any shape order, but numpy.dot does matrix # multiplication, so", "arg.expr c = arg.cond result.append('((') result.append(self._print(e)) result.append(') if (') result.append(self._print(c))", "\"True\" def _print_BooleanFalse(self, expr): return \"False\" def _print_ITE(self, expr): result", "_print_DenseMatrix = \\ _print_MutableDenseMatrix = \\ _print_ImmutableMatrix = \\ _print_ImmutableDenseMatrix", "% lstr def lambdarepr(expr, **settings): \"\"\" Returns a string usable", "StrPrinter's # version of the function and add 'logical_and' to", "or ') result = result[:-1] result.append(')') return ''.join(result) def _print_Not(self,", "'atanh': 'arctanh', 'ln' : 'log', 'log': 'log', 'exp': 'exp', 'sqrt'", "Equality and Unequality\" op = { '==' :'equal', '!=' :'not_equal',", "tuples here instead of lists because numba supports # tuples", "if arg1.shape[0] != 1: arg1 = arg1.T if arg2.shape[1] !=", "\\ _print_MutableSparseMatrix = \\ _print_ImmutableSparseMatrix = \\ _print_Matrix = \\", "class NumPyPrinter(LambdaPrinter): \"\"\" Numpy printer which handles vectorized piecewise functions,", "numpy.dot does matrix # multiplication, so we have to make", "it is the last element in expr.args. # If this", "for i in expr.args)) def _print_Not(self, expr): \"Logical Not printer\"", "'{0}(({1}))'.format('amax', ','.join(self._print(i) for i in expr.args)) # numexpr works by", "'(builtins.sum({function} {loops}))'.format( function=self._print(expr.function), loops=' '.join(loops)) def _print_And(self, expr): result =", "define it, we would still have to define our #", "'arccos', 'atan': 'arctan', 'atan2' : 'arctan2', 'sinh' : 'sinh', 'cosh'", "blacklisted def doprint(self, expr): lstr = super(NumExprPrinter, self).doprint(expr) return \"evaluate('%s',", "loops = ( 'for {i} in range({a}, {b}+1)'.format( i=self._print(i), a=self._print(a),", "')']) result.append(' and ') result = result[:-1] result.append(')') return ''.join(result)", "instead of lists because numba supports # tuples in nopython", "and add 'logical_and' to NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_and', ','.join(self._print(i) for i", "default_sort_key class LambdaPrinter(StrPrinter): \"\"\" This printer converts expressions into strings", "def _print_BooleanTrue(self, expr): return \"True\" def _print_BooleanFalse(self, expr): return \"False\"", "may be triggered prematurely. return 'select({0}, {1}, default=nan)'.format(conds, exprs) def", "def _print_Or(self, expr): result = ['('] for arg in sorted(expr.args,", "%s)\" % (self._print(arg1), self._print(arg2)) def _print_Piecewise(self, expr): \"Piecewise function printer\"", "logical operators, etc. \"\"\" _default_settings = { \"order\": \"none\", \"full_prec\":", "converts to tuple\" # Print tuples here instead of lists", "= \\ _print_MutableSparseMatrix = \\ _print_ImmutableSparseMatrix = \\ _print_Matrix =", "because numba supports # tuples in nopython mode. return '({},)'.format(delimiter.join(self._print(item)", "= \\ _print_MatrixBase def _print_Piecewise(self, expr): result = [] i", "truediv=True)\" % lstr def lambdarepr(expr, **settings): \"\"\" Returns a string", "is None: # check for implemented_function if hasattr(e, '_imp_'): return", "a special printer... class NumExprPrinter(LambdaPrinter): # key, value pairs correspond", "','.join(self._print(i) for i in expr.args)) # numexpr works by altering", "to define our # own because StrPrinter doesn't define it.", "def _print_ITE(self, expr): result = [ '((', self._print(expr.args[1]), ') if", "_print_ImmutableMatrix = \\ _print_ImmutableDenseMatrix = \\ _print_MatrixBase def _print_Piecewise(self, expr):", "% self._print(e._imp_(*e.args)) else: raise TypeError(\"numexpr does not support function '%s'\"", "'{op}({lhs}, {rhs})'.format(op=op[expr.rel_op], lhs=lhs, rhs=rhs) return super(NumPyPrinter, self)._print_Relational(expr) def _print_And(self, expr):", "__future__ import print_function, division from .str import StrPrinter from sympy.utilities", "as* it is the last element in expr.args. # If", "'{0}({1})'.format('logical_or', ','.join(self._print(i) for i in expr.args)) def _print_Not(self, expr): \"Logical", "expr): return \"%s(%s)\" % (expr.__class__.__name__, self._print((expr.tolist()))) _print_SparseMatrix = \\ _print_MutableSparseMatrix", "appearing in this dict will raise a TypeError _numexpr_functions =", "# Print tuples here instead of lists because numba supports", "function and add 'logical_or' to NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_or', ','.join(self._print(i) for", "True] is a (expr, cond) sequence in a Piecewise object", "return '1j' def _print_seq(self, seq, delimiter=', '): # simplified _print_seq", "printer for Equality and Unequality\" op = { '==' :'equal',", "_print_SparseMatrix = \\ _print_MutableSparseMatrix = \\ _print_ImmutableSparseMatrix = \\ _print_Matrix", "_print_Or(self, expr): \"Logical Or printer\" # We have to override", "for i in expr.args)) def _print_Max(self, expr): return '{0}(({1}))'.format('amax', ','.join(self._print(i)", "if hasattr(e, '_imp_'): return \"(%s)\" % self._print(e._imp_(*e.args)) else: raise TypeError(\"numexpr", "return '({},)'.format(delimiter.join(self._print(item) for item in seq)) def _print_MatMul(self, expr): \"Matrix", "return 'select({0}, {1}, default=nan)'.format(conds, exprs) def _print_Relational(self, expr): \"Relational printer", "nopython mode. return '({},)'.format(delimiter.join(self._print(item) for item in seq)) def _print_MatMul(self,", "by altering the string passed to numexpr.evaluate # rather than", "in expr.args)) def _print_DotProduct(self, expr): # DotProduct allows any shape", "def _print_Max(self, expr): return '{0}(({1}))'.format('amax', ','.join(self._print(i) for i in expr.args))", "have to override LambdaPrinter because it uses Python 'not' keyword.", "numexpr name # functions not appearing in this dict will", "( 'for {i} in range({a}, {b}+1)'.format( i=self._print(i), a=self._print(a), b=self._print(b)) for", "'{0}({1})'.format('logical_and', ','.join(self._print(i) for i in expr.args)) def _print_Or(self, expr): \"Logical", "result.append(' or ') result = result[:-1] result.append(')') return ''.join(result) def", "(') i += 1 result = result[:-1] result.append(') else None)')", "= [ '((', self._print(expr.args[1]), ') if (', self._print(expr.args[0]), ') else", "the case, it may be triggered prematurely. return 'select({0}, {1},", "If LambdaPrinter didn't define it, we could use StrPrinter's #", "result.append(')'*(2*i - 2)) return ''.join(result) def _print_Sum(self, expr): loops =", "shape order, but numpy.dot does matrix # multiplication, so we", "\"dot(%s, %s)\" % (self._print(arg1), self._print(arg2)) def _print_Piecewise(self, expr): \"Piecewise function", "\\ _print_ImmutableMatrix = \\ _print_ImmutableDenseMatrix = \\ blacklisted # blacklist", "of the function and add 'logical_or' to NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_or',", "is not the case, it may be triggered prematurely. return", "\"(%s)\" % self._print(e._imp_(*e.args)) else: raise TypeError(\"numexpr does not support function", "\"\" def _print_Function(self, e): func_name = e.func.__name__ nstr = self._numexpr_functions.get(func_name,", "result = ['('] for arg in sorted(expr.args, key=default_sort_key): result.extend(['(', self._print(arg),", "'sinh', 'cosh' : 'cosh', 'tanh' : 'tanh', 'asinh': 'arcsinh', 'acosh':", "in expr.limits) return '(builtins.sum({function} {loops}))'.format( function=self._print(expr.function), loops=' '.join(loops)) def _print_And(self,", "= '[{0}]'.format(','.join(self._print(arg.expr) for arg in expr.args)) conds = '[{0}]'.format(','.join(self._print(arg.cond) for", "it, we could use StrPrinter's # version of the function", "= self._numexpr_functions.get(func_name, None) if nstr is None: # check for", "override LambdaPrinter because it uses Python 'and' keyword. # If", "''.join(result) def _print_Not(self, expr): result = ['(', 'not (', self._print(expr.args[0]),", "rather than by populating a namespace. Thus a special printer...", "_print_Piecewise(self, expr): result = [] i = 0 for arg", "return \"%s(%s)\" % (nstr, self._print_seq(e.args)) def blacklisted(self, expr): raise TypeError(\"numexpr", "result[:-1] result.append(')') return ''.join(result) def _print_Not(self, expr): result = ['(',", "_print_Matrix = \\ _print_DenseMatrix = \\ _print_MutableDenseMatrix = \\ _print_ImmutableMatrix", "we could use StrPrinter's # version of the function and", "return '{0}(({1}))'.format('amin', ','.join(self._print(i) for i in expr.args)) def _print_Max(self, expr):", "'where', 'complex' : 'complex', 'contains' : 'contains', } def _print_ImaginaryUnit(self,", "'%s'\" % func_name) return \"%s(%s)\" % (nstr, self._print_seq(e.args)) def blacklisted(self,", "to NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_and', ','.join(self._print(i) for i in expr.args)) def", "this is not the case, it may be triggered prematurely.", "None: # check for implemented_function if hasattr(e, '_imp_'): return \"(%s)\"", "be used by lambdify. \"\"\" def _print_MatrixBase(self, expr): return \"%s(%s)\"", "# functions not appearing in this dict will raise a", "because it uses Python 'not' keyword. # If LambdaPrinter didn't", "does not support function '%s'\" % func_name) return \"%s(%s)\" %", "be triggered prematurely. return 'select({0}, {1}, default=nan)'.format(conds, exprs) def _print_Relational(self,", ":'less', '<=' :'less_equal', '>' :'greater', '>=' :'greater_equal', } if expr.rel_op", "result.append(') else None)') result.append(')'*(2*i - 2)) return ''.join(result) def _print_Sum(self,", "and ') result = result[:-1] result.append(')') return ''.join(result) def _print_Or(self,", "for item in seq)) def _print_MatMul(self, expr): \"Matrix multiplication printer\"", "so we have to make sure it gets 1 x", "passing the 'default' kwarg to select() # *as long as*", "result[:-1] result.append(')') return ''.join(result) def _print_Or(self, expr): result = ['(']", "result.append(' and ') result = result[:-1] result.append(')') return ''.join(result) def", "in op: lhs = self._print(expr.lhs) rhs = self._print(expr.rhs) return '{op}({lhs},", "s: return delimiter.join(s) else: return \"\" def _print_Function(self, e): func_name", "Numpy printer which handles vectorized piecewise functions, logical operators, etc.", "LambdaPrinter because it uses Python 'not' keyword. # If LambdaPrinter", "to make sure it gets 1 x n by n", "'))' ] return ''.join(result) class NumPyPrinter(LambdaPrinter): \"\"\" Numpy printer which", "be used with %s\" % expr.__class__.__name__) # blacklist all Matrix", "[] i = 0 for arg in expr.args: e =", "tuple\" # Print tuples here instead of lists because numba", "expr.args)) conds = '[{0}]'.format(','.join(self._print(arg.cond) for arg in expr.args)) # If", "LambdaPrinter because it uses Python 'or' keyword. # If LambdaPrinter", "because it uses Python 'and' keyword. # If LambdaPrinter didn't", "etc. \"\"\" _default_settings = { \"order\": \"none\", \"full_prec\": \"auto\", }", "expr.args)) def _print_DotProduct(self, expr): # DotProduct allows any shape order,", "'re' : 'real', 'where' : 'where', 'complex' : 'complex', 'contains'", "arg2 = arg2.T return \"dot(%s, %s)\" % (self._print(arg1), self._print(arg2)) def", "self._print_seq(e.args)) def blacklisted(self, expr): raise TypeError(\"numexpr cannot be used with", "printer: converts to tuple\" # Print tuples here instead of", "'asinh': 'arcsinh', 'acosh': 'arccosh', 'atanh': 'arctanh', 'ln' : 'log', 'log':", "than by populating a namespace. Thus a special printer... class", "python expressions _print_list = \\ _print_tuple = \\ _print_Tuple =", "expr.rel_op in op: lhs = self._print(expr.lhs) rhs = self._print(expr.rhs) return", "func_name = e.func.__name__ nstr = self._numexpr_functions.get(func_name, None) if nstr is", "behave the same as passing the 'default' kwarg to select()", "as passing the 'default' kwarg to select() # *as long", "_print_And(self, expr): result = ['('] for arg in sorted(expr.args, key=default_sort_key):", "expr): \"Logical Or printer\" # We have to override LambdaPrinter", ": 'log', 'log': 'log', 'exp': 'exp', 'sqrt' : 'sqrt', 'Abs'", "override LambdaPrinter because it uses Python 'or' keyword. # If", "'acos': 'arccos', 'atan': 'arctan', 'atan2' : 'arctan2', 'sinh' : 'sinh',", "= arg1.T if arg2.shape[1] != 1: arg2 = arg2.T return", "lstr = super(NumExprPrinter, self).doprint(expr) return \"evaluate('%s', truediv=True)\" % lstr def", "from sympy.utilities import default_sort_key class LambdaPrinter(StrPrinter): \"\"\" This printer converts", "self._print((expr.tolist()))) _print_SparseMatrix = \\ _print_MutableSparseMatrix = \\ _print_ImmutableSparseMatrix = \\", "result.append(') if (') result.append(self._print(c)) result.append(') else (') i += 1", "2)) return ''.join(result) def _print_Sum(self, expr): loops = ( 'for", "class NumExprPrinter(LambdaPrinter): # key, value pairs correspond to sympy name", "'sqrt', 'Abs' : 'abs', 'conjugate' : 'conj', 'im' : 'imag',", "NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_or', ','.join(self._print(i) for i in expr.args)) def _print_Not(self,", "i in expr.args)) def _print_DotProduct(self, expr): # DotProduct allows any", "_print_Min(self, expr): return '{0}(({1}))'.format('amin', ','.join(self._print(i) for i in expr.args)) def", ": 'cos', 'tan' : 'tan', 'asin': 'arcsin', 'acos': 'arccos', 'atan':", "lambdarepr(expr, **settings): \"\"\" Returns a string usable for lambdifying. \"\"\"", "printer... class NumExprPrinter(LambdaPrinter): # key, value pairs correspond to sympy", "= expr.args if arg1.shape[0] != 1: arg1 = arg1.T if", "define our # own because StrPrinter doesn't define it. return", "def _print_seq(self, seq, delimiter=', '): # simplified _print_seq taken from", "\\ _print_ImmutableSparseMatrix = \\ _print_Matrix = \\ _print_DenseMatrix = \\", "here instead of lists because numba supports # tuples in", "expr.args)) def _print_Min(self, expr): return '{0}(({1}))'.format('amin', ','.join(self._print(i) for i in", "'real', 'where' : 'where', 'complex' : 'complex', 'contains' : 'contains',", "printer\" # We have to override LambdaPrinter because it uses", "not the case, it may be triggered prematurely. return 'select({0},", "= 0 for arg in expr.args: e = arg.expr c", "'select({0}, {1}, default=nan)'.format(conds, exprs) def _print_Relational(self, expr): \"Relational printer for", "{1}, default=nan)'.format(conds, exprs) def _print_Relational(self, expr): \"Relational printer for Equality", "expr): lstr = super(NumExprPrinter, self).doprint(expr) return \"evaluate('%s', truediv=True)\" % lstr", "_print_MutableDenseMatrix = \\ _print_ImmutableMatrix = \\ _print_ImmutableDenseMatrix = \\ blacklisted", "super(NumExprPrinter, self).doprint(expr) return \"evaluate('%s', truediv=True)\" % lstr def lambdarepr(expr, **settings):", "''.join(result) def _print_Sum(self, expr): loops = ( 'for {i} in", "rhs=rhs) return super(NumPyPrinter, self)._print_Relational(expr) def _print_And(self, expr): \"Logical And printer\"", "['('] for arg in sorted(expr.args, key=default_sort_key): result.extend(['(', self._print(arg), ')']) result.append('", "'asin': 'arcsin', 'acos': 'arccos', 'atan': 'arctan', 'atan2' : 'arctan2', 'sinh'", "and Unequality\" op = { '==' :'equal', '!=' :'not_equal', '<'", "def doprint(self, expr): lstr = super(NumExprPrinter, self).doprint(expr) return \"evaluate('%s', truediv=True)\"", "'contains', } def _print_ImaginaryUnit(self, expr): return '1j' def _print_seq(self, seq,", "key=default_sort_key): result.extend(['(', self._print(arg), ')']) result.append(' or ') result = result[:-1]", "expr): \"Matrix multiplication printer\" return '({0})'.format(').dot('.join(self._print(i) for i in expr.args))", "the same as passing the 'default' kwarg to select() #", "functions, logical operators, etc. \"\"\" _default_settings = { \"order\": \"none\",", "return \"(%s)\" % self._print(e._imp_(*e.args)) else: raise TypeError(\"numexpr does not support", "printer which handles vectorized piecewise functions, logical operators, etc. \"\"\"", "= { 'sin' : 'sin', 'cos' : 'cos', 'tan' :", "') else (', self._print(expr.args[2]), '))' ] return ''.join(result) class NumPyPrinter(LambdaPrinter):", ": 'tan', 'asin': 'arcsin', 'acos': 'arccos', 'atan': 'arctan', 'atan2' :", "self._print(arg2)) def _print_Piecewise(self, expr): \"Piecewise function printer\" exprs = '[{0}]'.format(','.join(self._print(arg.expr)", "'default' kwarg to select() # *as long as* it is", "'log', 'exp': 'exp', 'sqrt' : 'sqrt', 'Abs' : 'abs', 'conjugate'", ": 'imag', 're' : 'real', 'where' : 'where', 'complex' :", "cond) sequence in a Piecewise object # it will behave", "_print_Max(self, expr): return '{0}(({1}))'.format('amax', ','.join(self._print(i) for i in expr.args)) #", "# If [default_value, True] is a (expr, cond) sequence in", "arg1.T if arg2.shape[1] != 1: arg2 = arg2.T return \"dot(%s,", "expr): return '{0}(({1}))'.format('amin', ','.join(self._print(i) for i in expr.args)) def _print_Max(self,", "_print_Or(self, expr): result = ['('] for arg in sorted(expr.args, key=default_sort_key):", "'[{0}]'.format(','.join(self._print(arg.expr) for arg in expr.args)) conds = '[{0}]'.format(','.join(self._print(arg.cond) for arg", "'{0}({1})'.format('logical_not', ','.join(self._print(i) for i in expr.args)) def _print_Min(self, expr): return", "') result = result[:-1] result.append(')') return ''.join(result) def _print_Not(self, expr):", "numexpr works by altering the string passed to numexpr.evaluate #", "correspond to sympy name and numexpr name # functions not", "result = result[:-1] result.append(')') return ''.join(result) def _print_Or(self, expr): result", "cannot be used with %s\" % expr.__class__.__name__) # blacklist all", "# own because StrPrinter doesn't define it. return '{0}({1})'.format('logical_not', ','.join(self._print(i)", "for i in expr.args)) def _print_Or(self, expr): \"Logical Or printer\"", "= [self._print(item) for item in seq] if s: return delimiter.join(s)", "return '(builtins.sum({function} {loops}))'.format( function=self._print(expr.function), loops=' '.join(loops)) def _print_And(self, expr): result", "pretty.py s = [self._print(item) for item in seq] if s:", "= \\ _print_Matrix = \\ _print_DenseMatrix = \\ _print_MutableDenseMatrix =", "= { '==' :'equal', '!=' :'not_equal', '<' :'less', '<=' :'less_equal',", "blacklisted(self, expr): raise TypeError(\"numexpr cannot be used with %s\" %", "'exp': 'exp', 'sqrt' : 'sqrt', 'Abs' : 'abs', 'conjugate' :", "add 'logical_and' to NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_and', ','.join(self._print(i) for i in", "'im' : 'imag', 're' : 'real', 'where' : 'where', 'complex'", "printer converts expressions into strings that can be used by", "1 result = result[:-1] result.append(') else None)') result.append(')'*(2*i - 2))", "'conj', 'im' : 'imag', 're' : 'real', 'where' : 'where',", "in sorted(expr.args, key=default_sort_key): result.extend(['(', self._print(arg), ')']) result.append(' or ') result", "_print_DotProduct(self, expr): # DotProduct allows any shape order, but numpy.dot", "# simplified _print_seq taken from pretty.py s = [self._print(item) for", "all Matrix printing _print_SparseMatrix = \\ _print_MutableSparseMatrix = \\ _print_ImmutableSparseMatrix", "\"Relational printer for Equality and Unequality\" op = { '=='", "(') result.append(self._print(c)) result.append(') else (') i += 1 result =", "self)._print_Relational(expr) def _print_And(self, expr): \"Logical And printer\" # We have", "= \\ _print_dict = \\ _print_Dict = \\ blacklisted def", "in range({a}, {b}+1)'.format( i=self._print(i), a=self._print(a), b=self._print(b)) for i, a, b", "numba supports # tuples in nopython mode. return '({},)'.format(delimiter.join(self._print(item) for", "\"Matrix multiplication printer\" return '({0})'.format(').dot('.join(self._print(i) for i in expr.args)) def", "it uses Python 'and' keyword. # If LambdaPrinter didn't define", "uses Python 'and' keyword. # If LambdaPrinter didn't define it,", "# If LambdaPrinter didn't define it, we would still have", "'sin', 'cos' : 'cos', 'tan' : 'tan', 'asin': 'arcsin', 'acos':", "expr): # DotProduct allows any shape order, but numpy.dot does", "division from .str import StrPrinter from sympy.utilities import default_sort_key class", "\"\"\" def _print_MatrixBase(self, expr): return \"%s(%s)\" % (expr.__class__.__name__, self._print((expr.tolist()))) _print_SparseMatrix", "because StrPrinter doesn't define it. return '{0}({1})'.format('logical_not', ','.join(self._print(i) for i", "a, b in expr.limits) return '(builtins.sum({function} {loops}))'.format( function=self._print(expr.function), loops=' '.join(loops))", "return '{0}({1})'.format('logical_or', ','.join(self._print(i) for i in expr.args)) def _print_Not(self, expr):", "self._print(e._imp_(*e.args)) else: raise TypeError(\"numexpr does not support function '%s'\" %", "if s: return delimiter.join(s) else: return \"\" def _print_Function(self, e):", "\"none\", \"full_prec\": \"auto\", } def _print_seq(self, seq, delimiter=', '): \"General", "StrPrinter's # version of the function and add 'logical_or' to", "a Piecewise object # it will behave the same as", "triggered prematurely. return 'select({0}, {1}, default=nan)'.format(conds, exprs) def _print_Relational(self, expr):", "= ( 'for {i} in range({a}, {b}+1)'.format( i=self._print(i), a=self._print(a), b=self._print(b))", "it uses Python 'or' keyword. # If LambdaPrinter didn't define", "for arg in expr.args)) conds = '[{0}]'.format(','.join(self._print(arg.cond) for arg in", "We have to override LambdaPrinter because it uses Python 'or'", "result.extend(['(', self._print(arg), ')']) result.append(' or ') result = result[:-1] result.append(')')", "b=self._print(b)) for i, a, b in expr.limits) return '(builtins.sum({function} {loops}))'.format(", "'({},)'.format(delimiter.join(self._print(item) for item in seq)) def _print_MatMul(self, expr): \"Matrix multiplication", "could use StrPrinter's # version of the function and add", "def _print_Function(self, e): func_name = e.func.__name__ nstr = self._numexpr_functions.get(func_name, None)", "function and add 'logical_and' to NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_and', ','.join(self._print(i) for", "hasattr(e, '_imp_'): return \"(%s)\" % self._print(e._imp_(*e.args)) else: raise TypeError(\"numexpr does", "if nstr is None: # check for implemented_function if hasattr(e,", "last element in expr.args. # If this is not the", "def _print_MatrixBase(self, expr): return \"%s(%s)\" % (expr.__class__.__name__, self._print((expr.tolist()))) _print_SparseMatrix =", "''.join(result) def _print_Or(self, expr): result = ['('] for arg in", "= \\ _print_ImmutableMatrix = \\ _print_ImmutableDenseMatrix = \\ _print_MatrixBase def", "seq)) def _print_MatMul(self, expr): \"Matrix multiplication printer\" return '({0})'.format(').dot('.join(self._print(i) for", "{b}+1)'.format( i=self._print(i), a=self._print(a), b=self._print(b)) for i, a, b in expr.limits)", "exprs = '[{0}]'.format(','.join(self._print(arg.expr) for arg in expr.args)) conds = '[{0}]'.format(','.join(self._print(arg.cond)", "taken from pretty.py s = [self._print(item) for item in seq]", "# numexpr works by altering the string passed to numexpr.evaluate", "function printer\" exprs = '[{0}]'.format(','.join(self._print(arg.expr) for arg in expr.args)) conds", "'1j' def _print_seq(self, seq, delimiter=', '): # simplified _print_seq taken", "\\ _print_ImmutableDenseMatrix = \\ blacklisted # blacklist some python expressions", "'cos' : 'cos', 'tan' : 'tan', 'asin': 'arcsin', 'acos': 'arccos',", "by populating a namespace. Thus a special printer... class NumExprPrinter(LambdaPrinter):", "for i in expr.args)) def _print_DotProduct(self, expr): # DotProduct allows", "operators, etc. \"\"\" _default_settings = { \"order\": \"none\", \"full_prec\": \"auto\",", ": 'abs', 'conjugate' : 'conj', 'im' : 'imag', 're' :", "if (') result.append(self._print(c)) result.append(') else (') i += 1 result", "= result[:-1] result.append(') else None)') result.append(')'*(2*i - 2)) return ''.join(result)", "default=nan)'.format(conds, exprs) def _print_Relational(self, expr): \"Relational printer for Equality and", "= \\ _print_Dict = \\ blacklisted def doprint(self, expr): lstr", "return delimiter.join(s) else: return \"\" def _print_Function(self, e): func_name =", "from .str import StrPrinter from sympy.utilities import default_sort_key class LambdaPrinter(StrPrinter):", "sure it gets 1 x n by n x 1.", "'or' keyword. # If LambdaPrinter didn't define it, we could", "TypeError(\"numexpr does not support function '%s'\" % func_name) return \"%s(%s)\"", "the 'default' kwarg to select() # *as long as* it", "the string passed to numexpr.evaluate # rather than by populating", "does matrix # multiplication, so we have to make sure", "def _print_And(self, expr): result = ['('] for arg in sorted(expr.args,", "'sinh' : 'sinh', 'cosh' : 'cosh', 'tanh' : 'tanh', 'asinh':", "'complex', 'contains' : 'contains', } def _print_ImaginaryUnit(self, expr): return '1j'", "'contains' : 'contains', } def _print_ImaginaryUnit(self, expr): return '1j' def", "and numexpr name # functions not appearing in this dict", "result = [] i = 0 for arg in expr.args:", "'>=' :'greater_equal', } if expr.rel_op in op: lhs = self._print(expr.lhs)", "LambdaPrinter didn't define it, we would still have to define", ": 'contains', } def _print_ImaginaryUnit(self, expr): return '1j' def _print_seq(self,", "in this dict will raise a TypeError _numexpr_functions = {", "expressions into strings that can be used by lambdify. \"\"\"", "(', self._print(expr.args[2]), '))' ] return ''.join(result) class NumPyPrinter(LambdaPrinter): \"\"\" Numpy", "simplified _print_seq taken from pretty.py s = [self._print(item) for item", "piecewise functions, logical operators, etc. \"\"\" _default_settings = { \"order\":", "# We have to override LambdaPrinter because it uses Python", "value pairs correspond to sympy name and numexpr name #", "i, a, b in expr.limits) return '(builtins.sum({function} {loops}))'.format( function=self._print(expr.function), loops='", "raise TypeError(\"numexpr cannot be used with %s\" % expr.__class__.__name__) #", "printing _print_SparseMatrix = \\ _print_MutableSparseMatrix = \\ _print_ImmutableSparseMatrix = \\", "return '({0})'.format(').dot('.join(self._print(i) for i in expr.args)) def _print_DotProduct(self, expr): #", "TypeError _numexpr_functions = { 'sin' : 'sin', 'cos' : 'cos',", "self._print(expr.args[0]), '))'] return ''.join(result) def _print_BooleanTrue(self, expr): return \"True\" def", "arg in sorted(expr.args, key=default_sort_key): result.extend(['(', self._print(arg), ')']) result.append(' or ')", "\"Logical Not printer\" # We have to override LambdaPrinter because", "= \\ _print_Tuple = \\ _print_dict = \\ _print_Dict =", "didn't define it, we would still have to define our", "n by n x 1. arg1, arg2 = expr.args if", "have to override LambdaPrinter because it uses Python 'and' keyword.", "_default_settings = { \"order\": \"none\", \"full_prec\": \"auto\", } def _print_seq(self,", "sorted(expr.args, key=default_sort_key): result.extend(['(', self._print(arg), ')']) result.append(' and ') result =", "for arg in expr.args)) # If [default_value, True] is a", "%s\" % expr.__class__.__name__) # blacklist all Matrix printing _print_SparseMatrix =", "add 'logical_or' to NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_or', ','.join(self._print(i) for i in", "') result = result[:-1] result.append(')') return ''.join(result) def _print_Or(self, expr):", "is the last element in expr.args. # If this is", "Python 'or' keyword. # If LambdaPrinter didn't define it, we", "= \\ _print_ImmutableDenseMatrix = \\ blacklisted # blacklist some python", "{ 'sin' : 'sin', 'cos' : 'cos', 'tan' : 'tan',", "if arg2.shape[1] != 1: arg2 = arg2.T return \"dot(%s, %s)\"", "# it will behave the same as passing the 'default'", "version of the function and add 'logical_and' to NUMPY_TRANSLATIONS. return", ": 'conj', 'im' : 'imag', 're' : 'real', 'where' :", "arg1, arg2 = expr.args if arg1.shape[0] != 1: arg1 =", "item in seq] if s: return delimiter.join(s) else: return \"\"", "\"%s(%s)\" % (nstr, self._print_seq(e.args)) def blacklisted(self, expr): raise TypeError(\"numexpr cannot", "# check for implemented_function if hasattr(e, '_imp_'): return \"(%s)\" %", "_print_Tuple = \\ _print_dict = \\ _print_Dict = \\ blacklisted", "_print_ImmutableDenseMatrix = \\ blacklisted # blacklist some python expressions _print_list", "sequence printer: converts to tuple\" # Print tuples here instead", "rhs = self._print(expr.rhs) return '{op}({lhs}, {rhs})'.format(op=op[expr.rel_op], lhs=lhs, rhs=rhs) return super(NumPyPrinter,", "for arg in expr.args: e = arg.expr c = arg.cond", "i in expr.args)) # numexpr works by altering the string", "from __future__ import print_function, division from .str import StrPrinter from", "arg2.shape[1] != 1: arg2 = arg2.T return \"dot(%s, %s)\" %", "b in expr.limits) return '(builtins.sum({function} {loops}))'.format( function=self._print(expr.function), loops=' '.join(loops)) def", "raise a TypeError _numexpr_functions = { 'sin' : 'sin', 'cos'", "= \\ _print_ImmutableDenseMatrix = \\ _print_MatrixBase def _print_Piecewise(self, expr): result", "_numexpr_functions = { 'sin' : 'sin', 'cos' : 'cos', 'tan'", "return ''.join(result) def _print_Not(self, expr): result = ['(', 'not (',", "keyword. # If LambdaPrinter didn't define it, we would still", "print_function, division from .str import StrPrinter from sympy.utilities import default_sort_key", "case, it may be triggered prematurely. return 'select({0}, {1}, default=nan)'.format(conds,", "expr): \"Logical And printer\" # We have to override LambdaPrinter", "'): # simplified _print_seq taken from pretty.py s = [self._print(item)", "doprint(self, expr): lstr = super(NumExprPrinter, self).doprint(expr) return \"evaluate('%s', truediv=True)\" %", "'{0}(({1}))'.format('amin', ','.join(self._print(i) for i in expr.args)) def _print_Max(self, expr): return", "support function '%s'\" % func_name) return \"%s(%s)\" % (nstr, self._print_seq(e.args))", "in expr.args)) # If [default_value, True] is a (expr, cond)", "lstr def lambdarepr(expr, **settings): \"\"\" Returns a string usable for", "own because StrPrinter doesn't define it. return '{0}({1})'.format('logical_not', ','.join(self._print(i) for", "\"\"\" Numpy printer which handles vectorized piecewise functions, logical operators,", "which handles vectorized piecewise functions, logical operators, etc. \"\"\" _default_settings", "super(NumPyPrinter, self)._print_Relational(expr) def _print_And(self, expr): \"Logical And printer\" # We", "TypeError(\"numexpr cannot be used with %s\" % expr.__class__.__name__) # blacklist", "Or printer\" # We have to override LambdaPrinter because it", "result.append(self._print(e)) result.append(') if (') result.append(self._print(c)) result.append(') else (') i +=", "this dict will raise a TypeError _numexpr_functions = { 'sin'", "expr): \"Logical Not printer\" # We have to override LambdaPrinter", "have to define our # own because StrPrinter doesn't define", "arg in expr.args)) # If [default_value, True] is a (expr,", "in expr.args: e = arg.expr c = arg.cond result.append('((') result.append(self._print(e))", "'): \"General sequence printer: converts to tuple\" # Print tuples", "in seq)) def _print_MatMul(self, expr): \"Matrix multiplication printer\" return '({0})'.format(').dot('.join(self._print(i)", "def _print_Not(self, expr): \"Logical Not printer\" # We have to", "function '%s'\" % func_name) return \"%s(%s)\" % (nstr, self._print_seq(e.args)) def", "multiplication printer\" return '({0})'.format(').dot('.join(self._print(i) for i in expr.args)) def _print_DotProduct(self,", "have to make sure it gets 1 x n by", "keyword. # If LambdaPrinter didn't define it, we could use", "'tanh', 'asinh': 'arcsinh', 'acosh': 'arccosh', 'atanh': 'arctanh', 'ln' : 'log',", "self._numexpr_functions.get(func_name, None) if nstr is None: # check for implemented_function", "= super(NumExprPrinter, self).doprint(expr) return \"evaluate('%s', truediv=True)\" % lstr def lambdarepr(expr,", "expr): result = ['('] for arg in sorted(expr.args, key=default_sort_key): result.extend(['(',", "seq, delimiter=', '): \"General sequence printer: converts to tuple\" #", "'arcsinh', 'acosh': 'arccosh', 'atanh': 'arctanh', 'ln' : 'log', 'log': 'log',", "expr.args)) def _print_Not(self, expr): \"Logical Not printer\" # We have", "= arg.expr c = arg.cond result.append('((') result.append(self._print(e)) result.append(') if (')", ": 'sin', 'cos' : 'cos', 'tan' : 'tan', 'asin': 'arcsin',", "return \"\" def _print_Function(self, e): func_name = e.func.__name__ nstr =", "% func_name) return \"%s(%s)\" % (nstr, self._print_seq(e.args)) def blacklisted(self, expr):", "self._print(arg), ')']) result.append(' and ') result = result[:-1] result.append(')') return", "expr): return \"True\" def _print_BooleanFalse(self, expr): return \"False\" def _print_ITE(self,", "check for implemented_function if hasattr(e, '_imp_'): return \"(%s)\" % self._print(e._imp_(*e.args))", "{rhs})'.format(op=op[expr.rel_op], lhs=lhs, rhs=rhs) return super(NumPyPrinter, self)._print_Relational(expr) def _print_And(self, expr): \"Logical", "[self._print(item) for item in seq] if s: return delimiter.join(s) else:", "= ['(', 'not (', self._print(expr.args[0]), '))'] return ''.join(result) def _print_BooleanTrue(self,", "_print_MutableSparseMatrix = \\ _print_ImmutableSparseMatrix = \\ _print_Matrix = \\ _print_DenseMatrix", "','.join(self._print(i) for i in expr.args)) def _print_Not(self, expr): \"Logical Not", "= self._print(expr.lhs) rhs = self._print(expr.rhs) return '{op}({lhs}, {rhs})'.format(op=op[expr.rel_op], lhs=lhs, rhs=rhs)", "_print_seq(self, seq, delimiter=', '): # simplified _print_seq taken from pretty.py", "'imag', 're' : 'real', 'where' : 'where', 'complex' : 'complex',", "'acosh': 'arccosh', 'atanh': 'arctanh', 'ln' : 'log', 'log': 'log', 'exp':", "by n x 1. arg1, arg2 = expr.args if arg1.shape[0]", "1 x n by n x 1. arg1, arg2 =", "i in expr.args)) def _print_Not(self, expr): \"Logical Not printer\" #", "'({0})'.format(').dot('.join(self._print(i) for i in expr.args)) def _print_DotProduct(self, expr): # DotProduct", "+= 1 result = result[:-1] result.append(') else None)') result.append(')'*(2*i -", "def _print_Relational(self, expr): \"Relational printer for Equality and Unequality\" op", "handles vectorized piecewise functions, logical operators, etc. \"\"\" _default_settings =", "delimiter=', '): \"General sequence printer: converts to tuple\" # Print", "kwarg to select() # *as long as* it is the", "i in expr.args)) def _print_Max(self, expr): return '{0}(({1}))'.format('amax', ','.join(self._print(i) for", "'tan' : 'tan', 'asin': 'arcsin', 'acos': 'arccos', 'atan': 'arctan', 'atan2'", "\\ _print_DenseMatrix = \\ _print_MutableDenseMatrix = \\ _print_ImmutableMatrix = \\", "'arctan2', 'sinh' : 'sinh', 'cosh' : 'cosh', 'tanh' : 'tanh',", "sequence in a Piecewise object # it will behave the", "it uses Python 'not' keyword. # If LambdaPrinter didn't define", "in seq] if s: return delimiter.join(s) else: return \"\" def", "} def _print_seq(self, seq, delimiter=', '): \"General sequence printer: converts", "*as long as* it is the last element in expr.args.", "_print_list = \\ _print_tuple = \\ _print_Tuple = \\ _print_dict", "to override LambdaPrinter because it uses Python 'not' keyword. #", "# blacklist some python expressions _print_list = \\ _print_tuple =", "sympy name and numexpr name # functions not appearing in", "in expr.args. # If this is not the case, it", "{i} in range({a}, {b}+1)'.format( i=self._print(i), a=self._print(a), b=self._print(b)) for i, a,", "- 2)) return ''.join(result) def _print_Sum(self, expr): loops = (", "def _print_Min(self, expr): return '{0}(({1}))'.format('amin', ','.join(self._print(i) for i in expr.args))", "\"General sequence printer: converts to tuple\" # Print tuples here", "lambdify. \"\"\" def _print_MatrixBase(self, expr): return \"%s(%s)\" % (expr.__class__.__name__, self._print((expr.tolist())))", "return super(NumPyPrinter, self)._print_Relational(expr) def _print_And(self, expr): \"Logical And printer\" #", "'and' keyword. # If LambdaPrinter didn't define it, we could", "raise TypeError(\"numexpr does not support function '%s'\" % func_name) return", "_print_dict = \\ _print_Dict = \\ blacklisted def doprint(self, expr):", "to override LambdaPrinter because it uses Python 'or' keyword. #", "Unequality\" op = { '==' :'equal', '!=' :'not_equal', '<' :'less',", "long as* it is the last element in expr.args. #", "return \"False\" def _print_ITE(self, expr): result = [ '((', self._print(expr.args[1]),", "in expr.args)) # numexpr works by altering the string passed", "return '{op}({lhs}, {rhs})'.format(op=op[expr.rel_op], lhs=lhs, rhs=rhs) return super(NumPyPrinter, self)._print_Relational(expr) def _print_And(self,", "'((', self._print(expr.args[1]), ') if (', self._print(expr.args[0]), ') else (', self._print(expr.args[2]),", "expr): result = [] i = 0 for arg in", "')']) result.append(' or ') result = result[:-1] result.append(')') return ''.join(result)", "in expr.args)) def _print_Not(self, expr): \"Logical Not printer\" # We", "_print_ImaginaryUnit(self, expr): return '1j' def _print_seq(self, seq, delimiter=', '): #", "converts expressions into strings that can be used by lambdify.", "expr.limits) return '(builtins.sum({function} {loops}))'.format( function=self._print(expr.function), loops=' '.join(loops)) def _print_And(self, expr):", "= '[{0}]'.format(','.join(self._print(arg.cond) for arg in expr.args)) # If [default_value, True]", "expr): return \"False\" def _print_ITE(self, expr): result = [ '((',", "delimiter.join(s) else: return \"\" def _print_Function(self, e): func_name = e.func.__name__", "blacklist all Matrix printing _print_SparseMatrix = \\ _print_MutableSparseMatrix = \\", "to tuple\" # Print tuples here instead of lists because", "for i, a, b in expr.limits) return '(builtins.sum({function} {loops}))'.format( function=self._print(expr.function),", "% (self._print(arg1), self._print(arg2)) def _print_Piecewise(self, expr): \"Piecewise function printer\" exprs", "# version of the function and add 'logical_and' to NUMPY_TRANSLATIONS.", "LambdaPrinter didn't define it, we could use StrPrinter's # version", "= ['('] for arg in sorted(expr.args, key=default_sort_key): result.extend(['(', self._print(arg), ')'])", "'logical_or' to NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_or', ','.join(self._print(i) for i in expr.args))", "'not' keyword. # If LambdaPrinter didn't define it, we would", "] return ''.join(result) class NumPyPrinter(LambdaPrinter): \"\"\" Numpy printer which handles", "to select() # *as long as* it is the last", "StrPrinter doesn't define it. return '{0}({1})'.format('logical_not', ','.join(self._print(i) for i in", "_print_MutableDenseMatrix = \\ _print_ImmutableMatrix = \\ _print_ImmutableDenseMatrix = \\ _print_MatrixBase", "<filename>sympy/printing/lambdarepr.py from __future__ import print_function, division from .str import StrPrinter", "the last element in expr.args. # If this is not", "_print_Sum(self, expr): loops = ( 'for {i} in range({a}, {b}+1)'.format(", "= { \"order\": \"none\", \"full_prec\": \"auto\", } def _print_seq(self, seq,", "dict will raise a TypeError _numexpr_functions = { 'sin' :", "'cosh' : 'cosh', 'tanh' : 'tanh', 'asinh': 'arcsinh', 'acosh': 'arccosh',", "_print_Not(self, expr): \"Logical Not printer\" # We have to override", "'_imp_'): return \"(%s)\" % self._print(e._imp_(*e.args)) else: raise TypeError(\"numexpr does not", "} def _print_ImaginaryUnit(self, expr): return '1j' def _print_seq(self, seq, delimiter=',", "result = result[:-1] result.append(')') return ''.join(result) def _print_Not(self, expr): result", "works by altering the string passed to numexpr.evaluate # rather", "our # own because StrPrinter doesn't define it. return '{0}({1})'.format('logical_not',", "mode. return '({},)'.format(delimiter.join(self._print(item) for item in seq)) def _print_MatMul(self, expr):", "item in seq)) def _print_MatMul(self, expr): \"Matrix multiplication printer\" return", "numexpr.evaluate # rather than by populating a namespace. Thus a", "arg in sorted(expr.args, key=default_sort_key): result.extend(['(', self._print(arg), ')']) result.append(' and ')", "select() # *as long as* it is the last element", "result = [ '((', self._print(expr.args[1]), ') if (', self._print(expr.args[0]), ')", "''.join(result) class NumPyPrinter(LambdaPrinter): \"\"\" Numpy printer which handles vectorized piecewise", "','.join(self._print(i) for i in expr.args)) def _print_Or(self, expr): \"Logical Or", "still have to define our # own because StrPrinter doesn't", "'sin' : 'sin', 'cos' : 'cos', 'tan' : 'tan', 'asin':", "'Abs' : 'abs', 'conjugate' : 'conj', 'im' : 'imag', 're'", "# tuples in nopython mode. return '({},)'.format(delimiter.join(self._print(item) for item in", "# multiplication, so we have to make sure it gets", "_print_ImmutableMatrix = \\ _print_ImmutableDenseMatrix = \\ blacklisted # blacklist some", ":'not_equal', '<' :'less', '<=' :'less_equal', '>' :'greater', '>=' :'greater_equal', }", ": 'tanh', 'asinh': 'arcsinh', 'acosh': 'arccosh', 'atanh': 'arctanh', 'ln' :", "'exp', 'sqrt' : 'sqrt', 'Abs' : 'abs', 'conjugate' : 'conj',", "# blacklist all Matrix printing _print_SparseMatrix = \\ _print_MutableSparseMatrix =", "return '{0}({1})'.format('logical_and', ','.join(self._print(i) for i in expr.args)) def _print_Or(self, expr):", "can be used by lambdify. \"\"\" def _print_MatrixBase(self, expr): return", "i=self._print(i), a=self._print(a), b=self._print(b)) for i, a, b in expr.limits) return", "return ''.join(result) class NumPyPrinter(LambdaPrinter): \"\"\" Numpy printer which handles vectorized", "Piecewise object # it will behave the same as passing", "1: arg2 = arg2.T return \"dot(%s, %s)\" % (self._print(arg1), self._print(arg2))", "i in expr.args)) def _print_Min(self, expr): return '{0}(({1}))'.format('amin', ','.join(self._print(i) for", "expr.args)) def _print_Max(self, expr): return '{0}(({1}))'.format('amax', ','.join(self._print(i) for i in", "\\ blacklisted def doprint(self, expr): lstr = super(NumExprPrinter, self).doprint(expr) return", "a (expr, cond) sequence in a Piecewise object # it", "if (', self._print(expr.args[0]), ') else (', self._print(expr.args[2]), '))' ] return", "= \\ _print_ImmutableMatrix = \\ _print_ImmutableDenseMatrix = \\ blacklisted #", "# If LambdaPrinter didn't define it, we could use StrPrinter's", "self).doprint(expr) return \"evaluate('%s', truediv=True)\" % lstr def lambdarepr(expr, **settings): \"\"\"", "return \"evaluate('%s', truediv=True)\" % lstr def lambdarepr(expr, **settings): \"\"\" Returns", "'))'] return ''.join(result) def _print_BooleanTrue(self, expr): return \"True\" def _print_BooleanFalse(self,", "(', self._print(expr.args[0]), ') else (', self._print(expr.args[2]), '))' ] return ''.join(result)", "Python 'not' keyword. # If LambdaPrinter didn't define it, we", ": 'complex', 'contains' : 'contains', } def _print_ImaginaryUnit(self, expr): return", "lhs = self._print(expr.lhs) rhs = self._print(expr.rhs) return '{op}({lhs}, {rhs})'.format(op=op[expr.rel_op], lhs=lhs,", "'<=' :'less_equal', '>' :'greater', '>=' :'greater_equal', } if expr.rel_op in", "expr.args: e = arg.expr c = arg.cond result.append('((') result.append(self._print(e)) result.append(')", "_print_Relational(self, expr): \"Relational printer for Equality and Unequality\" op =", "def _print_Piecewise(self, expr): result = [] i = 0 for", "\"auto\", } def _print_seq(self, seq, delimiter=', '): \"General sequence printer:", "return \"dot(%s, %s)\" % (self._print(arg1), self._print(arg2)) def _print_Piecewise(self, expr): \"Piecewise", "\\ blacklisted # blacklist some python expressions _print_list = \\", "return ''.join(result) def _print_Sum(self, expr): loops = ( 'for {i}", "# If this is not the case, it may be", "expr): \"Relational printer for Equality and Unequality\" op = {", "NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_and', ','.join(self._print(i) for i in expr.args)) def _print_Or(self,", "import print_function, division from .str import StrPrinter from sympy.utilities import", "arg in expr.args: e = arg.expr c = arg.cond result.append('((')", "'log': 'log', 'exp': 'exp', 'sqrt' : 'sqrt', 'Abs' : 'abs',", "the function and add 'logical_and' to NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_and', ','.join(self._print(i)", "used by lambdify. \"\"\" def _print_MatrixBase(self, expr): return \"%s(%s)\" %", "def lambdarepr(expr, **settings): \"\"\" Returns a string usable for lambdifying.", "matrix # multiplication, so we have to make sure it", "Python 'and' keyword. # If LambdaPrinter didn't define it, we", "expr): result = [ '((', self._print(expr.args[1]), ') if (', self._print(expr.args[0]),", "by lambdify. \"\"\" def _print_MatrixBase(self, expr): return \"%s(%s)\" % (expr.__class__.__name__,", "_print_seq(self, seq, delimiter=', '): \"General sequence printer: converts to tuple\"", "i += 1 result = result[:-1] result.append(') else None)') result.append(')'*(2*i", "to override LambdaPrinter because it uses Python 'and' keyword. #", "Thus a special printer... class NumExprPrinter(LambdaPrinter): # key, value pairs", "1. arg1, arg2 = expr.args if arg1.shape[0] != 1: arg1", "\"\"\" Returns a string usable for lambdifying. \"\"\" return LambdaPrinter(settings).doprint(expr)", "result[:-1] result.append(') else None)') result.append(')'*(2*i - 2)) return ''.join(result) def", "blacklisted # blacklist some python expressions _print_list = \\ _print_tuple", "to sympy name and numexpr name # functions not appearing", "expr): return '{0}(({1}))'.format('amax', ','.join(self._print(i) for i in expr.args)) # numexpr", "it. return '{0}({1})'.format('logical_not', ','.join(self._print(i) for i in expr.args)) def _print_Min(self,", ": 'sqrt', 'Abs' : 'abs', 'conjugate' : 'conj', 'im' :", "'arctanh', 'ln' : 'log', 'log': 'log', 'exp': 'exp', 'sqrt' :", "return '{0}({1})'.format('logical_not', ','.join(self._print(i) for i in expr.args)) def _print_Min(self, expr):", "populating a namespace. Thus a special printer... class NumExprPrinter(LambdaPrinter): #", "StrPrinter from sympy.utilities import default_sort_key class LambdaPrinter(StrPrinter): \"\"\" This printer", "expr): return '1j' def _print_seq(self, seq, delimiter=', '): # simplified", "result.append(')') return ''.join(result) def _print_Not(self, expr): result = ['(', 'not", "self._print(arg), ')']) result.append(' or ') result = result[:-1] result.append(')') return", "use StrPrinter's # version of the function and add 'logical_and'", ": 'real', 'where' : 'where', 'complex' : 'complex', 'contains' :", "self._print(expr.rhs) return '{op}({lhs}, {rhs})'.format(op=op[expr.rel_op], lhs=lhs, rhs=rhs) return super(NumPyPrinter, self)._print_Relational(expr) def", "define it. return '{0}({1})'.format('logical_not', ','.join(self._print(i) for i in expr.args)) def", "will raise a TypeError _numexpr_functions = { 'sin' : 'sin',", "'arccosh', 'atanh': 'arctanh', 'ln' : 'log', 'log': 'log', 'exp': 'exp',", "\"Piecewise function printer\" exprs = '[{0}]'.format(','.join(self._print(arg.expr) for arg in expr.args))", "{loops}))'.format( function=self._print(expr.function), loops=' '.join(loops)) def _print_And(self, expr): result = ['(']", "expr): loops = ( 'for {i} in range({a}, {b}+1)'.format( i=self._print(i),", "some python expressions _print_list = \\ _print_tuple = \\ _print_Tuple", "have to override LambdaPrinter because it uses Python 'or' keyword.", "\"\"\" This printer converts expressions into strings that can be", "'<' :'less', '<=' :'less_equal', '>' :'greater', '>=' :'greater_equal', } if", "self._print(expr.args[2]), '))' ] return ''.join(result) class NumPyPrinter(LambdaPrinter): \"\"\" Numpy printer", "allows any shape order, but numpy.dot does matrix # multiplication,", "DotProduct allows any shape order, but numpy.dot does matrix #", "result.append(')') return ''.join(result) def _print_Or(self, expr): result = ['('] for", "(', self._print(expr.args[0]), '))'] return ''.join(result) def _print_BooleanTrue(self, expr): return \"True\"", "and add 'logical_or' to NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_or', ','.join(self._print(i) for i", "If LambdaPrinter didn't define it, we would still have to", ":'equal', '!=' :'not_equal', '<' :'less', '<=' :'less_equal', '>' :'greater', '>='", "lists because numba supports # tuples in nopython mode. return", ": 'sinh', 'cosh' : 'cosh', 'tanh' : 'tanh', 'asinh': 'arcsinh',", "for item in seq] if s: return delimiter.join(s) else: return", "''.join(result) def _print_BooleanTrue(self, expr): return \"True\" def _print_BooleanFalse(self, expr): return", "','.join(self._print(i) for i in expr.args)) def _print_Min(self, expr): return '{0}(({1}))'.format('amin',", "in expr.args)) def _print_Min(self, expr): return '{0}(({1}))'.format('amin', ','.join(self._print(i) for i", "import StrPrinter from sympy.utilities import default_sort_key class LambdaPrinter(StrPrinter): \"\"\" This", "use StrPrinter's # version of the function and add 'logical_or'", "_print_Not(self, expr): result = ['(', 'not (', self._print(expr.args[0]), '))'] return", "doesn't define it. return '{0}({1})'.format('logical_not', ','.join(self._print(i) for i in expr.args))", "= \\ blacklisted def doprint(self, expr): lstr = super(NumExprPrinter, self).doprint(expr)", "def _print_Sum(self, expr): loops = ( 'for {i} in range({a},", "of the function and add 'logical_and' to NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_and',", "# key, value pairs correspond to sympy name and numexpr", "'>' :'greater', '>=' :'greater_equal', } if expr.rel_op in op: lhs", "'cosh', 'tanh' : 'tanh', 'asinh': 'arcsinh', 'acosh': 'arccosh', 'atanh': 'arctanh',", "def blacklisted(self, expr): raise TypeError(\"numexpr cannot be used with %s\"", "is a (expr, cond) sequence in a Piecewise object #", "function=self._print(expr.function), loops=' '.join(loops)) def _print_And(self, expr): result = ['('] for", "return ''.join(result) def _print_BooleanTrue(self, expr): return \"True\" def _print_BooleanFalse(self, expr):", "{ \"order\": \"none\", \"full_prec\": \"auto\", } def _print_seq(self, seq, delimiter=',", "'arctan', 'atan2' : 'arctan2', 'sinh' : 'sinh', 'cosh' : 'cosh',", "lhs=lhs, rhs=rhs) return super(NumPyPrinter, self)._print_Relational(expr) def _print_And(self, expr): \"Logical And", "else (', self._print(expr.args[2]), '))' ] return ''.join(result) class NumPyPrinter(LambdaPrinter): \"\"\"", "\"evaluate('%s', truediv=True)\" % lstr def lambdarepr(expr, **settings): \"\"\" Returns a", "% (expr.__class__.__name__, self._print((expr.tolist()))) _print_SparseMatrix = \\ _print_MutableSparseMatrix = \\ _print_ImmutableSparseMatrix", "_print_Function(self, e): func_name = e.func.__name__ nstr = self._numexpr_functions.get(func_name, None) if", "to NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_or', ','.join(self._print(i) for i in expr.args)) def", "special printer... class NumExprPrinter(LambdaPrinter): # key, value pairs correspond to", "[default_value, True] is a (expr, cond) sequence in a Piecewise", "would still have to define our # own because StrPrinter", "the function and add 'logical_or' to NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_or', ','.join(self._print(i)", "\\ _print_Tuple = \\ _print_dict = \\ _print_Dict = \\", "\"%s(%s)\" % (expr.__class__.__name__, self._print((expr.tolist()))) _print_SparseMatrix = \\ _print_MutableSparseMatrix = \\", "_print_Dict = \\ blacklisted def doprint(self, expr): lstr = super(NumExprPrinter,", "# *as long as* it is the last element in", "x n by n x 1. arg1, arg2 = expr.args", "exprs) def _print_Relational(self, expr): \"Relational printer for Equality and Unequality\"", "a TypeError _numexpr_functions = { 'sin' : 'sin', 'cos' :", "'log', 'log': 'log', 'exp': 'exp', 'sqrt' : 'sqrt', 'Abs' :", "loops=' '.join(loops)) def _print_And(self, expr): result = ['('] for arg", "def _print_Or(self, expr): \"Logical Or printer\" # We have to", "nstr is None: # check for implemented_function if hasattr(e, '_imp_'):", "'sqrt' : 'sqrt', 'Abs' : 'abs', 'conjugate' : 'conj', 'im'", "!= 1: arg1 = arg1.T if arg2.shape[1] != 1: arg2", "1: arg1 = arg1.T if arg2.shape[1] != 1: arg2 =", "'ln' : 'log', 'log': 'log', 'exp': 'exp', 'sqrt' : 'sqrt',", "n x 1. arg1, arg2 = expr.args if arg1.shape[0] !=", "return \"%s(%s)\" % (expr.__class__.__name__, self._print((expr.tolist()))) _print_SparseMatrix = \\ _print_MutableSparseMatrix =", "i in expr.args)) def _print_Or(self, expr): \"Logical Or printer\" #", "class LambdaPrinter(StrPrinter): \"\"\" This printer converts expressions into strings that", "= result[:-1] result.append(')') return ''.join(result) def _print_Or(self, expr): result =", "nstr = self._numexpr_functions.get(func_name, None) if nstr is None: # check", "arg2 = expr.args if arg1.shape[0] != 1: arg1 = arg1.T", "gets 1 x n by n x 1. arg1, arg2", "= arg.cond result.append('((') result.append(self._print(e)) result.append(') if (') result.append(self._print(c)) result.append(') else", "def _print_DotProduct(self, expr): # DotProduct allows any shape order, but", "expr.args)) # numexpr works by altering the string passed to", "it gets 1 x n by n x 1. arg1,", "uses Python 'not' keyword. # If LambdaPrinter didn't define it,", "'[{0}]'.format(','.join(self._print(arg.cond) for arg in expr.args)) # If [default_value, True] is", "self._print(expr.lhs) rhs = self._print(expr.rhs) return '{op}({lhs}, {rhs})'.format(op=op[expr.rel_op], lhs=lhs, rhs=rhs) return", "If this is not the case, it may be triggered", "= arg2.T return \"dot(%s, %s)\" % (self._print(arg1), self._print(arg2)) def _print_Piecewise(self,", "in expr.args)) def _print_Max(self, expr): return '{0}(({1}))'.format('amax', ','.join(self._print(i) for i", "'atan2' : 'arctan2', 'sinh' : 'sinh', 'cosh' : 'cosh', 'tanh'", "if expr.rel_op in op: lhs = self._print(expr.lhs) rhs = self._print(expr.rhs)", "\\ _print_ImmutableDenseMatrix = \\ _print_MatrixBase def _print_Piecewise(self, expr): result =", ":'less_equal', '>' :'greater', '>=' :'greater_equal', } if expr.rel_op in op:", "If [default_value, True] is a (expr, cond) sequence in a", "expr.args)) # If [default_value, True] is a (expr, cond) sequence", "else: return \"\" def _print_Function(self, e): func_name = e.func.__name__ nstr", "NumPyPrinter(LambdaPrinter): \"\"\" Numpy printer which handles vectorized piecewise functions, logical", "we have to make sure it gets 1 x n", "in a Piecewise object # it will behave the same", "same as passing the 'default' kwarg to select() # *as", "op: lhs = self._print(expr.lhs) rhs = self._print(expr.rhs) return '{op}({lhs}, {rhs})'.format(op=op[expr.rel_op],", "uses Python 'or' keyword. # If LambdaPrinter didn't define it,", "conds = '[{0}]'.format(','.join(self._print(arg.cond) for arg in expr.args)) # If [default_value,", "from pretty.py s = [self._print(item) for item in seq] if", "of lists because numba supports # tuples in nopython mode.", "in sorted(expr.args, key=default_sort_key): result.extend(['(', self._print(arg), ')']) result.append(' and ') result", "name # functions not appearing in this dict will raise", "None) if nstr is None: # check for implemented_function if", "a namespace. Thus a special printer... class NumExprPrinter(LambdaPrinter): # key,", "for arg in sorted(expr.args, key=default_sort_key): result.extend(['(', self._print(arg), ')']) result.append(' and", "e = arg.expr c = arg.cond result.append('((') result.append(self._print(e)) result.append(') if", "'complex' : 'complex', 'contains' : 'contains', } def _print_ImaginaryUnit(self, expr):", "key, value pairs correspond to sympy name and numexpr name", "we would still have to define our # own because", "expr): result = ['(', 'not (', self._print(expr.args[0]), '))'] return ''.join(result)", "Print tuples here instead of lists because numba supports #", "= e.func.__name__ nstr = self._numexpr_functions.get(func_name, None) if nstr is None:", "'not (', self._print(expr.args[0]), '))'] return ''.join(result) def _print_BooleanTrue(self, expr): return", "but numpy.dot does matrix # multiplication, so we have to", "to numexpr.evaluate # rather than by populating a namespace. Thus", "= \\ _print_tuple = \\ _print_Tuple = \\ _print_dict =", "self._print(expr.args[0]), ') else (', self._print(expr.args[2]), '))' ] return ''.join(result) class", "expr.args)) def _print_Or(self, expr): \"Logical Or printer\" # We have", "\"order\": \"none\", \"full_prec\": \"auto\", } def _print_seq(self, seq, delimiter=', '):", "expr): raise TypeError(\"numexpr cannot be used with %s\" % expr.__class__.__name__)", "['(', 'not (', self._print(expr.args[0]), '))'] return ''.join(result) def _print_BooleanTrue(self, expr):", "with %s\" % expr.__class__.__name__) # blacklist all Matrix printing _print_SparseMatrix", "','.join(self._print(i) for i in expr.args)) def _print_Max(self, expr): return '{0}(({1}))'.format('amax',", "NumExprPrinter(LambdaPrinter): # key, value pairs correspond to sympy name and", "\\ _print_tuple = \\ _print_Tuple = \\ _print_dict = \\", ":'greater', '>=' :'greater_equal', } if expr.rel_op in op: lhs =", "because it uses Python 'or' keyword. # If LambdaPrinter didn't", "_print_MatrixBase def _print_Piecewise(self, expr): result = [] i = 0", "else (') i += 1 result = result[:-1] result.append(') else", "LambdaPrinter because it uses Python 'and' keyword. # If LambdaPrinter", "that can be used by lambdify. \"\"\" def _print_MatrixBase(self, expr):", "'!=' :'not_equal', '<' :'less', '<=' :'less_equal', '>' :'greater', '>=' :'greater_equal',", "for i in expr.args)) # numexpr works by altering the", "a=self._print(a), b=self._print(b)) for i, a, b in expr.limits) return '(builtins.sum({function}", "supports # tuples in nopython mode. return '({},)'.format(delimiter.join(self._print(item) for item", "= self._print(expr.rhs) return '{op}({lhs}, {rhs})'.format(op=op[expr.rel_op], lhs=lhs, rhs=rhs) return super(NumPyPrinter, self)._print_Relational(expr)", "= \\ _print_MutableDenseMatrix = \\ _print_ImmutableMatrix = \\ _print_ImmutableDenseMatrix =", "else None)') result.append(')'*(2*i - 2)) return ''.join(result) def _print_Sum(self, expr):", "'for {i} in range({a}, {b}+1)'.format( i=self._print(i), a=self._print(a), b=self._print(b)) for i,", "[ '((', self._print(expr.args[1]), ') if (', self._print(expr.args[0]), ') else (',", "for implemented_function if hasattr(e, '_imp_'): return \"(%s)\" % self._print(e._imp_(*e.args)) else:", "result.append(') else (') i += 1 result = result[:-1] result.append(')", "Not printer\" # We have to override LambdaPrinter because it", "op = { '==' :'equal', '!=' :'not_equal', '<' :'less', '<='", "We have to override LambdaPrinter because it uses Python 'not'", "= \\ _print_DenseMatrix = \\ _print_MutableDenseMatrix = \\ _print_ImmutableMatrix =", "in nopython mode. return '({},)'.format(delimiter.join(self._print(item) for item in seq)) def", "_print_MatrixBase(self, expr): return \"%s(%s)\" % (expr.__class__.__name__, self._print((expr.tolist()))) _print_SparseMatrix = \\", "_print_ImmutableSparseMatrix = \\ _print_Matrix = \\ _print_DenseMatrix = \\ _print_MutableDenseMatrix", "range({a}, {b}+1)'.format( i=self._print(i), a=self._print(a), b=self._print(b)) for i, a, b in", "def _print_Piecewise(self, expr): \"Piecewise function printer\" exprs = '[{0}]'.format(','.join(self._print(arg.expr) for", "will behave the same as passing the 'default' kwarg to", "pairs correspond to sympy name and numexpr name # functions", "'tan', 'asin': 'arcsin', 'acos': 'arccos', 'atan': 'arctan', 'atan2' : 'arctan2',", "expressions _print_list = \\ _print_tuple = \\ _print_Tuple = \\", "# DotProduct allows any shape order, but numpy.dot does matrix", "= \\ blacklisted # blacklist some python expressions _print_list =", "arg in expr.args)) conds = '[{0}]'.format(','.join(self._print(arg.cond) for arg in expr.args))", "object # it will behave the same as passing the", "it, we would still have to define our # own", "This printer converts expressions into strings that can be used", "arg.cond result.append('((') result.append(self._print(e)) result.append(') if (') result.append(self._print(c)) result.append(') else (')", "And printer\" # We have to override LambdaPrinter because it", "def _print_seq(self, seq, delimiter=', '): \"General sequence printer: converts to", "'logical_and' to NUMPY_TRANSLATIONS. return '{0}({1})'.format('logical_and', ','.join(self._print(i) for i in expr.args))", "element in expr.args. # If this is not the case,", "= \\ _print_ImmutableSparseMatrix = \\ _print_Matrix = \\ _print_DenseMatrix =", "expr.args if arg1.shape[0] != 1: arg1 = arg1.T if arg2.shape[1]", "name and numexpr name # functions not appearing in this", "not appearing in this dict will raise a TypeError _numexpr_functions", "'abs', 'conjugate' : 'conj', 'im' : 'imag', 're' : 'real',", "(nstr, self._print_seq(e.args)) def blacklisted(self, expr): raise TypeError(\"numexpr cannot be used", "expr.__class__.__name__) # blacklist all Matrix printing _print_SparseMatrix = \\ _print_MutableSparseMatrix", "e.func.__name__ nstr = self._numexpr_functions.get(func_name, None) if nstr is None: #", "expr): \"Piecewise function printer\" exprs = '[{0}]'.format(','.join(self._print(arg.expr) for arg in", "override LambdaPrinter because it uses Python 'not' keyword. # If", "\"full_prec\": \"auto\", } def _print_seq(self, seq, delimiter=', '): \"General sequence", "# rather than by populating a namespace. Thus a special", "printer\" exprs = '[{0}]'.format(','.join(self._print(arg.expr) for arg in expr.args)) conds =", "for i in expr.args)) def _print_Min(self, expr): return '{0}(({1}))'.format('amin', ','.join(self._print(i)", "None)') result.append(')'*(2*i - 2)) return ''.join(result) def _print_Sum(self, expr): loops", "# version of the function and add 'logical_or' to NUMPY_TRANSLATIONS.", "} if expr.rel_op in op: lhs = self._print(expr.lhs) rhs =", "result.extend(['(', self._print(arg), ')']) result.append(' and ') result = result[:-1] result.append(')')", "string passed to numexpr.evaluate # rather than by populating a", "self._print(expr.args[1]), ') if (', self._print(expr.args[0]), ') else (', self._print(expr.args[2]), '))'", "\"False\" def _print_ITE(self, expr): result = [ '((', self._print(expr.args[1]), ')", "in expr.args)) def _print_Or(self, expr): \"Logical Or printer\" # We", "_print_ITE(self, expr): result = [ '((', self._print(expr.args[1]), ') if (',", "printer\" return '({0})'.format(').dot('.join(self._print(i) for i in expr.args)) def _print_DotProduct(self, expr):", "i = 0 for arg in expr.args: e = arg.expr", "% (nstr, self._print_seq(e.args)) def blacklisted(self, expr): raise TypeError(\"numexpr cannot be", "return \"True\" def _print_BooleanFalse(self, expr): return \"False\" def _print_ITE(self, expr):", "\\ _print_Matrix = \\ _print_DenseMatrix = \\ _print_MutableDenseMatrix = \\", "delimiter=', '): # simplified _print_seq taken from pretty.py s =", "'.join(loops)) def _print_And(self, expr): result = ['('] for arg in", "def _print_MatMul(self, expr): \"Matrix multiplication printer\" return '({0})'.format(').dot('.join(self._print(i) for i", "def _print_And(self, expr): \"Logical And printer\" # We have to", "\\ _print_MatrixBase def _print_Piecewise(self, expr): result = [] i =", "arg1 = arg1.T if arg2.shape[1] != 1: arg2 = arg2.T", "def _print_BooleanFalse(self, expr): return \"False\" def _print_ITE(self, expr): result =", "\"Logical And printer\" # We have to override LambdaPrinter because", "_print_BooleanTrue(self, expr): return \"True\" def _print_BooleanFalse(self, expr): return \"False\" def", "make sure it gets 1 x n by n x", ".str import StrPrinter from sympy.utilities import default_sort_key class LambdaPrinter(StrPrinter): \"\"\"", "\"\"\" _default_settings = { \"order\": \"none\", \"full_prec\": \"auto\", } def", "= result[:-1] result.append(')') return ''.join(result) def _print_Not(self, expr): result =" ]
[ "'business_id': 0, 'user_id': 0, 'postal_code': 0}: df_col = df[col].values na", "import datetime import re from collections import Counter from statistics", "\"\"\" import numpy as np import pandas as pd import", "if pd.isna(element): return np.nan elif isinstance(element, np.double): array = np.array(element_list)", "tqdm def find_most_common_value(element_list): for element in element_list: if not pd.isna(element):", "time import matplotlib.pyplot as plt from datetime import datetime import", "datetime import re from collections import Counter from statistics import", "np.array(element_list) array = array[~np.isnan(array)] if len(array) == 0: return np.nan", "= pd.read_pickle(file) categories = list(set(df['categories'].values)) n = len(categories) for i", "del count[np.nan] except ValueError: pass if count == dict(): return", "Counter from statistics import median from tqdm import tqdm def", "\"\"\" Fill na with most common of the whole column", "elif isinstance(element, np.double): array = np.array(element_list) array = array[~np.isnan(array)] if", "<filename>python/fill_na_v2.py \"\"\" Fill na with most common of the whole", "len(categories) for i in tqdm(range(len(df.columns))): col = df.columns[i] if not", "in tqdm(range(len(df.columns))): col = df.columns[i] if not col in {'review_id':", "as pd import time import matplotlib.pyplot as plt from datetime", "in element_list: if not pd.isna(element): break if pd.isna(element): return np.nan", "Fill na with most common of the whole column \"\"\"", "count.most_common(1)[0][0] file = '/home/nicolasbievre/yelp_data.pkl' file_na = '/home/nicolasbievre/yelp_data_no_na.pkl' df = pd.read_pickle(file)", "whole column \"\"\" import numpy as np import pandas as", "count[np.nan] except ValueError: pass if count == dict(): return np.nan", "'postal_code': 0}: df_col = df[col].values na = sum(pd.isna(df_col)) if na", "datetime import datetime import re from collections import Counter from", "for i in tqdm(range(len(df.columns))): col = df.columns[i] if not col", "df = pd.read_pickle(file) categories = list(set(df['categories'].values)) n = len(categories) for", "column \"\"\" import numpy as np import pandas as pd", "statistics import median from tqdm import tqdm def find_most_common_value(element_list): for", "element in element_list: if not pd.isna(element): break if pd.isna(element): return", "np.nan else: return count.most_common(1)[0][0] file = '/home/nicolasbievre/yelp_data.pkl' file_na = '/home/nicolasbievre/yelp_data_no_na.pkl'", "== 0: return np.nan else: array = array.astype(np.int) return np.double(np.bincount(array).argmax())", "not pd.isna(most_commom_term): df.loc[(pd.isna(df_col)), col] = most_commom_term if i % 35", "'/home/nicolasbievre/yelp_data_no_na.pkl' df = pd.read_pickle(file) categories = list(set(df['categories'].values)) n = len(categories)", "count = Counter(df[col]) try: del count[np.nan] except ValueError: pass if", "else: array = array.astype(np.int) return np.double(np.bincount(array).argmax()) elif isinstance(element, str): count", "import tqdm def find_most_common_value(element_list): for element in element_list: if not", "ValueError: pass if count == dict(): return np.nan else: return", "pd.isna(element): break if pd.isna(element): return np.nan elif isinstance(element, np.double): array", "n = len(categories) for i in tqdm(range(len(df.columns))): col = df.columns[i]", "import re from collections import Counter from statistics import median", "for element in element_list: if not pd.isna(element): break if pd.isna(element):", "pd import time import matplotlib.pyplot as plt from datetime import", "list(set(df['categories'].values)) n = len(categories) for i in tqdm(range(len(df.columns))): col =", "import pandas as pd import time import matplotlib.pyplot as plt", "df.loc[(pd.isna(df_col)), col] = most_commom_term if i % 35 == 0", "str): count = Counter(df[col]) try: del count[np.nan] except ValueError: pass", "np.double(np.bincount(array).argmax()) elif isinstance(element, str): count = Counter(df[col]) try: del count[np.nan]", "isinstance(element, str): count = Counter(df[col]) try: del count[np.nan] except ValueError:", "= sum(pd.isna(df_col)) if na > 0: most_commom_term = find_most_common_value(df_col) if", "if not pd.isna(most_commom_term): df.loc[(pd.isna(df_col)), col] = most_commom_term if i %", "np import pandas as pd import time import matplotlib.pyplot as", "pd.isna(most_commom_term): df.loc[(pd.isna(df_col)), col] = most_commom_term if i % 35 ==", "if len(array) == 0: return np.nan else: array = array.astype(np.int)", "return np.nan else: array = array.astype(np.int) return np.double(np.bincount(array).argmax()) elif isinstance(element,", "df.columns[i] if not col in {'review_id': 0, 'business_id': 0, 'user_id':", "= np.array(element_list) array = array[~np.isnan(array)] if len(array) == 0: return", "0, 'user_id': 0, 'postal_code': 0}: df_col = df[col].values na =", "count == dict(): return np.nan else: return count.most_common(1)[0][0] file =", "if i % 35 == 0 and i > 0:", "if not col in {'review_id': 0, 'business_id': 0, 'user_id': 0,", "as plt from datetime import datetime import re from collections", "the whole column \"\"\" import numpy as np import pandas", "= '/home/nicolasbievre/yelp_data_no_na.pkl' df = pd.read_pickle(file) categories = list(set(df['categories'].values)) n =", "0: most_commom_term = find_most_common_value(df_col) if not pd.isna(most_commom_term): df.loc[(pd.isna(df_col)), col] =", "> 0: most_commom_term = find_most_common_value(df_col) if not pd.isna(most_commom_term): df.loc[(pd.isna(df_col)), col]", "collections import Counter from statistics import median from tqdm import", "return np.double(np.bincount(array).argmax()) elif isinstance(element, str): count = Counter(df[col]) try: del", "tqdm import tqdm def find_most_common_value(element_list): for element in element_list: if", "array = np.array(element_list) array = array[~np.isnan(array)] if len(array) == 0:", "Counter(df[col]) try: del count[np.nan] except ValueError: pass if count ==", "return count.most_common(1)[0][0] file = '/home/nicolasbievre/yelp_data.pkl' file_na = '/home/nicolasbievre/yelp_data_no_na.pkl' df =", "common of the whole column \"\"\" import numpy as np", "median from tqdm import tqdm def find_most_common_value(element_list): for element in", "if count == dict(): return np.nan else: return count.most_common(1)[0][0] file", "import numpy as np import pandas as pd import time", "pd.read_pickle(file) categories = list(set(df['categories'].values)) n = len(categories) for i in", "file_na = '/home/nicolasbievre/yelp_data_no_na.pkl' df = pd.read_pickle(file) categories = list(set(df['categories'].values)) n", "import median from tqdm import tqdm def find_most_common_value(element_list): for element", "from statistics import median from tqdm import tqdm def find_most_common_value(element_list):", "= '/home/nicolasbievre/yelp_data.pkl' file_na = '/home/nicolasbievre/yelp_data_no_na.pkl' df = pd.read_pickle(file) categories =", "import matplotlib.pyplot as plt from datetime import datetime import re", "def find_most_common_value(element_list): for element in element_list: if not pd.isna(element): break", "dict(): return np.nan else: return count.most_common(1)[0][0] file = '/home/nicolasbievre/yelp_data.pkl' file_na", "0, 'postal_code': 0}: df_col = df[col].values na = sum(pd.isna(df_col)) if", "pd.isna(element): return np.nan elif isinstance(element, np.double): array = np.array(element_list) array", "with most common of the whole column \"\"\" import numpy", "find_most_common_value(df_col) if not pd.isna(most_commom_term): df.loc[(pd.isna(df_col)), col] = most_commom_term if i", "return np.nan else: return count.most_common(1)[0][0] file = '/home/nicolasbievre/yelp_data.pkl' file_na =", "= df[col].values na = sum(pd.isna(df_col)) if na > 0: most_commom_term", "'user_id': 0, 'postal_code': 0}: df_col = df[col].values na = sum(pd.isna(df_col))", "file = '/home/nicolasbievre/yelp_data.pkl' file_na = '/home/nicolasbievre/yelp_data_no_na.pkl' df = pd.read_pickle(file) categories", "i in tqdm(range(len(df.columns))): col = df.columns[i] if not col in", "as np import pandas as pd import time import matplotlib.pyplot", "from datetime import datetime import re from collections import Counter", "in {'review_id': 0, 'business_id': 0, 'user_id': 0, 'postal_code': 0}: df_col", "= df.columns[i] if not col in {'review_id': 0, 'business_id': 0,", "= most_commom_term if i % 35 == 0 and i", "== dict(): return np.nan else: return count.most_common(1)[0][0] file = '/home/nicolasbievre/yelp_data.pkl'", "from tqdm import tqdm def find_most_common_value(element_list): for element in element_list:", "array = array.astype(np.int) return np.double(np.bincount(array).argmax()) elif isinstance(element, str): count =", "len(array) == 0: return np.nan else: array = array.astype(np.int) return", "= array.astype(np.int) return np.double(np.bincount(array).argmax()) elif isinstance(element, str): count = Counter(df[col])", "np.nan elif isinstance(element, np.double): array = np.array(element_list) array = array[~np.isnan(array)]", "try: del count[np.nan] except ValueError: pass if count == dict():", "matplotlib.pyplot as plt from datetime import datetime import re from", "element_list: if not pd.isna(element): break if pd.isna(element): return np.nan elif", "% 35 == 0 and i > 0: df.to_pickle(file_na) df.to_pickle(file_na)", "re from collections import Counter from statistics import median from", "col = df.columns[i] if not col in {'review_id': 0, 'business_id':", "if not pd.isna(element): break if pd.isna(element): return np.nan elif isinstance(element,", "col in {'review_id': 0, 'business_id': 0, 'user_id': 0, 'postal_code': 0}:", "na = sum(pd.isna(df_col)) if na > 0: most_commom_term = find_most_common_value(df_col)", "0: return np.nan else: array = array.astype(np.int) return np.double(np.bincount(array).argmax()) elif", "{'review_id': 0, 'business_id': 0, 'user_id': 0, 'postal_code': 0}: df_col =", "= array[~np.isnan(array)] if len(array) == 0: return np.nan else: array", "tqdm(range(len(df.columns))): col = df.columns[i] if not col in {'review_id': 0,", "most common of the whole column \"\"\" import numpy as", "i % 35 == 0 and i > 0: df.to_pickle(file_na)", "categories = list(set(df['categories'].values)) n = len(categories) for i in tqdm(range(len(df.columns))):", "= list(set(df['categories'].values)) n = len(categories) for i in tqdm(range(len(df.columns))): col", "import time import matplotlib.pyplot as plt from datetime import datetime", "from collections import Counter from statistics import median from tqdm", "numpy as np import pandas as pd import time import", "'/home/nicolasbievre/yelp_data.pkl' file_na = '/home/nicolasbievre/yelp_data_no_na.pkl' df = pd.read_pickle(file) categories = list(set(df['categories'].values))", "not col in {'review_id': 0, 'business_id': 0, 'user_id': 0, 'postal_code':", "except ValueError: pass if count == dict(): return np.nan else:", "col] = most_commom_term if i % 35 == 0 and", "sum(pd.isna(df_col)) if na > 0: most_commom_term = find_most_common_value(df_col) if not", "df_col = df[col].values na = sum(pd.isna(df_col)) if na > 0:", "else: return count.most_common(1)[0][0] file = '/home/nicolasbievre/yelp_data.pkl' file_na = '/home/nicolasbievre/yelp_data_no_na.pkl' df", "np.nan else: array = array.astype(np.int) return np.double(np.bincount(array).argmax()) elif isinstance(element, str):", "not pd.isna(element): break if pd.isna(element): return np.nan elif isinstance(element, np.double):", "find_most_common_value(element_list): for element in element_list: if not pd.isna(element): break if", "np.double): array = np.array(element_list) array = array[~np.isnan(array)] if len(array) ==", "most_commom_term if i % 35 == 0 and i >", "elif isinstance(element, str): count = Counter(df[col]) try: del count[np.nan] except", "array[~np.isnan(array)] if len(array) == 0: return np.nan else: array =", "pandas as pd import time import matplotlib.pyplot as plt from", "pass if count == dict(): return np.nan else: return count.most_common(1)[0][0]", "= find_most_common_value(df_col) if not pd.isna(most_commom_term): df.loc[(pd.isna(df_col)), col] = most_commom_term if", "of the whole column \"\"\" import numpy as np import", "na > 0: most_commom_term = find_most_common_value(df_col) if not pd.isna(most_commom_term): df.loc[(pd.isna(df_col)),", "plt from datetime import datetime import re from collections import", "array.astype(np.int) return np.double(np.bincount(array).argmax()) elif isinstance(element, str): count = Counter(df[col]) try:", "na with most common of the whole column \"\"\" import", "most_commom_term = find_most_common_value(df_col) if not pd.isna(most_commom_term): df.loc[(pd.isna(df_col)), col] = most_commom_term", "= Counter(df[col]) try: del count[np.nan] except ValueError: pass if count", "import Counter from statistics import median from tqdm import tqdm", "if na > 0: most_commom_term = find_most_common_value(df_col) if not pd.isna(most_commom_term):", "0}: df_col = df[col].values na = sum(pd.isna(df_col)) if na >", "isinstance(element, np.double): array = np.array(element_list) array = array[~np.isnan(array)] if len(array)", "return np.nan elif isinstance(element, np.double): array = np.array(element_list) array =", "break if pd.isna(element): return np.nan elif isinstance(element, np.double): array =", "0, 'business_id': 0, 'user_id': 0, 'postal_code': 0}: df_col = df[col].values", "= len(categories) for i in tqdm(range(len(df.columns))): col = df.columns[i] if", "array = array[~np.isnan(array)] if len(array) == 0: return np.nan else:", "df[col].values na = sum(pd.isna(df_col)) if na > 0: most_commom_term =" ]
[ "import Tk from tkinter import Entry from tkinter import Button", "b2.configure(command=lambda:show(\"8\")) b3=Button(text=\"9\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b3.place(x=215,y=55,width=100,height=50) b3.configure(command=lambda:show(\"9\")) b4=Button(text=\"+\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b4.place(x=320,y=55,width=100,height=50) b4.configure(command=lambda:show(\"+\")) b5=Button(text=\"4\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b5.place(x=5,y=110,width=100,height=50) b5.configure(command=lambda:show(\"4\"))", "b3=Button(text=\"9\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b3.place(x=215,y=55,width=100,height=50) b3.configure(command=lambda:show(\"9\")) b4=Button(text=\"+\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b4.place(x=320,y=55,width=100,height=50) b4.configure(command=lambda:show(\"+\")) b5=Button(text=\"4\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b5.place(x=5,y=110,width=100,height=50) b5.configure(command=lambda:show(\"4\")) b6=Button(text=\"5\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\")", "b10=Button(text=\"2\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b10.place(x=110,y=165,width=100,height=50) b10.configure(command=lambda:show(\"2\")) b11=Button(text=\"3\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b11.place(x=215,y=165,width=100,height=50) b11.configure(command=lambda:show(\"3\")) b12=Button(text=\"*\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b12.place(x=320,y=165,width=100,height=50) b12.configure(command=lambda:show(\"*\")) b13=Button(text=\"C\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\")", "b10.place(x=110,y=165,width=100,height=50) b10.configure(command=lambda:show(\"2\")) b11=Button(text=\"3\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b11.place(x=215,y=165,width=100,height=50) b11.configure(command=lambda:show(\"3\")) b12=Button(text=\"*\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b12.place(x=320,y=165,width=100,height=50) b12.configure(command=lambda:show(\"*\")) b13=Button(text=\"C\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b13.place(x=5,y=220,width=100,height=50)", "t.resizable(0,0) t.configure(background=\"black\")#back ground color a=StringVar() def show(c): a.set(a.get()+c) def equal():", "b8.configure(command=lambda:show(\"-\")) b9=Button(text=\"1\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b9.place(x=5,y=165,width=100,height=50) b9.configure(command=lambda:show(\"1\")) b10=Button(text=\"2\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b10.place(x=110,y=165,width=100,height=50) b10.configure(command=lambda:show(\"2\")) b11=Button(text=\"3\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b11.place(x=215,y=165,width=100,height=50) b11.configure(command=lambda:show(\"3\"))", "from tkinter import Entry from tkinter import Button from tkinter", "b11=Button(text=\"3\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b11.place(x=215,y=165,width=100,height=50) b11.configure(command=lambda:show(\"3\")) b12=Button(text=\"*\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b12.place(x=320,y=165,width=100,height=50) b12.configure(command=lambda:show(\"*\")) b13=Button(text=\"C\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b13.place(x=5,y=220,width=100,height=50) b13.configure(command=clear) b14=Button(text=\"0\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\")", "b9.place(x=5,y=165,width=100,height=50) b9.configure(command=lambda:show(\"1\")) b10=Button(text=\"2\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b10.place(x=110,y=165,width=100,height=50) b10.configure(command=lambda:show(\"2\")) b11=Button(text=\"3\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b11.place(x=215,y=165,width=100,height=50) b11.configure(command=lambda:show(\"3\")) b12=Button(text=\"*\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b12.place(x=320,y=165,width=100,height=50)", "b1.place(x=5,y=55,width=100,height=50) b1.configure(command=lambda:show(\"7\")) b2=Button(text=\"8\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b2.place(x=110,y=55,width=100,height=50) b2.configure(command=lambda:show(\"8\")) b3=Button(text=\"9\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b3.place(x=215,y=55,width=100,height=50) b3.configure(command=lambda:show(\"9\")) b4=Button(text=\"+\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b4.place(x=320,y=55,width=100,height=50)", "from tkinter import Tk from tkinter import Entry from tkinter", "Button from tkinter import StringVar t=Tk() t.title(\"<NAME>\") t.geometry(\"425x300\") t.resizable(0,0) t.configure(background=\"black\")#back", "clear(): a.set(\"\") e1=Entry(font=(\"\",30),justify=\"right\",textvariable=a) e1.place(x=0,y=0,width=425,height=50) b1=Button(text=\"7\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=show) b1.place(x=5,y=55,width=100,height=50) b1.configure(command=lambda:show(\"7\")) b2=Button(text=\"8\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b2.place(x=110,y=55,width=100,height=50) b2.configure(command=lambda:show(\"8\"))", "b10.configure(command=lambda:show(\"2\")) b11=Button(text=\"3\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b11.place(x=215,y=165,width=100,height=50) b11.configure(command=lambda:show(\"3\")) b12=Button(text=\"*\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b12.place(x=320,y=165,width=100,height=50) b12.configure(command=lambda:show(\"*\")) b13=Button(text=\"C\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b13.place(x=5,y=220,width=100,height=50) b13.configure(command=clear)", "Entry from tkinter import Button from tkinter import StringVar t=Tk()", "b7.place(x=215,y=110,width=100,height=50) b7.configure(command=lambda:show(\"6\")) b8=Button(text=\"-\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b8.place(x=320,y=110,width=100,height=50) b8.configure(command=lambda:show(\"-\")) b9=Button(text=\"1\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b9.place(x=5,y=165,width=100,height=50) b9.configure(command=lambda:show(\"1\")) b10=Button(text=\"2\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b10.place(x=110,y=165,width=100,height=50)", "b3.configure(command=lambda:show(\"9\")) b4=Button(text=\"+\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b4.place(x=320,y=55,width=100,height=50) b4.configure(command=lambda:show(\"+\")) b5=Button(text=\"4\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b5.place(x=5,y=110,width=100,height=50) b5.configure(command=lambda:show(\"4\")) b6=Button(text=\"5\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b6.place(x=110,y=110,width=100,height=50) b6.configure(command=lambda:show(\"5\"))", "e1=Entry(font=(\"\",30),justify=\"right\",textvariable=a) e1.place(x=0,y=0,width=425,height=50) b1=Button(text=\"7\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=show) b1.place(x=5,y=55,width=100,height=50) b1.configure(command=lambda:show(\"7\")) b2=Button(text=\"8\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b2.place(x=110,y=55,width=100,height=50) b2.configure(command=lambda:show(\"8\")) b3=Button(text=\"9\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b3.place(x=215,y=55,width=100,height=50)", "from tkinter import StringVar t=Tk() t.title(\"<NAME>\") t.geometry(\"425x300\") t.resizable(0,0) t.configure(background=\"black\")#back ground", "b1.configure(command=lambda:show(\"7\")) b2=Button(text=\"8\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b2.place(x=110,y=55,width=100,height=50) b2.configure(command=lambda:show(\"8\")) b3=Button(text=\"9\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b3.place(x=215,y=55,width=100,height=50) b3.configure(command=lambda:show(\"9\")) b4=Button(text=\"+\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b4.place(x=320,y=55,width=100,height=50) b4.configure(command=lambda:show(\"+\"))", "<filename>GUI Applications/calc.py from tkinter import Tk from tkinter import Entry", "b2=Button(text=\"8\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b2.place(x=110,y=55,width=100,height=50) b2.configure(command=lambda:show(\"8\")) b3=Button(text=\"9\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b3.place(x=215,y=55,width=100,height=50) b3.configure(command=lambda:show(\"9\")) b4=Button(text=\"+\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b4.place(x=320,y=55,width=100,height=50) b4.configure(command=lambda:show(\"+\")) b5=Button(text=\"4\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\")", "b7.configure(command=lambda:show(\"6\")) b8=Button(text=\"-\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b8.place(x=320,y=110,width=100,height=50) b8.configure(command=lambda:show(\"-\")) b9=Button(text=\"1\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b9.place(x=5,y=165,width=100,height=50) b9.configure(command=lambda:show(\"1\")) b10=Button(text=\"2\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b10.place(x=110,y=165,width=100,height=50) b10.configure(command=lambda:show(\"2\"))", "b5.place(x=5,y=110,width=100,height=50) b5.configure(command=lambda:show(\"4\")) b6=Button(text=\"5\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b6.place(x=110,y=110,width=100,height=50) b6.configure(command=lambda:show(\"5\")) b7=Button(text=\"6\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b7.place(x=215,y=110,width=100,height=50) b7.configure(command=lambda:show(\"6\")) b8=Button(text=\"-\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b8.place(x=320,y=110,width=100,height=50)", "def show(c): a.set(a.get()+c) def equal(): x=a.get() a.set(eval(x)) def clear(): a.set(\"\")", "b6.configure(command=lambda:show(\"5\")) b7=Button(text=\"6\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b7.place(x=215,y=110,width=100,height=50) b7.configure(command=lambda:show(\"6\")) b8=Button(text=\"-\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b8.place(x=320,y=110,width=100,height=50) b8.configure(command=lambda:show(\"-\")) b9=Button(text=\"1\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b9.place(x=5,y=165,width=100,height=50) b9.configure(command=lambda:show(\"1\"))", "Applications/calc.py from tkinter import Tk from tkinter import Entry from", "b5.configure(command=lambda:show(\"4\")) b6=Button(text=\"5\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b6.place(x=110,y=110,width=100,height=50) b6.configure(command=lambda:show(\"5\")) b7=Button(text=\"6\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b7.place(x=215,y=110,width=100,height=50) b7.configure(command=lambda:show(\"6\")) b8=Button(text=\"-\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b8.place(x=320,y=110,width=100,height=50) b8.configure(command=lambda:show(\"-\"))", "b3.place(x=215,y=55,width=100,height=50) b3.configure(command=lambda:show(\"9\")) b4=Button(text=\"+\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b4.place(x=320,y=55,width=100,height=50) b4.configure(command=lambda:show(\"+\")) b5=Button(text=\"4\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b5.place(x=5,y=110,width=100,height=50) b5.configure(command=lambda:show(\"4\")) b6=Button(text=\"5\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b6.place(x=110,y=110,width=100,height=50)", "b14=Button(text=\"0\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b14.place(x=110,y=220,width=100,height=50) b14.configure(command=lambda:show(\"0\")) b15=Button(text=\"=\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=equal) b15.place(x=215,y=220,width=100,height=50) b15.configure(command=equal) b16=Button(text=\"/\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b16.place(x=320,y=220,width=100,height=50) b16.configure(command=lambda:show(\"/\")) t.mainloop()", "tkinter import Entry from tkinter import Button from tkinter import", "b5=Button(text=\"4\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b5.place(x=5,y=110,width=100,height=50) b5.configure(command=lambda:show(\"4\")) b6=Button(text=\"5\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b6.place(x=110,y=110,width=100,height=50) b6.configure(command=lambda:show(\"5\")) b7=Button(text=\"6\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b7.place(x=215,y=110,width=100,height=50) b7.configure(command=lambda:show(\"6\")) b8=Button(text=\"-\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\")", "b13=Button(text=\"C\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b13.place(x=5,y=220,width=100,height=50) b13.configure(command=clear) b14=Button(text=\"0\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b14.place(x=110,y=220,width=100,height=50) b14.configure(command=lambda:show(\"0\")) b15=Button(text=\"=\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=equal) b15.place(x=215,y=220,width=100,height=50) b15.configure(command=equal) b16=Button(text=\"/\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\")", "t.geometry(\"425x300\") t.resizable(0,0) t.configure(background=\"black\")#back ground color a=StringVar() def show(c): a.set(a.get()+c) def", "import StringVar t=Tk() t.title(\"<NAME>\") t.geometry(\"425x300\") t.resizable(0,0) t.configure(background=\"black\")#back ground color a=StringVar()", "from tkinter import Button from tkinter import StringVar t=Tk() t.title(\"<NAME>\")", "import Button from tkinter import StringVar t=Tk() t.title(\"<NAME>\") t.geometry(\"425x300\") t.resizable(0,0)", "b13.place(x=5,y=220,width=100,height=50) b13.configure(command=clear) b14=Button(text=\"0\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b14.place(x=110,y=220,width=100,height=50) b14.configure(command=lambda:show(\"0\")) b15=Button(text=\"=\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=equal) b15.place(x=215,y=220,width=100,height=50) b15.configure(command=equal) b16=Button(text=\"/\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b16.place(x=320,y=220,width=100,height=50)", "import Entry from tkinter import Button from tkinter import StringVar", "b9=Button(text=\"1\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b9.place(x=5,y=165,width=100,height=50) b9.configure(command=lambda:show(\"1\")) b10=Button(text=\"2\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b10.place(x=110,y=165,width=100,height=50) b10.configure(command=lambda:show(\"2\")) b11=Button(text=\"3\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b11.place(x=215,y=165,width=100,height=50) b11.configure(command=lambda:show(\"3\")) b12=Button(text=\"*\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\")", "equal(): x=a.get() a.set(eval(x)) def clear(): a.set(\"\") e1=Entry(font=(\"\",30),justify=\"right\",textvariable=a) e1.place(x=0,y=0,width=425,height=50) b1=Button(text=\"7\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=show) b1.place(x=5,y=55,width=100,height=50)", "b8=Button(text=\"-\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b8.place(x=320,y=110,width=100,height=50) b8.configure(command=lambda:show(\"-\")) b9=Button(text=\"1\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b9.place(x=5,y=165,width=100,height=50) b9.configure(command=lambda:show(\"1\")) b10=Button(text=\"2\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b10.place(x=110,y=165,width=100,height=50) b10.configure(command=lambda:show(\"2\")) b11=Button(text=\"3\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\")", "def clear(): a.set(\"\") e1=Entry(font=(\"\",30),justify=\"right\",textvariable=a) e1.place(x=0,y=0,width=425,height=50) b1=Button(text=\"7\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=show) b1.place(x=5,y=55,width=100,height=50) b1.configure(command=lambda:show(\"7\")) b2=Button(text=\"8\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b2.place(x=110,y=55,width=100,height=50)", "b6=Button(text=\"5\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b6.place(x=110,y=110,width=100,height=50) b6.configure(command=lambda:show(\"5\")) b7=Button(text=\"6\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b7.place(x=215,y=110,width=100,height=50) b7.configure(command=lambda:show(\"6\")) b8=Button(text=\"-\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b8.place(x=320,y=110,width=100,height=50) b8.configure(command=lambda:show(\"-\")) b9=Button(text=\"1\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\")", "e1.place(x=0,y=0,width=425,height=50) b1=Button(text=\"7\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=show) b1.place(x=5,y=55,width=100,height=50) b1.configure(command=lambda:show(\"7\")) b2=Button(text=\"8\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b2.place(x=110,y=55,width=100,height=50) b2.configure(command=lambda:show(\"8\")) b3=Button(text=\"9\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b3.place(x=215,y=55,width=100,height=50) b3.configure(command=lambda:show(\"9\"))", "b11.configure(command=lambda:show(\"3\")) b12=Button(text=\"*\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b12.place(x=320,y=165,width=100,height=50) b12.configure(command=lambda:show(\"*\")) b13=Button(text=\"C\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b13.place(x=5,y=220,width=100,height=50) b13.configure(command=clear) b14=Button(text=\"0\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b14.place(x=110,y=220,width=100,height=50) b14.configure(command=lambda:show(\"0\"))", "b8.place(x=320,y=110,width=100,height=50) b8.configure(command=lambda:show(\"-\")) b9=Button(text=\"1\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b9.place(x=5,y=165,width=100,height=50) b9.configure(command=lambda:show(\"1\")) b10=Button(text=\"2\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b10.place(x=110,y=165,width=100,height=50) b10.configure(command=lambda:show(\"2\")) b11=Button(text=\"3\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b11.place(x=215,y=165,width=100,height=50)", "a.set(\"\") e1=Entry(font=(\"\",30),justify=\"right\",textvariable=a) e1.place(x=0,y=0,width=425,height=50) b1=Button(text=\"7\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=show) b1.place(x=5,y=55,width=100,height=50) b1.configure(command=lambda:show(\"7\")) b2=Button(text=\"8\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b2.place(x=110,y=55,width=100,height=50) b2.configure(command=lambda:show(\"8\")) b3=Button(text=\"9\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\")", "b6.place(x=110,y=110,width=100,height=50) b6.configure(command=lambda:show(\"5\")) b7=Button(text=\"6\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b7.place(x=215,y=110,width=100,height=50) b7.configure(command=lambda:show(\"6\")) b8=Button(text=\"-\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b8.place(x=320,y=110,width=100,height=50) b8.configure(command=lambda:show(\"-\")) b9=Button(text=\"1\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b9.place(x=5,y=165,width=100,height=50)", "def equal(): x=a.get() a.set(eval(x)) def clear(): a.set(\"\") e1=Entry(font=(\"\",30),justify=\"right\",textvariable=a) e1.place(x=0,y=0,width=425,height=50) b1=Button(text=\"7\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=show)", "b12=Button(text=\"*\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b12.place(x=320,y=165,width=100,height=50) b12.configure(command=lambda:show(\"*\")) b13=Button(text=\"C\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b13.place(x=5,y=220,width=100,height=50) b13.configure(command=clear) b14=Button(text=\"0\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b14.place(x=110,y=220,width=100,height=50) b14.configure(command=lambda:show(\"0\")) b15=Button(text=\"=\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=equal)", "a.set(a.get()+c) def equal(): x=a.get() a.set(eval(x)) def clear(): a.set(\"\") e1=Entry(font=(\"\",30),justify=\"right\",textvariable=a) e1.place(x=0,y=0,width=425,height=50)", "b11.place(x=215,y=165,width=100,height=50) b11.configure(command=lambda:show(\"3\")) b12=Button(text=\"*\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b12.place(x=320,y=165,width=100,height=50) b12.configure(command=lambda:show(\"*\")) b13=Button(text=\"C\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b13.place(x=5,y=220,width=100,height=50) b13.configure(command=clear) b14=Button(text=\"0\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b14.place(x=110,y=220,width=100,height=50)", "StringVar t=Tk() t.title(\"<NAME>\") t.geometry(\"425x300\") t.resizable(0,0) t.configure(background=\"black\")#back ground color a=StringVar() def", "x=a.get() a.set(eval(x)) def clear(): a.set(\"\") e1=Entry(font=(\"\",30),justify=\"right\",textvariable=a) e1.place(x=0,y=0,width=425,height=50) b1=Button(text=\"7\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=show) b1.place(x=5,y=55,width=100,height=50) b1.configure(command=lambda:show(\"7\"))", "a=StringVar() def show(c): a.set(a.get()+c) def equal(): x=a.get() a.set(eval(x)) def clear():", "b12.place(x=320,y=165,width=100,height=50) b12.configure(command=lambda:show(\"*\")) b13=Button(text=\"C\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b13.place(x=5,y=220,width=100,height=50) b13.configure(command=clear) b14=Button(text=\"0\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b14.place(x=110,y=220,width=100,height=50) b14.configure(command=lambda:show(\"0\")) b15=Button(text=\"=\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=equal) b15.place(x=215,y=220,width=100,height=50)", "tkinter import Tk from tkinter import Entry from tkinter import", "b9.configure(command=lambda:show(\"1\")) b10=Button(text=\"2\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b10.place(x=110,y=165,width=100,height=50) b10.configure(command=lambda:show(\"2\")) b11=Button(text=\"3\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b11.place(x=215,y=165,width=100,height=50) b11.configure(command=lambda:show(\"3\")) b12=Button(text=\"*\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b12.place(x=320,y=165,width=100,height=50) b12.configure(command=lambda:show(\"*\"))", "t=Tk() t.title(\"<NAME>\") t.geometry(\"425x300\") t.resizable(0,0) t.configure(background=\"black\")#back ground color a=StringVar() def show(c):", "b1=Button(text=\"7\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=show) b1.place(x=5,y=55,width=100,height=50) b1.configure(command=lambda:show(\"7\")) b2=Button(text=\"8\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b2.place(x=110,y=55,width=100,height=50) b2.configure(command=lambda:show(\"8\")) b3=Button(text=\"9\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b3.place(x=215,y=55,width=100,height=50) b3.configure(command=lambda:show(\"9\")) b4=Button(text=\"+\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\")", "show(c): a.set(a.get()+c) def equal(): x=a.get() a.set(eval(x)) def clear(): a.set(\"\") e1=Entry(font=(\"\",30),justify=\"right\",textvariable=a)", "tkinter import StringVar t=Tk() t.title(\"<NAME>\") t.geometry(\"425x300\") t.resizable(0,0) t.configure(background=\"black\")#back ground color", "b12.configure(command=lambda:show(\"*\")) b13=Button(text=\"C\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b13.place(x=5,y=220,width=100,height=50) b13.configure(command=clear) b14=Button(text=\"0\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b14.place(x=110,y=220,width=100,height=50) b14.configure(command=lambda:show(\"0\")) b15=Button(text=\"=\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=equal) b15.place(x=215,y=220,width=100,height=50) b15.configure(command=equal)", "color a=StringVar() def show(c): a.set(a.get()+c) def equal(): x=a.get() a.set(eval(x)) def", "b4=Button(text=\"+\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b4.place(x=320,y=55,width=100,height=50) b4.configure(command=lambda:show(\"+\")) b5=Button(text=\"4\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b5.place(x=5,y=110,width=100,height=50) b5.configure(command=lambda:show(\"4\")) b6=Button(text=\"5\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b6.place(x=110,y=110,width=100,height=50) b6.configure(command=lambda:show(\"5\")) b7=Button(text=\"6\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\")", "b2.place(x=110,y=55,width=100,height=50) b2.configure(command=lambda:show(\"8\")) b3=Button(text=\"9\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b3.place(x=215,y=55,width=100,height=50) b3.configure(command=lambda:show(\"9\")) b4=Button(text=\"+\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b4.place(x=320,y=55,width=100,height=50) b4.configure(command=lambda:show(\"+\")) b5=Button(text=\"4\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b5.place(x=5,y=110,width=100,height=50)", "tkinter import Button from tkinter import StringVar t=Tk() t.title(\"<NAME>\") t.geometry(\"425x300\")", "b7=Button(text=\"6\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b7.place(x=215,y=110,width=100,height=50) b7.configure(command=lambda:show(\"6\")) b8=Button(text=\"-\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b8.place(x=320,y=110,width=100,height=50) b8.configure(command=lambda:show(\"-\")) b9=Button(text=\"1\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b9.place(x=5,y=165,width=100,height=50) b9.configure(command=lambda:show(\"1\")) b10=Button(text=\"2\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\")", "Tk from tkinter import Entry from tkinter import Button from", "b4.place(x=320,y=55,width=100,height=50) b4.configure(command=lambda:show(\"+\")) b5=Button(text=\"4\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b5.place(x=5,y=110,width=100,height=50) b5.configure(command=lambda:show(\"4\")) b6=Button(text=\"5\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b6.place(x=110,y=110,width=100,height=50) b6.configure(command=lambda:show(\"5\")) b7=Button(text=\"6\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b7.place(x=215,y=110,width=100,height=50)", "t.title(\"<NAME>\") t.geometry(\"425x300\") t.resizable(0,0) t.configure(background=\"black\")#back ground color a=StringVar() def show(c): a.set(a.get()+c)", "b4.configure(command=lambda:show(\"+\")) b5=Button(text=\"4\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b5.place(x=5,y=110,width=100,height=50) b5.configure(command=lambda:show(\"4\")) b6=Button(text=\"5\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b6.place(x=110,y=110,width=100,height=50) b6.configure(command=lambda:show(\"5\")) b7=Button(text=\"6\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b7.place(x=215,y=110,width=100,height=50) b7.configure(command=lambda:show(\"6\"))", "b13.configure(command=clear) b14=Button(text=\"0\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b14.place(x=110,y=220,width=100,height=50) b14.configure(command=lambda:show(\"0\")) b15=Button(text=\"=\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=equal) b15.place(x=215,y=220,width=100,height=50) b15.configure(command=equal) b16=Button(text=\"/\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\") b16.place(x=320,y=220,width=100,height=50) b16.configure(command=lambda:show(\"/\"))", "t.configure(background=\"black\")#back ground color a=StringVar() def show(c): a.set(a.get()+c) def equal(): x=a.get()", "a.set(eval(x)) def clear(): a.set(\"\") e1=Entry(font=(\"\",30),justify=\"right\",textvariable=a) e1.place(x=0,y=0,width=425,height=50) b1=Button(text=\"7\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\",command=show) b1.place(x=5,y=55,width=100,height=50) b1.configure(command=lambda:show(\"7\")) b2=Button(text=\"8\",font=(\"\",25),bg=\"gray\",fg=\"white\",activebackground=\"yellow\")", "ground color a=StringVar() def show(c): a.set(a.get()+c) def equal(): x=a.get() a.set(eval(x))" ]
[ "return self.page.title class TourStep(Orderable): title = models.CharField(max_length=255) body = models.CharField(max_length=255)", "existing field ) subtitles_en = models.TextField( verbose_name=_('English subtitles'), null=True, blank=True,", "read list_page = ( ListPage.objects.ancestor_of(self) .filter(record_read_progress=True) .exclude(page_views_list__sso_id=request.user.pk, page_views_list__page=self) .first() )", "page = models.ForeignKey(DetailPage, on_delete=models.CASCADE, related_name='page_views') list_page = models.ForeignKey(ListPage, on_delete=models.CASCADE, related_name='page_views_list')", "of ' \"the user's export markets falls into unless there", "noqa N806 for node in value: if node.block_type == MEDIA_BLOCK:", "[ ('Image', core_blocks.ImageBlock(template='core/includes/_hero_image.html')), ('Video', core_blocks.SimpleVideoBlock(template='core/includes/_hero_video.html')), ], null=True, blank=True, validators=[hero_singular_validation], )", "of any of the user's products \" 'unless there is", "(('learn/interstitial.html', 'Learn'),) ################ # Content fields ################ button = StreamField([('button',", "False field_template = 'admin/wagtailadmin/edit_handlers/field_panel_field.html' def render_as_field(self): instance_obj = self.get_chosen_item() context", "markets.\", default=4, decimal_places=3, max_digits=5, ) country_region = models.DecimalField( help_text=\"Score given", "an exact country or region match.\", default=2, decimal_places=3, max_digits=5, )", "it) and/or a Quote section, then one Text section following", "exact country match.', default=2, decimal_places=3, max_digits=5, ) trading_blocs = models.DecimalField(", "unlikely # to happen. return backlink_path return None # safe", "passed as mode_name - we always redirect return self._redirect_to_parent_module() def", "for Personalisation', ), ] def __str__(self): display_name = self.title if", "not allow this page type to be created in wagtail", "class Meta: ordering = ('name',) def __str__(self): return self.name class", "= super().get_context(request) # Give the template a simple way to", "an ISO-2 Country code ('DE') \"\"\" free_tagging = False class", "def __str__(self): return self.name @register_snippet class Region(models.Model): name = models.CharField(max_length=100,", "when any case study HS4 tag matches the first 4", "blocks.StreamBlock( [ ( 'item', core_blocks.Item(icon='fa-arrow-right'), ) ] ), ), (", "self._redirect_to_parent_module() class LessonPlaceholderPage(mixins.AuthenticatedUserRequired, Page): \"\"\"Structural page to allow for configuring", "], template='learn/recap.html', icon='fa-commenting-o', ), ) ] ) ######### # Panels", "+ [ StreamFieldPanel('hero'), StreamFieldPanel('objective'), StreamFieldPanel('body'), StreamFieldPanel('recap'), ] def handle_page_view(self, request):", "= models.CharField(max_length=1000) @staticmethod def generate_content_hash(field_file): filehash = hashlib.md5() field_file.open() filehash.update(field_file.read())", "get_module_completion_progress, ) from domestic.helpers import get_lesson_completion_status context = super().get_context(request) #", "__str__(self): return self.name @register_snippet class Country(models.Model): name = models.CharField(max_length=255) slug", "on_delete=models.CASCADE, related_name='page_views') list_page = models.ForeignKey(ListPage, on_delete=models.CASCADE, related_name='page_views_list') sso_id = models.TextField()", "blocks.CharBlock(icon='fa-header')), ( 'item', blocks.StreamBlock( [ ( 'item', core_blocks.Item(), ) ]", "ClusterTaggableManager( through='core.RegionTaggedCaseStudy', blank=True, verbose_name='Region tags' ) trading_bloc_code_tags = ClusterTaggableManager( through='core.TradingBlocTaggedCaseStudy',", "from django.utils.text import slugify from django.utils.translation import ugettext_lazy as _", "and make the UX easier for editors hs_code_tags = ClusterTaggableManager(through='core.HSCodeTaggedCaseStudy',", "full-page-width block', ), ), ] ) recap = StreamField( [", "@register_snippet class Tag(models.Model): name = models.CharField(max_length=100, unique=True) panels = [FieldPanel('name')]", "# old name summary lead_title = models.TextField(blank=False) # Deliberately not", ") created = CreationDateTimeField('created', null=True) modified = ModificationDateTimeField('modified', null=True) panels", "1: raise StreamBlockValidationError( non_block_errors=ValidationError('Only one image or video allowed in", "remove @register_snippet class ContentModule(ClusterableModel): title = models.CharField(max_length=255) content = RichTextField()", "models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, on_delete=models.CASCADE, related_name='+' ) class ImageHash(AbstractObjectHash): image", "lesson belongs to\"\"\" return CuratedListPage.objects.live().specific().ancestor_of(self).first() @cached_property def _export_plan_url_map(self): \"\"\"Return a", "StreamField( [ ( 'media', blocks.StreamBlock( [ ('video', core_blocks.SimpleVideoBlock(template='core/includes/_case_study_video.html')), ('image', core_blocks.ImageBlock()),", "obtain an ID for indexing self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified',", "] ) ######### # Panels ########## content_panels = Page.content_panels +", "return self._export_plan_url_map.get(_path) def get_context(self, request, *args, **kwargs): context = super().get_context(request)", "lesson's module is tagged in the case study \" 'unless", "plan, else ignore it.\"\"\" backlink_path = request.GET.get(BACKLINK_QUERYSTRING_NAME, '') if backlink_path", "completion_status = get_lesson_completion_status(request.user) context['module_completion_progress'] = get_module_completion_progress( completion_status=completion_status, module_page=self, ) context['high_level_completion_progress']", "################ # Content fields ################ hero = StreamField( [ ('Image',", "hashlib.md5() field_file.open() filehash.update(field_file.read()) field_file.close() return filehash.hexdigest() class DocumentHash(AbstractObjectHash): document =", "next_module: return context context['next_module'] = next_module.specific context['next_lesson'] = get_first_lesson(next_module) return", "that this is rendered via Wagtail's ModelAdmin, so appears in", "register_setting from wagtail.core import blocks from wagtail.core.blocks.stream_block import StreamBlockValidationError from", "issues with field clash. \"\"\" created = CreationDateTimeField('created', null=True) modified", "import cached_classmethod from wagtailmedia.models import Media from core import blocks", "AbstractObjectHash(models.Model): class Meta: abstract = True content_hash = models.CharField(max_length=1000) @staticmethod", "can get a title that goes with it. For now,", "wondering what's going on here: # https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models class HSCodeTaggedCaseStudy(ItemBase): tag", "heading='Lesson'), ObjectList(threshold_tab, heading='Threshold'), ] ) class Meta: verbose_name = 'Case", "# If you're wondering what's going on here: # https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models", "core_blocks.Item(icon='fa-arrow-right'), ) ] ), ), ], template='learn/pros_and_cons.html', icon='fa-arrow-right', ), ),", "check for '://' will stop us accepting a backlink which", "PersonalisationHSCodeTag(TagBase): \"\"\"Custom tag for personalisation. Tag value will be a", "= CMSGenericPage.content_panels + [ FieldPanel('description'), StreamFieldPanel('button'), ImageChooserPanel('image'), StreamFieldPanel('components'), StreamFieldPanel('body'), ]", "= models.TextField( verbose_name=_('Transcript'), blank=False, null=True # left null because was", "( 'pros', blocks.StreamBlock( [ ( 'item', core_blocks.Item(icon='fa-arrow-right'), ) ] ),", "personalisation' verbose_name_plural = 'Country tags for personalisation' class PersonalisationRegionTag(TagBase): \"\"\"Custom", "= super().get_context(request) self.set_ga360_payload( page_id=self.id, business_unit=settings.GA360_BUSINESS_UNIT, site_section=str(self.url or '/').split('/')[1], ) self.add_ga360_data_to_payload(request)", "should be present here MEDIA_BLOCK = 'media' # noqa N806", "[ InlinePanel('related_pages', label='Related pages'), ], heading='Related Lesson, Topic & Module,", ") return output class AbstractObjectHash(models.Model): class Meta: abstract = True", "core_blocks.SimpleVideoBlock(template='core/includes/_case_study_video.html')), ('image', core_blocks.ImageBlock()), ], min_num=1, max_num=2, ), ), ( 'text',", "True # Do not allow this page type to be", "representing very simple to modules (`CuratedListPage`s). Not intented to be", "field.required = True @cached_classmethod def get_edit_handler(cls): # NOQA N805 panels", "= True # Do not allow this page type to", "of the user's export markets.\", default=4, decimal_places=3, max_digits=5, ) country_region", "template='learn/fictional_company_example.html', icon='fa-commenting-o', ), ), ( 'ITA_Quote', core_blocks.ITAQuoteBlock(icon='fa-quote-left'), ), ( 'pros_cons',", "page_topic_helper.get_page_topic() if topic_page: context['current_topic'] = topic_page context['page_topic'] = topic_page.title if", "################ heading = RichTextField() image = models.ForeignKey( get_image_model_string(), null=True, blank=True,", "= models.CharField(max_length=255) slug = models.SlugField(max_length=100, unique=True) region = models.ForeignKey(Region, null=True,", "class HSCodeTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationHSCodeTag, related_name='hscode_tagged_case_studies', on_delete=models.CASCADE ) content_object", "] template_choices = (('learn/curated_list_page.html', 'Learn'),) ################ # Content fields ################", "default=2, decimal_places=3, max_digits=5, ) trading_blocs = models.DecimalField( help_text='Score given when", "(with one or ' 'two items in it) and/or a", ") admin_form_fields = Media.admin_form_fields + ( 'transcript', 'subtitles_en', ) @property", "register_snippet from wagtail.utils.decorators import cached_classmethod from wagtailmedia.models import Media from", "help_text=\"Score given when any case study country tag exactly matches", "decimal_places=3, max_digits=5, ) topic = models.DecimalField( help_text=\"Score given when user's", "mimetypes from urllib.parse import unquote from django.conf import settings from", "null=True # left null because was an existing field )", "FieldPanel('heading'), ImageChooserPanel('image'), ] def get_topics(self, live=True) -> models.QuerySet: qs =", "here def _redirect_to_parent_module(self): dest = CuratedListPage.objects.ancestor_of(self).first().url return HttpResponseRedirect(dest) def serve_preview(self,", "**kwargs): context = super().get_context(request) context['refresh_on_market_change'] = True # Prepare backlink", "TopicPage): # In a conditional because a DetailPage currently MAY", "on_delete=models.CASCADE ) content_object = ParentalKey( to='core.CaseStudy', on_delete=models.CASCADE, related_name='trading_bloc_tagged_items' ) def", "any of the user's export markets \" 'unless there is", "class GreatMedia(Media): transcript = models.TextField( verbose_name=_('Transcript'), blank=False, null=True # left", "return TabbedInterface(panels).bind_to(model=cls) def get_template(self, request, *args, **kwargs): return self.template def", "Content fields ################ hero = StreamField( [ ('Image', core_blocks.ImageBlock(template='core/includes/_hero_image.html')), ('Video',", "accepting a backlink which # features a full URL as", "tag exactly matches one of the user's export markets.\", default=4,", "\"\"\"Custom tag for personalisation. Tag value will be an ISO-2", "help_text='Should we record when a user views a page in", "self.get_topics().count() @cached_property def count_detail_pages(self): count = 0 for topic in", ") # If we make a Redirect appear as a", "( 'video', core_blocks.SimpleVideoBlock( template='core/includes/_video_full_width.html', help_text='Video displayed within a full-page-width block',", "page=self) if provider: context.update(provider.get_context_data(request=request, page=self)) return context class LandingPage(CMSGenericPage): parent_page_types", "is the minimum score which a case study needs to", "['core.LandingPage'] template_choices = (('learn/interstitial.html', 'Learn'),) ################ # Content fields ################", "template='core/includes/_image_full_width.html', help_text='Image displayed within a full-page-width block', ), ), (", "is also lesson match.', default=4, decimal_places=3, max_digits=5, ) module =", "topic_page: context['current_topic'] = topic_page context['page_topic'] = topic_page.title if next_lesson: context['next_lesson']", ".first() ) if list_page: PageView.objects.get_or_create( page=self, list_page=list_page, sso_id=request.user.pk, ) def", "be viewed by end users, so will redirect to the", "content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='region_tagged_items') class TradingBlocTaggedCaseStudy(ItemBase): tag = models.ForeignKey(", "models.CharField(max_length=255) panels = [ FieldPanel('name'), ] def __str__(self): return self.name", "from wagtail.contrib.settings.models import BaseSetting, register_setting from wagtail.core import blocks from", "self.object_type_name: instance_obj, 'is_chosen': bool(instance_obj), # DEPRECATED - passed to templates", "N806 VIDEO_BLOCK = 'video' # noqa N806 for node in", "get_context(self, request, *args, **kwargs): from core.helpers import ( get_high_level_completion_progress, get_module_completion_progress,", "N806 # we need to be strict about presence and", "blocks.RichTextBlock())], template='core/struct_paragraph_block.html', icon='fa-font', ), ), ( 'video', blocks.StructBlock( [('video', core_blocks.VideoBlock())],", "and remove class ContentModuleTag(TaggedItemBase): content_object = ParentalKey('core.ContentModule', on_delete=models.CASCADE, related_name='tagged_items') #", "icon = models.ForeignKey( AltTextImage, null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) panels", "a full URL as its OWN querystring param (eg a", "display_name = self.title if self.title else self.summary_context return f'{display_name}' def", "= models.ForeignKey( get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) ######## #", "'application/octet-stream', 'transcript': self.transcript, } ] @property def subtitles(self): output =", "description = RichTextField() button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True) image", "= self._meta.get_field('template') field.choices = self.template_choices field.required = True @cached_classmethod def", "in the sidebar, but we have to keep it registered", "'core.LessonPlaceholderPage', ] # `title` comes from Page superclass and that's", "= [ MultiFieldPanel( [ FieldPanel('threshold'), ] ) ] edit_handler =", "panels = [ PageChooserPanel('page'), FieldPanel('title'), FieldPanel('body'), FieldPanel('button_text'), MultiFieldPanel([InlinePanel('steps')], heading='Steps'), ]", "= (('learn/automated_list_page.html', 'Learn'),) record_read_progress = models.BooleanField( default=False, help_text='Should we record", "the first 4 digits of any of the user's products", "used.\"\"\" parent_page_types = ['core.TopicPage'] subpage_types = [] # No child", "= models.DecimalField( help_text=\"Score given when any case study region tag", "'core.DetailPage', 'core.LessonPlaceholderPage', ] # `title` comes from Page superclass and", "models are imported if backlink_path and len(backlink_path.split('/')) > 3: _path", "'Country tag for personalisation' verbose_name_plural = 'Country tags for personalisation'", "core_blocks.CaseStudyStaticBlock(icon='fa-book')), ( 'Step', core_blocks.StepByStepBlock(icon='cog'), ), ( 'fictional_example', blocks.StructBlock( [('fiction_body', blocks.RichTextBlock(icon='openquote'))],", "= _backlink context['backlink_title'] = self._get_backlink_title(_backlink) if isinstance(self.get_parent().specific, TopicPage): # In", "if self.subtitles_en: output.append( { 'srclang': 'en', 'label': 'English', 'url': reverse('core:subtitles-serve',", "a HS6, HS4 or HS2 code\"\"\" # free_tagging = False", "mixins from core.case_study_index import delete_cs_index, update_cs_index from core.constants import BACKLINK_QUERYSTRING_NAME,", "page should record read progress # checking if the page", "get_high_level_completion_progress( completion_status=completion_status, ) return context def hero_singular_validation(value): if value and", ") content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='region_tagged_items') class TradingBlocTaggedCaseStudy(ItemBase): tag =", "Check content of media node, which should be present here", "tag data only comes via data migration class Meta: verbose_name", "on_delete=models.CASCADE, related_name='+', ) panels = [ MagnaPageChooserPanel('page', [DetailPage, CuratedListPage, TopicPage]),", "django.utils.text import slugify from django.utils.translation import ugettext_lazy as _ from", "Plan pages/links. \"\"\" # We have to re-arrange EXPORT_PLAN_SECTION_TITLES_URLS after", "), ), ( 'quote', core_blocks.CaseStudyQuoteBlock(), ), ], validators=[case_study_body_validation], help_text=( 'This", "BACKLINK_QUERYSTRING_NAME, RICHTEXT_FEATURES__MINIMAL from core.context import get_context_provider from core.utils import PageTopicHelper,", "'Generic'), ) ################ # Content fields ################ description = RichTextField()", "field = self._meta.get_field('template') field.choices = self.template_choices field.required = True @cached_classmethod", "= ['core.LandingPage'] template_choices = (('learn/interstitial.html', 'Learn'),) ################ # Content fields", "very unlikely # to happen. return backlink_path return None #", "# We have to re-arrange EXPORT_PLAN_SECTION_TITLES_URLS after import # because", "given backlink, see if we can get a title that", "return error_messages def _low_level_validation(value, error_messages): # Check content of media", "when any case study trading bloc tag matches the any", "content of media node, which should be present here MEDIA_BLOCK", "video + One image * (video must comes first so", "'label': 'English', 'url': reverse('core:subtitles-serve', args=[self.id, 'en']), 'default': False, }, )", "**kwargs) def __str__(self): return self.name @register_snippet class Tag(models.Model): name =", "image or video allowed in Hero section', code='invalid'), ) class", "values['title'] for url, values in EXPORTPLAN_URL_MAP.items()} def _get_backlink(self, request): \"\"\"Try", "return self.title class PersonalisationHSCodeTag(TagBase): \"\"\"Custom tag for personalisation. Tag value", ") country_region = models.DecimalField( help_text=\"Score given when any case study", "on save, if not already set if not self.slug: self.slug", "= [FieldPanel('name')] class Meta: ordering = ('name',) def __str__(self): return", "'Learn'), ('core/generic_page.html', 'Generic'), ) ################ # Content fields ################ description", "by end users, so will redirect to the parent module", "[('video', core_blocks.VideoBlock())], template='core/struct_video_block.html', icon='fa-play', ), ), ('case_study', core_blocks.CaseStudyStaticBlock(icon='fa-book')), ( 'Step',", "): \"\"\" Generic page, freely inspired by Codered page \"\"\"", "as # a child of another page type... page_topic_helper =", "value will be a HS6, HS4 or HS2 code\"\"\" #", "), MultiFieldPanel( [ FieldPanel('hs_code_tags'), FieldPanel('country_code_tags'), FieldPanel('region_code_tags'), FieldPanel('trading_bloc_code_tags'), ], heading='Case Study", "used.\"\"\" parent_page_types = ['core.CuratedListPage'] subpage_types = [ 'core.DetailPage', 'core.LessonPlaceholderPage', ]", "it via Wagtail-Transfer register_snippet(Redirect) class GreatMedia(Media): transcript = models.TextField( verbose_name=_('Transcript'),", "('image', 'filter_spec', 'focal_point_key') @property def alt(self): return self.image.alt_text @register_snippet class", "\"\"\"Return a lookup dictionary of URL Slugs->title for all the", "), ], template='learn/pros_and_cons.html', icon='fa-arrow-right', ), ), ('choose_do_not_choose', core_blocks.ChooseDoNotChooseBlock()), ( 'image',", "CreationDateTimeField('created', null=True) modified = ModificationDateTimeField('modified', null=True) def save(self, **kwargs): self.update_modified", "), ( 'fictional_example', blocks.StructBlock( [('fiction_body', blocks.RichTextBlock(icon='openquote'))], template='learn/fictional_company_example.html', icon='fa-commenting-o', ), ),", "render_as_field(self): instance_obj = self.get_chosen_item() context = { 'field': self.bound_field, self.object_type_name:", "for personalisation. Tag value will be an ISO-2 Country code", "strict about presence and ordering of these nodes if [node.block_type", "When we create a new CS need to call create", "models.ForeignKey(AltTextImage, on_delete=models.CASCADE, related_name='renditions') class Meta: unique_together = ('image', 'filter_spec', 'focal_point_key')", "user's export markets falls into unless there is an exact", "= slugify(self.name) super().save(*args, **kwargs) def __str__(self): return self.name @register_snippet class", "freely inspired by Codered page \"\"\" class Meta: abstract =", "N806 QUOTE_BLOCK = 'quote' # noqa N806 # we need", "request that brought us to this view. Only accepts backlinks", "('Europe') \"\"\" free_tagging = False class Meta: verbose_name = 'Region", "need to be strict about presence and ordering of these", "Meta: unique_together = ('image', 'filter_spec', 'focal_point_key') @property def alt(self): return", "comes from Page superclass and that's all we need here", "def __str__(self): return self.name class TimeStampedModel(models.Model): \"\"\"Modified version of django_extensions.db.models.TimeStampedModel", "provider = get_context_provider(request=request, page=self) if provider: context.update(provider.get_context_data(request=request, page=self)) return context", "topic in self.get_topics(): count += DetailPage.objects.live().descendant_of(topic).count() return count def get_context(self,", "redirect to the parent module if accessed. Also, for the", "import ( get_high_level_completion_progress, get_module_completion_progress, ) from domestic.helpers import get_lesson_completion_status context", "######### # Panels ########## content_panels = Page.content_panels + [ StreamFieldPanel('hero'),", "from core.helpers import ( get_high_level_completion_progress, get_module_completion_progress, ) from domestic.helpers import", "read progress # checking if the page is already marked", "= models.DecimalField( help_text=\"Score given when any case study country tag", "'core.ListPage', 'core.InterstitialPage', 'domestic.DomesticDashboard', ] template_choices = ( ('learn/landing_page.html', 'Learn'), ('core/generic_page.html',", "get_first_lesson from exportplan.core.data import ( SECTION_SLUGS as EXPORTPLAN_SLUGS, SECTIONS as", "] subpage_types = [ 'core.ListPage', 'core.InterstitialPage', 'domestic.DomesticDashboard', ] template_choices =", "= [ ObjectList(cls.content_panels, heading='Content'), ObjectList(cls.layout_panels, heading='Layout'), ObjectList(cls.settings_panels, heading='Settings', classname='settings'), ]", "ImageChooserPanel('image'), ] def get_topics(self, live=True) -> models.QuerySet: qs = TopicPage.objects.live().specific().descendant_of(self)", "super().get_context(request) if request.user.is_authenticated: completion_status = get_lesson_completion_status(request.user) context['high_level_completion_progress'] = get_high_level_completion_progress( completion_status=completion_status,", ") # We are keeping the personalisation-relevant tags in separate", "first 4 digits of any of the user's products \"", "class IndustryTag(models.Model): name = models.CharField(max_length=100, unique=True) icon = models.ForeignKey( AltTextImage,", "get_context_provider(request=request, page=self) if provider: context.update(provider.get_context_data(request=request, page=self)) return context class LandingPage(CMSGenericPage):", "# noqa N806 # we need to be strict about", "block', ), ), ( 'video', core_blocks.SimpleVideoBlock( template='core/includes/_video_full_width.html', help_text='Video displayed within", "can validate it _backlink = self._get_backlink(request) if _backlink: context['backlink'] =", "'Automated list pages' def get_context(self, request, *args, **kwargs): from core.helpers", "_backlink context['backlink_title'] = self._get_backlink_title(_backlink) if isinstance(self.get_parent().specific, TopicPage): # In a", "@cached_property def count_detail_pages(self): count = 0 for topic in self.get_topics():", "to the export plan) from the querystring on the request", "if provider: context.update(provider.get_context_data(request=request, page=self)) return context class LandingPage(CMSGenericPage): parent_page_types =", "fields ################ heading = RichTextField() image = models.ForeignKey( get_image_model_string(), null=True,", "as a Snippet to be able to transfer it with", "def _get_backlink(self, request): \"\"\"Try to extract a backlink (used for", "contain one Media section (with one or ' 'two items", "__init__(self, *args, **kwargs): super().__init__(*args, **kwargs) field = self._meta.get_field('template') field.choices =", "] class Meta: verbose_name_plural = 'Countries' ordering = ('name',) def", "default=10, decimal_places=3, max_digits=5, ) lesson = models.DecimalField( help_text=\"Score given when", "icon='fa-commenting-o', ), ), ( 'ITA_Quote', core_blocks.ITAQuoteBlock(icon='fa-quote-left'), ), ( 'pros_cons', blocks.StructBlock(", "[ ( 'recap_item', blocks.StructBlock( [ ('title', blocks.CharBlock(icon='fa-header')), ( 'item', blocks.StreamBlock(", "# features a full URL as its OWN querystring param", "that it is displayed first) * Two images \"\"\" error_messages", "module = models.DecimalField( help_text=\"Score given when the user's lesson's module", "models.DecimalField( help_text=\"Score given when any case study country tag exactly", "any of ' \"the user's export markets falls into unless", "class ListPage(CMSGenericPage): parent_page_types = ['core.LandingPage'] subpage_types = ['core.CuratedListPage'] template_choices =", "matches the region of any of the user's export markets", "ListPage(CMSGenericPage): parent_page_types = ['core.LandingPage'] subpage_types = ['core.CuratedListPage'] template_choices = (('learn/automated_list_page.html',", "core_blocks, mixins from core.case_study_index import delete_cs_index, update_cs_index from core.constants import", "class method render_as_field 'obj_type': instance_obj.specific.__class__.__name__ if instance_obj else None, }", "= [ FieldPanel('name'), FieldPanel('region'), ] class Meta: verbose_name_plural = 'Countries'", ") ################ # Content fields ################ description = RichTextField() button", "mixins.WagtailGA360Mixin and GA360Mixin are not used.\"\"\" parent_page_types = ['core.CuratedListPage'] subpage_types", "get_context(self, request, *args, **kwargs): context = super().get_context(request) context['refresh_on_market_change'] = True", "len(subnode_block_types) == 2: if set(subnode_block_types) == {VIDEO_BLOCK}: # Two videos:", "personalisation' class PersonalisationCountryTag(TagBase): \"\"\"Custom tag for personalisation. Tag value will", ") panels = [FieldPanel('name'), ImageChooserPanel('icon')] class Meta: ordering = ('name',)", "we have.\"\"\" return {url: values['title'] for url, values in EXPORTPLAN_URL_MAP.items()}", "ID for indexing self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified', True)) super().save(**kwargs)", "tag for personalisation' verbose_name_plural = 'Country tags for personalisation' class", "import GA360Mixin from modelcluster.contrib.taggit import ClusterTaggableManager from modelcluster.models import ClusterableModel,", "= TaggableManager(through=ContentModuleTag, blank=True) panels = [ FieldPanel('title'), FieldPanel('content'), FieldPanel('tags'), ]", "a full-page-width block', ), ), ] ) recap = StreamField(", "decimal_places=3, max_digits=5, ) module = models.DecimalField( help_text=\"Score given when the", "be an Trading blocs \"\"\" free_tagging = False class Meta:", "class LandingPage(CMSGenericPage): parent_page_types = [ 'domestic.DomesticHomePage', # TODO: once we've", "!= QUOTE_BLOCK] != [MEDIA_BLOCK, TEXT_BLOCK]: error_messages.append( ( 'This block must", "import mark_safe from django.utils.text import slugify from django.utils.translation import ugettext_lazy", "and modified fields, inheritance causes issues with field clash. \"\"\"", ") trading_blocs = models.DecimalField( help_text='Score given when any case study", "field ) subtitles_en = models.TextField( verbose_name=_('English subtitles'), null=True, blank=True, help_text='English-language", "'quote', core_blocks.CaseStudyQuoteBlock(), ), ], validators=[case_study_body_validation], help_text=( 'This block must contain", "noqa N806 VIDEO_BLOCK = 'video' # noqa N806 for node", "as EXPORTPLAN_URL_MAP, ) # If we make a Redirect appear", "from taggit.managers import TaggableManager from taggit.models import ItemBase, TagBase, TaggedItemBase", "NOQA N805 panels = [ ObjectList(cls.content_panels, heading='Content'), ObjectList(cls.layout_panels, heading='Layout'), ObjectList(cls.settings_panels,", "backlink_path ): # The check for '://' will stop us", "return backlink_path return None # safe default def _get_backlink_title(self, backlink_path):", "are not used.\"\"\" parent_page_types = ['core.TopicPage'] subpage_types = [] #", "redirect return self._redirect_to_parent_module() def serve(self, request): return self._redirect_to_parent_module() class DetailPage(CMSGenericPage):", "\" 'unless there is an HS6 match.', default=4, decimal_places=3, max_digits=5,", "wagtail.snippets.models import register_snippet from wagtail.utils.decorators import cached_classmethod from wagtailmedia.models import", "= models.CharField(max_length=255) panels = [ FieldPanel('name'), ] def __str__(self): return", "class CaseStudyScoringSettings(BaseSetting): threshold = models.DecimalField( help_text='This is the minimum score", "matches the first 4 digits of any of the user's", "ordering = ('name',) def __str__(self): return self.name @register_snippet class Country(models.Model):", "*args, **kwargs): # Automatically set slug on save, if not", "to have to be ' 'considered before being presented to", "max_length=255, choices=None, ) ######### # Panels ########## layout_panels = [FieldPanel('template')]", "EXPORTPLAN_SLUGS and '://' not in backlink_path ): # The check", "blank=True, on_delete=models.SET_NULL) panels = [ FieldPanel('name'), FieldPanel('region'), ] class Meta:", "see if we can get a title that goes with", "context context['next_module'] = next_module.specific context['next_lesson'] = get_first_lesson(next_module) return context class", "= models.CharField(max_length=255) content = RichTextField() tags = TaggableManager(through=ContentModuleTag, blank=True) panels", "import PageTopicHelper, get_first_lesson from exportplan.core.data import ( SECTION_SLUGS as EXPORTPLAN_SLUGS,", "simple to modules (`CuratedListPage`s). Not intented to be viewed by", "'Region tag for personalisation' verbose_name_plural = 'Region tags for personalisation'", "= ['core.LandingPage'] subpage_types = ['core.CuratedListPage'] template_choices = (('learn/automated_list_page.html', 'Learn'),) record_read_progress", "[subnode.block_type for subnode in node.value] if len(subnode_block_types) == 2: if", "fields ################ description = RichTextField() button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True,", "class AbstractObjectHash(models.Model): class Meta: abstract = True content_hash = models.CharField(max_length=1000)", "get_lesson_completion_status(request.user) context['high_level_completion_progress'] = get_high_level_completion_progress( completion_status=completion_status, ) return context ################ #", "selection via its tags. The decision about the appropriate Case", "'recap_item', blocks.StructBlock( [ ('title', blocks.CharBlock(icon='fa-header')), ( 'item', blocks.StreamBlock( [ (", "PersonalisationCountryTag(TagBase): \"\"\"Custom tag for personalisation. Tag value will be an", "models.ForeignKey( PersonalisationHSCodeTag, related_name='hscode_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='hs_code_tagged_items')", "ISO-2 Country code ('DE') \"\"\" free_tagging = False class Meta:", "super().save(**kwargs) update_cs_index(self) def delete(self, **kwargs): delete_cs_index(self.id) super().delete(**kwargs) def get_cms_standalone_view_url(self): return", "video, only * One video + One image * (video", "case study trading bloc tag matches the any trading bloc", "= page_topic_helper.module if page_topic_helper: topic_page = page_topic_helper.get_page_topic() if topic_page: context['current_topic']", "provider: context.update(provider.get_context_data(request=request, page=self)) return context class LandingPage(CMSGenericPage): parent_page_types = [", "which should be present here MEDIA_BLOCK = 'media' # noqa", "super().get_context(request) # Give the template a simple way to link", "register_snippet(Redirect) class GreatMedia(Media): transcript = models.TextField( verbose_name=_('Transcript'), blank=False, null=True #", "class Meta: verbose_name_plural = 'Case studies' get_latest_by = 'modified' ordering", "on_delete=models.CASCADE, related_name='steps') panels = [ FieldPanel('title'), FieldPanel('body'), FieldPanel('position'), FieldPanel('selector'), ]", "# Deliberately not rich-text / no formatting body = StreamField(", "['page__pk'] unique_together = ['page', 'sso_id'] # TODO: deprecate and remove", "to templates for backwards compatibility only # Added obj_type on", "self.name @register_snippet class Region(models.Model): name = models.CharField(max_length=100, unique=True) panels =", "wagtail.contrib.redirects.models import Redirect from wagtail.contrib.settings.models import BaseSetting, register_setting from wagtail.core", "a DetailPage currently MAY be used as # a child", "editors hs_code_tags = ClusterTaggableManager(through='core.HSCodeTaggedCaseStudy', blank=True, verbose_name='HS-code tags') country_code_tags = ClusterTaggableManager(", "reason, mixins.WagtailGA360Mixin and GA360Mixin are not used.\"\"\" parent_page_types = ['core.CuratedListPage']", "('core/generic_page.html', 'Generic'), ) ################ # Content fields ################ description =", "instance_obj = self.get_chosen_item() context = { 'field': self.bound_field, self.object_type_name: instance_obj,", "user's lesson's module is tagged in the case study \"", "the request that brought us to this view. Only accepts", "], null=True, blank=True, ) ######### # Panels ######### content_panels =", "[ 'core.CuratedListPage', # TEMPORARY: remove after topics refactor migration has", "return output class AbstractObjectHash(models.Model): class Meta: abstract = True content_hash", "(('learn/automated_list_page.html', 'Learn'),) record_read_progress = models.BooleanField( default=False, help_text='Should we record when", "return self.get_topics().count() @cached_property def count_detail_pages(self): count = 0 for topic", "cleaner mapping of lessons (`DetailPage`s) to modules (`CuratedListPage`s). Not intented", "mapping of lessons (`DetailPage`s) to modules (`CuratedListPage`s). Not intented to", "is very unlikely # to happen. return backlink_path return None", "raise StreamBlockValidationError( non_block_errors=ValidationError('; '.join(error_messages), code='invalid'), ) class MagnaPageChooserPanel(PageChooserPanel): show_label =", "= models.CharField( max_length=255, choices=None, ) ######### # Panels ########## layout_panels", "once, so we don't waste the network call to get", "(eg a crafted attack # URL), but that's an acceptable", "verbose_name = 'Trading bloc tag for personalisation' verbose_name_plural = 'Trading", "= [ MultiFieldPanel([FieldPanel('country_exact'), FieldPanel('country_region'), FieldPanel('trading_blocs')]) ] lesson_tab = [MultiFieldPanel([FieldPanel('lesson'), FieldPanel('topic'),", "title that goes with it. For now, this is limited", "via Wagtail-Transfer register_snippet(Redirect) class GreatMedia(Media): transcript = models.TextField( verbose_name=_('Transcript'), blank=False,", "heading='Steps'), ] def __str__(self): return self.page.title class TourStep(Orderable): title =", "CreationDateTimeField('created', null=True) modified = ModificationDateTimeField('modified', null=True) panels = [ MultiFieldPanel(", "block to show will happen when the page attempts to", "modelcluster.models import ClusterableModel, ParentalKey from taggit.managers import TaggableManager from taggit.models", "return self._redirect_to_parent_module() def serve(self, request): return self._redirect_to_parent_module() class LessonPlaceholderPage(mixins.AuthenticatedUserRequired, Page):", "mark_safe(render_to_string(self.field_template, context)) class CaseStudyRelatedPages(Orderable): case_study = ParentalKey( 'core.CaseStudy', related_name='related_pages', on_delete=models.SET_NULL,", "a case study. Supports personalised selection via its tags. The", "lesson = models.DecimalField( help_text=\"Score given when user's lesson is tagged", "['core.TopicPage'] subpage_types = [] # No child pages allowed for", "= False class Meta: verbose_name = 'Region tag for personalisation'", "[ ObjectList(cls.content_panels, heading='Content'), ObjectList(cls.layout_panels, heading='Layout'), ObjectList(cls.settings_panels, heading='Settings', classname='settings'), ] return", "(with one or two items in it) ' 'and/or Quote", "will be an Trading blocs \"\"\" free_tagging = False class", "contain one Media section (with one or two items in", "- passed to templates for backwards compatibility only # Added", "] # `title` comes from Page superclass and that's all", "null=True, blank=True, on_delete=models.SET_NULL) panels = [ FieldPanel('name'), FieldPanel('region'), ] class", "node has the following content: * One image, only *", ") country_exact = models.DecimalField( help_text=\"Score given when any case study", "( 'fictional_example', blocks.StructBlock( [('fiction_body', blocks.RichTextBlock(icon='openquote'))], template='learn/fictional_company_example.html', icon='fa-commenting-o', ), ), (", "import ClusterTaggableManager from modelcluster.models import ClusterableModel, ParentalKey from taggit.managers import", "return self.name @register_snippet class Country(models.Model): name = models.CharField(max_length=255) slug =", "] template_choices = (('learn/detail_page.html', 'Learn'),) class Meta: verbose_name = 'Detail", "fields ################ hero = StreamField( [ ('Image', core_blocks.ImageBlock(template='core/includes/_hero_image.html')), ('Video', core_blocks.SimpleVideoBlock(template='core/includes/_hero_video.html')),", "parent_page_types = ['core.CuratedListPage'] subpage_types = [ 'core.DetailPage', 'core.LessonPlaceholderPage', ] #", "[ { 'src': self.url, 'type': mimetypes.guess_type(self.filename)[0] or 'application/octet-stream', 'transcript': self.transcript,", "class Meta: get_latest_by = 'modified' ordering = ( '-modified', '-created',", "('choose_do_not_choose', core_blocks.ChooseDoNotChooseBlock()), ( 'image', core_blocks.ImageBlock( template='core/includes/_image_full_width.html', help_text='Image displayed within a", "render the relevant CaseStudyBlock. Note that this is rendered via", "), ), ( 'text', blocks.RichTextBlock( features=RICHTEXT_FEATURES__MINIMAL, ), ), ( 'quote',", "but we have to keep it registered as a Snippet", "to create and modified fields, inheritance causes issues with field", "*args, **kwargs): self.handle_page_view(request) return super().serve(request, **kwargs) @cached_property def topic_title(self): return", "*args, **kwargs): super().__init__(*args, **kwargs) field = self._meta.get_field('template') field.choices = self.template_choices", "] def __str__(self): return self.title class PersonalisationHSCodeTag(TagBase): \"\"\"Custom tag for", "'modified' ordering = ( '-modified', '-created', ) abstract = True", "list_page=list_page, sso_id=request.user.pk, ) def serve(self, request, *args, **kwargs): self.handle_page_view(request) return", "sections we have.\"\"\" return {url: values['title'] for url, values in", "get_lesson_completion_status context = super().get_context(request) # Give the template a simple", ") ######### # Panels ########## content_panels = Page.content_panels + [", "created in wagtail admin is_creatable = False template_choices = []", "this view. Only accepts backlinks that we KNOW are for", "it _backlink = self._get_backlink(request) if _backlink: context['backlink'] = _backlink context['backlink_title']", "############### # Layout fields ############### template = models.CharField( max_length=255, choices=None,", "blank=True) ######### # Panels ######### content_panels = CMSGenericPage.content_panels + [", "name = models.CharField(max_length=100, unique=True) icon = models.ForeignKey( AltTextImage, null=True, blank=True,", "return error_messages def case_study_body_validation(value): \"\"\"Ensure the case study has exactly", "generate_content_hash(field_file): filehash = hashlib.md5() field_file.open() filehash.update(field_file.read()) field_file.close() return filehash.hexdigest() class", "all we need here def _redirect_to_parent_module(self): return HttpResponseRedirect(self.get_parent().url) def serve_preview(self,", "VIDEO_BLOCK: # implicitly, [0] must be an image # video", "core.case_study_index import delete_cs_index, update_cs_index from core.constants import BACKLINK_QUERYSTRING_NAME, RICHTEXT_FEATURES__MINIMAL from", "given when any case study region tag matches the region", "when any case study region tag matches the region of", "False class Meta: verbose_name = 'Region tag for personalisation' verbose_name_plural", "pages' ################ # Content fields ################ hero = StreamField( [", "OWN querystring param (eg a crafted attack # URL), but", "image # video after image: not allowed error_messages.append('The video must", "for '://' will stop us accepting a backlink which #", "import StreamBlockValidationError from wagtail.core.fields import RichTextField, StreamField from wagtail.core.models import", "conditional because a DetailPage currently MAY be used as #", "not used.\"\"\" parent_page_types = ['core.CuratedListPage'] subpage_types = [ 'core.DetailPage', 'core.LessonPlaceholderPage',", "as its OWN querystring param (eg a crafted attack #", "if len(subnode_block_types) == 2: if set(subnode_block_types) == {VIDEO_BLOCK}: # Two", "error_messages) if error_messages: raise StreamBlockValidationError( non_block_errors=ValidationError('; '.join(error_messages), code='invalid'), ) class", "'default': False, }, ) return output class AbstractObjectHash(models.Model): class Meta:", "* (video must comes first so that it is displayed", "support for more than just English if self.subtitles_en: output.append( {", "_high_level_validation(value, error_messages) error_messages = _low_level_validation(value, error_messages) if error_messages: raise StreamBlockValidationError(", "new CS need to call create to obtain an ID", "( '-modified', '-created', ) @register_setting class CaseStudyScoringSettings(BaseSetting): threshold = models.DecimalField(", "return None # safe default def _get_backlink_title(self, backlink_path): \"\"\"For a", "market_tab = [ MultiFieldPanel([FieldPanel('country_exact'), FieldPanel('country_region'), FieldPanel('trading_blocs')]) ] lesson_tab = [MultiFieldPanel([FieldPanel('lesson'),", "= super().get_context(request) if request.user.is_authenticated: completion_status = get_lesson_completion_status(request.user) context['high_level_completion_progress'] = get_high_level_completion_progress(", ") context['high_level_completion_progress'] = get_high_level_completion_progress( completion_status=completion_status, ) return context def hero_singular_validation(value):", "study HS6 tag matches the complete HS6 code of '", "return self._redirect_to_parent_module() def serve(self, request): return self._redirect_to_parent_module() class DetailPage(CMSGenericPage): estimated_read_duration", "RichTextField() button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True) image = models.ForeignKey(", "data migration class Meta: verbose_name = 'HS Code tag for", "because a DetailPage currently MAY be used as # a", "tag matches the complete HS6 code of ' \"any of", "image = models.ForeignKey( get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) ########", "models.CharField(max_length=255) tour = ParentalKey(Tour, on_delete=models.CASCADE, related_name='steps') panels = [ FieldPanel('title'),", "on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='hs_code_tagged_items') class CountryTaggedCaseStudy(ItemBase): tag", "is rendered via Wagtail's ModelAdmin, so appears in the sidebar,", "CMSGenericPage.content_panels + [FieldPanel('description'), FieldPanel('button_label')] class CuratedListPage(CMSGenericPage): parent_page_types = ['core.ListPage'] subpage_types", "Meta: verbose_name = 'Automated list page' verbose_name_plural = 'Automated list", "for personalisation' verbose_name_plural = 'HS Code tags for personalisation' class", "'obj_type': instance_obj.specific.__class__.__name__ if instance_obj else None, } return mark_safe(render_to_string(self.field_template, context))", "or topic match.', default=2, decimal_places=3, max_digits=5, ) product_hs6 = models.DecimalField(", "Panels ######### content_panels = CMSGenericPage.content_panels + [ StreamFieldPanel('button'), ] class", "user's lesson's topic is tagged in the case study \"", "Meta: verbose_name = 'Detail page' verbose_name_plural = 'Detail pages' ################", "class TradingBlocTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationTradingBlocTag, related_name='trading_bloc_tagged_case_studies', on_delete=models.CASCADE ) content_object", "self.name @register_snippet class Tag(models.Model): name = models.CharField(max_length=100, unique=True) panels =", "'text' # noqa N806 MEDIA_BLOCK = 'media' # noqa N806", "allowed for placeholders # `title` comes from Page superclass and", "the first 2 digits of any of the user's products", "appropriate Case Study block to show will happen when the", "models.DecimalField( help_text=\"Score given when any case study region tag matches", "import slugify from django.utils.translation import ugettext_lazy as _ from django_extensions.db.fields", "VTT format', ) admin_form_fields = Media.admin_form_fields + ( 'transcript', 'subtitles_en',", "ordering = ['page__pk'] unique_together = ['page', 'sso_id'] # TODO: deprecate", "noqa N806 MEDIA_BLOCK = 'media' # noqa N806 QUOTE_BLOCK =", "request, *args, **kwargs): context = super().get_context(request) self.set_ga360_payload( page_id=self.id, business_unit=settings.GA360_BUSINESS_UNIT, site_section=str(self.url", "self.add_ga360_data_to_payload(request) context['ga360'] = self.ga360_payload provider = get_context_provider(request=request, page=self) if provider:", "panels = [ FieldPanel('name'), ] def __str__(self): return self.name @register_snippet", "TabbedInterface( [ ObjectList(product_tab, heading='Product'), ObjectList(market_tab, heading='Market'), ObjectList(lesson_tab, heading='Lesson'), ObjectList(threshold_tab, heading='Threshold'),", "you're wondering what's going on here: # https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models class HSCodeTaggedCaseStudy(ItemBase):", "\"\"\"Custom tag for personalisation. Tag value will be an Trading", "are keeping the personalisation-relevant tags in separate # fields to", "= models.DecimalField( help_text='Score given when any case study trading bloc", "CountryTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationCountryTag, related_name='country_tagged_case_studies', on_delete=models.CASCADE ) content_object =", "matches the any trading bloc that any of ' \"the", "one Media section (with one or two items in it)", "ordering = ( '-modified', '-created', ) abstract = True #", "( 'video', blocks.StructBlock( [('video', core_blocks.VideoBlock())], template='core/struct_video_block.html', icon='fa-play', ), ), ('case_study',", "( 'recap_item', blocks.StructBlock( [ ('title', blocks.CharBlock(icon='fa-header')), ( 'item', blocks.StreamBlock( [", "# checking if the page should record read progress #", "decimal_places=3, max_digits=5, ) country_exact = models.DecimalField( help_text=\"Score given when any", "# Panels ######## content_panels = CMSGenericPage.content_panels + [ FieldPanel('heading'), ImageChooserPanel('image'),", "'paragraph', blocks.RichTextBlock(options={'class': 'objectives'}), ), ('ListItem', core_blocks.Item()), ] ) body =", "[FieldPanel('record_read_progress')] content_panels = CMSGenericPage.content_panels + [FieldPanel('description'), FieldPanel('button_label')] class CuratedListPage(CMSGenericPage): parent_page_types", "max_num=2, ), ), ( 'text', blocks.RichTextBlock( features=RICHTEXT_FEATURES__MINIMAL, ), ), (", ") @register_setting class CaseStudyScoringSettings(BaseSetting): threshold = models.DecimalField( help_text='This is the", "not used.\"\"\" parent_page_types = ['core.TopicPage'] subpage_types = [] # No", "the page should record read progress # checking if the", "/ no formatting body = StreamField( [ ( 'media', blocks.StreamBlock(", "HS2 tag matches the first 2 digits of any of", "for configuring and representing very simple to modules (`CuratedListPage`s). Not", "also lesson or topic match.', default=2, decimal_places=3, max_digits=5, ) product_hs6", "there is an exact country or region match.\", default=2, decimal_places=3,", "= models.SlugField(max_length=100, unique=True) region = models.ForeignKey(Region, null=True, blank=True, on_delete=models.SET_NULL) panels", "self.summary_context return f'{display_name}' def save(self, **kwargs): # When we create", "] edit_handler = TabbedInterface( [ ObjectList(product_tab, heading='Product'), ObjectList(market_tab, heading='Market'), ObjectList(lesson_tab,", "True content_hash = models.CharField(max_length=1000) @staticmethod def generate_content_hash(field_file): filehash = hashlib.md5()", "'core.TopicPage', ] template_choices = (('learn/curated_list_page.html', 'Learn'),) ################ # Content fields", "( 'cons', blocks.StreamBlock( [ ( 'item', core_blocks.Item(icon='fa-arrow-right'), ) ] ),", "# Content fields ################ button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True)", "FieldPanel('button_label')] class CuratedListPage(CMSGenericPage): parent_page_types = ['core.ListPage'] subpage_types = [ 'core.TopicPage',", "we need to be strict about presence and ordering of", "[ ( 'media', blocks.StreamBlock( [ ('video', core_blocks.SimpleVideoBlock(template='core/includes/_case_study_video.html')), ('image', core_blocks.ImageBlock()), ],", "about the appropriate Case Study block to show will happen", "snippet for use as a case study. Supports personalised selection", "def __str__(self): return self.name @register_snippet class Country(models.Model): name = models.CharField(max_length=255)", "Wagtail-Transfer register_snippet(Redirect) class GreatMedia(Media): transcript = models.TextField( verbose_name=_('Transcript'), blank=False, null=True", "country_region = models.DecimalField( help_text=\"Score given when any case study region", "# Content fields ################ description = RichTextField() button = StreamField([('button',", "an HS6 or HS4 match.', default=2, decimal_places=3, max_digits=5, ) country_exact", "from django.utils.functional import cached_property from django.utils.safestring import mark_safe from django.utils.text", "import ( FieldPanel, InlinePanel, MultiFieldPanel, ObjectList, PageChooserPanel, StreamFieldPanel, TabbedInterface, )", "it.' ) ) return error_messages def _low_level_validation(value, error_messages): # Check", "= models.ForeignKey( AltTextImage, null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) panels =", "we create a new CS need to call create to", "class Meta: ordering = ['page__pk'] unique_together = ['page', 'sso_id'] #", "MEDIA_BLOCK: subnode_block_types = [subnode.block_type for subnode in node.value] if len(subnode_block_types)", "by Codered page \"\"\" class Meta: abstract = True #", "'objectives'}), ), ('ListItem', core_blocks.Item()), ] ) body = StreamField( [", "verbose_name_plural = 'Detail pages' ################ # Content fields ################ hero", "import settings from django.core.exceptions import ValidationError from django.db import models", "save(self, **kwargs): self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified', True)) super().save(**kwargs) class", "and that's all we need here def _redirect_to_parent_module(self): return HttpResponseRedirect(self.get_parent().url)", "context['current_topic'] = topic_page context['page_topic'] = topic_page.title if next_lesson: context['next_lesson'] =", "network call to get the data twice completion_status = get_lesson_completion_status(request.user)", "########## content_panels = Page.content_panels + [ StreamFieldPanel('hero'), StreamFieldPanel('objective'), StreamFieldPanel('body'), StreamFieldPanel('recap'),", "= StreamField( [ ( 'paragraph', blocks.RichTextBlock(options={'class': 'objectives'}), ), ('ListItem', core_blocks.Item()),", "panels = [FieldPanel('name'), ImageChooserPanel('icon')] class Meta: ordering = ('name',) def", "'unless there is also lesson match.', default=4, decimal_places=3, max_digits=5, )", "related_name='+' ) ######## # Panels ######## content_panels = CMSGenericPage.content_panels +", "on_delete=models.CASCADE, related_name='hs_code_tagged_items') class CountryTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationCountryTag, related_name='country_tagged_case_studies', on_delete=models.CASCADE", "Quote sections, then one Text section.' ), ) # We", ") ] ), ), ( 'cons', blocks.StreamBlock( [ ( 'item',", "there is also lesson match.', default=4, decimal_places=3, max_digits=5, ) module", "data only comes via data migration class Meta: verbose_name =", "node, which should be present here MEDIA_BLOCK = 'media' #", "it is displayed first) * Two images \"\"\" error_messages =", "body = StreamField( [ ( 'paragraph', blocks.StructBlock( [('paragraph', blocks.RichTextBlock())], template='core/struct_paragraph_block.html',", "PageTopicHelper, get_first_lesson from exportplan.core.data import ( SECTION_SLUGS as EXPORTPLAN_SLUGS, SECTIONS", "= ( '-modified', '-created', ) abstract = True # Content", "def count_detail_pages(self): count = 0 for topic in self.get_topics(): count", "= models.ForeignKey(AltTextImage, on_delete=models.CASCADE, related_name='renditions') class Meta: unique_together = ('image', 'filter_spec',", "return self.image.alt_text @register_snippet class Tour(ClusterableModel): page = models.OneToOneField('wagtailcore.Page', on_delete=models.CASCADE, related_name='tour')", "class InterstitialPage(CMSGenericPage): parent_page_types = ['core.LandingPage'] template_choices = (('learn/interstitial.html', 'Learn'),) ################", "models.ForeignKey( PersonalisationCountryTag, related_name='country_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='country_tagged_items')", "allow this page type to be created in wagtail admin", "heading='Layout'), ObjectList(cls.settings_panels, heading='Settings', classname='settings'), ] return TabbedInterface(panels).bind_to(model=cls) def get_template(self, request,", "'Learn'),) class Meta: verbose_name = 'Detail page' verbose_name_plural = 'Detail", "# to happen. return backlink_path return None # safe default", "way to link back to the parent # learning module", "_redirect_to_parent_module(self): return HttpResponseRedirect(self.get_parent().url) def serve_preview(self, request, mode_name='dummy'): # It doesn't", "import get_context_provider from core.utils import PageTopicHelper, get_first_lesson from exportplan.core.data import", "for personalisation. Tag value will be a HS6, HS4 or", "), ('case_study', core_blocks.CaseStudyStaticBlock(icon='fa-book')), ( 'Step', core_blocks.StepByStepBlock(icon='cog'), ), ( 'fictional_example', blocks.StructBlock(", "in value: if node.block_type == MEDIA_BLOCK: subnode_block_types = [subnode.block_type for", "( ListPage.objects.ancestor_of(self) .filter(record_read_progress=True) .exclude(page_views_list__sso_id=request.user.pk, page_views_list__page=self) .first() ) if list_page: PageView.objects.get_or_create(", "# URL), but that's an acceptable limitation here and is", "a still image.') return error_messages def case_study_body_validation(value): \"\"\"Ensure the case", "country or region match.\", default=2, decimal_places=3, max_digits=5, ) product_tab =", "show will happen when the page attempts to render the", "remove class ContentModuleTag(TaggedItemBase): content_object = ParentalKey('core.ContentModule', on_delete=models.CASCADE, related_name='tagged_items') # TODO:", "request.user.is_authenticated: # get this once, so we don't waste the", "[ PageChooserPanel('page'), FieldPanel('title'), FieldPanel('body'), FieldPanel('button_text'), MultiFieldPanel([InlinePanel('steps')], heading='Steps'), ] def __str__(self):", "AltTextImage, null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) panels = [FieldPanel('name'), ImageChooserPanel('icon')]", "the template a simple way to link back to the", "] def __str__(self): display_name = self.title if self.title else self.summary_context", "if page_topic_helper: topic_page = page_topic_helper.get_page_topic() if topic_page: context['current_topic'] = topic_page", "`title` comes from Page superclass and that's all we need", "the parent module if accessed. Also, for the above reason,", "here def _redirect_to_parent_module(self): return HttpResponseRedirect(self.get_parent().url) def serve_preview(self, request, mode_name='dummy'): #", "we always redirect return self._redirect_to_parent_module() def serve(self, request): return self._redirect_to_parent_module()", "personalisation. Tag value will be an ISO-2 Country code ('DE')", "templates for backwards compatibility only # Added obj_type on base", "return {url: values['title'] for url, values in EXPORTPLAN_URL_MAP.items()} def _get_backlink(self,", "the user's export markets \" 'unless there is an exact", "from wagtail.images.models import AbstractImage, AbstractRendition, Image from wagtail.snippets.models import register_snippet", "= models.CharField(max_length=255) panels = [ PageChooserPanel('page'), FieldPanel('title'), FieldPanel('body'), FieldPanel('button_text'), MultiFieldPanel([InlinePanel('steps')],", "_backlink: context['backlink'] = _backlink context['backlink_title'] = self._get_backlink_title(_backlink) if isinstance(self.get_parent().specific, TopicPage):", "slugify(self.name) super().save(*args, **kwargs) def __str__(self): return self.name @register_snippet class Tag(models.Model):", "3: _path = backlink_path.split('/')[3] return self._export_plan_url_map.get(_path) def get_context(self, request, *args,", "'en']), 'default': False, }, ) return output class AbstractObjectHash(models.Model): class", "through='core.CountryTaggedCaseStudy', blank=True, verbose_name='Country tags' ) region_code_tags = ClusterTaggableManager( through='core.RegionTaggedCaseStudy', blank=True,", "self.template_choices field.required = True @cached_classmethod def get_edit_handler(cls): # NOQA N805", "models.SlugField(max_length=100, unique=True) region = models.ForeignKey(Region, null=True, blank=True, on_delete=models.SET_NULL) panels =", "icon='fa-commenting-o', ), ) ] ) ######### # Panels ########## content_panels", "######### content_panels = CMSGenericPage.content_panels + [ StreamFieldPanel('button'), ] class ListPage(CMSGenericPage):", "ModificationDateTimeField from great_components.mixins import GA360Mixin from modelcluster.contrib.taggit import ClusterTaggableManager from", "'video' # noqa N806 for node in value: if node.block_type", "of django_extensions.db.models.TimeStampedModel Unfortunately, because null=True needed to be added to", "FieldPanel('title'), FieldPanel('lead_title'), FieldPanel('summary_context'), StreamFieldPanel('body'), ], heading='Case Study content', ), MultiFieldPanel(", "] def get_topics(self, live=True) -> models.QuerySet: qs = TopicPage.objects.live().specific().descendant_of(self) if", "context['backlink'] = _backlink context['backlink_title'] = self._get_backlink_title(_backlink) if isinstance(self.get_parent().specific, TopicPage): #", "= False # DISABLED until tag data only comes via", "models.DecimalField( help_text=\"Score given when the user's lesson's module is tagged", "is an exact country match.', default=2, decimal_places=3, max_digits=5, ) trading_blocs", "template = models.CharField( max_length=255, choices=None, ) ######### # Panels ##########", "######### # Panels ######### content_panels = CMSGenericPage.content_panels + [ StreamFieldPanel('button'),", "'core.TopicPage', ] template_choices = (('learn/detail_page.html', 'Learn'),) class Meta: verbose_name =", "the export plan) from the querystring on the request that", "One video, only * One video + One image *", "template_choices = (('learn/automated_list_page.html', 'Learn'),) record_read_progress = models.BooleanField( default=False, help_text='Should we", "= topic_page.title if next_lesson: context['next_lesson'] = next_lesson else: next_module =", "( get_high_level_completion_progress, get_module_completion_progress, ) from domestic.helpers import get_lesson_completion_status context =", "lookup and make the UX easier for editors hs_code_tags =", "django_extensions.db.fields import CreationDateTimeField, ModificationDateTimeField from great_components.mixins import GA360Mixin from modelcluster.contrib.taggit", "import render_to_string from django.urls import reverse from django.utils.functional import cached_property", "extract a backlink (used for a link to the export", "import register_snippet from wagtail.utils.decorators import cached_classmethod from wagtailmedia.models import Media", ") class Meta: verbose_name = 'Automated list page' verbose_name_plural =", "the any trading bloc that any of ' \"the user's", "QUOTE_BLOCK = 'quote' # noqa N806 # we need to", "__str__(self): return self.name class TimeStampedModel(models.Model): \"\"\"Modified version of django_extensions.db.models.TimeStampedModel Unfortunately,", "Tag value will be an Trading blocs \"\"\" free_tagging =", "max_digits=5, ) country_region = models.DecimalField( help_text=\"Score given when any case", "heading='Product'), ObjectList(market_tab, heading='Market'), ObjectList(lesson_tab, heading='Lesson'), ObjectList(threshold_tab, heading='Threshold'), ] ) class", "create a new CS need to call create to obtain", "def render_as_field(self): instance_obj = self.get_chosen_item() context = { 'field': self.bound_field,", "= page_topic_helper.get_page_topic() if topic_page: context['current_topic'] = topic_page context['page_topic'] = topic_page.title", "@cached_property def module(self): \"\"\"Gets the learning module this lesson belongs", "*args, **kwargs): from core.helpers import get_high_level_completion_progress from domestic.helpers import get_lesson_completion_status", "study.\", default=8, decimal_places=3, max_digits=5, ) topic = models.DecimalField( help_text=\"Score given", "class CMSGenericPage( mixins.EnableTourMixin, mixins.AuthenticatedUserRequired, mixins.WagtailGA360Mixin, GA360Mixin, Page, ): \"\"\" Generic", "needs to have to be ' 'considered before being presented", "class ImageHash(AbstractObjectHash): image = models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.CASCADE, related_name='+') class", "return self.name @register_snippet class IndustryTag(models.Model): name = models.CharField(max_length=100, unique=True) icon", "Trading blocs \"\"\" free_tagging = False class Meta: verbose_name =", "not self.slug: self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return", "hero = StreamField( [ ('Image', core_blocks.ImageBlock(template='core/includes/_hero_image.html')), ('Video', core_blocks.SimpleVideoBlock(template='core/includes/_hero_video.html')), ], null=True,", "via its tags. The decision about the appropriate Case Study", "hero_singular_validation(value): if value and len(value) > 1: raise StreamBlockValidationError( non_block_errors=ValidationError('Only", "base class method render_as_field 'obj_type': instance_obj.specific.__class__.__name__ if instance_obj else None,", "StreamFieldPanel('body'), ], heading='Case Study content', ), MultiFieldPanel( [ FieldPanel('hs_code_tags'), FieldPanel('country_code_tags'),", "getattr(self, 'update_modified', True)) super().save(**kwargs) class Meta: get_latest_by = 'modified' ordering", "@property def alt(self): return self.image.alt_text @register_snippet class Tour(ClusterableModel): page =", "\"\"\"Custom tag for personalisation. Tag value will be a geographical", "following it.' ) ) return error_messages def _low_level_validation(value, error_messages): #", "for this video, in VTT format', ) admin_form_fields = Media.admin_form_fields", "to the parent module if accessed. Also, for the above", "free_tagging = False class Meta: verbose_name = 'Region tag for", "########## layout_panels = [FieldPanel('template')] settings_panels = [FieldPanel('slug')] + Page.settings_panels def", "self.slug: self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return self.name", "context['page_topic'] = topic_page.title if next_lesson: context['next_lesson'] = next_lesson else: next_module", "= 'Case studies' get_latest_by = 'modified' ordering = ( '-modified',", "= ParentalKey( to='core.CaseStudy', on_delete=models.CASCADE, related_name='trading_bloc_tagged_items' ) def _high_level_validation(value, error_messages): TEXT_BLOCK", "to transfer it with Wagtail-Transfer \"\"\" title = models.CharField( max_length=255,", "page_topic_helper: topic_page = page_topic_helper.get_page_topic() if topic_page: context['current_topic'] = topic_page context['page_topic']", "displayed within a full-page-width block', ), ), ] ) recap", "more than just English if self.subtitles_en: output.append( { 'srclang': 'en',", "\"the user's export markets falls into unless there is an", "exportplan.core.data import ( SECTION_SLUGS as EXPORTPLAN_SLUGS, SECTIONS as EXPORTPLAN_URL_MAP, )", "placeholders # `title` comes from Page superclass and that's all", "# noqa N806 MEDIA_BLOCK = 'media' # noqa N806 QUOTE_BLOCK", "= unquote(backlink_path) if len(backlink_path.split('/')) > 2 and ( backlink_path.split('/')[3] in", "personalised selection via its tags. The decision about the appropriate", "must contain one Media section (with one or two items", "Country(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=100, unique=True) region =", "2: if set(subnode_block_types) == {VIDEO_BLOCK}: # Two videos: not allowed", "from modelcluster.models import ClusterableModel, ParentalKey from taggit.managers import TaggableManager from", "\"\"\" title = models.CharField( max_length=255, blank=False, verbose_name='Internal case study title',", "to be created in wagtail admin is_creatable = False template_choices", "= 'media' # noqa N806 QUOTE_BLOCK = 'quote' # noqa", "= False class Meta: verbose_name = 'Trading bloc tag for", "{ 'src': self.url, 'type': mimetypes.guess_type(self.filename)[0] or 'application/octet-stream', 'transcript': self.transcript, }", "self._meta.get_field('template') field.choices = self.template_choices field.required = True @cached_classmethod def get_edit_handler(cls):", "through='core.RegionTaggedCaseStudy', blank=True, verbose_name='Region tags' ) trading_bloc_code_tags = ClusterTaggableManager( through='core.TradingBlocTaggedCaseStudy', blank=True,", "InterstitialPage(CMSGenericPage): parent_page_types = ['core.LandingPage'] template_choices = (('learn/interstitial.html', 'Learn'),) ################ #", "Orderable, Page from wagtail.images import get_image_model_string from wagtail.images.edit_handlers import ImageChooserPanel", "minimum score which a case study needs to have to", "wagtail.core.fields import RichTextField, StreamField from wagtail.core.models import Orderable, Page from", "help_text=( 'This block must contain one Media section (with one", "because it features lazily-evaluated URLs that aren't ready when #", "default def _get_backlink_title(self, backlink_path): \"\"\"For a given backlink, see if", "as a case study. Supports personalised selection via its tags.", "instance_obj else None, } return mark_safe(render_to_string(self.field_template, context)) class CaseStudyRelatedPages(Orderable): case_study", "just English if self.subtitles_en: output.append( { 'srclang': 'en', 'label': 'English',", "import ItemBase, TagBase, TaggedItemBase from wagtail.admin.edit_handlers import ( FieldPanel, InlinePanel,", "['core.LandingPage'] subpage_types = ['core.CuratedListPage'] template_choices = (('learn/automated_list_page.html', 'Learn'),) record_read_progress =", "instance_obj.specific.__class__.__name__ if instance_obj else None, } return mark_safe(render_to_string(self.field_template, context)) class", "= models.TextField() class Meta: ordering = ['page__pk'] unique_together = ['page',", "markets falls into unless there is an exact country or", "MEDIA_BLOCK = 'media' # noqa N806 VIDEO_BLOCK = 'video' #", "in node.value] if len(subnode_block_types) == 2: if set(subnode_block_types) == {VIDEO_BLOCK}:", "args=[self.id]) class Meta: verbose_name_plural = 'Case studies' get_latest_by = 'modified'", "filehash.update(field_file.read()) field_file.close() return filehash.hexdigest() class DocumentHash(AbstractObjectHash): document = models.ForeignKey( 'wagtaildocs.Document',", "def topic_title(self): return self.get_parent().title @cached_property def module(self): \"\"\"Gets the learning", "link back to the parent # learning module (ListPage) context['parent_page_url']", "is displayed first) * Two images \"\"\" error_messages = []", "displayed first) * Two images \"\"\" error_messages = [] if", "as read list_page = ( ListPage.objects.ancestor_of(self) .filter(record_read_progress=True) .exclude(page_views_list__sso_id=request.user.pk, page_views_list__page=self) .first()", "def __str__(self): return self.name @register_snippet class Tag(models.Model): name = models.CharField(max_length=100,", "unique=True) icon = models.ForeignKey( AltTextImage, null=True, blank=True, on_delete=models.SET_NULL, related_name='+', )", "super().get_context(request) context['refresh_on_market_change'] = True # Prepare backlink to the export", "# noqa N806 for node in value: if node.block_type ==", "a new CS need to call create to obtain an", "N806 for node in value: if node.block_type == MEDIA_BLOCK: subnode_block_types", "get_context(self, request, *args, **kwargs): context = super().get_context(request) self.set_ga360_payload( page_id=self.id, business_unit=settings.GA360_BUSINESS_UNIT,", "= models.CharField( max_length=255, blank=False, verbose_name='Internal case study title', ) #", "Personalisation', ), MultiFieldPanel( [ InlinePanel('related_pages', label='Related pages'), ], heading='Related Lesson,", "needed to be added to create and modified fields, inheritance", "until tag data only comes via data migration class Meta:", "MagnaPageChooserPanel(PageChooserPanel): show_label = False field_template = 'admin/wagtailadmin/edit_handlers/field_panel_field.html' def render_as_field(self): instance_obj", "to call create to obtain an ID for indexing self.update_modified", "> 2 and ( backlink_path.split('/')[3] in EXPORTPLAN_SLUGS and '://' not", "= ModificationDateTimeField('modified', null=True) panels = [ MultiFieldPanel( [ FieldPanel('title'), FieldPanel('lead_title'),", "tags' ) region_code_tags = ClusterTaggableManager( through='core.RegionTaggedCaseStudy', blank=True, verbose_name='Region tags' )", "FieldPanel('summary_context'), StreamFieldPanel('body'), ], heading='Case Study content', ), MultiFieldPanel( [ FieldPanel('hs_code_tags'),", "[ ('route', core_blocks.RouteSectionBlock()), ], null=True, blank=True, ) ######### # Panels", "node in value if node.block_type != QUOTE_BLOCK] != [MEDIA_BLOCK, TEXT_BLOCK]:", "Meta: verbose_name = 'Trading bloc tag for personalisation' verbose_name_plural =", "help_text=\"Score given when any case study HS2 tag matches the", "if request.user.is_authenticated: completion_status = get_lesson_completion_status(request.user) context['high_level_completion_progress'] = get_high_level_completion_progress( completion_status=completion_status, )", "FieldPanel('trading_blocs')]) ] lesson_tab = [MultiFieldPanel([FieldPanel('lesson'), FieldPanel('topic'), FieldPanel('module')])] threshold_tab = [", "######### # Panels ######### content_panels = CMSGenericPage.content_panels + [ FieldPanel('description'),", "a Quote section, then one Text section following it.' )", "for use as a case study. Supports personalised selection via", "[MultiFieldPanel([FieldPanel('lesson'), FieldPanel('topic'), FieldPanel('module')])] threshold_tab = [ MultiFieldPanel( [ FieldPanel('threshold'), ]", "related_name='related_pages', on_delete=models.SET_NULL, null=True, blank=True, ) page = models.ForeignKey( 'wagtailcore.Page', on_delete=models.CASCADE,", "models.TextField( verbose_name=_('Transcript'), blank=False, null=True # left null because was an", "collection?', ) class Meta: verbose_name = 'Automated list page' verbose_name_plural", "comes via data migration class Meta: verbose_name = 'HS Code", "models.CharField( max_length=255, blank=False, verbose_name='Internal case study title', ) # old", "unique=True) panels = [FieldPanel('name')] class Meta: ordering = ('name',) def", "after topics refactor migration has run 'core.TopicPage', ] template_choices =", "in backlink_path ): # The check for '://' will stop", "def module(self): \"\"\"Gets the learning module this lesson belongs to\"\"\"", "@register_setting class CaseStudyScoringSettings(BaseSetting): threshold = models.DecimalField( help_text='This is the minimum", "and ordering of these nodes if [node.block_type for node in", "page attempts to render the relevant CaseStudyBlock. Note that this", "TaggableManager(through=ContentModuleTag, blank=True) panels = [ FieldPanel('title'), FieldPanel('content'), FieldPanel('tags'), ] def", "blocks.StructBlock( [ ('title', blocks.CharBlock(icon='fa-header')), ( 'item', blocks.StreamBlock( [ ( 'item',", "to aid lookup and make the UX easier for editors", "easier for editors hs_code_tags = ClusterTaggableManager(through='core.HSCodeTaggedCaseStudy', blank=True, verbose_name='HS-code tags') country_code_tags", "self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified', True)) super().save(**kwargs) update_cs_index(self) def delete(self,", "'update_modified', True)) super().save(**kwargs) update_cs_index(self) def delete(self, **kwargs): delete_cs_index(self.id) super().delete(**kwargs) def", "restructured, remove this permission 'domestic.GreatDomesticHomePage', ] subpage_types = [ 'core.ListPage',", "# Panels ########## content_panels = Page.content_panels + [ StreamFieldPanel('hero'), StreamFieldPanel('objective'),", "serve(self, request): return self._redirect_to_parent_module() class DetailPage(CMSGenericPage): estimated_read_duration = models.DurationField(null=True, blank=True)", "context['current_module'] = page_topic_helper.module if page_topic_helper: topic_page = page_topic_helper.get_page_topic() if topic_page:", "content_object = ParentalKey('core.ContentModule', on_delete=models.CASCADE, related_name='tagged_items') # TODO: deprecate and remove", "def serve(self, request, *args, **kwargs): self.handle_page_view(request) return super().serve(request, **kwargs) @cached_property", ") return context ################ # Content fields ################ description =", "the region of any of the user's export markets \"", "ordering = ('name',) def __str__(self): return self.name class TimeStampedModel(models.Model): \"\"\"Modified", "MultiFieldPanel, ObjectList, PageChooserPanel, StreamFieldPanel, TabbedInterface, ) from wagtail.contrib.redirects.models import Redirect", "PageChooserPanel, StreamFieldPanel, TabbedInterface, ) from wagtail.contrib.redirects.models import Redirect from wagtail.contrib.settings.models", "help_text='English-language subtitles for this video, in VTT format', ) admin_form_fields", "title', ) # old name company_name summary_context = models.CharField(max_length=255, blank=False,", "django_extensions.db.models.TimeStampedModel Unfortunately, because null=True needed to be added to create", "FieldPanel('lead_title'), FieldPanel('summary_context'), StreamFieldPanel('body'), ], heading='Case Study content', ), MultiFieldPanel( [", "when the user's lesson's module is tagged in the case", "when any case study country tag exactly matches one of", "= models.ForeignKey( PersonalisationRegionTag, related_name='region_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE,", "of another page type... page_topic_helper = PageTopicHelper(self) next_lesson = page_topic_helper.get_next_lesson()", "waste the network call to get the data twice completion_status", "import TaggableManager from taggit.models import ItemBase, TagBase, TaggedItemBase from wagtail.admin.edit_handlers", "page=self, list_page=list_page, sso_id=request.user.pk, ) def serve(self, request, *args, **kwargs): self.handle_page_view(request)", "ModelAdmin, so appears in the sidebar, but we have to", "# TEMPORARY: remove after topics refactor migration has run 'core.TopicPage',", "= ['core.CuratedListPage'] subpage_types = [ 'core.DetailPage', 'core.LessonPlaceholderPage', ] # `title`", "non_block_errors=ValidationError('; '.join(error_messages), code='invalid'), ) class MagnaPageChooserPanel(PageChooserPanel): show_label = False field_template", "subpage_types = [ 'core.TopicPage', ] template_choices = (('learn/curated_list_page.html', 'Learn'),) ################", "*args, **kwargs): return self.template def get_context(self, request, *args, **kwargs): context", "\"\"\"Structural page to allow for configuring and representing very simple", "!= [MEDIA_BLOCK, TEXT_BLOCK]: error_messages.append( ( 'This block must contain one", "# a child of another page type... page_topic_helper = PageTopicHelper(self)", "for indexing self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified', True)) super().save(**kwargs) update_cs_index(self)", "'image', core_blocks.ImageBlock( template='core/includes/_image_full_width.html', help_text='Image displayed within a full-page-width block', ),", "'Automated list page' verbose_name_plural = 'Automated list pages' def get_context(self,", "('name',) def save(self, *args, **kwargs): # Automatically set slug on", "region_code_tags = ClusterTaggableManager( through='core.RegionTaggedCaseStudy', blank=True, verbose_name='Region tags' ) trading_bloc_code_tags =", "related_name='page_views_list') sso_id = models.TextField() class Meta: ordering = ['page__pk'] unique_together", "= TabbedInterface( [ ObjectList(product_tab, heading='Product'), ObjectList(market_tab, heading='Market'), ObjectList(lesson_tab, heading='Lesson'), ObjectList(threshold_tab,", "] ) body = StreamField( [ ( 'paragraph', blocks.StructBlock( [('paragraph',", "Meta: abstract = True # Do not allow this page", "null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) panels = [FieldPanel('name'), ImageChooserPanel('icon')] class", "to show will happen when the page attempts to render", "values in EXPORTPLAN_URL_MAP.items()} def _get_backlink(self, request): \"\"\"Try to extract a", "= [ FieldPanel('title'), FieldPanel('body'), FieldPanel('position'), FieldPanel('selector'), ] @register_snippet class Product(models.Model):", "request): return self._redirect_to_parent_module() class LessonPlaceholderPage(mixins.AuthenticatedUserRequired, Page): \"\"\"Structural page to allow", "Redirect from wagtail.contrib.settings.models import BaseSetting, register_setting from wagtail.core import blocks", "are for the export plan, else ignore it.\"\"\" backlink_path =", "safe default def _get_backlink_title(self, backlink_path): \"\"\"For a given backlink, see", "= False field_template = 'admin/wagtailadmin/edit_handlers/field_panel_field.html' def render_as_field(self): instance_obj = self.get_chosen_item()", "first 2 digits of any of the user's products \"", "country_code_tags = ClusterTaggableManager( through='core.CountryTaggedCaseStudy', blank=True, verbose_name='Country tags' ) region_code_tags =", "and/or a Quote section, then one Text section following it.'", "Automatically set slug on save, if not already set if", "######### settings_panels = CMSGenericPage.settings_panels + [FieldPanel('record_read_progress')] content_panels = CMSGenericPage.content_panels +", "on_delete=models.SET_NULL, related_name='+' ) ######## # Panels ######## content_panels = CMSGenericPage.content_panels", "next_lesson else: next_module = self.module.get_next_sibling() if not next_module: return context", "in separate # fields to aid lookup and make the", "CaseStudyBlock. Note that this is rendered via Wagtail's ModelAdmin, so", "= Image.admin_form_fields + ('alt_text',) class Rendition(AbstractRendition): image = models.ForeignKey(AltTextImage, on_delete=models.CASCADE,", "return qs @cached_property def count_topics(self): return self.get_topics().count() @cached_property def count_detail_pages(self):", "self._redirect_to_parent_module() def serve(self, request): return self._redirect_to_parent_module() class DetailPage(CMSGenericPage): estimated_read_duration =", "from the querystring on the request that brought us to", "we did it') # old name summary lead_title = models.TextField(blank=False)", "= models.TextField(blank=False) # Deliberately not rich-text / no formatting body", "blocks as core_blocks, mixins from core.case_study_index import delete_cs_index, update_cs_index from", "may be used in a case study.') elif subnode_block_types[1] ==", "FieldPanel('topic'), FieldPanel('module')])] threshold_tab = [ MultiFieldPanel( [ FieldPanel('threshold'), ] )", "value and len(value) > 1: raise StreamBlockValidationError( non_block_errors=ValidationError('Only one image", "[] # No child pages allowed for placeholders # `title`", "Module, also used for Personalisation', ), ] def __str__(self): display_name", "'') if backlink_path is not None: backlink_path = unquote(backlink_path) if", "the user's products \" 'unless there is an HS6 or", "document = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, on_delete=models.CASCADE, related_name='+' ) class", "= get_lesson_completion_status(request.user) context['high_level_completion_progress'] = get_high_level_completion_progress( completion_status=completion_status, ) return context ################", "RichTextField() tags = TaggableManager(through=ContentModuleTag, blank=True) panels = [ FieldPanel('title'), FieldPanel('content'),", "default=8, decimal_places=3, max_digits=5, ) topic = models.DecimalField( help_text=\"Score given when", "max_digits=5, ) product_hs4 = models.DecimalField( help_text=\"Score given when any case", "StreamField( [ ( 'recap_item', blocks.StructBlock( [ ('title', blocks.CharBlock(icon='fa-header')), ( 'item',", "get_latest_by = 'modified' ordering = ( '-modified', '-created', ) abstract", "related_name='hs_code_tagged_items') class CountryTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationCountryTag, related_name='country_tagged_case_studies', on_delete=models.CASCADE )", "which a case study needs to have to be '", "an HS6 match.', default=4, decimal_places=3, max_digits=5, ) product_hs2 = models.DecimalField(", "request, *args, **kwargs): from core.helpers import get_high_level_completion_progress from domestic.helpers import", "because null=True needed to be added to create and modified", "= [] # TO COME: support for more than just", "= [ 'core.CuratedListPage', # TEMPORARY: remove after topics refactor migration", "models.DecimalField( help_text=\"Score given when user's lesson is tagged in the", "verbose_name_plural = 'Countries' ordering = ('name',) def save(self, *args, **kwargs):", "if list_page: PageView.objects.get_or_create( page=self, list_page=list_page, sso_id=request.user.pk, ) def serve(self, request,", "or HS2 code\"\"\" # free_tagging = False # DISABLED until", "= ['core.ListPage'] subpage_types = [ 'core.TopicPage', ] template_choices = (('learn/curated_list_page.html',", "CaseStudyRelatedPages(Orderable): case_study = ParentalKey( 'core.CaseStudy', related_name='related_pages', on_delete=models.SET_NULL, null=True, blank=True, )", "the user's export markets.\", default=4, decimal_places=3, max_digits=5, ) country_region =", "'core.CuratedListPage', # TEMPORARY: remove after topics refactor migration has run", "default=2, decimal_places=3, max_digits=5, ) product_hs6 = models.DecimalField( help_text='Score given when", "ImageChooserPanel from wagtail.images.models import AbstractImage, AbstractRendition, Image from wagtail.snippets.models import", "verbose_name_plural = 'Region tags for personalisation' class PersonalisationTradingBlocTag(TagBase): \"\"\"Custom tag", "page_topic_helper.module if page_topic_helper: topic_page = page_topic_helper.get_page_topic() if topic_page: context['current_topic'] =", "MEDIA_BLOCK = 'media' # noqa N806 QUOTE_BLOCK = 'quote' #", "== MEDIA_BLOCK: subnode_block_types = [subnode.block_type for subnode in node.value] if", "], heading='Case Study content', ), MultiFieldPanel( [ FieldPanel('hs_code_tags'), FieldPanel('country_code_tags'), FieldPanel('region_code_tags'),", "self._export_plan_url_map.get(_path) def get_context(self, request, *args, **kwargs): context = super().get_context(request) context['refresh_on_market_change']", "self.set_ga360_payload( page_id=self.id, business_unit=settings.GA360_BUSINESS_UNIT, site_section=str(self.url or '/').split('/')[1], ) self.add_ga360_data_to_payload(request) context['ga360'] =", "request, *args, **kwargs): context = super().get_context(request) context['refresh_on_market_change'] = True #", "subpage_types = ['core.CuratedListPage'] template_choices = (('learn/automated_list_page.html', 'Learn'),) record_read_progress = models.BooleanField(", "_get_backlink_title(self, backlink_path): \"\"\"For a given backlink, see if we can", "in the case study \" 'unless there is also lesson", "################ button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True) ######### # Panels", "FieldPanel('content'), FieldPanel('tags'), ] def __str__(self): return self.title class PersonalisationHSCodeTag(TagBase): \"\"\"Custom", "icon='fa-font', ), ), ( 'video', blocks.StructBlock( [('video', core_blocks.VideoBlock())], template='core/struct_video_block.html', icon='fa-play',", "'core.InterstitialPage', 'domestic.DomesticDashboard', ] template_choices = ( ('learn/landing_page.html', 'Learn'), ('core/generic_page.html', 'Generic'),", "('title', blocks.CharBlock(icon='fa-header')), ( 'item', blocks.StreamBlock( [ ( 'item', core_blocks.Item(), )", "for personalisation' verbose_name_plural = 'Region tags for personalisation' class PersonalisationTradingBlocTag(TagBase):", "class CountryTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationCountryTag, related_name='country_tagged_case_studies', on_delete=models.CASCADE ) content_object", "lessons (`DetailPage`s) to modules (`CuratedListPage`s). Not intented to be viewed", "pages allowed for placeholders # `title` comes from Page superclass", "page_topic_helper.get_next_lesson() context['current_lesson'] = self context['current_module'] = page_topic_helper.module if page_topic_helper: topic_page", "a backlink (used for a link to the export plan)", "case_study = ParentalKey( 'core.CaseStudy', related_name='related_pages', on_delete=models.SET_NULL, null=True, blank=True, ) page", "null because was an existing field ) subtitles_en = models.TextField(", "page = models.OneToOneField('wagtailcore.Page', on_delete=models.CASCADE, related_name='tour') title = models.CharField(max_length=255) body =", "type to be created in wagtail admin is_creatable = False", "), ( 'video', core_blocks.SimpleVideoBlock( template='core/includes/_video_full_width.html', help_text='Video displayed within a full-page-width", "class RegionTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationRegionTag, related_name='region_tagged_case_studies', on_delete=models.CASCADE ) content_object", "will be an ISO-2 Country code ('DE') \"\"\" free_tagging =", "# Panels ########## layout_panels = [FieldPanel('template')] settings_panels = [FieldPanel('slug')] +", "[ MultiFieldPanel( [ FieldPanel('threshold'), ] ) ] edit_handler = TabbedInterface(", "complete HS6 code of ' \"any of the user's products\",", "), ) # We are keeping the personalisation-relevant tags in", "), ('ListItem', core_blocks.Item()), ] ) body = StreamField( [ (", "personalisation' verbose_name_plural = 'HS Code tags for personalisation' class PersonalisationCountryTag(TagBase):", "the case study has exactly both a media node and", "attempts to render the relevant CaseStudyBlock. Note that this is", "for personalisation. Tag value will be a geographical string ('Europe')", "@register_snippet class IndustryTag(models.Model): name = models.CharField(max_length=100, unique=True) icon = models.ForeignKey(", "in Hero section', code='invalid'), ) class TopicPage(mixins.AuthenticatedUserRequired, Page): \"\"\"Structural page", "TODO: deprecate and remove class ContentModuleTag(TaggedItemBase): content_object = ParentalKey('core.ContentModule', on_delete=models.CASCADE,", "verbose_name_plural = 'Trading bloc tags for personalisation' # If you're", "modified fields, inheritance causes issues with field clash. \"\"\" created", "page=self)) return context class LandingPage(CMSGenericPage): parent_page_types = [ 'domestic.DomesticHomePage', #", "################ # Content fields ################ heading = RichTextField() image =", "any case study HS6 tag matches the complete HS6 code", "] @property def subtitles(self): output = [] # TO COME:", "'domestic.GreatDomesticHomePage', ] subpage_types = [ 'core.ListPage', 'core.InterstitialPage', 'domestic.DomesticDashboard', ] template_choices", "= page_topic_helper.get_next_lesson() context['current_lesson'] = self context['current_module'] = page_topic_helper.module if page_topic_helper:", "Snippet, we can sync it via Wagtail-Transfer register_snippet(Redirect) class GreatMedia(Media):", "users, so will redirect to the parent module if accessed.", "allowed error_messages.append('The video must come before a still image.') return", "ObjectList(cls.content_panels, heading='Content'), ObjectList(cls.layout_panels, heading='Layout'), ObjectList(cls.settings_panels, heading='Settings', classname='settings'), ] return TabbedInterface(panels).bind_to(model=cls)", "title = models.CharField(max_length=255) body = models.CharField(max_length=255) position = models.CharField(max_length=255) selector", "= models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.CASCADE, related_name='+') class AltTextImage(AbstractImage): alt_text =", "null=True, blank=True, help_text='English-language subtitles for this video, in VTT format',", "self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return self.name @register_snippet", "= get_high_level_completion_progress( completion_status=completion_status, ) return context ################ # Content fields", "tags for personalisation' class PersonalisationRegionTag(TagBase): \"\"\"Custom tag for personalisation. Tag", "error_messages: raise StreamBlockValidationError( non_block_errors=ValidationError('; '.join(error_messages), code='invalid'), ) class MagnaPageChooserPanel(PageChooserPanel): show_label", ") page = models.ForeignKey( 'wagtailcore.Page', on_delete=models.CASCADE, related_name='+', ) panels =", "= next_module.specific context['next_lesson'] = get_first_lesson(next_module) return context class PageView(TimeStampedModel): page", "if node.block_type == MEDIA_BLOCK: subnode_block_types = [subnode.block_type for subnode in", "update_cs_index(self) def delete(self, **kwargs): delete_cs_index(self.id) super().delete(**kwargs) def get_cms_standalone_view_url(self): return reverse('cms_extras:case-study-view',", "is also lesson or topic match.', default=2, decimal_places=3, max_digits=5, )", "It doesn't matter what is passed as mode_name - we", "qs = TopicPage.objects.live().specific().descendant_of(self) if live: qs = qs.live() return qs", "and representing very simple to modules (`CuratedListPage`s). Not intented to", "StreamFieldPanel('body'), ] class InterstitialPage(CMSGenericPage): parent_page_types = ['core.LandingPage'] template_choices = (('learn/interstitial.html',", "# implicitly, [0] must be an image # video after", "cached_classmethod from wagtailmedia.models import Media from core import blocks as", "Wagtail-Transfer \"\"\" title = models.CharField( max_length=255, blank=False, verbose_name='Internal case study", "title = models.CharField(max_length=255) body = models.CharField(max_length=255) button_text = models.CharField(max_length=255) panels", "into unless there is an exact country or region match.\",", "One video + One image * (video must comes first", "unique=True) region = models.ForeignKey(Region, null=True, blank=True, on_delete=models.SET_NULL) panels = [", "* One video, only * One video + One image", "any trading bloc that any of ' \"the user's export", "we've restructured, remove this permission 'domestic.GreatDomesticHomePage', ] subpage_types = [", "as mode_name - we always redirect return self._redirect_to_parent_module() def serve(self,", "\" 'unless there is an HS6 or HS4 match.', default=2,", "live: qs = qs.live() return qs @cached_property def count_topics(self): return", "lead_title = models.TextField(blank=False) # Deliberately not rich-text / no formatting", "= Page.content_panels + [ StreamFieldPanel('hero'), StreamFieldPanel('objective'), StreamFieldPanel('body'), StreamFieldPanel('recap'), ] def", "we record when a user views a page in this", "parent_page_types = ['core.TopicPage'] subpage_types = [] # No child pages", "('video', core_blocks.SimpleVideoBlock(template='core/includes/_case_study_video.html')), ('image', core_blocks.ImageBlock()), ], min_num=1, max_num=2, ), ), (", "= ('image', 'filter_spec', 'focal_point_key') @property def alt(self): return self.image.alt_text @register_snippet", "( 'item', core_blocks.Item(icon='fa-arrow-right'), ) ] ), ), ( 'cons', blocks.StreamBlock(", "label='Related pages'), ], heading='Related Lesson, Topic & Module, also used", "compatibility only # Added obj_type on base class method render_as_field", "on_delete=models.CASCADE, related_name='renditions') class Meta: unique_together = ('image', 'filter_spec', 'focal_point_key') @property", ") from wagtail.contrib.redirects.models import Redirect from wagtail.contrib.settings.models import BaseSetting, register_setting", "'cons', blocks.StreamBlock( [ ( 'item', core_blocks.Item(icon='fa-arrow-right'), ) ] ), ),", "personalisation. Tag value will be a HS6, HS4 or HS2", "), ] ) recap = StreamField( [ ( 'recap_item', blocks.StructBlock(", "'item', blocks.StreamBlock( [ ( 'item', core_blocks.Item(), ) ] ), ),", "lazily-evaluated URLs that aren't ready when # models are imported", "tags for personalisation' class PersonalisationTradingBlocTag(TagBase): \"\"\"Custom tag for personalisation. Tag", "Case Study block to show will happen when the page", "django.http import HttpResponseRedirect from django.template.loader import render_to_string from django.urls import", "models.CharField(max_length=100) ######### # Panels ######### settings_panels = CMSGenericPage.settings_panels + [FieldPanel('record_read_progress')]", "very simple to modules (`CuratedListPage`s). Not intented to be viewed", "of the user's export markets \" 'unless there is an", "2 and ( backlink_path.split('/')[3] in EXPORTPLAN_SLUGS and '://' not in", "that we KNOW are for the export plan, else ignore", "CMSGenericPage.content_panels + [ StreamFieldPanel('button'), ] class ListPage(CMSGenericPage): parent_page_types = ['core.LandingPage']", "False class Meta: verbose_name = 'Trading bloc tag for personalisation'", ") subtitles_en = models.TextField( verbose_name=_('English subtitles'), null=True, blank=True, help_text='English-language subtitles", "PersonalisationHSCodeTag, related_name='hscode_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='hs_code_tagged_items') class", "models.ForeignKey( PersonalisationTradingBlocTag, related_name='trading_bloc_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey( to='core.CaseStudy', on_delete=models.CASCADE,", "= StreamField( [ ('section', core_blocks.SectionBlock()), ('title', core_blocks.TitleBlock()), ('text', blocks.RichTextBlock(icon='openquote', helptext='Add", "set slug on save, if not already set if not", "class DocumentHash(AbstractObjectHash): document = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, on_delete=models.CASCADE, related_name='+'", "# Content fields ################ description = RichTextField() button_label = models.CharField(max_length=100)", "icon='fa-arrow-right', ), ), ('choose_do_not_choose', core_blocks.ChooseDoNotChooseBlock()), ( 'image', core_blocks.ImageBlock( template='core/includes/_image_full_width.html', help_text='Image", "class TopicPage(mixins.AuthenticatedUserRequired, Page): \"\"\"Structural page to allow for cleaner mapping", "from core.constants import BACKLINK_QUERYSTRING_NAME, RICHTEXT_FEATURES__MINIMAL from core.context import get_context_provider from", "= 'video' # noqa N806 for node in value: if", "error_messages = _low_level_validation(value, error_messages) if error_messages: raise StreamBlockValidationError( non_block_errors=ValidationError('; '.join(error_messages),", "Text section.' ), ) # We are keeping the personalisation-relevant", "# TODO: once we've restructured, remove this permission 'domestic.GreatDomesticHomePage', ]", "CMSGenericPage.content_panels + [ FieldPanel('description'), StreamFieldPanel('button'), ImageChooserPanel('image'), StreamFieldPanel('components'), StreamFieldPanel('body'), ] class", "superclass and that's all we need here def _redirect_to_parent_module(self): return", "FieldPanel('country_code_tags'), FieldPanel('region_code_tags'), FieldPanel('trading_bloc_code_tags'), ], heading='Case Study tags for Personalisation', ),", "= models.DecimalField( help_text=\"Score given when user's lesson's topic is tagged", "on_delete=models.SET_NULL) panels = [ FieldPanel('name'), FieldPanel('region'), ] class Meta: verbose_name_plural", "null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) body = StreamField( [ ('section',", "need to call create to obtain an ID for indexing", "description = RichTextField() button_label = models.CharField(max_length=100) ######### # Panels #########", "= self.get_parent().url if request.user.is_authenticated: # get this once, so we", "on_delete=models.CASCADE, related_name='+') class AltTextImage(AbstractImage): alt_text = models.CharField(max_length=255, blank=True) admin_form_fields =", "= RichTextField() image = models.ForeignKey( get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL, related_name='+'", "completion_status=completion_status, module_page=self, ) context['high_level_completion_progress'] = get_high_level_completion_progress( completion_status=completion_status, ) return context", "# models are imported if backlink_path and len(backlink_path.split('/')) > 3:", "core_blocks.StepByStepBlock(icon='cog'), ), ( 'fictional_example', blocks.StructBlock( [('fiction_body', blocks.RichTextBlock(icon='openquote'))], template='learn/fictional_company_example.html', icon='fa-commenting-o', ),", "'wagtailcore.Page', on_delete=models.CASCADE, related_name='+', ) panels = [ MagnaPageChooserPanel('page', [DetailPage, CuratedListPage,", "FieldPanel, InlinePanel, MultiFieldPanel, ObjectList, PageChooserPanel, StreamFieldPanel, TabbedInterface, ) from wagtail.contrib.redirects.models", "not rich-text / no formatting body = StreamField( [ (", "= ( '-modified', '-created', ) @register_setting class CaseStudyScoringSettings(BaseSetting): threshold =", "from wagtail.images import get_image_model_string from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.images.models", "(('learn/curated_list_page.html', 'Learn'),) ################ # Content fields ################ heading = RichTextField()", ") ] ), ), ], template='learn/pros_and_cons.html', icon='fa-arrow-right', ), ), ('choose_do_not_choose',", "@cached_property def topic_title(self): return self.get_parent().title @cached_property def module(self): \"\"\"Gets the", "mixins.WagtailGA360Mixin and GA360Mixin are not used.\"\"\" parent_page_types = ['core.TopicPage'] subpage_types", "Tag value will be an ISO-2 Country code ('DE') \"\"\"", "from wagtail.admin.edit_handlers import ( FieldPanel, InlinePanel, MultiFieldPanel, ObjectList, PageChooserPanel, StreamFieldPanel,", "for backwards compatibility only # Added obj_type on base class", "_ from django_extensions.db.fields import CreationDateTimeField, ModificationDateTimeField from great_components.mixins import GA360Mixin", "used in a case study.') elif subnode_block_types[1] == VIDEO_BLOCK: #", "admin is_creatable = False template_choices = [] ############### # Layout", "module is tagged in the case study \" 'unless there", "an existing field ) subtitles_en = models.TextField( verbose_name=_('English subtitles'), null=True,", "help_text='Image displayed within a full-page-width block', ), ), ( 'video',", "+ [ FieldPanel('description'), StreamFieldPanel('button'), ImageChooserPanel('image'), StreamFieldPanel('components'), StreamFieldPanel('body'), ] class InterstitialPage(CMSGenericPage):", "**kwargs) @cached_property def topic_title(self): return self.get_parent().title @cached_property def module(self): \"\"\"Gets", "value will be a geographical string ('Europe') \"\"\" free_tagging =", "'page'] @register_snippet class CaseStudy(ClusterableModel): \"\"\"Dedicated snippet for use as a", "noqa N806 QUOTE_BLOCK = 'quote' # noqa N806 # we", "No child pages allowed for placeholders # `title` comes from", "CaseStudy(ClusterableModel): \"\"\"Dedicated snippet for use as a case study. Supports", "Media section (with one or two items in it) '", "= get_first_lesson(next_module) return context class PageView(TimeStampedModel): page = models.ForeignKey(DetailPage, on_delete=models.CASCADE,", "from core.case_study_index import delete_cs_index, update_cs_index from core.constants import BACKLINK_QUERYSTRING_NAME, RICHTEXT_FEATURES__MINIMAL", "= 'text' # noqa N806 MEDIA_BLOCK = 'media' # noqa", "blank=True, on_delete=models.SET_NULL, related_name='+', ) panels = [FieldPanel('name'), ImageChooserPanel('icon')] class Meta:", "[ MagnaPageChooserPanel('page', [DetailPage, CuratedListPage, TopicPage]), ] class Meta: unique_together =", "related_name='hscode_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='hs_code_tagged_items') class CountryTaggedCaseStudy(ItemBase):", "rendered via Wagtail's ModelAdmin, so appears in the sidebar, but", "# Two videos: not allowed error_messages.append('Only one video may be", "before being presented to users. ', default=10, decimal_places=3, max_digits=5, )", "class ContentModuleTag(TaggedItemBase): content_object = ParentalKey('core.ContentModule', on_delete=models.CASCADE, related_name='tagged_items') # TODO: deprecate", "django.utils.safestring import mark_safe from django.utils.text import slugify from django.utils.translation import", "core_blocks.ITAQuoteBlock(icon='fa-quote-left'), ), ( 'pros_cons', blocks.StructBlock( [ ( 'pros', blocks.StreamBlock( [", "True)) super().save(**kwargs) class Meta: get_latest_by = 'modified' ordering = (", "to be strict about presence and ordering of these nodes", "( 'This block must contain one Media section (with one", "import ValidationError from django.db import models from django.http import HttpResponseRedirect", "from core import blocks as core_blocks, mixins from core.case_study_index import", "subtitles'), null=True, blank=True, help_text='English-language subtitles for this video, in VTT", "models.CharField(max_length=255) position = models.CharField(max_length=255) selector = models.CharField(max_length=255) tour = ParentalKey(Tour,", "delete(self, **kwargs): delete_cs_index(self.id) super().delete(**kwargs) def get_cms_standalone_view_url(self): return reverse('cms_extras:case-study-view', args=[self.id]) class", "exactly both a media node and a text node and", "Supports personalised selection via its tags. The decision about the", "( 'image', core_blocks.ImageBlock( template='core/includes/_image_full_width.html', help_text='Image displayed within a full-page-width block',", "Added obj_type on base class method render_as_field 'obj_type': instance_obj.specific.__class__.__name__ if", "be used as # a child of another page type...", "the case study \" 'unless there is also lesson or", "[ 'core.ListPage', 'core.InterstitialPage', 'domestic.DomesticDashboard', ] template_choices = ( ('learn/landing_page.html', 'Learn'),", "'Case studies' get_latest_by = 'modified' ordering = ( '-modified', '-created',", "of lessons (`DetailPage`s) to modules (`CuratedListPage`s). Not intented to be", "[ FieldPanel('name'), FieldPanel('region'), ] class Meta: verbose_name_plural = 'Countries' ordering", "related_name='country_tagged_items') class RegionTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationRegionTag, related_name='region_tagged_case_studies', on_delete=models.CASCADE )", "error_messages.append( ( 'This block must contain one Media section (with", "reason, mixins.WagtailGA360Mixin and GA360Mixin are not used.\"\"\" parent_page_types = ['core.TopicPage']", "( ('learn/landing_page.html', 'Learn'), ('core/generic_page.html', 'Generic'), ) ################ # Content fields", "to allow for cleaner mapping of lessons (`DetailPage`s) to modules", "lookup dictionary of URL Slugs->title for all the Export Plan", "models.ForeignKey( PersonalisationRegionTag, related_name='region_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='region_tagged_items')", "region of any of the user's export markets \" 'unless", "core import blocks as core_blocks, mixins from core.case_study_index import delete_cs_index,", "bloc that any of ' \"the user's export markets falls", "sections, then one Text section.' ), ) # We are", "default=4, decimal_places=3, max_digits=5, ) module = models.DecimalField( help_text=\"Score given when", "\"\"\" created = CreationDateTimeField('created', null=True) modified = ModificationDateTimeField('modified', null=True) def", "super().get_context(request) self.set_ga360_payload( page_id=self.id, business_unit=settings.GA360_BUSINESS_UNIT, site_section=str(self.url or '/').split('/')[1], ) self.add_ga360_data_to_payload(request) context['ga360']", "business_unit=settings.GA360_BUSINESS_UNIT, site_section=str(self.url or '/').split('/')[1], ) self.add_ga360_data_to_payload(request) context['ga360'] = self.ga360_payload provider", "for personalisation' # If you're wondering what's going on here:", "else None, } return mark_safe(render_to_string(self.field_template, context)) class CaseStudyRelatedPages(Orderable): case_study =", "settings from django.core.exceptions import ValidationError from django.db import models from", ") ] ), ), ], template='learn/recap.html', icon='fa-commenting-o', ), ) ]", "get the data twice completion_status = get_lesson_completion_status(request.user) context['module_completion_progress'] = get_module_completion_progress(", "@staticmethod def generate_content_hash(field_file): filehash = hashlib.md5() field_file.open() filehash.update(field_file.read()) field_file.close() return", "come before a still image.') return error_messages def case_study_body_validation(value): \"\"\"Ensure", "ClusterTaggableManager( through='core.TradingBlocTaggedCaseStudy', blank=True, verbose_name='Trading bloc tags' ) created = CreationDateTimeField('created',", "MultiFieldPanel( [ FieldPanel('hs_code_tags'), FieldPanel('country_code_tags'), FieldPanel('region_code_tags'), FieldPanel('trading_bloc_code_tags'), ], heading='Case Study tags", "querystring param (eg a crafted attack # URL), but that's", "as a Snippet, we can sync it via Wagtail-Transfer register_snippet(Redirect)", "when # models are imported if backlink_path and len(backlink_path.split('/')) >", "'Country tags for personalisation' class PersonalisationRegionTag(TagBase): \"\"\"Custom tag for personalisation.", "page' verbose_name_plural = 'Automated list pages' def get_context(self, request, *args,", "def handle_page_view(self, request): if request.user.is_authenticated: # checking if the page", "be an ISO-2 Country code ('DE') \"\"\" free_tagging = False", "be able to transfer it with Wagtail-Transfer \"\"\" title =", "features a full URL as its OWN querystring param (eg", "return filehash.hexdigest() class DocumentHash(AbstractObjectHash): document = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True,", "count_topics(self): return self.get_topics().count() @cached_property def count_detail_pages(self): count = 0 for", "case_study_body_validation(value): \"\"\"Ensure the case study has exactly both a media", "these nodes if [node.block_type for node in value if node.block_type", "blank=True, ) components = StreamField( [ ('route', core_blocks.RouteSectionBlock()), ], null=True,", "One image * (video must comes first so that it", "plan if we detect one and can validate it _backlink", "import get_image_model_string from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.images.models import AbstractImage,", "), ), ( 'ITA_Quote', core_blocks.ITAQuoteBlock(icon='fa-quote-left'), ), ( 'pros_cons', blocks.StructBlock( [", "to extract a backlink (used for a link to the", "# Panels ######### content_panels = CMSGenericPage.content_panels + [ FieldPanel('description'), StreamFieldPanel('button'),", "via data migration class Meta: verbose_name = 'HS Code tag", "content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='hs_code_tagged_items') class CountryTaggedCaseStudy(ItemBase): tag = models.ForeignKey(", "StreamBlockValidationError from wagtail.core.fields import RichTextField, StreamField from wagtail.core.models import Orderable,", "self.title if self.title else self.summary_context return f'{display_name}' def save(self, **kwargs):", "('Image', core_blocks.ImageBlock(template='core/includes/_hero_image.html')), ('Video', core_blocks.SimpleVideoBlock(template='core/includes/_hero_video.html')), ], null=True, blank=True, validators=[hero_singular_validation], ) objective", "**kwargs): from core.helpers import ( get_high_level_completion_progress, get_module_completion_progress, ) from domestic.helpers", "\"\"\" free_tagging = False class Meta: verbose_name = 'Region tag", "VIDEO_BLOCK = 'video' # noqa N806 for node in value:", "] ) recap = StreamField( [ ( 'recap_item', blocks.StructBlock( [", "learning module (ListPage) context['parent_page_url'] = self.get_parent().url if request.user.is_authenticated: # get", "ClusterTaggableManager from modelcluster.models import ClusterableModel, ParentalKey from taggit.managers import TaggableManager", "from wagtail.snippets.models import register_snippet from wagtail.utils.decorators import cached_classmethod from wagtailmedia.models", "class Meta: verbose_name = 'HS Code tag for personalisation' verbose_name_plural", "Two videos: not allowed error_messages.append('Only one video may be used", "for all the Export Plan sections we have.\"\"\" return {url:", "study needs to have to be ' 'considered before being", "verbose_name_plural = 'Automated list pages' def get_context(self, request, *args, **kwargs):", "reverse('cms_extras:case-study-view', args=[self.id]) class Meta: verbose_name_plural = 'Case studies' get_latest_by =", "the above reason, mixins.WagtailGA360Mixin and GA360Mixin are not used.\"\"\" parent_page_types", "PersonalisationCountryTag, related_name='country_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='country_tagged_items') class", "# Panels ######### content_panels = CMSGenericPage.content_panels + [ StreamFieldPanel('button'), ]", "= StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True) image = models.ForeignKey( get_image_model_string(), null=True,", "tagged in the case study \" 'unless there is also", "context)) class CaseStudyRelatedPages(Orderable): case_study = ParentalKey( 'core.CaseStudy', related_name='related_pages', on_delete=models.SET_NULL, null=True,", "django.db import models from django.http import HttpResponseRedirect from django.template.loader import", "= (('learn/detail_page.html', 'Learn'),) class Meta: verbose_name = 'Detail page' verbose_name_plural", "MultiFieldPanel([InlinePanel('steps')], heading='Steps'), ] def __str__(self): return self.page.title class TourStep(Orderable): title", "study HS2 tag matches the first 2 digits of any", "get a title that goes with it. For now, this", "GA360Mixin, Page, ): \"\"\" Generic page, freely inspired by Codered", ") ] ) ######### # Panels ########## content_panels = Page.content_panels", "kwargs.pop('update_modified', getattr(self, 'update_modified', True)) super().save(**kwargs) update_cs_index(self) def delete(self, **kwargs): delete_cs_index(self.id)", "[FieldPanel('description'), FieldPanel('button_label')] class CuratedListPage(CMSGenericPage): parent_page_types = ['core.ListPage'] subpage_types = [", "record_read_progress = models.BooleanField( default=False, help_text='Should we record when a user", "('learn/landing_page.html', 'Learn'), ('core/generic_page.html', 'Generic'), ) ################ # Content fields ################", "= 'Country tags for personalisation' class PersonalisationRegionTag(TagBase): \"\"\"Custom tag for", "subpage_types = [] # No child pages allowed for placeholders", "ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='country_tagged_items') class RegionTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationRegionTag, related_name='region_tagged_case_studies',", "), ('choose_do_not_choose', core_blocks.ChooseDoNotChooseBlock()), ( 'image', core_blocks.ImageBlock( template='core/includes/_image_full_width.html', help_text='Image displayed within", "blank=True, verbose_name='Country tags' ) region_code_tags = ClusterTaggableManager( through='core.RegionTaggedCaseStudy', blank=True, verbose_name='Region", "the media node has the following content: * One image,", "block must contain one Media section (with one or two", "], heading='Related Lesson, Topic & Module, also used for Personalisation',", "blank=True) image = models.ForeignKey( get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL, related_name='+' )", "when user's lesson is tagged in the case study.\", default=8,", "core.constants import BACKLINK_QUERYSTRING_NAME, RICHTEXT_FEATURES__MINIMAL from core.context import get_context_provider from core.utils", "class Tag(models.Model): name = models.CharField(max_length=100, unique=True) panels = [FieldPanel('name')] class", "help_text=\"Score given when any case study HS4 tag matches the", "def count_topics(self): return self.get_topics().count() @cached_property def count_detail_pages(self): count = 0", "\" 'unless there is also lesson match.', default=4, decimal_places=3, max_digits=5,", "product_hs4 = models.DecimalField( help_text=\"Score given when any case study HS4", "related_name='+' ) body = StreamField( [ ('section', core_blocks.SectionBlock()), ('title', core_blocks.TitleBlock()),", "HS4 match.', default=2, decimal_places=3, max_digits=5, ) country_exact = models.DecimalField( help_text=\"Score", "list pages' def get_context(self, request, *args, **kwargs): from core.helpers import", "this page type to be created in wagtail admin is_creatable", "PageChooserPanel('page'), FieldPanel('title'), FieldPanel('body'), FieldPanel('button_text'), MultiFieldPanel([InlinePanel('steps')], heading='Steps'), ] def __str__(self): return", "country tag exactly matches one of the user's export markets.\",", "from django.utils.translation import ugettext_lazy as _ from django_extensions.db.fields import CreationDateTimeField,", "FieldPanel('region'), ] class Meta: verbose_name_plural = 'Countries' ordering = ('name',)", "FieldPanel('hs_code_tags'), FieldPanel('country_code_tags'), FieldPanel('region_code_tags'), FieldPanel('trading_bloc_code_tags'), ], heading='Case Study tags for Personalisation',", "] def __str__(self): return self.page.title class TourStep(Orderable): title = models.CharField(max_length=255)", "models.DecimalField( help_text='Score given when any case study HS6 tag matches", ") if list_page: PageView.objects.get_or_create( page=self, list_page=list_page, sso_id=request.user.pk, ) def serve(self,", "presented to users. ', default=10, decimal_places=3, max_digits=5, ) lesson =", "wagtail.contrib.settings.models import BaseSetting, register_setting from wagtail.core import blocks from wagtail.core.blocks.stream_block", "'pros_cons', blocks.StructBlock( [ ( 'pros', blocks.StreamBlock( [ ( 'item', core_blocks.Item(icon='fa-arrow-right'),", "attack # URL), but that's an acceptable limitation here and", "only # Added obj_type on base class method render_as_field 'obj_type':", "UX easier for editors hs_code_tags = ClusterTaggableManager(through='core.HSCodeTaggedCaseStudy', blank=True, verbose_name='HS-code tags')", ") content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='hs_code_tagged_items') class CountryTaggedCaseStudy(ItemBase): tag =", "self._redirect_to_parent_module() def serve(self, request): return self._redirect_to_parent_module() class LessonPlaceholderPage(mixins.AuthenticatedUserRequired, Page): \"\"\"Structural", "tags' ) created = CreationDateTimeField('created', null=True) modified = ModificationDateTimeField('modified', null=True)", "template='learn/recap.html', icon='fa-commenting-o', ), ) ] ) ######### # Panels ##########", "have to keep it registered as a Snippet to be", "= [ 'domestic.DomesticHomePage', # TODO: once we've restructured, remove this", "[ ( 'paragraph', blocks.RichTextBlock(options={'class': 'objectives'}), ), ('ListItem', core_blocks.Item()), ] )", "to the parent # learning module (ListPage) context['parent_page_url'] = self.get_parent().url", "qs = qs.live() return qs @cached_property def count_topics(self): return self.get_topics().count()", "error_messages def case_study_body_validation(value): \"\"\"Ensure the case study has exactly both", "return context def hero_singular_validation(value): if value and len(value) > 1:", ") product_hs4 = models.DecimalField( help_text=\"Score given when any case study", "= self.module.get_next_sibling() if not next_module: return context context['next_module'] = next_module.specific", "error_messages) error_messages = _low_level_validation(value, error_messages) if error_messages: raise StreamBlockValidationError( non_block_errors=ValidationError(';", "product_hs2 = models.DecimalField( help_text=\"Score given when any case study HS2", "related_name='trading_bloc_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey( to='core.CaseStudy', on_delete=models.CASCADE, related_name='trading_bloc_tagged_items' )", "CMSGenericPage.content_panels + [ FieldPanel('heading'), ImageChooserPanel('image'), ] def get_topics(self, live=True) ->", "', default=10, decimal_places=3, max_digits=5, ) lesson = models.DecimalField( help_text=\"Score given", "self context['current_module'] = page_topic_helper.module if page_topic_helper: topic_page = page_topic_helper.get_page_topic() if", "decimal_places=3, max_digits=5, ) product_hs4 = models.DecimalField( help_text=\"Score given when any", "tag for personalisation. Tag value will be an Trading blocs", "CMSGenericPage( mixins.EnableTourMixin, mixins.AuthenticatedUserRequired, mixins.WagtailGA360Mixin, GA360Mixin, Page, ): \"\"\" Generic page,", "'-modified', '-created', ) abstract = True # Content models class", "+ [FieldPanel('description'), FieldPanel('button_label')] class CuratedListPage(CMSGenericPage): parent_page_types = ['core.ListPage'] subpage_types =", "tag = models.ForeignKey( PersonalisationTradingBlocTag, related_name='trading_bloc_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(", "Media from core import blocks as core_blocks, mixins from core.case_study_index", "update_cs_index from core.constants import BACKLINK_QUERYSTRING_NAME, RICHTEXT_FEATURES__MINIMAL from core.context import get_context_provider", "super().save(*args, **kwargs) def __str__(self): return self.name @register_snippet class Tag(models.Model): name", "# Layout fields ############### template = models.CharField( max_length=255, choices=None, )", "import get_lesson_completion_status context = super().get_context(request) if request.user.is_authenticated: completion_status = get_lesson_completion_status(request.user)", "aid lookup and make the UX easier for editors hs_code_tags", "accessed. Also, for the above reason, mixins.WagtailGA360Mixin and GA360Mixin are", "len(backlink_path.split('/')) > 3: _path = backlink_path.split('/')[3] return self._export_plan_url_map.get(_path) def get_context(self,", "domestic.helpers import get_lesson_completion_status context = super().get_context(request) # Give the template", "through='core.TradingBlocTaggedCaseStudy', blank=True, verbose_name='Trading bloc tags' ) created = CreationDateTimeField('created', null=True)", ") ######### # Panels ########## layout_panels = [FieldPanel('template')] settings_panels =", "heading='Case Study tags for Personalisation', ), MultiFieldPanel( [ InlinePanel('related_pages', label='Related", "section, then one Text section following it.' ) ) return", "\"\"\"Ensure the case study has exactly both a media node", "mimetypes.guess_type(self.filename)[0] or 'application/octet-stream', 'transcript': self.transcript, } ] @property def subtitles(self):", "related_name='renditions') class Meta: unique_together = ('image', 'filter_spec', 'focal_point_key') @property def", "settings_panels = CMSGenericPage.settings_panels + [FieldPanel('record_read_progress')] content_panels = CMSGenericPage.content_panels + [FieldPanel('description'),", "[ FieldPanel('title'), FieldPanel('lead_title'), FieldPanel('summary_context'), StreamFieldPanel('body'), ], heading='Case Study content', ),", "'type': mimetypes.guess_type(self.filename)[0] or 'application/octet-stream', 'transcript': self.transcript, } ] @property def", "= True # Prepare backlink to the export plan if", "max_digits=5, ) topic = models.DecimalField( help_text=\"Score given when user's lesson's", "from wagtail.core.fields import RichTextField, StreamField from wagtail.core.models import Orderable, Page", "of any of the user's export markets \" 'unless there", "data twice completion_status = get_lesson_completion_status(request.user) context['module_completion_progress'] = get_module_completion_progress( completion_status=completion_status, module_page=self,", "added to create and modified fields, inheritance causes issues with", "page is already marked as read list_page = ( ListPage.objects.ancestor_of(self)", "== 2: if set(subnode_block_types) == {VIDEO_BLOCK}: # Two videos: not", "an image # video after image: not allowed error_messages.append('The video", "content_panels = CMSGenericPage.content_panels + [ FieldPanel('heading'), ImageChooserPanel('image'), ] def get_topics(self,", "= [ MultiFieldPanel( [ FieldPanel('title'), FieldPanel('lead_title'), FieldPanel('summary_context'), StreamFieldPanel('body'), ], heading='Case", "trading bloc that any of ' \"the user's export markets", "content: * One image, only * One video, only *", "GA360Mixin are not used.\"\"\" parent_page_types = ['core.TopicPage'] subpage_types = []", "class PersonalisationCountryTag(TagBase): \"\"\"Custom tag for personalisation. Tag value will be", "user's products\", default=8, decimal_places=3, max_digits=5, ) product_hs4 = models.DecimalField( help_text=\"Score", "match.', default=2, decimal_places=3, max_digits=5, ) trading_blocs = models.DecimalField( help_text='Score given", "] def handle_page_view(self, request): if request.user.is_authenticated: # checking if the", "should record read progress # checking if the page is", "= ParentalKey('core.ContentModule', on_delete=models.CASCADE, related_name='tagged_items') # TODO: deprecate and remove @register_snippet", "blank=True, verbose_name='Region tags' ) trading_bloc_code_tags = ClusterTaggableManager( through='core.TradingBlocTaggedCaseStudy', blank=True, verbose_name='Trading", "HS6 or HS4 match.', default=2, decimal_places=3, max_digits=5, ) country_exact =", "position = models.CharField(max_length=255) selector = models.CharField(max_length=255) tour = ParentalKey(Tour, on_delete=models.CASCADE,", "wagtail.core.models import Orderable, Page from wagtail.images import get_image_model_string from wagtail.images.edit_handlers", "StreamFieldPanel('hero'), StreamFieldPanel('objective'), StreamFieldPanel('body'), StreamFieldPanel('recap'), ] def handle_page_view(self, request): if request.user.is_authenticated:", "core_blocks.ImageBlock( template='core/includes/_image_full_width.html', help_text='Image displayed within a full-page-width block', ), ),", "subpage_types = [ 'core.ListPage', 'core.InterstitialPage', 'domestic.DomesticDashboard', ] template_choices = (", "'unless there is an HS6 or HS4 match.', default=2, decimal_places=3,", "parent module if accessed. Also, for the above reason, mixins.WagtailGA360Mixin", "and that the media node has the following content: *", "from wagtail.contrib.redirects.models import Redirect from wagtail.contrib.settings.models import BaseSetting, register_setting from", "null=True, blank=True, validators=[hero_singular_validation], ) objective = StreamField( [ ( 'paragraph',", "going on here: # https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models class HSCodeTaggedCaseStudy(ItemBase): tag = models.ForeignKey(", "'-created', ) abstract = True # Content models class CMSGenericPage(", "= 0 for topic in self.get_topics(): count += DetailPage.objects.live().descendant_of(topic).count() return", "and remove @register_snippet class ContentModule(ClusterableModel): title = models.CharField(max_length=255) content =", "(`DetailPage`s) to modules (`CuratedListPage`s). Not intented to be viewed by", "which # features a full URL as its OWN querystring", "class Meta: verbose_name_plural = 'Countries' ordering = ('name',) def save(self,", "for editors hs_code_tags = ClusterTaggableManager(through='core.HSCodeTaggedCaseStudy', blank=True, verbose_name='HS-code tags') country_code_tags =", "def serve(self, request): return self._redirect_to_parent_module() class DetailPage(CMSGenericPage): estimated_read_duration = models.DurationField(null=True,", "create to obtain an ID for indexing self.update_modified = kwargs.pop('update_modified',", "viewed by end users, so will redirect to the parent", "node.value] if len(subnode_block_types) == 2: if set(subnode_block_types) == {VIDEO_BLOCK}: #", "( 'ITA_Quote', core_blocks.ITAQuoteBlock(icon='fa-quote-left'), ), ( 'pros_cons', blocks.StructBlock( [ ( 'pros',", "models from django.http import HttpResponseRedirect from django.template.loader import render_to_string from", "\"\"\"For a given backlink, see if we can get a", "self.get_parent().url if request.user.is_authenticated: # get this once, so we don't", "models.TextField(blank=False) # Deliberately not rich-text / no formatting body =", "'wagtaildocs.Document', null=True, blank=True, on_delete=models.CASCADE, related_name='+' ) class ImageHash(AbstractObjectHash): image =", "exactly matches one of the user's export markets.\", default=4, decimal_places=3,", "plan) from the querystring on the request that brought us", "heading='Settings', classname='settings'), ] return TabbedInterface(panels).bind_to(model=cls) def get_template(self, request, *args, **kwargs):", ") from domestic.helpers import get_lesson_completion_status context = super().get_context(request) # Give", "if request.user.is_authenticated: # get this once, so we don't waste", "verbose_name_plural = 'Case studies' get_latest_by = 'modified' ordering = (", "['core.ListPage'] subpage_types = [ 'core.TopicPage', ] template_choices = (('learn/curated_list_page.html', 'Learn'),)", "backlink which # features a full URL as its OWN", "so appears in the sidebar, but we have to keep", "given when user's lesson's topic is tagged in the case", "pages' def get_context(self, request, *args, **kwargs): from core.helpers import get_high_level_completion_progress", "'modified' ordering = ( '-modified', '-created', ) @register_setting class CaseStudyScoringSettings(BaseSetting):", "For now, this is limited only to Export Plan pages/links.", "section (with one or ' 'two items in it) and/or", ") lesson = models.DecimalField( help_text=\"Score given when user's lesson is", "\"\"\" free_tagging = False class Meta: verbose_name = 'Country tag", "in a case study.') elif subnode_block_types[1] == VIDEO_BLOCK: # implicitly,", "if node.block_type != QUOTE_BLOCK] != [MEDIA_BLOCK, TEXT_BLOCK]: error_messages.append( ( 'This", "URL), but that's an acceptable limitation here and is very", "[ FieldPanel('title'), FieldPanel('content'), FieldPanel('tags'), ] def __str__(self): return self.title class", "completion_status=completion_status, ) return context ################ # Content fields ################ description", "StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True) image = models.ForeignKey( get_image_model_string(), null=True, blank=True,", "# No child pages allowed for placeholders # `title` comes", "context = super().get_context(request) self.set_ga360_payload( page_id=self.id, business_unit=settings.GA360_BUSINESS_UNIT, site_section=str(self.url or '/').split('/')[1], )", "wagtail.images.models import AbstractImage, AbstractRendition, Image from wagtail.snippets.models import register_snippet from", "request.GET.get(BACKLINK_QUERYSTRING_NAME, '') if backlink_path is not None: backlink_path = unquote(backlink_path)", "class PersonalisationHSCodeTag(TagBase): \"\"\"Custom tag for personalisation. Tag value will be", "to='core.CaseStudy', on_delete=models.CASCADE, related_name='trading_bloc_tagged_items' ) def _high_level_validation(value, error_messages): TEXT_BLOCK = 'text'", "return super().serve(request, **kwargs) @cached_property def topic_title(self): return self.get_parent().title @cached_property def", "[node.block_type for node in value if node.block_type != QUOTE_BLOCK] !=", "objective = StreamField( [ ( 'paragraph', blocks.RichTextBlock(options={'class': 'objectives'}), ), ('ListItem',", "= models.ForeignKey( 'wagtailcore.Page', on_delete=models.CASCADE, related_name='+', ) panels = [ MagnaPageChooserPanel('page',", "**kwargs) field = self._meta.get_field('template') field.choices = self.template_choices field.required = True", "= models.DecimalField( help_text='This is the minimum score which a case", "node in value: if node.block_type == MEDIA_BLOCK: subnode_block_types = [subnode.block_type", "[] if value: error_messages = _high_level_validation(value, error_messages) error_messages = _low_level_validation(value,", "raise StreamBlockValidationError( non_block_errors=ValidationError('Only one image or video allowed in Hero", "is tagged in the case study \" 'unless there is", "on_delete=models.CASCADE, related_name='+' ) class ImageHash(AbstractObjectHash): image = models.ForeignKey('wagtailimages.Image', null=True, blank=True,", "request, *args, **kwargs): from core.helpers import ( get_high_level_completion_progress, get_module_completion_progress, )", "EXPORTPLAN_URL_MAP.items()} def _get_backlink(self, request): \"\"\"Try to extract a backlink (used", "get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) ######## # Panels ########", "import RichTextField, StreamField from wagtail.core.models import Orderable, Page from wagtail.images", "if the page is already marked as read list_page =", "this lesson belongs to\"\"\" return CuratedListPage.objects.live().specific().ancestor_of(self).first() @cached_property def _export_plan_url_map(self): \"\"\"Return", "end users, so will redirect to the parent module if", "def get_context(self, request, *args, **kwargs): from core.helpers import get_high_level_completion_progress from", "two items in it) ' 'and/or Quote sections, then one", "or ' 'two items in it) and/or a Quote section,", "null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) ######## # Panels ######## content_panels", "will be a HS6, HS4 or HS2 code\"\"\" # free_tagging", ") abstract = True # Content models class CMSGenericPage( mixins.EnableTourMixin,", "= ClusterTaggableManager( through='core.TradingBlocTaggedCaseStudy', blank=True, verbose_name='Trading bloc tags' ) created =", ") body = StreamField( [ ( 'paragraph', blocks.StructBlock( [('paragraph', blocks.RichTextBlock())],", "from core.utils import PageTopicHelper, get_first_lesson from exportplan.core.data import ( SECTION_SLUGS", "+ [ FieldPanel('heading'), ImageChooserPanel('image'), ] def get_topics(self, live=True) -> models.QuerySet:", "be strict about presence and ordering of these nodes if", "used for Personalisation', ), ] def __str__(self): display_name = self.title", "from django_extensions.db.fields import CreationDateTimeField, ModificationDateTimeField from great_components.mixins import GA360Mixin from", "= True content_hash = models.CharField(max_length=1000) @staticmethod def generate_content_hash(field_file): filehash =", "if we can get a title that goes with it.", "backlink (used for a link to the export plan) from", "TEXT_BLOCK]: error_messages.append( ( 'This block must contain one Media section", "have.\"\"\" return {url: values['title'] for url, values in EXPORTPLAN_URL_MAP.items()} def", "TagBase, TaggedItemBase from wagtail.admin.edit_handlers import ( FieldPanel, InlinePanel, MultiFieldPanel, ObjectList,", "'two items in it) and/or a Quote section, then one", "Image from wagtail.snippets.models import register_snippet from wagtail.utils.decorators import cached_classmethod from", "tagged in the case study.\", default=8, decimal_places=3, max_digits=5, ) topic", "Study content', ), MultiFieldPanel( [ FieldPanel('hs_code_tags'), FieldPanel('country_code_tags'), FieldPanel('region_code_tags'), FieldPanel('trading_bloc_code_tags'), ],", "or 'application/octet-stream', 'transcript': self.transcript, } ] @property def subtitles(self): output", "COME: support for more than just English if self.subtitles_en: output.append(", "in self.get_topics(): count += DetailPage.objects.live().descendant_of(topic).count() return count def get_context(self, request,", "# safe default def _get_backlink_title(self, backlink_path): \"\"\"For a given backlink,", "'Region tags for personalisation' class PersonalisationTradingBlocTag(TagBase): \"\"\"Custom tag for personalisation.", "being presented to users. ', default=10, decimal_places=3, max_digits=5, ) lesson", "[ FieldPanel('heading'), ImageChooserPanel('image'), ] def get_topics(self, live=True) -> models.QuerySet: qs", "user's export markets.\", default=4, decimal_places=3, max_digits=5, ) country_region = models.DecimalField(", "region match.\", default=2, decimal_places=3, max_digits=5, ) product_tab = [MultiFieldPanel([FieldPanel('product_hs6'), FieldPanel('product_hs4'),", "one or ' 'two items in it) and/or a Quote", "TradingBlocTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationTradingBlocTag, related_name='trading_bloc_tagged_case_studies', on_delete=models.CASCADE ) content_object =", "args=[self.id, 'en']), 'default': False, }, ) return output class AbstractObjectHash(models.Model):", "first) * Two images \"\"\" error_messages = [] if value:", "Layout fields ############### template = models.CharField( max_length=255, choices=None, ) #########", "= kwargs.pop('update_modified', getattr(self, 'update_modified', True)) super().save(**kwargs) update_cs_index(self) def delete(self, **kwargs):", "study region tag matches the region of any of the", "self.page.title class TourStep(Orderable): title = models.CharField(max_length=255) body = models.CharField(max_length=255) position", "null=True needed to be added to create and modified fields,", "layout_panels = [FieldPanel('template')] settings_panels = [FieldPanel('slug')] + Page.settings_panels def __init__(self,", "[ FieldPanel('name'), ] def __str__(self): return self.name @register_snippet class Region(models.Model):", "models.BooleanField( default=False, help_text='Should we record when a user views a", "get this once, so we don't waste the network call", "AltTextImage(AbstractImage): alt_text = models.CharField(max_length=255, blank=True) admin_form_fields = Image.admin_form_fields + ('alt_text',)", "models.ForeignKey( 'wagtailcore.Page', on_delete=models.CASCADE, related_name='+', ) panels = [ MagnaPageChooserPanel('page', [DetailPage,", "null=True, blank=True, on_delete=models.CASCADE, related_name='+' ) class ImageHash(AbstractObjectHash): image = models.ForeignKey('wagtailimages.Image',", "Meta: ordering = ('name',) def __str__(self): return self.name @register_snippet class", "media node, which should be present here MEDIA_BLOCK = 'media'", "# We are keeping the personalisation-relevant tags in separate #", "created = CreationDateTimeField('created', null=True) modified = ModificationDateTimeField('modified', null=True) panels =", "= models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, on_delete=models.CASCADE, related_name='+' ) class ImageHash(AbstractObjectHash):", "'fictional_example', blocks.StructBlock( [('fiction_body', blocks.RichTextBlock(icon='openquote'))], template='learn/fictional_company_example.html', icon='fa-commenting-o', ), ), ( 'ITA_Quote',", "modelcluster.contrib.taggit import ClusterTaggableManager from modelcluster.models import ClusterableModel, ParentalKey from taggit.managers", "# https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models class HSCodeTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationHSCodeTag, related_name='hscode_tagged_case_studies', on_delete=models.CASCADE", "for node in value: if node.block_type == MEDIA_BLOCK: subnode_block_types =", "for node in value if node.block_type != QUOTE_BLOCK] != [MEDIA_BLOCK,", "True)) super().save(**kwargs) update_cs_index(self) def delete(self, **kwargs): delete_cs_index(self.id) super().delete(**kwargs) def get_cms_standalone_view_url(self):", "= True @cached_classmethod def get_edit_handler(cls): # NOQA N805 panels =", "[ 'core.DetailPage', 'core.LessonPlaceholderPage', ] # `title` comes from Page superclass", "a Redirect appear as a Snippet, we can sync it", "video, in VTT format', ) admin_form_fields = Media.admin_form_fields + (", "= _low_level_validation(value, error_messages) if error_messages: raise StreamBlockValidationError( non_block_errors=ValidationError('; '.join(error_messages), code='invalid'),", "= [] ############### # Layout fields ############### template = models.CharField(", "on_delete=models.CASCADE, related_name='region_tagged_items') class TradingBlocTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationTradingBlocTag, related_name='trading_bloc_tagged_case_studies', on_delete=models.CASCADE", "'update_modified', True)) super().save(**kwargs) class Meta: get_latest_by = 'modified' ordering =", "that's an acceptable limitation here and is very unlikely #", "allowed in Hero section', code='invalid'), ) class TopicPage(mixins.AuthenticatedUserRequired, Page): \"\"\"Structural", "code='invalid'), ) class TopicPage(mixins.AuthenticatedUserRequired, Page): \"\"\"Structural page to allow for", "= False template_choices = [] ############### # Layout fields ###############", "context['next_module'] = next_module.specific context['next_lesson'] = get_first_lesson(next_module) return context class PageView(TimeStampedModel):", "* One video + One image * (video must comes", "('section', core_blocks.SectionBlock()), ('title', core_blocks.TitleBlock()), ('text', blocks.RichTextBlock(icon='openquote', helptext='Add a textblock')), ('image',", "blank=True) panels = [ FieldPanel('title'), FieldPanel('content'), FieldPanel('tags'), ] def __str__(self):", "studies' get_latest_by = 'modified' ordering = ( '-modified', '-created', )", "), ( 'quote', core_blocks.CaseStudyQuoteBlock(), ), ], validators=[case_study_body_validation], help_text=( 'This block", "doesn't matter what is passed as mode_name - we always", "'Detail page' verbose_name_plural = 'Detail pages' ################ # Content fields", "block must contain one Media section (with one or '", "a text node and that the media node has the", "= ('name',) def __str__(self): return self.name class TimeStampedModel(models.Model): \"\"\"Modified version", "= [FieldPanel('template')] settings_panels = [FieldPanel('slug')] + Page.settings_panels def __init__(self, *args,", "tag for personalisation' verbose_name_plural = 'Region tags for personalisation' class", "implicitly, [0] must be an image # video after image:", "], min_num=1, max_num=2, ), ), ( 'text', blocks.RichTextBlock( features=RICHTEXT_FEATURES__MINIMAL, ),", "count def get_context(self, request, *args, **kwargs): from core.helpers import (", "twice completion_status = get_lesson_completion_status(request.user) context['module_completion_progress'] = get_module_completion_progress( completion_status=completion_status, module_page=self, )", "we don't waste the network call to get the data", "class Country(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=100, unique=True) region", "] lesson_tab = [MultiFieldPanel([FieldPanel('lesson'), FieldPanel('topic'), FieldPanel('module')])] threshold_tab = [ MultiFieldPanel(", "FieldPanel('body'), FieldPanel('button_text'), MultiFieldPanel([InlinePanel('steps')], heading='Steps'), ] def __str__(self): return self.page.title class", "self._get_backlink(request) if _backlink: context['backlink'] = _backlink context['backlink_title'] = self._get_backlink_title(_backlink) if", "free_tagging = False class Meta: verbose_name = 'Trading bloc tag", "return context context['next_module'] = next_module.specific context['next_lesson'] = get_first_lesson(next_module) return context", "__str__(self): return self.title class PersonalisationHSCodeTag(TagBase): \"\"\"Custom tag for personalisation. Tag", "output class AbstractObjectHash(models.Model): class Meta: abstract = True content_hash =", "ParentalKey from taggit.managers import TaggableManager from taggit.models import ItemBase, TagBase,", "Country code ('DE') \"\"\" free_tagging = False class Meta: verbose_name", "'://' will stop us accepting a backlink which # features", "to this view. Only accepts backlinks that we KNOW are", "models.CharField(max_length=100, unique=True) icon = models.ForeignKey( AltTextImage, null=True, blank=True, on_delete=models.SET_NULL, related_name='+',", "KNOW are for the export plan, else ignore it.\"\"\" backlink_path", "DetailPage currently MAY be used as # a child of", "Meta: verbose_name = 'Region tag for personalisation' verbose_name_plural = 'Region", "class MagnaPageChooserPanel(PageChooserPanel): show_label = False field_template = 'admin/wagtailadmin/edit_handlers/field_panel_field.html' def render_as_field(self):", "] class Meta: unique_together = ['case_study', 'page'] @register_snippet class CaseStudy(ClusterableModel):", ") product_hs6 = models.DecimalField( help_text='Score given when any case study", "formatting body = StreamField( [ ( 'media', blocks.StreamBlock( [ ('video',", "BaseSetting, register_setting from wagtail.core import blocks from wagtail.core.blocks.stream_block import StreamBlockValidationError", "core_blocks.VideoBlock())], template='core/struct_video_block.html', icon='fa-play', ), ), ('case_study', core_blocks.CaseStudyStaticBlock(icon='fa-book')), ( 'Step', core_blocks.StepByStepBlock(icon='cog'),", "be added to create and modified fields, inheritance causes issues", "here and is very unlikely # to happen. return backlink_path", "decimal_places=3, max_digits=5, ) lesson = models.DecimalField( help_text=\"Score given when user's", "__str__(self): return self.name @register_snippet class Region(models.Model): name = models.CharField(max_length=100, unique=True)", "= ['core.CuratedListPage'] template_choices = (('learn/automated_list_page.html', 'Learn'),) record_read_progress = models.BooleanField( default=False,", "no formatting body = StreamField( [ ( 'media', blocks.StreamBlock( [", "when any case study HS2 tag matches the first 2", "from wagtail.utils.decorators import cached_classmethod from wagtailmedia.models import Media from core", "class Meta: verbose_name = 'Automated list page' verbose_name_plural = 'Automated", "= 'modified' ordering = ( '-modified', '-created', ) abstract =", "sidebar, but we have to keep it registered as a", "TaggedItemBase from wagtail.admin.edit_handlers import ( FieldPanel, InlinePanel, MultiFieldPanel, ObjectList, PageChooserPanel,", "for cleaner mapping of lessons (`DetailPage`s) to modules (`CuratedListPage`s). Not", "ValidationError from django.db import models from django.http import HttpResponseRedirect from", "null=True, blank=True, ) components = StreamField( [ ('route', core_blocks.RouteSectionBlock()), ],", "= models.CharField(max_length=100, unique=True) icon = models.ForeignKey( AltTextImage, null=True, blank=True, on_delete=models.SET_NULL,", "then one Text section following it.' ) ) return error_messages", "return count def get_context(self, request, *args, **kwargs): from core.helpers import", "def get_context(self, request, *args, **kwargs): context = super().get_context(request) context['refresh_on_market_change'] =", "core_blocks.ImageBlock()), ], null=True, blank=True, ) components = StreamField( [ ('route',", "an ID for indexing self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified', True))", "or video allowed in Hero section', code='invalid'), ) class TopicPage(mixins.AuthenticatedUserRequired,", "a page in this collection?', ) class Meta: verbose_name =", "( 'text', blocks.RichTextBlock( features=RICHTEXT_FEATURES__MINIMAL, ), ), ( 'quote', core_blocks.CaseStudyQuoteBlock(), ),", "recap = StreamField( [ ( 'recap_item', blocks.StructBlock( [ ('title', blocks.CharBlock(icon='fa-header')),", "Two images \"\"\" error_messages = [] if value: error_messages =", "= [subnode.block_type for subnode in node.value] if len(subnode_block_types) == 2:", "if instance_obj else None, } return mark_safe(render_to_string(self.field_template, context)) class CaseStudyRelatedPages(Orderable):", "= ( ('learn/landing_page.html', 'Learn'), ('core/generic_page.html', 'Generic'), ) ################ # Content", "CuratedListPage.objects.live().specific().ancestor_of(self).first() @cached_property def _export_plan_url_map(self): \"\"\"Return a lookup dictionary of URL", ") module = models.DecimalField( help_text=\"Score given when the user's lesson's", "a geographical string ('Europe') \"\"\" free_tagging = False class Meta:", "case study HS2 tag matches the first 2 digits of", "def _get_backlink_title(self, backlink_path): \"\"\"For a given backlink, see if we", "EXPORT_PLAN_SECTION_TITLES_URLS after import # because it features lazily-evaluated URLs that", "models.CharField(max_length=255) body = models.CharField(max_length=255) position = models.CharField(max_length=255) selector = models.CharField(max_length=255)", "_low_level_validation(value, error_messages) if error_messages: raise StreamBlockValidationError( non_block_errors=ValidationError('; '.join(error_messages), code='invalid'), )", "help_text='Score given when any case study trading bloc tag matches", "panels = [ ObjectList(cls.content_panels, heading='Content'), ObjectList(cls.layout_panels, heading='Layout'), ObjectList(cls.settings_panels, heading='Settings', classname='settings'),", "page in this collection?', ) class Meta: verbose_name = 'Automated", "code\"\"\" # free_tagging = False # DISABLED until tag data", "parent_page_types = ['core.LandingPage'] subpage_types = ['core.CuratedListPage'] template_choices = (('learn/automated_list_page.html', 'Learn'),)", "def hero_singular_validation(value): if value and len(value) > 1: raise StreamBlockValidationError(", "parent_page_types = ['core.LandingPage'] template_choices = (('learn/interstitial.html', 'Learn'),) ################ # Content", "GA360Mixin from modelcluster.contrib.taggit import ClusterTaggableManager from modelcluster.models import ClusterableModel, ParentalKey", "parent_page_types = [ 'core.CuratedListPage', # TEMPORARY: remove after topics refactor", "SECTIONS as EXPORTPLAN_URL_MAP, ) # If we make a Redirect", "# Prepare backlink to the export plan if we detect", "# In a conditional because a DetailPage currently MAY be", "class Rendition(AbstractRendition): image = models.ForeignKey(AltTextImage, on_delete=models.CASCADE, related_name='renditions') class Meta: unique_together", "), ), ], template='learn/recap.html', icon='fa-commenting-o', ), ) ] ) #########", "\"\"\"Custom tag for personalisation. Tag value will be a HS6,", "that goes with it. For now, this is limited only", "@register_snippet class Product(models.Model): name = models.CharField(max_length=255) panels = [ FieldPanel('name'),", "decimal_places=3, max_digits=5, ) product_hs6 = models.DecimalField( help_text='Score given when any", "the user's lesson's module is tagged in the case study", "ordering = ( '-modified', '-created', ) @register_setting class CaseStudyScoringSettings(BaseSetting): threshold", "get_first_lesson(next_module) return context class PageView(TimeStampedModel): page = models.ForeignKey(DetailPage, on_delete=models.CASCADE, related_name='page_views')", "are not used.\"\"\" parent_page_types = ['core.CuratedListPage'] subpage_types = [ 'core.DetailPage',", "we need here def _redirect_to_parent_module(self): return HttpResponseRedirect(self.get_parent().url) def serve_preview(self, request,", "min_num=1, max_num=2, ), ), ( 'text', blocks.RichTextBlock( features=RICHTEXT_FEATURES__MINIMAL, ), ),", "core_blocks.Item(), ) ] ), ), ], template='learn/recap.html', icon='fa-commenting-o', ), )", "after image: not allowed error_messages.append('The video must come before a", "= CreationDateTimeField('created', null=True) modified = ModificationDateTimeField('modified', null=True) def save(self, **kwargs):", "Redirect appear as a Snippet, we can sync it via", "all the Export Plan sections we have.\"\"\" return {url: values['title']", "given when any case study HS2 tag matches the first", "for url, values in EXPORTPLAN_URL_MAP.items()} def _get_backlink(self, request): \"\"\"Try to", "import AbstractImage, AbstractRendition, Image from wagtail.snippets.models import register_snippet from wagtail.utils.decorators", "verbose_name='Country tags' ) region_code_tags = ClusterTaggableManager( through='core.RegionTaggedCaseStudy', blank=True, verbose_name='Region tags'", "StreamFieldPanel('components'), StreamFieldPanel('body'), ] class InterstitialPage(CMSGenericPage): parent_page_types = ['core.LandingPage'] template_choices =", "IndustryTag(models.Model): name = models.CharField(max_length=100, unique=True) icon = models.ForeignKey( AltTextImage, null=True,", "else ignore it.\"\"\" backlink_path = request.GET.get(BACKLINK_QUERYSTRING_NAME, '') if backlink_path is", ") product_hs2 = models.DecimalField( help_text=\"Score given when any case study", "value if node.block_type != QUOTE_BLOCK] != [MEDIA_BLOCK, TEXT_BLOCK]: error_messages.append( (", "'field': self.bound_field, self.object_type_name: instance_obj, 'is_chosen': bool(instance_obj), # DEPRECATED - passed", "English if self.subtitles_en: output.append( { 'srclang': 'en', 'label': 'English', 'url':", "lesson match.', default=4, decimal_places=3, max_digits=5, ) module = models.DecimalField( help_text=\"Score", "output = [] # TO COME: support for more than", "self._get_backlink_title(_backlink) if isinstance(self.get_parent().specific, TopicPage): # In a conditional because a", "have to re-arrange EXPORT_PLAN_SECTION_TITLES_URLS after import # because it features", "('route', core_blocks.RouteSectionBlock()), ], null=True, blank=True, ) ######### # Panels #########", "['case_study', 'page'] @register_snippet class CaseStudy(ClusterableModel): \"\"\"Dedicated snippet for use as", "models.ForeignKey( get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) ######## # Panels", "'Trading bloc tags for personalisation' # If you're wondering what's", "trading bloc tag matches the any trading bloc that any", "from django.http import HttpResponseRedirect from django.template.loader import render_to_string from django.urls", "verbose_name=_('Transcript'), blank=False, null=True # left null because was an existing", "TaggableManager from taggit.models import ItemBase, TagBase, TaggedItemBase from wagtail.admin.edit_handlers import", "there is an exact country match.', default=2, decimal_places=3, max_digits=5, )", "def subtitles(self): output = [] # TO COME: support for", "modified = ModificationDateTimeField('modified', null=True) panels = [ MultiFieldPanel( [ FieldPanel('title'),", "import ClusterableModel, ParentalKey from taggit.managers import TaggableManager from taggit.models import", "a user views a page in this collection?', ) class", "def get_edit_handler(cls): # NOQA N805 panels = [ ObjectList(cls.content_panels, heading='Content'),", "context = super().get_context(request) # Give the template a simple way", "), ( 'pros_cons', blocks.StructBlock( [ ( 'pros', blocks.StreamBlock( [ (", "'transcript', 'subtitles_en', ) @property def sources(self): return [ { 'src':", "from django.urls import reverse from django.utils.functional import cached_property from django.utils.safestring", "page_id=self.id, business_unit=settings.GA360_BUSINESS_UNIT, site_section=str(self.url or '/').split('/')[1], ) self.add_ga360_data_to_payload(request) context['ga360'] = self.ga360_payload", "field_template = 'admin/wagtailadmin/edit_handlers/field_panel_field.html' def render_as_field(self): instance_obj = self.get_chosen_item() context =", "GA360Mixin are not used.\"\"\" parent_page_types = ['core.CuratedListPage'] subpage_types = [", "unique_together = ['page', 'sso_id'] # TODO: deprecate and remove class", "one Text section.' ), ) # We are keeping the", "delete_cs_index, update_cs_index from core.constants import BACKLINK_QUERYSTRING_NAME, RICHTEXT_FEATURES__MINIMAL from core.context import", "), ( 'text', blocks.RichTextBlock( features=RICHTEXT_FEATURES__MINIMAL, ), ), ( 'quote', core_blocks.CaseStudyQuoteBlock(),", "the relevant CaseStudyBlock. Note that this is rendered via Wagtail's", "'Step', core_blocks.StepByStepBlock(icon='cog'), ), ( 'fictional_example', blocks.StructBlock( [('fiction_body', blocks.RichTextBlock(icon='openquote'))], template='learn/fictional_company_example.html', icon='fa-commenting-o',", "all we need here def _redirect_to_parent_module(self): dest = CuratedListPage.objects.ancestor_of(self).first().url return", "subpage_types = [ 'core.DetailPage', 'core.LessonPlaceholderPage', ] # `title` comes from", "bool(instance_obj), # DEPRECATED - passed to templates for backwards compatibility", "if not next_module: return context context['next_module'] = next_module.specific context['next_lesson'] =", "blank=True, on_delete=models.CASCADE, related_name='+') class AltTextImage(AbstractImage): alt_text = models.CharField(max_length=255, blank=True) admin_form_fields", "both a media node and a text node and that", "def delete(self, **kwargs): delete_cs_index(self.id) super().delete(**kwargs) def get_cms_standalone_view_url(self): return reverse('cms_extras:case-study-view', args=[self.id])", "TopicPage.objects.live().specific().descendant_of(self) if live: qs = qs.live() return qs @cached_property def", "import blocks as core_blocks, mixins from core.case_study_index import delete_cs_index, update_cs_index", "[ ObjectList(product_tab, heading='Product'), ObjectList(market_tab, heading='Market'), ObjectList(lesson_tab, heading='Lesson'), ObjectList(threshold_tab, heading='Threshold'), ]", ") trading_bloc_code_tags = ClusterTaggableManager( through='core.TradingBlocTaggedCaseStudy', blank=True, verbose_name='Trading bloc tags' )", "not already set if not self.slug: self.slug = slugify(self.name) super().save(*args,", "False, }, ) return output class AbstractObjectHash(models.Model): class Meta: abstract", "user views a page in this collection?', ) class Meta:", "features=RICHTEXT_FEATURES__MINIMAL, ), ), ( 'quote', core_blocks.CaseStudyQuoteBlock(), ), ], validators=[case_study_body_validation], help_text=(", "MultiFieldPanel( [ FieldPanel('title'), FieldPanel('lead_title'), FieldPanel('summary_context'), StreamFieldPanel('body'), ], heading='Case Study content',", "to be added to create and modified fields, inheritance causes", "transcript = models.TextField( verbose_name=_('Transcript'), blank=False, null=True # left null because", "CuratedListPage, TopicPage]), ] class Meta: unique_together = ['case_study', 'page'] @register_snippet", "FieldPanel('name'), FieldPanel('region'), ] class Meta: verbose_name_plural = 'Countries' ordering =", "content_panels = CMSGenericPage.content_panels + [ StreamFieldPanel('button'), ] class ListPage(CMSGenericPage): parent_page_types", "= self context['current_module'] = page_topic_helper.module if page_topic_helper: topic_page = page_topic_helper.get_page_topic()", "will be a geographical string ('Europe') \"\"\" free_tagging = False", "* Two images \"\"\" error_messages = [] if value: error_messages", "= self.ga360_payload provider = get_context_provider(request=request, page=self) if provider: context.update(provider.get_context_data(request=request, page=self))", "EXPORTPLAN_SLUGS, SECTIONS as EXPORTPLAN_URL_MAP, ) # If we make a", "): # The check for '://' will stop us accepting", "If you're wondering what's going on here: # https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models class", "ObjectList(market_tab, heading='Market'), ObjectList(lesson_tab, heading='Lesson'), ObjectList(threshold_tab, heading='Threshold'), ] ) class Meta:", "super().save(**kwargs) class Meta: get_latest_by = 'modified' ordering = ( '-modified',", "], null=True, blank=True, ) components = StreamField( [ ('route', core_blocks.RouteSectionBlock()),", "tags for personalisation' # If you're wondering what's going on", "a child of another page type... page_topic_helper = PageTopicHelper(self) next_lesson", "'item', core_blocks.Item(), ) ] ), ), ], template='learn/recap.html', icon='fa-commenting-o', ),", "= RichTextField() button_label = models.CharField(max_length=100) ######### # Panels ######### settings_panels", "error_messages.append('Only one video may be used in a case study.')", "models.ForeignKey( AltTextImage, null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) panels = [FieldPanel('name'),", "ordering = ('name',) def __str__(self): return self.name @register_snippet class IndustryTag(models.Model):", "from core.helpers import get_high_level_completion_progress from domestic.helpers import get_lesson_completion_status context =", "FieldPanel('product_hs2')])] market_tab = [ MultiFieldPanel([FieldPanel('country_exact'), FieldPanel('country_region'), FieldPanel('trading_blocs')]) ] lesson_tab =", "return self.name @register_snippet class Tag(models.Model): name = models.CharField(max_length=100, unique=True) panels", "one of the user's export markets.\", default=4, decimal_places=3, max_digits=5, )", "threshold_tab = [ MultiFieldPanel( [ FieldPanel('threshold'), ] ) ] edit_handler", "that's all we need here def _redirect_to_parent_module(self): dest = CuratedListPage.objects.ancestor_of(self).first().url", "'is_chosen': bool(instance_obj), # DEPRECATED - passed to templates for backwards", "allow for cleaner mapping of lessons (`DetailPage`s) to modules (`CuratedListPage`s).", "TabbedInterface(panels).bind_to(model=cls) def get_template(self, request, *args, **kwargs): return self.template def get_context(self,", "tour = ParentalKey(Tour, on_delete=models.CASCADE, related_name='steps') panels = [ FieldPanel('title'), FieldPanel('body'),", "name summary lead_title = models.TextField(blank=False) # Deliberately not rich-text /", "image = models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.CASCADE, related_name='+') class AltTextImage(AbstractImage): alt_text", "= StreamField( [ ('Image', core_blocks.ImageBlock(template='core/includes/_hero_image.html')), ('Video', core_blocks.SimpleVideoBlock(template='core/includes/_hero_video.html')), ], null=True, blank=True,", "def sources(self): return [ { 'src': self.url, 'type': mimetypes.guess_type(self.filename)[0] or", "from django.conf import settings from django.core.exceptions import ValidationError from django.db", "blank=True, on_delete=models.SET_NULL, related_name='+' ) ######## # Panels ######## content_panels =", "self.image.alt_text @register_snippet class Tour(ClusterableModel): page = models.OneToOneField('wagtailcore.Page', on_delete=models.CASCADE, related_name='tour') title", "back to the parent # learning module (ListPage) context['parent_page_url'] =", "'item', core_blocks.Item(icon='fa-arrow-right'), ) ] ), ), ( 'cons', blocks.StreamBlock( [", "class CaseStudy(ClusterableModel): \"\"\"Dedicated snippet for use as a case study.", "product_tab = [MultiFieldPanel([FieldPanel('product_hs6'), FieldPanel('product_hs4'), FieldPanel('product_hs2')])] market_tab = [ MultiFieldPanel([FieldPanel('country_exact'), FieldPanel('country_region'),", "[ StreamFieldPanel('button'), ] class ListPage(CMSGenericPage): parent_page_types = ['core.LandingPage'] subpage_types =", "Hero section', code='invalid'), ) class TopicPage(mixins.AuthenticatedUserRequired, Page): \"\"\"Structural page to", "[] ############### # Layout fields ############### template = models.CharField( max_length=255,", "class Meta: verbose_name = 'Country tag for personalisation' verbose_name_plural =", "when the page attempts to render the relevant CaseStudyBlock. Note", "Not intented to be viewed by end users, so will", "'subtitles_en', ) @property def sources(self): return [ { 'src': self.url,", "request): if request.user.is_authenticated: # checking if the page should record", "'Learn'),) record_read_progress = models.BooleanField( default=False, help_text='Should we record when a", "import mimetypes from urllib.parse import unquote from django.conf import settings", "models.CharField(max_length=255) body = models.CharField(max_length=255) button_text = models.CharField(max_length=255) panels = [", "# Do not allow this page type to be created", "'srclang': 'en', 'label': 'English', 'url': reverse('core:subtitles-serve', args=[self.id, 'en']), 'default': False,", "FieldPanel('title'), FieldPanel('body'), FieldPanel('button_text'), MultiFieldPanel([InlinePanel('steps')], heading='Steps'), ] def __str__(self): return self.page.title", ") self.add_ga360_data_to_payload(request) context['ga360'] = self.ga360_payload provider = get_context_provider(request=request, page=self) if", "any case study trading bloc tag matches the any trading", "related_name='country_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='country_tagged_items') class RegionTaggedCaseStudy(ItemBase):", "ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='region_tagged_items') class TradingBlocTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationTradingBlocTag, related_name='trading_bloc_tagged_case_studies',", "case study region tag matches the region of any of", "# noqa N806 QUOTE_BLOCK = 'quote' # noqa N806 #", "class TimeStampedModel(models.Model): \"\"\"Modified version of django_extensions.db.models.TimeStampedModel Unfortunately, because null=True needed", "Panels ########## layout_panels = [FieldPanel('template')] settings_panels = [FieldPanel('slug')] + Page.settings_panels", "we KNOW are for the export plan, else ignore it.\"\"\"", "Lesson, Topic & Module, also used for Personalisation', ), ]", "the parent # learning module (ListPage) context['parent_page_url'] = self.get_parent().url if", "content_panels = CMSGenericPage.content_panels + [ FieldPanel('description'), StreamFieldPanel('button'), ImageChooserPanel('image'), StreamFieldPanel('components'), StreamFieldPanel('body'),", "FieldPanel('product_hs4'), FieldPanel('product_hs2')])] market_tab = [ MultiFieldPanel([FieldPanel('country_exact'), FieldPanel('country_region'), FieldPanel('trading_blocs')]) ] lesson_tab", "ClusterTaggableManager( through='core.CountryTaggedCaseStudy', blank=True, verbose_name='Country tags' ) region_code_tags = ClusterTaggableManager( through='core.RegionTaggedCaseStudy',", "= self.title if self.title else self.summary_context return f'{display_name}' def save(self,", "= [FieldPanel('slug')] + Page.settings_panels def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)", "= models.CharField(max_length=255, blank=False, default='How we did it') # old name", "= ParentalKey(Tour, on_delete=models.CASCADE, related_name='steps') panels = [ FieldPanel('title'), FieldPanel('body'), FieldPanel('position'),", "'ITA_Quote', core_blocks.ITAQuoteBlock(icon='fa-quote-left'), ), ( 'pros_cons', blocks.StructBlock( [ ( 'pros', blocks.StreamBlock(", "module_page=self, ) context['high_level_completion_progress'] = get_high_level_completion_progress( completion_status=completion_status, ) return context def", "study HS4 tag matches the first 4 digits of any", "' \"the user's export markets falls into unless there is", "= models.CharField(max_length=255) body = models.CharField(max_length=255) position = models.CharField(max_length=255) selector =", "if _backlink: context['backlink'] = _backlink context['backlink_title'] = self._get_backlink_title(_backlink) if isinstance(self.get_parent().specific,", "'filter_spec', 'focal_point_key') @property def alt(self): return self.image.alt_text @register_snippet class Tour(ClusterableModel):", "for the export plan, else ignore it.\"\"\" backlink_path = request.GET.get(BACKLINK_QUERYSTRING_NAME,", "'/').split('/')[1], ) self.add_ga360_data_to_payload(request) context['ga360'] = self.ga360_payload provider = get_context_provider(request=request, page=self)", "the appropriate Case Study block to show will happen when", "import get_lesson_completion_status context = super().get_context(request) # Give the template a", "= ('name',) def __str__(self): return self.name @register_snippet class Country(models.Model): name", "def get_context(self, request, *args, **kwargs): from core.helpers import ( get_high_level_completion_progress,", "* One image, only * One video, only * One", "given when user's lesson is tagged in the case study.\",", "models.CharField(max_length=1000) @staticmethod def generate_content_hash(field_file): filehash = hashlib.md5() field_file.open() filehash.update(field_file.read()) field_file.close()", "the Export Plan sections we have.\"\"\" return {url: values['title'] for", "button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True) image = models.ForeignKey( get_image_model_string(),", "serve(self, request): return self._redirect_to_parent_module() class LessonPlaceholderPage(mixins.AuthenticatedUserRequired, Page): \"\"\"Structural page to", "TopicPage(mixins.AuthenticatedUserRequired, Page): \"\"\"Structural page to allow for cleaner mapping of", "this is rendered via Wagtail's ModelAdmin, so appears in the", "from wagtail.core.models import Orderable, Page from wagtail.images import get_image_model_string from", ") content_object = ParentalKey( to='core.CaseStudy', on_delete=models.CASCADE, related_name='trading_bloc_tagged_items' ) def _high_level_validation(value,", "FieldPanel('trading_bloc_code_tags'), ], heading='Case Study tags for Personalisation', ), MultiFieldPanel( [", "= 'Trading bloc tag for personalisation' verbose_name_plural = 'Trading bloc", "in it) and/or a Quote section, then one Text section", "import get_high_level_completion_progress from domestic.helpers import get_lesson_completion_status context = super().get_context(request) if", "if topic_page: context['current_topic'] = topic_page context['page_topic'] = topic_page.title if next_lesson:", "filehash.hexdigest() class DocumentHash(AbstractObjectHash): document = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, on_delete=models.CASCADE,", "permission 'domestic.GreatDomesticHomePage', ] subpage_types = [ 'core.ListPage', 'core.InterstitialPage', 'domestic.DomesticDashboard', ]", "intented to be viewed by end users, so will redirect", "# Content fields ################ hero = StreamField( [ ('Image', core_blocks.ImageBlock(template='core/includes/_hero_image.html')),", "tags. The decision about the appropriate Case Study block to", "verbose_name='HS-code tags') country_code_tags = ClusterTaggableManager( through='core.CountryTaggedCaseStudy', blank=True, verbose_name='Country tags' )", "models.CharField( max_length=255, choices=None, ) ######### # Panels ########## layout_panels =", "ParentalKey('core.ContentModule', on_delete=models.CASCADE, related_name='tagged_items') # TODO: deprecate and remove @register_snippet class", "backlink to the export plan if we detect one and", "field_file.close() return filehash.hexdigest() class DocumentHash(AbstractObjectHash): document = models.ForeignKey( 'wagtaildocs.Document', null=True,", "template_choices = (('learn/curated_list_page.html', 'Learn'),) ################ # Content fields ################ heading", "LessonPlaceholderPage(mixins.AuthenticatedUserRequired, Page): \"\"\"Structural page to allow for configuring and representing", "sync it via Wagtail-Transfer register_snippet(Redirect) class GreatMedia(Media): transcript = models.TextField(", "( 'paragraph', blocks.StructBlock( [('paragraph', blocks.RichTextBlock())], template='core/struct_paragraph_block.html', icon='fa-font', ), ), (", "content = RichTextField() tags = TaggableManager(through=ContentModuleTag, blank=True) panels = [", "content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='country_tagged_items') class RegionTaggedCaseStudy(ItemBase): tag = models.ForeignKey(", "appear as a Snippet, we can sync it via Wagtail-Transfer", "for Personalisation', ), MultiFieldPanel( [ InlinePanel('related_pages', label='Related pages'), ], heading='Related", "django.utils.translation import ugettext_lazy as _ from django_extensions.db.fields import CreationDateTimeField, ModificationDateTimeField", "blocks from wagtail.core.blocks.stream_block import StreamBlockValidationError from wagtail.core.fields import RichTextField, StreamField", "core.context import get_context_provider from core.utils import PageTopicHelper, get_first_lesson from exportplan.core.data", "user's products \" 'unless there is an HS6 match.', default=4,", "The check for '://' will stop us accepting a backlink", "else self.summary_context return f'{display_name}' def save(self, **kwargs): # When we", "def alt(self): return self.image.alt_text @register_snippet class Tour(ClusterableModel): page = models.OneToOneField('wagtailcore.Page',", "[FieldPanel('name')] class Meta: ordering = ('name',) def __str__(self): return self.name", "will stop us accepting a backlink which # features a", "backlink_path.split('/')[3] return self._export_plan_url_map.get(_path) def get_context(self, request, *args, **kwargs): context =", "tags for personalisation' class PersonalisationCountryTag(TagBase): \"\"\"Custom tag for personalisation. Tag", "True # Content models class CMSGenericPage( mixins.EnableTourMixin, mixins.AuthenticatedUserRequired, mixins.WagtailGA360Mixin, GA360Mixin,", "one or two items in it) ' 'and/or Quote sections,", "'item', core_blocks.Item(icon='fa-arrow-right'), ) ] ), ), ], template='learn/pros_and_cons.html', icon='fa-arrow-right', ),", "Slugs->title for all the Export Plan sections we have.\"\"\" return", "markets \" 'unless there is an exact country match.', default=2,", "] @register_snippet class Product(models.Model): name = models.CharField(max_length=255) panels = [", "= backlink_path.split('/')[3] return self._export_plan_url_map.get(_path) def get_context(self, request, *args, **kwargs): context", "noqa N806 # we need to be strict about presence", "_backlink = self._get_backlink(request) if _backlink: context['backlink'] = _backlink context['backlink_title'] =", "= 'Automated list page' verbose_name_plural = 'Automated list pages' def", "given when the user's lesson's module is tagged in the", "**kwargs): # Automatically set slug on save, if not already", "TabbedInterface, ) from wagtail.contrib.redirects.models import Redirect from wagtail.contrib.settings.models import BaseSetting,", "count_detail_pages(self): count = 0 for topic in self.get_topics(): count +=", "crafted attack # URL), but that's an acceptable limitation here", "case study.\", default=8, decimal_places=3, max_digits=5, ) topic = models.DecimalField( help_text=\"Score", "is not None: backlink_path = unquote(backlink_path) if len(backlink_path.split('/')) > 2", "= models.ForeignKey(DetailPage, on_delete=models.CASCADE, related_name='page_views') list_page = models.ForeignKey(ListPage, on_delete=models.CASCADE, related_name='page_views_list') sso_id", "blank=True, help_text='English-language subtitles for this video, in VTT format', )", "panels = [ FieldPanel('title'), FieldPanel('body'), FieldPanel('position'), FieldPanel('selector'), ] @register_snippet class", "when a user views a page in this collection?', )", "HS6, HS4 or HS2 code\"\"\" # free_tagging = False #", "call create to obtain an ID for indexing self.update_modified =", "= 'Detail pages' ################ # Content fields ################ hero =", "param (eg a crafted attack # URL), but that's an", "context['ga360'] = self.ga360_payload provider = get_context_provider(request=request, page=self) if provider: context.update(provider.get_context_data(request=request,", "models.ForeignKey(DetailPage, on_delete=models.CASCADE, related_name='page_views') list_page = models.ForeignKey(ListPage, on_delete=models.CASCADE, related_name='page_views_list') sso_id =", "self.title class PersonalisationHSCodeTag(TagBase): \"\"\"Custom tag for personalisation. Tag value will", "verbose_name_plural = 'Country tags for personalisation' class PersonalisationRegionTag(TagBase): \"\"\"Custom tag", "= 'Countries' ordering = ('name',) def save(self, *args, **kwargs): #", "( FieldPanel, InlinePanel, MultiFieldPanel, ObjectList, PageChooserPanel, StreamFieldPanel, TabbedInterface, ) from", "in this collection?', ) class Meta: verbose_name = 'Automated list", "'sso_id'] # TODO: deprecate and remove class ContentModuleTag(TaggedItemBase): content_object =", "from core.context import get_context_provider from core.utils import PageTopicHelper, get_first_lesson from", "context['current_lesson'] = self context['current_module'] = page_topic_helper.module if page_topic_helper: topic_page =", "a full-page-width block', ), ), ( 'video', core_blocks.SimpleVideoBlock( template='core/includes/_video_full_width.html', help_text='Video", "appears in the sidebar, but we have to keep it", "max_digits=5, ) country_exact = models.DecimalField( help_text=\"Score given when any case", "'://' not in backlink_path ): # The check for '://'", "return context class PageView(TimeStampedModel): page = models.ForeignKey(DetailPage, on_delete=models.CASCADE, related_name='page_views') list_page", "geographical string ('Europe') \"\"\" free_tagging = False class Meta: verbose_name", "f'{display_name}' def save(self, **kwargs): # When we create a new", "( 'pros_cons', blocks.StructBlock( [ ( 'pros', blocks.StreamBlock( [ ( 'item',", "CreationDateTimeField, ModificationDateTimeField from great_components.mixins import GA360Mixin from modelcluster.contrib.taggit import ClusterTaggableManager", "media node and a text node and that the media", "StreamFieldPanel('button'), ImageChooserPanel('image'), StreamFieldPanel('components'), StreamFieldPanel('body'), ] class InterstitialPage(CMSGenericPage): parent_page_types = ['core.LandingPage']", "it.\"\"\" backlink_path = request.GET.get(BACKLINK_QUERYSTRING_NAME, '') if backlink_path is not None:", "registered as a Snippet to be able to transfer it", "decimal_places=3, max_digits=5, ) product_hs2 = models.DecimalField( help_text=\"Score given when any", "user's export markets \" 'unless there is an exact country", "request, *args, **kwargs): self.handle_page_view(request) return super().serve(request, **kwargs) @cached_property def topic_title(self):", "# fields to aid lookup and make the UX easier", "view. Only accepts backlinks that we KNOW are for the", "for personalisation' verbose_name_plural = 'Country tags for personalisation' class PersonalisationRegionTag(TagBase):", "= models.DecimalField( help_text=\"Score given when user's lesson is tagged in", "_get_backlink(self, request): \"\"\"Try to extract a backlink (used for a", "we can get a title that goes with it. For", "before a still image.') return error_messages def case_study_body_validation(value): \"\"\"Ensure the", "personalisation-relevant tags in separate # fields to aid lookup and", ") objective = StreamField( [ ( 'paragraph', blocks.RichTextBlock(options={'class': 'objectives'}), ),", "import models from django.http import HttpResponseRedirect from django.template.loader import render_to_string", "= [ 'core.ListPage', 'core.InterstitialPage', 'domestic.DomesticDashboard', ] template_choices = ( ('learn/landing_page.html',", "= 'admin/wagtailadmin/edit_handlers/field_panel_field.html' def render_as_field(self): instance_obj = self.get_chosen_item() context = {", "get_template(self, request, *args, **kwargs): return self.template def get_context(self, request, *args,", "Code tags for personalisation' class PersonalisationCountryTag(TagBase): \"\"\"Custom tag for personalisation.", "), ] def __str__(self): display_name = self.title if self.title else", "StreamField from wagtail.core.models import Orderable, Page from wagtail.images import get_image_model_string", "self.name class TimeStampedModel(models.Model): \"\"\"Modified version of django_extensions.db.models.TimeStampedModel Unfortunately, because null=True", "ImageChooserPanel('image'), StreamFieldPanel('components'), StreamFieldPanel('body'), ] class InterstitialPage(CMSGenericPage): parent_page_types = ['core.LandingPage'] template_choices", "[ ('video', core_blocks.SimpleVideoBlock(template='core/includes/_case_study_video.html')), ('image', core_blocks.ImageBlock()), ], min_num=1, max_num=2, ), ),", "tag matches the any trading bloc that any of '", "text node and that the media node has the following", "default=4, decimal_places=3, max_digits=5, ) product_hs2 = models.DecimalField( help_text=\"Score given when", "help_text='This is the minimum score which a case study needs", "return self.template def get_context(self, request, *args, **kwargs): context = super().get_context(request)", "= get_context_provider(request=request, page=self) if provider: context.update(provider.get_context_data(request=request, page=self)) return context class", "checking if the page is already marked as read list_page", "Study block to show will happen when the page attempts", "\" 'unless there is an exact country match.', default=2, decimal_places=3,", "a given backlink, see if we can get a title", "if error_messages: raise StreamBlockValidationError( non_block_errors=ValidationError('; '.join(error_messages), code='invalid'), ) class MagnaPageChooserPanel(PageChooserPanel):", "HttpResponseRedirect(self.get_parent().url) def serve_preview(self, request, mode_name='dummy'): # It doesn't matter what", "get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) body = StreamField( [", "('ListItem', core_blocks.Item()), ] ) body = StreamField( [ ( 'paragraph',", "= models.DecimalField( help_text='Score given when any case study HS6 tag", "= ClusterTaggableManager(through='core.HSCodeTaggedCaseStudy', blank=True, verbose_name='HS-code tags') country_code_tags = ClusterTaggableManager( through='core.CountryTaggedCaseStudy', blank=True,", "max_digits=5, ) trading_blocs = models.DecimalField( help_text='Score given when any case", "blocks.RichTextBlock( features=RICHTEXT_FEATURES__MINIMAL, ), ), ( 'quote', core_blocks.CaseStudyQuoteBlock(), ), ], validators=[case_study_body_validation],", "'media' # noqa N806 QUOTE_BLOCK = 'quote' # noqa N806", "title = models.CharField( max_length=255, blank=False, verbose_name='Internal case study title', )", "= 'Trading bloc tags for personalisation' # If you're wondering", "{ 'field': self.bound_field, self.object_type_name: instance_obj, 'is_chosen': bool(instance_obj), # DEPRECATED -", "TimeStampedModel(models.Model): \"\"\"Modified version of django_extensions.db.models.TimeStampedModel Unfortunately, because null=True needed to", "] def __str__(self): return self.name @register_snippet class Region(models.Model): name =", "= ['case_study', 'page'] @register_snippet class CaseStudy(ClusterableModel): \"\"\"Dedicated snippet for use", "return self.name @register_snippet class Region(models.Model): name = models.CharField(max_length=100, unique=True) panels", "an acceptable limitation here and is very unlikely # to", "), ], validators=[case_study_body_validation], help_text=( 'This block must contain one Media", "= [] # No child pages allowed for placeholders #", "related_name='region_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='region_tagged_items') class TradingBlocTaggedCaseStudy(ItemBase):", "HS6 code of ' \"any of the user's products\", default=8,", "nodes if [node.block_type for node in value if node.block_type !=", "models.DecimalField( help_text=\"Score given when user's lesson's topic is tagged in", "Text section following it.' ) ) return error_messages def _low_level_validation(value,", "features lazily-evaluated URLs that aren't ready when # models are", "# free_tagging = False # DISABLED until tag data only", "get_module_completion_progress( completion_status=completion_status, module_page=self, ) context['high_level_completion_progress'] = get_high_level_completion_progress( completion_status=completion_status, ) return", "**kwargs): self.handle_page_view(request) return super().serve(request, **kwargs) @cached_property def topic_title(self): return self.get_parent().title", "value will be an Trading blocs \"\"\" free_tagging = False", "unquote(backlink_path) if len(backlink_path.split('/')) > 2 and ( backlink_path.split('/')[3] in EXPORTPLAN_SLUGS", "PageView.objects.get_or_create( page=self, list_page=list_page, sso_id=request.user.pk, ) def serve(self, request, *args, **kwargs):", "pages/links. \"\"\" # We have to re-arrange EXPORT_PLAN_SECTION_TITLES_URLS after import", "bloc tags for personalisation' # If you're wondering what's going", "helptext='Add a textblock')), ('image', core_blocks.ImageBlock()), ], null=True, blank=True, ) components", "panels = [ FieldPanel('name'), FieldPanel('region'), ] class Meta: verbose_name_plural =", "= CuratedListPage.objects.ancestor_of(self).first().url return HttpResponseRedirect(dest) def serve_preview(self, request, mode_name='dummy'): # It", "######### content_panels = CMSGenericPage.content_panels + [ FieldPanel('description'), StreamFieldPanel('button'), ImageChooserPanel('image'), StreamFieldPanel('components'),", "us to this view. Only accepts backlinks that we KNOW", "'-created', ) @register_setting class CaseStudyScoringSettings(BaseSetting): threshold = models.DecimalField( help_text='This is", "context['next_lesson'] = next_lesson else: next_module = self.module.get_next_sibling() if not next_module:", "( 'quote', core_blocks.CaseStudyQuoteBlock(), ), ], validators=[case_study_body_validation], help_text=( 'This block must", "Meta: verbose_name = 'HS Code tag for personalisation' verbose_name_plural =", "wagtail.core.blocks.stream_block import StreamBlockValidationError from wagtail.core.fields import RichTextField, StreamField from wagtail.core.models", "= models.DecimalField( help_text=\"Score given when the user's lesson's module is", "), ), ], template='learn/pros_and_cons.html', icon='fa-arrow-right', ), ), ('choose_do_not_choose', core_blocks.ChooseDoNotChooseBlock()), (", ".filter(record_read_progress=True) .exclude(page_views_list__sso_id=request.user.pk, page_views_list__page=self) .first() ) if list_page: PageView.objects.get_or_create( page=self, list_page=list_page,", "= (('learn/interstitial.html', 'Learn'),) ################ # Content fields ################ button =", "= Media.admin_form_fields + ( 'transcript', 'subtitles_en', ) @property def sources(self):", "button_text = models.CharField(max_length=255) panels = [ PageChooserPanel('page'), FieldPanel('title'), FieldPanel('body'), FieldPanel('button_text'),", "class AltTextImage(AbstractImage): alt_text = models.CharField(max_length=255, blank=True) admin_form_fields = Image.admin_form_fields +", "migration class Meta: verbose_name = 'HS Code tag for personalisation'", "unless there is an exact country or region match.\", default=2,", "############### template = models.CharField( max_length=255, choices=None, ) ######### # Panels", "also lesson match.', default=4, decimal_places=3, max_digits=5, ) module = models.DecimalField(", "CMSGenericPage.settings_panels + [FieldPanel('record_read_progress')] content_panels = CMSGenericPage.content_panels + [FieldPanel('description'), FieldPanel('button_label')] class", "decimal_places=3, max_digits=5, ) country_region = models.DecimalField( help_text=\"Score given when any", "case study country tag exactly matches one of the user's", "field.choices = self.template_choices field.required = True @cached_classmethod def get_edit_handler(cls): #", "body = models.CharField(max_length=255) button_text = models.CharField(max_length=255) panels = [ PageChooserPanel('page'),", "if backlink_path is not None: backlink_path = unquote(backlink_path) if len(backlink_path.split('/'))", "ListPage.objects.ancestor_of(self) .filter(record_read_progress=True) .exclude(page_views_list__sso_id=request.user.pk, page_views_list__page=self) .first() ) if list_page: PageView.objects.get_or_create( page=self,", "), ( 'ITA_Quote', core_blocks.ITAQuoteBlock(icon='fa-quote-left'), ), ( 'pros_cons', blocks.StructBlock( [ (", "call to get the data twice completion_status = get_lesson_completion_status(request.user) context['module_completion_progress']", "self._redirect_to_parent_module() class DetailPage(CMSGenericPage): estimated_read_duration = models.DurationField(null=True, blank=True) parent_page_types = [", "self.ga360_payload provider = get_context_provider(request=request, page=self) if provider: context.update(provider.get_context_data(request=request, page=self)) return", "only * One video, only * One video + One", "passed to templates for backwards compatibility only # Added obj_type", "admin_form_fields = Image.admin_form_fields + ('alt_text',) class Rendition(AbstractRendition): image = models.ForeignKey(AltTextImage,", "when any case study HS6 tag matches the complete HS6", "return self._redirect_to_parent_module() class LessonPlaceholderPage(mixins.AuthenticatedUserRequired, Page): \"\"\"Structural page to allow for", "= get_module_completion_progress( completion_status=completion_status, module_page=self, ) context['high_level_completion_progress'] = get_high_level_completion_progress( completion_status=completion_status, )", "parent_page_types = [ 'domestic.DomesticHomePage', # TODO: once we've restructured, remove", "its tags. The decision about the appropriate Case Study block", "core.utils import PageTopicHelper, get_first_lesson from exportplan.core.data import ( SECTION_SLUGS as", "\"\"\" # We have to re-arrange EXPORT_PLAN_SECTION_TITLES_URLS after import #", "null=True) panels = [ MultiFieldPanel( [ FieldPanel('title'), FieldPanel('lead_title'), FieldPanel('summary_context'), StreamFieldPanel('body'),", "return reverse('cms_extras:case-study-view', args=[self.id]) class Meta: verbose_name_plural = 'Case studies' get_latest_by", "# The check for '://' will stop us accepting a", "Product(models.Model): name = models.CharField(max_length=255) panels = [ FieldPanel('name'), ] def", "class CaseStudyRelatedPages(Orderable): case_study = ParentalKey( 'core.CaseStudy', related_name='related_pages', on_delete=models.SET_NULL, null=True, blank=True,", "max_digits=5, ) product_hs6 = models.DecimalField( help_text='Score given when any case", "match.', default=4, decimal_places=3, max_digits=5, ) module = models.DecimalField( help_text=\"Score given", "node.block_type == MEDIA_BLOCK: subnode_block_types = [subnode.block_type for subnode in node.value]", "blocks.RichTextBlock(icon='openquote', helptext='Add a textblock')), ('image', core_blocks.ImageBlock()), ], null=True, blank=True, )", "def get_template(self, request, *args, **kwargs): return self.template def get_context(self, request,", "def get_topics(self, live=True) -> models.QuerySet: qs = TopicPage.objects.live().specific().descendant_of(self) if live:", "page_topic_helper = PageTopicHelper(self) next_lesson = page_topic_helper.get_next_lesson() context['current_lesson'] = self context['current_module']", "must comes first so that it is displayed first) *", "models.DecimalField( help_text=\"Score given when any case study HS4 tag matches", "HttpResponseRedirect(dest) def serve_preview(self, request, mode_name='dummy'): # It doesn't matter what", "mixins.AuthenticatedUserRequired, mixins.WagtailGA360Mixin, GA360Mixin, Page, ): \"\"\" Generic page, freely inspired", "class Region(models.Model): name = models.CharField(max_length=100, unique=True) panels = [FieldPanel('name')] class", "is an HS6 match.', default=4, decimal_places=3, max_digits=5, ) product_hs2 =", "\"\"\"Try to extract a backlink (used for a link to", "not allowed error_messages.append('The video must come before a still image.')", "+ Page.settings_panels def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) field =", "# NOQA N805 panels = [ ObjectList(cls.content_panels, heading='Content'), ObjectList(cls.layout_panels, heading='Layout'),", "image = models.ForeignKey( get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) body", "@property def subtitles(self): output = [] # TO COME: support", "'media', blocks.StreamBlock( [ ('video', core_blocks.SimpleVideoBlock(template='core/includes/_case_study_video.html')), ('image', core_blocks.ImageBlock()), ], min_num=1, max_num=2,", "False template_choices = [] ############### # Layout fields ############### template", "template_choices = [] ############### # Layout fields ############### template =", "models.DurationField(null=True, blank=True) parent_page_types = [ 'core.CuratedListPage', # TEMPORARY: remove after", "is an exact country or region match.\", default=2, decimal_places=3, max_digits=5,", "Media section (with one or ' 'two items in it)", "on_delete=models.SET_NULL, null=True, blank=True, ) page = models.ForeignKey( 'wagtailcore.Page', on_delete=models.CASCADE, related_name='+',", "__str__(self): return self.name @register_snippet class Tag(models.Model): name = models.CharField(max_length=100, unique=True)", "def __str__(self): return self.name @register_snippet class IndustryTag(models.Model): name = models.CharField(max_length=100,", "blocks.StructBlock( [('paragraph', blocks.RichTextBlock())], template='core/struct_paragraph_block.html', icon='fa-font', ), ), ( 'video', blocks.StructBlock(", "'considered before being presented to users. ', default=10, decimal_places=3, max_digits=5,", "to re-arrange EXPORT_PLAN_SECTION_TITLES_URLS after import # because it features lazily-evaluated", "'src': self.url, 'type': mimetypes.guess_type(self.filename)[0] or 'application/octet-stream', 'transcript': self.transcript, } ]", "still image.') return error_messages def case_study_body_validation(value): \"\"\"Ensure the case study", "on here: # https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models class HSCodeTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationHSCodeTag,", "value: error_messages = _high_level_validation(value, error_messages) error_messages = _low_level_validation(value, error_messages) if", "Page, ): \"\"\" Generic page, freely inspired by Codered page", "import hashlib import mimetypes from urllib.parse import unquote from django.conf", "( 'Step', core_blocks.StepByStepBlock(icon='cog'), ), ( 'fictional_example', blocks.StructBlock( [('fiction_body', blocks.RichTextBlock(icon='openquote'))], template='learn/fictional_company_example.html',", "'Trading bloc tag for personalisation' verbose_name_plural = 'Trading bloc tags", ") @property def sources(self): return [ { 'src': self.url, 'type':", "**kwargs): delete_cs_index(self.id) super().delete(**kwargs) def get_cms_standalone_view_url(self): return reverse('cms_extras:case-study-view', args=[self.id]) class Meta:", "Content fields ################ description = RichTextField() button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))],", "from taggit.models import ItemBase, TagBase, TaggedItemBase from wagtail.admin.edit_handlers import (", "ModificationDateTimeField('modified', null=True) def save(self, **kwargs): self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified',", "for personalisation' verbose_name_plural = 'Trading bloc tags for personalisation' #", "case study. Supports personalised selection via its tags. The decision", "create and modified fields, inheritance causes issues with field clash.", "[ ( 'item', core_blocks.Item(icon='fa-arrow-right'), ) ] ), ), ], template='learn/pros_and_cons.html',", "4 digits of any of the user's products \" 'unless", "= False class Meta: verbose_name = 'Country tag for personalisation'", "in value if node.block_type != QUOTE_BLOCK] != [MEDIA_BLOCK, TEXT_BLOCK]: error_messages.append(", "[ StreamFieldPanel('hero'), StreamFieldPanel('objective'), StreamFieldPanel('body'), StreamFieldPanel('recap'), ] def handle_page_view(self, request): if", "with it. For now, this is limited only to Export", "personalisation' class PersonalisationTradingBlocTag(TagBase): \"\"\"Custom tag for personalisation. Tag value will", "the page is already marked as read list_page = (", "after import # because it features lazily-evaluated URLs that aren't", "to get the data twice completion_status = get_lesson_completion_status(request.user) context['module_completion_progress'] =", "return context class LandingPage(CMSGenericPage): parent_page_types = [ 'domestic.DomesticHomePage', # TODO:", "[ FieldPanel('description'), StreamFieldPanel('button'), ImageChooserPanel('image'), StreamFieldPanel('components'), StreamFieldPanel('body'), ] class InterstitialPage(CMSGenericPage): parent_page_types", "progress # checking if the page is already marked as", "= ModificationDateTimeField('modified', null=True) def save(self, **kwargs): self.update_modified = kwargs.pop('update_modified', getattr(self,", "max_digits=5, ) product_hs2 = models.DecimalField( help_text=\"Score given when any case", "= models.ForeignKey(ListPage, on_delete=models.CASCADE, related_name='page_views_list') sso_id = models.TextField() class Meta: ordering", "subtitles(self): output = [] # TO COME: support for more", "TO COME: support for more than just English if self.subtitles_en:", "render_to_string from django.urls import reverse from django.utils.functional import cached_property from", "tags for Personalisation', ), MultiFieldPanel( [ InlinePanel('related_pages', label='Related pages'), ],", "class Meta: abstract = True # Do not allow this", "# because it features lazily-evaluated URLs that aren't ready when", "{VIDEO_BLOCK}: # Two videos: not allowed error_messages.append('Only one video may", "code ('DE') \"\"\" free_tagging = False class Meta: verbose_name =", "matter what is passed as mode_name - we always redirect", "'Countries' ordering = ('name',) def save(self, *args, **kwargs): # Automatically", "from wagtail.core.blocks.stream_block import StreamBlockValidationError from wagtail.core.fields import RichTextField, StreamField from", "'English', 'url': reverse('core:subtitles-serve', args=[self.id, 'en']), 'default': False, }, ) return", "MultiFieldPanel([FieldPanel('country_exact'), FieldPanel('country_region'), FieldPanel('trading_blocs')]) ] lesson_tab = [MultiFieldPanel([FieldPanel('lesson'), FieldPanel('topic'), FieldPanel('module')])] threshold_tab", "link to the export plan) from the querystring on the", "0 for topic in self.get_topics(): count += DetailPage.objects.live().descendant_of(topic).count() return count", "models.CharField(max_length=255) slug = models.SlugField(max_length=100, unique=True) region = models.ForeignKey(Region, null=True, blank=True,", "a media node and a text node and that the", "ClusterTaggableManager(through='core.HSCodeTaggedCaseStudy', blank=True, verbose_name='HS-code tags') country_code_tags = ClusterTaggableManager( through='core.CountryTaggedCaseStudy', blank=True, verbose_name='Country", "models.CharField(max_length=100, unique=True) panels = [FieldPanel('name')] class Meta: ordering = ('name',)", "from django.template.loader import render_to_string from django.urls import reverse from django.utils.functional", "inheritance causes issues with field clash. \"\"\" created = CreationDateTimeField('created',", "= CMSGenericPage.content_panels + [FieldPanel('description'), FieldPanel('button_label')] class CuratedListPage(CMSGenericPage): parent_page_types = ['core.ListPage']", "= models.ForeignKey( PersonalisationTradingBlocTag, related_name='trading_bloc_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey( to='core.CaseStudy',", "heading='Case Study content', ), MultiFieldPanel( [ FieldPanel('hs_code_tags'), FieldPanel('country_code_tags'), FieldPanel('region_code_tags'), FieldPanel('trading_bloc_code_tags'),", "('alt_text',) class Rendition(AbstractRendition): image = models.ForeignKey(AltTextImage, on_delete=models.CASCADE, related_name='renditions') class Meta:", "one video may be used in a case study.') elif", "[ MultiFieldPanel([FieldPanel('country_exact'), FieldPanel('country_region'), FieldPanel('trading_blocs')]) ] lesson_tab = [MultiFieldPanel([FieldPanel('lesson'), FieldPanel('topic'), FieldPanel('module')])]", "] ), ), ], template='learn/recap.html', icon='fa-commenting-o', ), ) ] )", "hashlib import mimetypes from urllib.parse import unquote from django.conf import", "of URL Slugs->title for all the Export Plan sections we", "if set(subnode_block_types) == {VIDEO_BLOCK}: # Two videos: not allowed error_messages.append('Only", "subtitles_en = models.TextField( verbose_name=_('English subtitles'), null=True, blank=True, help_text='English-language subtitles for", "def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) field = self._meta.get_field('template') field.choices", "mixins.EnableTourMixin, mixins.AuthenticatedUserRequired, mixins.WagtailGA360Mixin, GA360Mixin, Page, ): \"\"\" Generic page, freely", "field_file.open() filehash.update(field_file.read()) field_file.close() return filehash.hexdigest() class DocumentHash(AbstractObjectHash): document = models.ForeignKey(", "), ), ( 'cons', blocks.StreamBlock( [ ( 'item', core_blocks.Item(icon='fa-arrow-right'), )", "for a link to the export plan) from the querystring", "content_hash = models.CharField(max_length=1000) @staticmethod def generate_content_hash(field_file): filehash = hashlib.md5() field_file.open()", "('image', core_blocks.ImageBlock()), ], min_num=1, max_num=2, ), ), ( 'text', blocks.RichTextBlock(", "serve(self, request, *args, **kwargs): self.handle_page_view(request) return super().serve(request, **kwargs) @cached_property def", "heading='Threshold'), ] ) class Meta: verbose_name = 'Case Study Scoring'", "views a page in this collection?', ) class Meta: verbose_name", "a link to the export plan) from the querystring on", "blocks.StreamBlock( [ ('video', core_blocks.SimpleVideoBlock(template='core/includes/_case_study_video.html')), ('image', core_blocks.ImageBlock()), ], min_num=1, max_num=2, ),", "the export plan, else ignore it.\"\"\" backlink_path = request.GET.get(BACKLINK_QUERYSTRING_NAME, '')", "ObjectList, PageChooserPanel, StreamFieldPanel, TabbedInterface, ) from wagtail.contrib.redirects.models import Redirect from", "= ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='region_tagged_items') class TradingBlocTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationTradingBlocTag,", "abstract = True content_hash = models.CharField(max_length=1000) @staticmethod def generate_content_hash(field_file): filehash", "['core.CuratedListPage'] subpage_types = [ 'core.DetailPage', 'core.LessonPlaceholderPage', ] # `title` comes", "from great_components.mixins import GA360Mixin from modelcluster.contrib.taggit import ClusterTaggableManager from modelcluster.models", "items in it) ' 'and/or Quote sections, then one Text", "images \"\"\" error_messages = [] if value: error_messages = _high_level_validation(value,", "as _ from django_extensions.db.fields import CreationDateTimeField, ModificationDateTimeField from great_components.mixins import", "child pages allowed for placeholders # `title` comes from Page", "deprecate and remove @register_snippet class ContentModule(ClusterableModel): title = models.CharField(max_length=255) content", "and that's all we need here def _redirect_to_parent_module(self): dest =", "to modules (`CuratedListPage`s). Not intented to be viewed by end", "# DISABLED until tag data only comes via data migration", "be used in a case study.') elif subnode_block_types[1] == VIDEO_BLOCK:", "= CMSGenericPage.settings_panels + [FieldPanel('record_read_progress')] content_panels = CMSGenericPage.content_panels + [FieldPanel('description'), FieldPanel('button_label')]", "@cached_classmethod def get_edit_handler(cls): # NOQA N805 panels = [ ObjectList(cls.content_panels,", "image, only * One video, only * One video +", "= 'Region tag for personalisation' verbose_name_plural = 'Region tags for", "related_name='+') class AltTextImage(AbstractImage): alt_text = models.CharField(max_length=255, blank=True) admin_form_fields = Image.admin_form_fields", "refactor migration has run 'core.TopicPage', ] template_choices = (('learn/detail_page.html', 'Learn'),)", "+ [FieldPanel('record_read_progress')] content_panels = CMSGenericPage.content_panels + [FieldPanel('description'), FieldPanel('button_label')] class CuratedListPage(CMSGenericPage):", "a crafted attack # URL), but that's an acceptable limitation", "( 'media', blocks.StreamBlock( [ ('video', core_blocks.SimpleVideoBlock(template='core/includes/_case_study_video.html')), ('image', core_blocks.ImageBlock()), ], min_num=1,", "def case_study_body_validation(value): \"\"\"Ensure the case study has exactly both a", "body = StreamField( [ ( 'media', blocks.StreamBlock( [ ('video', core_blocks.SimpleVideoBlock(template='core/includes/_case_study_video.html')),", "a Snippet to be able to transfer it with Wagtail-Transfer", "TEMPORARY: remove after topics refactor migration has run 'core.TopicPage', ]", "module if accessed. Also, for the above reason, mixins.WagtailGA360Mixin and", "'admin/wagtailadmin/edit_handlers/field_panel_field.html' def render_as_field(self): instance_obj = self.get_chosen_item() context = { 'field':", "Media.admin_form_fields + ( 'transcript', 'subtitles_en', ) @property def sources(self): return", "to users. ', default=10, decimal_places=3, max_digits=5, ) lesson = models.DecimalField(", "def generate_content_hash(field_file): filehash = hashlib.md5() field_file.open() filehash.update(field_file.read()) field_file.close() return filehash.hexdigest()", "__str__(self): return self.page.title class TourStep(Orderable): title = models.CharField(max_length=255) body =", "topic is tagged in the case study \" 'unless there", "# learning module (ListPage) context['parent_page_url'] = self.get_parent().url if request.user.is_authenticated: #", "FieldPanel('module')])] threshold_tab = [ MultiFieldPanel( [ FieldPanel('threshold'), ] ) ]", "on the request that brought us to this view. Only", "template_choices = (('learn/interstitial.html', 'Learn'),) ################ # Content fields ################ button", "study country tag exactly matches one of the user's export", "blank=True, on_delete=models.CASCADE, related_name='+' ) class ImageHash(AbstractObjectHash): image = models.ForeignKey('wagtailimages.Image', null=True,", "Snippet to be able to transfer it with Wagtail-Transfer \"\"\"", "= self.template_choices field.required = True @cached_classmethod def get_edit_handler(cls): # NOQA", "estimated_read_duration = models.DurationField(null=True, blank=True) parent_page_types = [ 'core.CuratedListPage', # TEMPORARY:", "In a conditional because a DetailPage currently MAY be used", "verbose_name = 'Detail page' verbose_name_plural = 'Detail pages' ################ #", "checking if the page should record read progress # checking", "an Trading blocs \"\"\" free_tagging = False class Meta: verbose_name", "blocs \"\"\" free_tagging = False class Meta: verbose_name = 'Trading", "[DetailPage, CuratedListPage, TopicPage]), ] class Meta: unique_together = ['case_study', 'page']", "from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.images.models import AbstractImage, AbstractRendition, Image", "self.name @register_snippet class IndustryTag(models.Model): name = models.CharField(max_length=100, unique=True) icon =", "= ( ListPage.objects.ancestor_of(self) .filter(record_read_progress=True) .exclude(page_views_list__sso_id=request.user.pk, page_views_list__page=self) .first() ) if list_page:", "that brought us to this view. Only accepts backlinks that", "def get_cms_standalone_view_url(self): return reverse('cms_extras:case-study-view', args=[self.id]) class Meta: verbose_name_plural = 'Case", "ObjectList(cls.layout_panels, heading='Layout'), ObjectList(cls.settings_panels, heading='Settings', classname='settings'), ] return TabbedInterface(panels).bind_to(model=cls) def get_template(self,", "default=2, decimal_places=3, max_digits=5, ) product_tab = [MultiFieldPanel([FieldPanel('product_hs6'), FieldPanel('product_hs4'), FieldPanel('product_hs2')])] market_tab", "def _export_plan_url_map(self): \"\"\"Return a lookup dictionary of URL Slugs->title for", "self.get_parent().title @cached_property def module(self): \"\"\"Gets the learning module this lesson", "*args, **kwargs): context = super().get_context(request) context['refresh_on_market_change'] = True # Prepare", "FieldPanel('description'), StreamFieldPanel('button'), ImageChooserPanel('image'), StreamFieldPanel('components'), StreamFieldPanel('body'), ] class InterstitialPage(CMSGenericPage): parent_page_types =", "wagtailmedia.models import Media from core import blocks as core_blocks, mixins", "export markets falls into unless there is an exact country", "related_name='+', ) panels = [ MagnaPageChooserPanel('page', [DetailPage, CuratedListPage, TopicPage]), ]", "['page', 'sso_id'] # TODO: deprecate and remove class ContentModuleTag(TaggedItemBase): content_object", "context.update(provider.get_context_data(request=request, page=self)) return context class LandingPage(CMSGenericPage): parent_page_types = [ 'domestic.DomesticHomePage',", "core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True) ######### # Panels ######### content_panels = CMSGenericPage.content_panels", "models.QuerySet: qs = TopicPage.objects.live().specific().descendant_of(self) if live: qs = qs.live() return", "FieldPanel('tags'), ] def __str__(self): return self.title class PersonalisationHSCodeTag(TagBase): \"\"\"Custom tag", "Note that this is rendered via Wagtail's ModelAdmin, so appears", "dictionary of URL Slugs->title for all the Export Plan sections", "delete_cs_index(self.id) super().delete(**kwargs) def get_cms_standalone_view_url(self): return reverse('cms_extras:case-study-view', args=[self.id]) class Meta: verbose_name_plural", "Meta: ordering = ['page__pk'] unique_together = ['page', 'sso_id'] # TODO:", "blank=True, ) ######### # Panels ######### content_panels = CMSGenericPage.content_panels +", "user's lesson is tagged in the case study.\", default=8, decimal_places=3,", "= topic_page context['page_topic'] = topic_page.title if next_lesson: context['next_lesson'] = next_lesson", "\" 'unless there is also lesson or topic match.', default=2,", "context['backlink_title'] = self._get_backlink_title(_backlink) if isinstance(self.get_parent().specific, TopicPage): # In a conditional", "error_messages): # Check content of media node, which should be", "return HttpResponseRedirect(self.get_parent().url) def serve_preview(self, request, mode_name='dummy'): # It doesn't matter", "= 'quote' # noqa N806 # we need to be", "be an image # video after image: not allowed error_messages.append('The", "goes with it. For now, this is limited only to", "################ description = RichTextField() button_label = models.CharField(max_length=100) ######### # Panels", "urllib.parse import unquote from django.conf import settings from django.core.exceptions import", "core_blocks.CaseStudyQuoteBlock(), ), ], validators=[case_study_body_validation], help_text=( 'This block must contain one", "+ [ StreamFieldPanel('button'), ] class ListPage(CMSGenericPage): parent_page_types = ['core.LandingPage'] subpage_types", "\"\"\" error_messages = [] if value: error_messages = _high_level_validation(value, error_messages)", "topic_page = page_topic_helper.get_page_topic() if topic_page: context['current_topic'] = topic_page context['page_topic'] =", "blocks.RichTextBlock(icon='openquote'))], template='learn/fictional_company_example.html', icon='fa-commenting-o', ), ), ( 'ITA_Quote', core_blocks.ITAQuoteBlock(icon='fa-quote-left'), ), (", "self.subtitles_en: output.append( { 'srclang': 'en', 'label': 'English', 'url': reverse('core:subtitles-serve', args=[self.id,", "= TopicPage.objects.live().specific().descendant_of(self) if live: qs = qs.live() return qs @cached_property", "################ hero = StreamField( [ ('Image', core_blocks.ImageBlock(template='core/includes/_hero_image.html')), ('Video', core_blocks.SimpleVideoBlock(template='core/includes/_hero_video.html')), ],", "match.', default=2, decimal_places=3, max_digits=5, ) product_hs6 = models.DecimalField( help_text='Score given", "ParentalKey(Tour, on_delete=models.CASCADE, related_name='steps') panels = [ FieldPanel('title'), FieldPanel('body'), FieldPanel('position'), FieldPanel('selector'),", "@cached_property def _export_plan_url_map(self): \"\"\"Return a lookup dictionary of URL Slugs->title", "return mark_safe(render_to_string(self.field_template, context)) class CaseStudyRelatedPages(Orderable): case_study = ParentalKey( 'core.CaseStudy', related_name='related_pages',", "= models.OneToOneField('wagtailcore.Page', on_delete=models.CASCADE, related_name='tour') title = models.CharField(max_length=255) body = models.CharField(max_length=255)", "button_label = models.CharField(max_length=100) ######### # Panels ######### settings_panels = CMSGenericPage.settings_panels", "fields ################ description = RichTextField() button_label = models.CharField(max_length=100) ######### #", "as core_blocks, mixins from core.case_study_index import delete_cs_index, update_cs_index from core.constants", "output.append( { 'srclang': 'en', 'label': 'English', 'url': reverse('core:subtitles-serve', args=[self.id, 'en']),", "FieldPanel('country_region'), FieldPanel('trading_blocs')]) ] lesson_tab = [MultiFieldPanel([FieldPanel('lesson'), FieldPanel('topic'), FieldPanel('module')])] threshold_tab =", "study.') elif subnode_block_types[1] == VIDEO_BLOCK: # implicitly, [0] must be", "# Automatically set slug on save, if not already set", "' 'two items in it) and/or a Quote section, then", "remove this permission 'domestic.GreatDomesticHomePage', ] subpage_types = [ 'core.ListPage', 'core.InterstitialPage',", "*args, **kwargs): from core.helpers import ( get_high_level_completion_progress, get_module_completion_progress, ) from", "if backlink_path and len(backlink_path.split('/')) > 3: _path = backlink_path.split('/')[3] return", "= ['page', 'sso_id'] # TODO: deprecate and remove class ContentModuleTag(TaggedItemBase):", "title = models.CharField(max_length=255) content = RichTextField() tags = TaggableManager(through=ContentModuleTag, blank=True)", "a backlink which # features a full URL as its", "code='invalid'), ) class MagnaPageChooserPanel(PageChooserPanel): show_label = False field_template = 'admin/wagtailadmin/edit_handlers/field_panel_field.html'", "**kwargs): return self.template def get_context(self, request, *args, **kwargs): context =", "return context ################ # Content fields ################ description = RichTextField()", "topics refactor migration has run 'core.TopicPage', ] template_choices = (('learn/detail_page.html',", "bloc tag for personalisation' verbose_name_plural = 'Trading bloc tags for", "alt_text = models.CharField(max_length=255, blank=True) admin_form_fields = Image.admin_form_fields + ('alt_text',) class", "= [ PageChooserPanel('page'), FieldPanel('title'), FieldPanel('body'), FieldPanel('button_text'), MultiFieldPanel([InlinePanel('steps')], heading='Steps'), ] def", "backlink_path = request.GET.get(BACKLINK_QUERYSTRING_NAME, '') if backlink_path is not None: backlink_path", "or HS4 match.', default=2, decimal_places=3, max_digits=5, ) country_exact = models.DecimalField(", "' 'and/or Quote sections, then one Text section.' ), )", "Do not allow this page type to be created in", "get_high_level_completion_progress, get_module_completion_progress, ) from domestic.helpers import get_lesson_completion_status context = super().get_context(request)", ") return context def hero_singular_validation(value): if value and len(value) >", "choices=None, ) ######### # Panels ########## layout_panels = [FieldPanel('template')] settings_panels", "getattr(self, 'update_modified', True)) super().save(**kwargs) update_cs_index(self) def delete(self, **kwargs): delete_cs_index(self.id) super().delete(**kwargs)", "== VIDEO_BLOCK: # implicitly, [0] must be an image #", "self.url, 'type': mimetypes.guess_type(self.filename)[0] or 'application/octet-stream', 'transcript': self.transcript, } ] @property", "HSCodeTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationHSCodeTag, related_name='hscode_tagged_case_studies', on_delete=models.CASCADE ) content_object =", "case study has exactly both a media node and a", "parent_page_types = ['core.ListPage'] subpage_types = [ 'core.TopicPage', ] template_choices =", "matches the first 2 digits of any of the user's", "Generic page, freely inspired by Codered page \"\"\" class Meta:", "case study HS6 tag matches the complete HS6 code of", "page, freely inspired by Codered page \"\"\" class Meta: abstract", "'core.CaseStudy', related_name='related_pages', on_delete=models.SET_NULL, null=True, blank=True, ) page = models.ForeignKey( 'wagtailcore.Page',", "FieldPanel('region_code_tags'), FieldPanel('trading_bloc_code_tags'), ], heading='Case Study tags for Personalisation', ), MultiFieldPanel(", "a Snippet, we can sync it via Wagtail-Transfer register_snippet(Redirect) class", "don't waste the network call to get the data twice", "and GA360Mixin are not used.\"\"\" parent_page_types = ['core.CuratedListPage'] subpage_types =", "Give the template a simple way to link back to", "_redirect_to_parent_module(self): dest = CuratedListPage.objects.ancestor_of(self).first().url return HttpResponseRedirect(dest) def serve_preview(self, request, mode_name='dummy'):", "obj_type on base class method render_as_field 'obj_type': instance_obj.specific.__class__.__name__ if instance_obj", "request.user.is_authenticated: completion_status = get_lesson_completion_status(request.user) context['high_level_completion_progress'] = get_high_level_completion_progress( completion_status=completion_status, ) return", "('text', blocks.RichTextBlock(icon='openquote', helptext='Add a textblock')), ('image', core_blocks.ImageBlock()), ], null=True, blank=True,", "string ('Europe') \"\"\" free_tagging = False class Meta: verbose_name =", "that the media node has the following content: * One", "or two items in it) ' 'and/or Quote sections, then", "MultiFieldPanel( [ FieldPanel('threshold'), ] ) ] edit_handler = TabbedInterface( [", "need here def _redirect_to_parent_module(self): return HttpResponseRedirect(self.get_parent().url) def serve_preview(self, request, mode_name='dummy'):", "node.block_type != QUOTE_BLOCK] != [MEDIA_BLOCK, TEXT_BLOCK]: error_messages.append( ( 'This block", "a title that goes with it. For now, this is", "help_text=\"Score given when any case study region tag matches the", "and '://' not in backlink_path ): # The check for", "[ 'core.TopicPage', ] template_choices = (('learn/curated_list_page.html', 'Learn'),) ################ # Content", "max_digits=5, ) module = models.DecimalField( help_text=\"Score given when the user's", "following content: * One image, only * One video, only", "above reason, mixins.WagtailGA360Mixin and GA360Mixin are not used.\"\"\" parent_page_types =", "from django.core.exceptions import ValidationError from django.db import models from django.http", "image.') return error_messages def case_study_body_validation(value): \"\"\"Ensure the case study has", "so that it is displayed first) * Two images \"\"\"", "== {VIDEO_BLOCK}: # Two videos: not allowed error_messages.append('Only one video", "TEXT_BLOCK = 'text' # noqa N806 MEDIA_BLOCK = 'media' #", "= get_high_level_completion_progress( completion_status=completion_status, ) return context def hero_singular_validation(value): if value", "https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models class HSCodeTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationHSCodeTag, related_name='hscode_tagged_case_studies', on_delete=models.CASCADE )", "related_name='+', ) panels = [FieldPanel('name'), ImageChooserPanel('icon')] class Meta: ordering =", "] return TabbedInterface(panels).bind_to(model=cls) def get_template(self, request, *args, **kwargs): return self.template", "get_latest_by = 'modified' ordering = ( '-modified', '-created', ) @register_setting", "study \" 'unless there is also lesson match.', default=4, decimal_places=3,", "self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified', True)) super().save(**kwargs) class Meta: get_latest_by", "show_label = False field_template = 'admin/wagtailadmin/edit_handlers/field_panel_field.html' def render_as_field(self): instance_obj =", "study trading bloc tag matches the any trading bloc that", "TopicPage]), ] class Meta: unique_together = ['case_study', 'page'] @register_snippet class", "= 'HS Code tag for personalisation' verbose_name_plural = 'HS Code", "class DetailPage(CMSGenericPage): estimated_read_duration = models.DurationField(null=True, blank=True) parent_page_types = [ 'core.CuratedListPage',", "= models.ForeignKey( get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) body =", "it features lazily-evaluated URLs that aren't ready when # models", "to link back to the parent # learning module (ListPage)", "be created in wagtail admin is_creatable = False template_choices =", "taggit.models import ItemBase, TagBase, TaggedItemBase from wagtail.admin.edit_handlers import ( FieldPanel,", "request, mode_name='dummy'): # It doesn't matter what is passed as", "blank=True) parent_page_types = [ 'core.CuratedListPage', # TEMPORARY: remove after topics", "only * One video + One image * (video must", "topic_page context['page_topic'] = topic_page.title if next_lesson: context['next_lesson'] = next_lesson else:", "get_cms_standalone_view_url(self): return reverse('cms_extras:case-study-view', args=[self.id]) class Meta: verbose_name_plural = 'Case studies'", "django.utils.functional import cached_property from django.utils.safestring import mark_safe from django.utils.text import", "site_section=str(self.url or '/').split('/')[1], ) self.add_ga360_data_to_payload(request) context['ga360'] = self.ga360_payload provider =", "# checking if the page is already marked as read", "def _high_level_validation(value, error_messages): TEXT_BLOCK = 'text' # noqa N806 MEDIA_BLOCK", "kwargs.pop('update_modified', getattr(self, 'update_modified', True)) super().save(**kwargs) class Meta: get_latest_by = 'modified'", "super().serve(request, **kwargs) @cached_property def topic_title(self): return self.get_parent().title @cached_property def module(self):", "get_lesson_completion_status context = super().get_context(request) if request.user.is_authenticated: completion_status = get_lesson_completion_status(request.user) context['high_level_completion_progress']", "= models.ForeignKey( PersonalisationCountryTag, related_name='country_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE,", "models.CharField(max_length=255) content = RichTextField() tags = TaggableManager(through=ContentModuleTag, blank=True) panels =", "handle_page_view(self, request): if request.user.is_authenticated: # checking if the page should", "for placeholders # `title` comes from Page superclass and that's", "module (ListPage) context['parent_page_url'] = self.get_parent().url if request.user.is_authenticated: # get this", "ParentalKey( to='core.CaseStudy', on_delete=models.CASCADE, related_name='trading_bloc_tagged_items' ) def _high_level_validation(value, error_messages): TEXT_BLOCK =", "body = models.CharField(max_length=255) position = models.CharField(max_length=255) selector = models.CharField(max_length=255) tour", "context = super().get_context(request) if request.user.is_authenticated: completion_status = get_lesson_completion_status(request.user) context['high_level_completion_progress'] =", "Content models class CMSGenericPage( mixins.EnableTourMixin, mixins.AuthenticatedUserRequired, mixins.WagtailGA360Mixin, GA360Mixin, Page, ):", ") recap = StreamField( [ ( 'recap_item', blocks.StructBlock( [ ('title',", "left null because was an existing field ) subtitles_en =", "HS4 or HS2 code\"\"\" # free_tagging = False # DISABLED", "will happen when the page attempts to render the relevant", "= CreationDateTimeField('created', null=True) modified = ModificationDateTimeField('modified', null=True) panels = [", "the querystring on the request that brought us to this", "blocks.StreamBlock( [ ( 'item', core_blocks.Item(), ) ] ), ), ],", "= self.get_chosen_item() context = { 'field': self.bound_field, self.object_type_name: instance_obj, 'is_chosen':", "match.\", default=2, decimal_places=3, max_digits=5, ) product_tab = [MultiFieldPanel([FieldPanel('product_hs6'), FieldPanel('product_hs4'), FieldPanel('product_hs2')])]", "Page from wagtail.images import get_image_model_string from wagtail.images.edit_handlers import ImageChooserPanel from", "= models.DecimalField( help_text=\"Score given when any case study HS4 tag", "blank=True, validators=[hero_singular_validation], ) objective = StreamField( [ ( 'paragraph', blocks.RichTextBlock(options={'class':", "self.template def get_context(self, request, *args, **kwargs): context = super().get_context(request) self.set_ga360_payload(", "\"\"\"Modified version of django_extensions.db.models.TimeStampedModel Unfortunately, because null=True needed to be", "an exact country match.', default=2, decimal_places=3, max_digits=5, ) trading_blocs =", "core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True) image = models.ForeignKey( get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL,", "live=True) -> models.QuerySet: qs = TopicPage.objects.live().specific().descendant_of(self) if live: qs =", "= (('learn/curated_list_page.html', 'Learn'),) ################ # Content fields ################ heading =", "return self.name class TimeStampedModel(models.Model): \"\"\"Modified version of django_extensions.db.models.TimeStampedModel Unfortunately, because", "_export_plan_url_map(self): \"\"\"Return a lookup dictionary of URL Slugs->title for all", ") topic = models.DecimalField( help_text=\"Score given when user's lesson's topic", "help_text=\"Score given when user's lesson's topic is tagged in the", "from urllib.parse import unquote from django.conf import settings from django.core.exceptions", "context['parent_page_url'] = self.get_parent().url if request.user.is_authenticated: # get this once, so", "CaseStudyScoringSettings(BaseSetting): threshold = models.DecimalField( help_text='This is the minimum score which", "Tour(ClusterableModel): page = models.OneToOneField('wagtailcore.Page', on_delete=models.CASCADE, related_name='tour') title = models.CharField(max_length=255) body", "FieldPanel('selector'), ] @register_snippet class Product(models.Model): name = models.CharField(max_length=255) panels =", "core_blocks.Item()), ] ) body = StreamField( [ ( 'paragraph', blocks.StructBlock(", "that aren't ready when # models are imported if backlink_path", "{url: values['title'] for url, values in EXPORTPLAN_URL_MAP.items()} def _get_backlink(self, request):", "subnode_block_types = [subnode.block_type for subnode in node.value] if len(subnode_block_types) ==", "in EXPORTPLAN_URL_MAP.items()} def _get_backlink(self, request): \"\"\"Try to extract a backlink", "null=True, blank=True, ) page = models.ForeignKey( 'wagtailcore.Page', on_delete=models.CASCADE, related_name='+', )", "because was an existing field ) subtitles_en = models.TextField( verbose_name=_('English", "verbose_name = 'Automated list page' verbose_name_plural = 'Automated list pages'", "us accepting a backlink which # features a full URL", "class ContentModule(ClusterableModel): title = models.CharField(max_length=255) content = RichTextField() tags =", "), ) ] ) ######### # Panels ########## content_panels =", "for personalisation' class PersonalisationTradingBlocTag(TagBase): \"\"\"Custom tag for personalisation. Tag value", "code of ' \"any of the user's products\", default=8, decimal_places=3,", "study has exactly both a media node and a text", "it with Wagtail-Transfer \"\"\" title = models.CharField( max_length=255, blank=False, verbose_name='Internal", "[ ( 'paragraph', blocks.StructBlock( [('paragraph', blocks.RichTextBlock())], template='core/struct_paragraph_block.html', icon='fa-font', ), ),", "and len(backlink_path.split('/')) > 3: _path = backlink_path.split('/')[3] return self._export_plan_url_map.get(_path) def", ") ######## # Panels ######## content_panels = CMSGenericPage.content_panels + [", "if accessed. Also, for the above reason, mixins.WagtailGA360Mixin and GA360Mixin", "+ ('alt_text',) class Rendition(AbstractRendition): image = models.ForeignKey(AltTextImage, on_delete=models.CASCADE, related_name='renditions') class", "ItemBase, TagBase, TaggedItemBase from wagtail.admin.edit_handlers import ( FieldPanel, InlinePanel, MultiFieldPanel,", "domestic.helpers import get_lesson_completion_status context = super().get_context(request) if request.user.is_authenticated: completion_status =", "for topic in self.get_topics(): count += DetailPage.objects.live().descendant_of(topic).count() return count def", "qs.live() return qs @cached_property def count_topics(self): return self.get_topics().count() @cached_property def", "= next_lesson else: next_module = self.module.get_next_sibling() if not next_module: return", "tag = models.ForeignKey( PersonalisationHSCodeTag, related_name='hscode_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy',", "Study tags for Personalisation', ), MultiFieldPanel( [ InlinePanel('related_pages', label='Related pages'),", "for the above reason, mixins.WagtailGA360Mixin and GA360Mixin are not used.\"\"\"", "@register_snippet class Tour(ClusterableModel): page = models.OneToOneField('wagtailcore.Page', on_delete=models.CASCADE, related_name='tour') title =", "models.TextField( verbose_name=_('English subtitles'), null=True, blank=True, help_text='English-language subtitles for this video,", "of these nodes if [node.block_type for node in value if", "Wagtail's ModelAdmin, so appears in the sidebar, but we have", "class Product(models.Model): name = models.CharField(max_length=255) panels = [ FieldPanel('name'), ]", "] ), ), ( 'cons', blocks.StreamBlock( [ ( 'item', core_blocks.Item(icon='fa-arrow-right'),", "+ One image * (video must comes first so that", "> 3: _path = backlink_path.split('/')[3] return self._export_plan_url_map.get(_path) def get_context(self, request,", "class Meta: unique_together = ('image', 'filter_spec', 'focal_point_key') @property def alt(self):", "context = super().get_context(request) context['refresh_on_market_change'] = True # Prepare backlink to", "ordering of these nodes if [node.block_type for node in value", "happen. return backlink_path return None # safe default def _get_backlink_title(self,", "tag = models.ForeignKey( PersonalisationCountryTag, related_name='country_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy',", "blank=False, verbose_name='Internal case study title', ) # old name company_name", "get_image_model_string from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.images.models import AbstractImage, AbstractRendition,", "a conditional because a DetailPage currently MAY be used as", "), MultiFieldPanel( [ InlinePanel('related_pages', label='Related pages'), ], heading='Related Lesson, Topic", "= ['page__pk'] unique_together = ['page', 'sso_id'] # TODO: deprecate and", "(video must comes first so that it is displayed first)", "url, values in EXPORTPLAN_URL_MAP.items()} def _get_backlink(self, request): \"\"\"Try to extract", "unquote from django.conf import settings from django.core.exceptions import ValidationError from", "Page.content_panels + [ StreamFieldPanel('hero'), StreamFieldPanel('objective'), StreamFieldPanel('body'), StreamFieldPanel('recap'), ] def handle_page_view(self,", "models.TextField() class Meta: ordering = ['page__pk'] unique_together = ['page', 'sso_id']", "get_context(self, request, *args, **kwargs): from core.helpers import get_high_level_completion_progress from domestic.helpers", "if not already set if not self.slug: self.slug = slugify(self.name)", "Rendition(AbstractRendition): image = models.ForeignKey(AltTextImage, on_delete=models.CASCADE, related_name='renditions') class Meta: unique_together =", "context class LandingPage(CMSGenericPage): parent_page_types = [ 'domestic.DomesticHomePage', # TODO: once", "case study needs to have to be ' 'considered before", "export plan if we detect one and can validate it", "for more than just English if self.subtitles_en: output.append( { 'srclang':", "('image', core_blocks.ImageBlock()), ], null=True, blank=True, ) components = StreamField( [", "self.module.get_next_sibling() if not next_module: return context context['next_module'] = next_module.specific context['next_lesson']", "core_blocks.SectionBlock()), ('title', core_blocks.TitleBlock()), ('text', blocks.RichTextBlock(icon='openquote', helptext='Add a textblock')), ('image', core_blocks.ImageBlock()),", "blank=True, on_delete=models.SET_NULL, related_name='+' ) body = StreamField( [ ('section', core_blocks.SectionBlock()),", "PersonalisationRegionTag(TagBase): \"\"\"Custom tag for personalisation. Tag value will be a", "################ # Content fields ################ description = RichTextField() button_label =", "@register_snippet class ContentModule(ClusterableModel): title = models.CharField(max_length=255) content = RichTextField() tags", "on_delete=models.SET_NULL, related_name='+', ) panels = [FieldPanel('name'), ImageChooserPanel('icon')] class Meta: ordering", ") panels = [ MagnaPageChooserPanel('page', [DetailPage, CuratedListPage, TopicPage]), ] class", "the following content: * One image, only * One video,", "= True # Content models class CMSGenericPage( mixins.EnableTourMixin, mixins.AuthenticatedUserRequired, mixins.WagtailGA360Mixin,", "import Media from core import blocks as core_blocks, mixins from", "the sidebar, but we have to keep it registered as", "}, ) return output class AbstractObjectHash(models.Model): class Meta: abstract =", "] ) ] edit_handler = TabbedInterface( [ ObjectList(product_tab, heading='Product'), ObjectList(market_tab,", "great_components.mixins import GA360Mixin from modelcluster.contrib.taggit import ClusterTaggableManager from modelcluster.models import", "in it) ' 'and/or Quote sections, then one Text section.'", "], null=True, blank=True, validators=[hero_singular_validation], ) objective = StreamField( [ (", "list_page: PageView.objects.get_or_create( page=self, list_page=list_page, sso_id=request.user.pk, ) def serve(self, request, *args,", "max_length=255, blank=False, verbose_name='Internal case study title', ) # old name", "textblock')), ('image', core_blocks.ImageBlock()), ], null=True, blank=True, ) components = StreamField(", "2 digits of any of the user's products \" 'unless", "personalisation. Tag value will be an Trading blocs \"\"\" free_tagging", "subnode in node.value] if len(subnode_block_types) == 2: if set(subnode_block_types) ==", "it. For now, this is limited only to Export Plan", "CuratedListPage.objects.ancestor_of(self).first().url return HttpResponseRedirect(dest) def serve_preview(self, request, mode_name='dummy'): # It doesn't", "= models.ForeignKey(Region, null=True, blank=True, on_delete=models.SET_NULL) panels = [ FieldPanel('name'), FieldPanel('region'),", "country match.', default=2, decimal_places=3, max_digits=5, ) trading_blocs = models.DecimalField( help_text='Score", "blocks.StructBlock( [ ( 'pros', blocks.StreamBlock( [ ( 'item', core_blocks.Item(icon='fa-arrow-right'), )", "icon='fa-play', ), ), ('case_study', core_blocks.CaseStudyStaticBlock(icon='fa-book')), ( 'Step', core_blocks.StepByStepBlock(icon='cog'), ), (", "one Text section following it.' ) ) return error_messages def", "django.core.exceptions import ValidationError from django.db import models from django.http import", "transfer it with Wagtail-Transfer \"\"\" title = models.CharField( max_length=255, blank=False,", "= [ 'core.DetailPage', 'core.LessonPlaceholderPage', ] # `title` comes from Page", "so we don't waste the network call to get the", "( SECTION_SLUGS as EXPORTPLAN_SLUGS, SECTIONS as EXPORTPLAN_URL_MAP, ) # If", "save, if not already set if not self.slug: self.slug =", "matches the complete HS6 code of ' \"any of the", "= [ FieldPanel('name'), ] def __str__(self): return self.name @register_snippet class", "core_blocks.Item(icon='fa-arrow-right'), ) ] ), ), ( 'cons', blocks.StreamBlock( [ (", "page type... page_topic_helper = PageTopicHelper(self) next_lesson = page_topic_helper.get_next_lesson() context['current_lesson'] =", "save(self, **kwargs): # When we create a new CS need", "configuring and representing very simple to modules (`CuratedListPage`s). Not intented", "from django.db import models from django.http import HttpResponseRedirect from django.template.loader", "StreamField( [ ('route', core_blocks.RouteSectionBlock()), ], null=True, blank=True, ) ######### #", "page' verbose_name_plural = 'Detail pages' ################ # Content fields ################", "self.transcript, } ] @property def subtitles(self): output = [] #", "context['next_lesson'] = get_first_lesson(next_module) return context class PageView(TimeStampedModel): page = models.ForeignKey(DetailPage,", "name company_name summary_context = models.CharField(max_length=255, blank=False, default='How we did it')", "_path = backlink_path.split('/')[3] return self._export_plan_url_map.get(_path) def get_context(self, request, *args, **kwargs):", "ParentalKey( 'core.CaseStudy', related_name='related_pages', on_delete=models.SET_NULL, null=True, blank=True, ) page = models.ForeignKey(", "if value and len(value) > 1: raise StreamBlockValidationError( non_block_errors=ValidationError('Only one", "import blocks from wagtail.core.blocks.stream_block import StreamBlockValidationError from wagtail.core.fields import RichTextField,", "value will be an ISO-2 Country code ('DE') \"\"\" free_tagging", "lesson's topic is tagged in the case study \" 'unless", "on_delete=models.CASCADE, related_name='tour') title = models.CharField(max_length=255) body = models.CharField(max_length=255) button_text =", "core.helpers import ( get_high_level_completion_progress, get_module_completion_progress, ) from domestic.helpers import get_lesson_completion_status", ") return error_messages def _low_level_validation(value, error_messages): # Check content of", "Meta: abstract = True content_hash = models.CharField(max_length=1000) @staticmethod def generate_content_hash(field_file):", "given when any case study HS4 tag matches the first", "& Module, also used for Personalisation', ), ] def __str__(self):", "def save(self, **kwargs): # When we create a new CS", "trading_bloc_code_tags = ClusterTaggableManager( through='core.TradingBlocTaggedCaseStudy', blank=True, verbose_name='Trading bloc tags' ) created", "method render_as_field 'obj_type': instance_obj.specific.__class__.__name__ if instance_obj else None, } return", "parent # learning module (ListPage) context['parent_page_url'] = self.get_parent().url if request.user.is_authenticated:", "video after image: not allowed error_messages.append('The video must come before", "used as # a child of another page type... page_topic_helper", "verbose_name = 'Country tag for personalisation' verbose_name_plural = 'Country tags", "to be ' 'considered before being presented to users. ',", "null=True) modified = ModificationDateTimeField('modified', null=True) def save(self, **kwargs): self.update_modified =", "RichTextField() button_label = models.CharField(max_length=100) ######### # Panels ######### settings_panels =", "PersonalisationTradingBlocTag(TagBase): \"\"\"Custom tag for personalisation. Tag value will be an", "('title', core_blocks.TitleBlock()), ('text', blocks.RichTextBlock(icon='openquote', helptext='Add a textblock')), ('image', core_blocks.ImageBlock()), ],", "[ ( 'item', core_blocks.Item(), ) ] ), ), ], template='learn/recap.html',", "value: if node.block_type == MEDIA_BLOCK: subnode_block_types = [subnode.block_type for subnode", "= models.CharField(max_length=100) ######### # Panels ######### settings_panels = CMSGenericPage.settings_panels +", "= models.CharField(max_length=255) body = models.CharField(max_length=255) button_text = models.CharField(max_length=255) panels =", "is tagged in the case study.\", default=8, decimal_places=3, max_digits=5, )", "ObjectList(lesson_tab, heading='Lesson'), ObjectList(threshold_tab, heading='Threshold'), ] ) class Meta: verbose_name =", "verbose_name = 'HS Code tag for personalisation' verbose_name_plural = 'HS", "the complete HS6 code of ' \"any of the user's", "StreamFieldPanel('button'), ] class ListPage(CMSGenericPage): parent_page_types = ['core.LandingPage'] subpage_types = ['core.CuratedListPage']", "= StreamField( [ ('route', core_blocks.RouteSectionBlock()), ], null=True, blank=True, ) #########", "serve_preview(self, request, mode_name='dummy'): # It doesn't matter what is passed", "= models.CharField(max_length=100, unique=True) panels = [FieldPanel('name')] class Meta: ordering =", "DISABLED until tag data only comes via data migration class", "decimal_places=3, max_digits=5, ) product_tab = [MultiFieldPanel([FieldPanel('product_hs6'), FieldPanel('product_hs4'), FieldPanel('product_hs2')])] market_tab =", "was an existing field ) subtitles_en = models.TextField( verbose_name=_('English subtitles'),", "*args, **kwargs): context = super().get_context(request) self.set_ga360_payload( page_id=self.id, business_unit=settings.GA360_BUSINESS_UNIT, site_section=str(self.url or", "models.CharField(max_length=255) selector = models.CharField(max_length=255) tour = ParentalKey(Tour, on_delete=models.CASCADE, related_name='steps') panels", "core.helpers import get_high_level_completion_progress from domestic.helpers import get_lesson_completion_status context = super().get_context(request)", "If we make a Redirect appear as a Snippet, we", "= ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='country_tagged_items') class RegionTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationRegionTag,", "node and a text node and that the media node", "= models.CharField(max_length=255) selector = models.CharField(max_length=255) tour = ParentalKey(Tour, on_delete=models.CASCADE, related_name='steps')", "= StreamField( [ ( 'recap_item', blocks.StructBlock( [ ('title', blocks.CharBlock(icon='fa-header')), (", "have to be ' 'considered before being presented to users.", "videos: not allowed error_messages.append('Only one video may be used in", "related_name='page_views') list_page = models.ForeignKey(ListPage, on_delete=models.CASCADE, related_name='page_views_list') sso_id = models.TextField() class", "RichTextField, StreamField from wagtail.core.models import Orderable, Page from wagtail.images import", "\"\"\" free_tagging = False class Meta: verbose_name = 'Trading bloc", "export markets \" 'unless there is an exact country match.',", "and is very unlikely # to happen. return backlink_path return", "core_blocks.ImageBlock()), ], min_num=1, max_num=2, ), ), ( 'text', blocks.RichTextBlock( features=RICHTEXT_FEATURES__MINIMAL,", "@register_snippet class Region(models.Model): name = models.CharField(max_length=100, unique=True) panels = [FieldPanel('name')]", "full-page-width block', ), ), ( 'video', core_blocks.SimpleVideoBlock( template='core/includes/_video_full_width.html', help_text='Video displayed", "# TO COME: support for more than just English if", "on_delete=models.CASCADE, related_name='trading_bloc_tagged_items' ) def _high_level_validation(value, error_messages): TEXT_BLOCK = 'text' #", "tag matches the region of any of the user's export", "################ # Content fields ################ button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True,", "button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True) ######### # Panels #########", "limitation here and is very unlikely # to happen. return", "heading = RichTextField() image = models.ForeignKey( get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL,", "type... page_topic_helper = PageTopicHelper(self) next_lesson = page_topic_helper.get_next_lesson() context['current_lesson'] = self", "N806 MEDIA_BLOCK = 'media' # noqa N806 QUOTE_BLOCK = 'quote'", "'transcript': self.transcript, } ] @property def subtitles(self): output = []", "it) ' 'and/or Quote sections, then one Text section.' ),", "selector = models.CharField(max_length=255) tour = ParentalKey(Tour, on_delete=models.CASCADE, related_name='steps') panels =", "blocks.StructBlock( [('fiction_body', blocks.RichTextBlock(icon='openquote'))], template='learn/fictional_company_example.html', icon='fa-commenting-o', ), ), ( 'ITA_Quote', core_blocks.ITAQuoteBlock(icon='fa-quote-left'),", "blocks.StreamBlock( [ ( 'item', core_blocks.Item(icon='fa-arrow-right'), ) ] ), ), ],", "summary_context = models.CharField(max_length=255, blank=False, default='How we did it') # old", "\"\"\"Dedicated snippet for use as a case study. Supports personalised", "if we detect one and can validate it _backlink =", "def __str__(self): display_name = self.title if self.title else self.summary_context return", "= PageTopicHelper(self) next_lesson = page_topic_helper.get_next_lesson() context['current_lesson'] = self context['current_module'] =", "relevant CaseStudyBlock. Note that this is rendered via Wagtail's ModelAdmin,", "ClusterableModel, ParentalKey from taggit.managers import TaggableManager from taggit.models import ItemBase,", "digits of any of the user's products \" 'unless there", "page type to be created in wagtail admin is_creatable =", "'domestic.DomesticHomePage', # TODO: once we've restructured, remove this permission 'domestic.GreatDomesticHomePage',", "page = models.ForeignKey( 'wagtailcore.Page', on_delete=models.CASCADE, related_name='+', ) panels = [", "= [ 'core.TopicPage', ] template_choices = (('learn/curated_list_page.html', 'Learn'),) ################ #", "[MultiFieldPanel([FieldPanel('product_hs6'), FieldPanel('product_hs4'), FieldPanel('product_hs2')])] market_tab = [ MultiFieldPanel([FieldPanel('country_exact'), FieldPanel('country_region'), FieldPanel('trading_blocs')]) ]", "DetailPage.objects.live().descendant_of(topic).count() return count def get_context(self, request, *args, **kwargs): from core.helpers", "FieldPanel('body'), FieldPanel('position'), FieldPanel('selector'), ] @register_snippet class Product(models.Model): name = models.CharField(max_length=255)", "import HttpResponseRedirect from django.template.loader import render_to_string from django.urls import reverse", "ContentModule(ClusterableModel): title = models.CharField(max_length=255) content = RichTextField() tags = TaggableManager(through=ContentModuleTag,", "), ), ( 'video', core_blocks.SimpleVideoBlock( template='core/includes/_video_full_width.html', help_text='Video displayed within a", "must be an image # video after image: not allowed", "= StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True) ######### # Panels ######### content_panels", "len(backlink_path.split('/')) > 2 and ( backlink_path.split('/')[3] in EXPORTPLAN_SLUGS and '://'", "MAY be used as # a child of another page", "than just English if self.subtitles_en: output.append( { 'srclang': 'en', 'label':", "to be able to transfer it with Wagtail-Transfer \"\"\" title", "content', ), MultiFieldPanel( [ FieldPanel('hs_code_tags'), FieldPanel('country_code_tags'), FieldPanel('region_code_tags'), FieldPanel('trading_bloc_code_tags'), ], heading='Case", "here MEDIA_BLOCK = 'media' # noqa N806 VIDEO_BLOCK = 'video'", "next_module = self.module.get_next_sibling() if not next_module: return context context['next_module'] =", "what's going on here: # https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models class HSCodeTaggedCaseStudy(ItemBase): tag =", "[('paragraph', blocks.RichTextBlock())], template='core/struct_paragraph_block.html', icon='fa-font', ), ), ( 'video', blocks.StructBlock( [('video',", "if not self.slug: self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self):", "of ' \"any of the user's products\", default=8, decimal_places=3, max_digits=5,", "and GA360Mixin are not used.\"\"\" parent_page_types = ['core.TopicPage'] subpage_types =", "set if not self.slug: self.slug = slugify(self.name) super().save(*args, **kwargs) def", "mode_name='dummy'): # It doesn't matter what is passed as mode_name", "personalisation' # If you're wondering what's going on here: #", "to\"\"\" return CuratedListPage.objects.live().specific().ancestor_of(self).first() @cached_property def _export_plan_url_map(self): \"\"\"Return a lookup dictionary", "that any of ' \"the user's export markets falls into", "Content fields ################ description = RichTextField() button_label = models.CharField(max_length=100) #########", "core_blocks.SimpleVideoBlock(template='core/includes/_hero_video.html')), ], null=True, blank=True, validators=[hero_singular_validation], ) objective = StreamField( [", "Tag value will be a HS6, HS4 or HS2 code\"\"\"", "+= DetailPage.objects.live().descendant_of(topic).count() return count def get_context(self, request, *args, **kwargs): from", "} ] @property def subtitles(self): output = [] # TO", "ready when # models are imported if backlink_path and len(backlink_path.split('/'))", "class PersonalisationRegionTag(TagBase): \"\"\"Custom tag for personalisation. Tag value will be", "def _redirect_to_parent_module(self): return HttpResponseRedirect(self.get_parent().url) def serve_preview(self, request, mode_name='dummy'): # It", "= hashlib.md5() field_file.open() filehash.update(field_file.read()) field_file.close() return filehash.hexdigest() class DocumentHash(AbstractObjectHash): document", "Prepare backlink to the export plan if we detect one", "clash. \"\"\" created = CreationDateTimeField('created', null=True) modified = ModificationDateTimeField('modified', null=True)", "once we've restructured, remove this permission 'domestic.GreatDomesticHomePage', ] subpage_types =", "def _low_level_validation(value, error_messages): # Check content of media node, which", "Tag(models.Model): name = models.CharField(max_length=100, unique=True) panels = [FieldPanel('name')] class Meta:", "= 'modified' ordering = ( '-modified', '-created', ) @register_setting class", "context = { 'field': self.bound_field, self.object_type_name: instance_obj, 'is_chosen': bool(instance_obj), #", "has exactly both a media node and a text node", "match.', default=4, decimal_places=3, max_digits=5, ) product_hs2 = models.DecimalField( help_text=\"Score given", "HttpResponseRedirect from django.template.loader import render_to_string from django.urls import reverse from", "Codered page \"\"\" class Meta: abstract = True # Do", "import Orderable, Page from wagtail.images import get_image_model_string from wagtail.images.edit_handlers import", "country_exact = models.DecimalField( help_text=\"Score given when any case study country", "**kwargs): super().__init__(*args, **kwargs) field = self._meta.get_field('template') field.choices = self.template_choices field.required", "tag for personalisation' verbose_name_plural = 'HS Code tags for personalisation'", "import unquote from django.conf import settings from django.core.exceptions import ValidationError", "'Detail pages' ################ # Content fields ################ hero = StreamField(", "**kwargs): # When we create a new CS need to", "lesson is tagged in the case study.\", default=8, decimal_places=3, max_digits=5,", "already marked as read list_page = ( ListPage.objects.ancestor_of(self) .filter(record_read_progress=True) .exclude(page_views_list__sso_id=request.user.pk,", "one Media section (with one or ' 'two items in", "core_blocks.ChooseDoNotChooseBlock()), ( 'image', core_blocks.ImageBlock( template='core/includes/_image_full_width.html', help_text='Image displayed within a full-page-width", "the user's products\", default=8, decimal_places=3, max_digits=5, ) product_hs4 = models.DecimalField(", "there is also lesson or topic match.', default=2, decimal_places=3, max_digits=5,", "StreamFieldPanel('objective'), StreamFieldPanel('body'), StreamFieldPanel('recap'), ] def handle_page_view(self, request): if request.user.is_authenticated: #", "' \"any of the user's products\", default=8, decimal_places=3, max_digits=5, )", "what is passed as mode_name - we always redirect return", "('name',) def __str__(self): return self.name class TimeStampedModel(models.Model): \"\"\"Modified version of", "the learning module this lesson belongs to\"\"\" return CuratedListPage.objects.live().specific().ancestor_of(self).first() @cached_property", "default=8, decimal_places=3, max_digits=5, ) product_hs4 = models.DecimalField( help_text=\"Score given when", "request.user.is_authenticated: # checking if the page should record read progress", "version of django_extensions.db.models.TimeStampedModel Unfortunately, because null=True needed to be added", "for personalisation' class PersonalisationRegionTag(TagBase): \"\"\"Custom tag for personalisation. Tag value", "models.DecimalField( help_text='This is the minimum score which a case study", "cached_property from django.utils.safestring import mark_safe from django.utils.text import slugify from", "this permission 'domestic.GreatDomesticHomePage', ] subpage_types = [ 'core.ListPage', 'core.InterstitialPage', 'domestic.DomesticDashboard',", "reverse from django.utils.functional import cached_property from django.utils.safestring import mark_safe from", "# Content fields ################ heading = RichTextField() image = models.ForeignKey(", "slugify from django.utils.translation import ugettext_lazy as _ from django_extensions.db.fields import", "abstract = True # Content models class CMSGenericPage( mixins.EnableTourMixin, mixins.AuthenticatedUserRequired,", "block', ), ), ] ) recap = StreamField( [ (", "child of another page type... page_topic_helper = PageTopicHelper(self) next_lesson =", "**kwargs): from core.helpers import get_high_level_completion_progress from domestic.helpers import get_lesson_completion_status context", "] template_choices = ( ('learn/landing_page.html', 'Learn'), ('core/generic_page.html', 'Generic'), ) ################", "hs_code_tags = ClusterTaggableManager(through='core.HSCodeTaggedCaseStudy', blank=True, verbose_name='HS-code tags') country_code_tags = ClusterTaggableManager( through='core.CountryTaggedCaseStudy',", "to render the relevant CaseStudyBlock. Note that this is rendered", "core_blocks.TitleBlock()), ('text', blocks.RichTextBlock(icon='openquote', helptext='Add a textblock')), ('image', core_blocks.ImageBlock()), ], null=True,", "TODO: once we've restructured, remove this permission 'domestic.GreatDomesticHomePage', ] subpage_types", "page to allow for configuring and representing very simple to", "@register_snippet class CaseStudy(ClusterableModel): \"\"\"Dedicated snippet for use as a case", "record read progress # checking if the page is already", "ImageChooserPanel('icon')] class Meta: ordering = ('name',) def __str__(self): return self.name", "'quote' # noqa N806 # we need to be strict", "set(subnode_block_types) == {VIDEO_BLOCK}: # Two videos: not allowed error_messages.append('Only one", "a case study needs to have to be ' 'considered", "backwards compatibility only # Added obj_type on base class method", "self.get_chosen_item() context = { 'field': self.bound_field, self.object_type_name: instance_obj, 'is_chosen': bool(instance_obj),", "to allow for configuring and representing very simple to modules", "} return mark_safe(render_to_string(self.field_template, context)) class CaseStudyRelatedPages(Orderable): case_study = ParentalKey( 'core.CaseStudy',", "then one Text section.' ), ) # We are keeping", "make the UX easier for editors hs_code_tags = ClusterTaggableManager(through='core.HSCodeTaggedCaseStudy', blank=True,", "unique_together = ['case_study', 'page'] @register_snippet class CaseStudy(ClusterableModel): \"\"\"Dedicated snippet for", "= get_lesson_completion_status(request.user) context['module_completion_progress'] = get_module_completion_progress( completion_status=completion_status, module_page=self, ) context['high_level_completion_progress'] =", "Meta: verbose_name = 'Country tag for personalisation' verbose_name_plural = 'Country", "subtitles for this video, in VTT format', ) admin_form_fields =", "imported if backlink_path and len(backlink_path.split('/')) > 3: _path = backlink_path.split('/')[3]", "( backlink_path.split('/')[3] in EXPORTPLAN_SLUGS and '://' not in backlink_path ):", "N805 panels = [ ObjectList(cls.content_panels, heading='Content'), ObjectList(cls.layout_panels, heading='Layout'), ObjectList(cls.settings_panels, heading='Settings',", "given when any case study trading bloc tag matches the", "= models.CharField(max_length=255) tour = ParentalKey(Tour, on_delete=models.CASCADE, related_name='steps') panels = [", "'This block must contain one Media section (with one or", "Export Plan pages/links. \"\"\" # We have to re-arrange EXPORT_PLAN_SECTION_TITLES_URLS", "first so that it is displayed first) * Two images", "a lookup dictionary of URL Slugs->title for all the Export", "accepts backlinks that we KNOW are for the export plan,", "'HS Code tags for personalisation' class PersonalisationCountryTag(TagBase): \"\"\"Custom tag for", "= 'Detail page' verbose_name_plural = 'Detail pages' ################ # Content", "LandingPage(CMSGenericPage): parent_page_types = [ 'domestic.DomesticHomePage', # TODO: once we've restructured,", "backlink_path and len(backlink_path.split('/')) > 3: _path = backlink_path.split('/')[3] return self._export_plan_url_map.get(_path)", "there is an HS6 match.', default=4, decimal_places=3, max_digits=5, ) product_hs2", "belongs to\"\"\" return CuratedListPage.objects.live().specific().ancestor_of(self).first() @cached_property def _export_plan_url_map(self): \"\"\"Return a lookup", "with Wagtail-Transfer \"\"\" title = models.CharField( max_length=255, blank=False, verbose_name='Internal case", "blank=True, ) page = models.ForeignKey( 'wagtailcore.Page', on_delete=models.CASCADE, related_name='+', ) panels", "HS6 match.', default=4, decimal_places=3, max_digits=5, ) product_hs2 = models.DecimalField( help_text=\"Score", "('case_study', core_blocks.CaseStudyStaticBlock(icon='fa-book')), ( 'Step', core_blocks.StepByStepBlock(icon='cog'), ), ( 'fictional_example', blocks.StructBlock( [('fiction_body',", "self.handle_page_view(request) return super().serve(request, **kwargs) @cached_property def topic_title(self): return self.get_parent().title @cached_property", "**kwargs): context = super().get_context(request) self.set_ga360_payload( page_id=self.id, business_unit=settings.GA360_BUSINESS_UNIT, site_section=str(self.url or '/').split('/')[1],", "= super().get_context(request) context['refresh_on_market_change'] = True # Prepare backlink to the", "RegionTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationRegionTag, related_name='region_tagged_case_studies', on_delete=models.CASCADE ) content_object =", "tag for personalisation. Tag value will be a geographical string", "also used for Personalisation', ), ] def __str__(self): display_name =", "'focal_point_key') @property def alt(self): return self.image.alt_text @register_snippet class Tour(ClusterableModel): page", "= kwargs.pop('update_modified', getattr(self, 'update_modified', True)) super().save(**kwargs) class Meta: get_latest_by =", "if isinstance(self.get_parent().specific, TopicPage): # In a conditional because a DetailPage", "created = CreationDateTimeField('created', null=True) modified = ModificationDateTimeField('modified', null=True) def save(self,", "import ImageChooserPanel from wagtail.images.models import AbstractImage, AbstractRendition, Image from wagtail.snippets.models", "taggit.managers import TaggableManager from taggit.models import ItemBase, TagBase, TaggedItemBase from", "on_delete=models.SET_NULL, related_name='+' ) body = StreamField( [ ('section', core_blocks.SectionBlock()), ('title',", "must contain one Media section (with one or ' 'two", "has the following content: * One image, only * One", "if value: error_messages = _high_level_validation(value, error_messages) error_messages = _low_level_validation(value, error_messages)", "null=True, blank=True) ######### # Panels ######### content_panels = CMSGenericPage.content_panels +", "Page): \"\"\"Structural page to allow for cleaner mapping of lessons", "blank=False, default='How we did it') # old name summary lead_title", ") class TopicPage(mixins.AuthenticatedUserRequired, Page): \"\"\"Structural page to allow for cleaner", "# Panels ######### settings_panels = CMSGenericPage.settings_panels + [FieldPanel('record_read_progress')] content_panels =", "(('learn/detail_page.html', 'Learn'),) class Meta: verbose_name = 'Detail page' verbose_name_plural =", "related_name='tour') title = models.CharField(max_length=255) body = models.CharField(max_length=255) button_text = models.CharField(max_length=255)", "user's products \" 'unless there is an HS6 or HS4", "trading_blocs = models.DecimalField( help_text='Score given when any case study trading", "a simple way to link back to the parent #", "so will redirect to the parent module if accessed. Also,", "{ 'srclang': 'en', 'label': 'English', 'url': reverse('core:subtitles-serve', args=[self.id, 'en']), 'default':", "] class ListPage(CMSGenericPage): parent_page_types = ['core.LandingPage'] subpage_types = ['core.CuratedListPage'] template_choices", "= models.CharField(max_length=255) button_text = models.CharField(max_length=255) panels = [ PageChooserPanel('page'), FieldPanel('title'),", "return [ { 'src': self.url, 'type': mimetypes.guess_type(self.filename)[0] or 'application/octet-stream', 'transcript':", "core_blocks.RouteSectionBlock()), ], null=True, blank=True, ) ######### # Panels ######### content_panels", "in VTT format', ) admin_form_fields = Media.admin_form_fields + ( 'transcript',", "We have to re-arrange EXPORT_PLAN_SECTION_TITLES_URLS after import # because it", "next_lesson: context['next_lesson'] = next_lesson else: next_module = self.module.get_next_sibling() if not", "node and that the media node has the following content:", "case study.') elif subnode_block_types[1] == VIDEO_BLOCK: # implicitly, [0] must", "is_creatable = False template_choices = [] ############### # Layout fields", "= [ FieldPanel('title'), FieldPanel('content'), FieldPanel('tags'), ] def __str__(self): return self.title", "not None: backlink_path = unquote(backlink_path) if len(backlink_path.split('/')) > 2 and", "always redirect return self._redirect_to_parent_module() def serve(self, request): return self._redirect_to_parent_module() class", "[ FieldPanel('threshold'), ] ) ] edit_handler = TabbedInterface( [ ObjectList(product_tab,", "[('fiction_body', blocks.RichTextBlock(icon='openquote'))], template='learn/fictional_company_example.html', icon='fa-commenting-o', ), ), ( 'ITA_Quote', core_blocks.ITAQuoteBlock(icon='fa-quote-left'), ),", ") def serve(self, request, *args, **kwargs): self.handle_page_view(request) return super().serve(request, **kwargs)", "free_tagging = False # DISABLED until tag data only comes", "heading='Content'), ObjectList(cls.layout_panels, heading='Layout'), ObjectList(cls.settings_panels, heading='Settings', classname='settings'), ] return TabbedInterface(panels).bind_to(model=cls) def", "URLs that aren't ready when # models are imported if", "is an HS6 or HS4 match.', default=2, decimal_places=3, max_digits=5, )", "or '/').split('/')[1], ) self.add_ga360_data_to_payload(request) context['ga360'] = self.ga360_payload provider = get_context_provider(request=request,", "list_page = models.ForeignKey(ListPage, on_delete=models.CASCADE, related_name='page_views_list') sso_id = models.TextField() class Meta:", "format', ) admin_form_fields = Media.admin_form_fields + ( 'transcript', 'subtitles_en', )", "[ MultiFieldPanel( [ FieldPanel('title'), FieldPanel('lead_title'), FieldPanel('summary_context'), StreamFieldPanel('body'), ], heading='Case Study", "return CuratedListPage.objects.live().specific().ancestor_of(self).first() @cached_property def _export_plan_url_map(self): \"\"\"Return a lookup dictionary of", "False # DISABLED until tag data only comes via data", "Meta: verbose_name_plural = 'Case studies' get_latest_by = 'modified' ordering =", "# Added obj_type on base class method render_as_field 'obj_type': instance_obj.specific.__class__.__name__", "Content fields ################ button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True) #########", "only to Export Plan pages/links. \"\"\" # We have to", "The decision about the appropriate Case Study block to show", "DEPRECATED - passed to templates for backwards compatibility only #", "wagtail admin is_creatable = False template_choices = [] ############### #", "a case study.') elif subnode_block_types[1] == VIDEO_BLOCK: # implicitly, [0]", "import CreationDateTimeField, ModificationDateTimeField from great_components.mixins import GA360Mixin from modelcluster.contrib.taggit import", "We are keeping the personalisation-relevant tags in separate # fields", "keep it registered as a Snippet to be able to", "Page): \"\"\"Structural page to allow for configuring and representing very", "('Video', core_blocks.SimpleVideoBlock(template='core/includes/_hero_video.html')), ], null=True, blank=True, validators=[hero_singular_validation], ) objective = StreamField(", "not allowed error_messages.append('Only one video may be used in a", "null=True, blank=True, ) ######### # Panels ######### content_panels = CMSGenericPage.content_panels", "class TourStep(Orderable): title = models.CharField(max_length=255) body = models.CharField(max_length=255) position =", "is already marked as read list_page = ( ListPage.objects.ancestor_of(self) .filter(record_read_progress=True)", "not next_module: return context context['next_module'] = next_module.specific context['next_lesson'] = get_first_lesson(next_module)", "fields ############### template = models.CharField( max_length=255, choices=None, ) ######### #", "import cached_property from django.utils.safestring import mark_safe from django.utils.text import slugify", "Tag value will be a geographical string ('Europe') \"\"\" free_tagging", "personalisation' verbose_name_plural = 'Region tags for personalisation' class PersonalisationTradingBlocTag(TagBase): \"\"\"Custom", "= [] if value: error_messages = _high_level_validation(value, error_messages) error_messages =", "= ParentalKey( 'core.CaseStudy', related_name='related_pages', on_delete=models.SET_NULL, null=True, blank=True, ) page =", "ImageHash(AbstractObjectHash): image = models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.CASCADE, related_name='+') class AltTextImage(AbstractImage):", "wagtail.images.edit_handlers import ImageChooserPanel from wagtail.images.models import AbstractImage, AbstractRendition, Image from", "isinstance(self.get_parent().specific, TopicPage): # In a conditional because a DetailPage currently", "as EXPORTPLAN_SLUGS, SECTIONS as EXPORTPLAN_URL_MAP, ) # If we make", "= StreamField( [ ( 'paragraph', blocks.StructBlock( [('paragraph', blocks.RichTextBlock())], template='core/struct_paragraph_block.html', icon='fa-font',", "is limited only to Export Plan pages/links. \"\"\" # We", "'pros', blocks.StreamBlock( [ ( 'item', core_blocks.Item(icon='fa-arrow-right'), ) ] ), ),", "Meta: ordering = ('name',) def __str__(self): return self.name class TimeStampedModel(models.Model):", "this is limited only to Export Plan pages/links. \"\"\" #", "context['refresh_on_market_change'] = True # Prepare backlink to the export plan", "causes issues with field clash. \"\"\" created = CreationDateTimeField('created', null=True)", "score which a case study needs to have to be", "be present here MEDIA_BLOCK = 'media' # noqa N806 VIDEO_BLOCK", "return self._redirect_to_parent_module() class DetailPage(CMSGenericPage): estimated_read_duration = models.DurationField(null=True, blank=True) parent_page_types =", "AbstractImage, AbstractRendition, Image from wagtail.snippets.models import register_snippet from wagtail.utils.decorators import", "for subnode in node.value] if len(subnode_block_types) == 2: if set(subnode_block_types)", "[FieldPanel('name'), ImageChooserPanel('icon')] class Meta: ordering = ('name',) def __str__(self): return", "backlink_path): \"\"\"For a given backlink, see if we can get", "help_text='Video displayed within a full-page-width block', ), ), ] )", "unique_together = ('image', 'filter_spec', 'focal_point_key') @property def alt(self): return self.image.alt_text", "], template='learn/pros_and_cons.html', icon='fa-arrow-right', ), ), ('choose_do_not_choose', core_blocks.ChooseDoNotChooseBlock()), ( 'image', core_blocks.ImageBlock(", "= 'Automated list pages' def get_context(self, request, *args, **kwargs): from", "), ), ] ) recap = StreamField( [ ( 'recap_item',", "querystring on the request that brought us to this view.", "heading='Related Lesson, Topic & Module, also used for Personalisation', ),", "request, *args, **kwargs): return self.template def get_context(self, request, *args, **kwargs):", "old name summary lead_title = models.TextField(blank=False) # Deliberately not rich-text", "@register_snippet class Country(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=100, unique=True)", "mixins.WagtailGA360Mixin, GA360Mixin, Page, ): \"\"\" Generic page, freely inspired by", "wagtail.images import get_image_model_string from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.images.models import", "and can validate it _backlink = self._get_backlink(request) if _backlink: context['backlink']", "tags' ) trading_bloc_code_tags = ClusterTaggableManager( through='core.TradingBlocTaggedCaseStudy', blank=True, verbose_name='Trading bloc tags'", "inspired by Codered page \"\"\" class Meta: abstract = True", "save(self, *args, **kwargs): # Automatically set slug on save, if", "null=True) modified = ModificationDateTimeField('modified', null=True) panels = [ MultiFieldPanel( [", "models class CMSGenericPage( mixins.EnableTourMixin, mixins.AuthenticatedUserRequired, mixins.WagtailGA360Mixin, GA360Mixin, Page, ): \"\"\"", "def save(self, *args, **kwargs): # Automatically set slug on save,", "models.ForeignKey(Region, null=True, blank=True, on_delete=models.SET_NULL) panels = [ FieldPanel('name'), FieldPanel('region'), ]", "blocks.RichTextBlock(options={'class': 'objectives'}), ), ('ListItem', core_blocks.Item()), ] ) body = StreamField(", "personalisation' class PersonalisationRegionTag(TagBase): \"\"\"Custom tag for personalisation. Tag value will", "fields, inheritance causes issues with field clash. \"\"\" created =", "from Page superclass and that's all we need here def", "lesson or topic match.', default=2, decimal_places=3, max_digits=5, ) product_hs6 =", "free_tagging = False class Meta: verbose_name = 'Country tag for", "( 'transcript', 'subtitles_en', ) @property def sources(self): return [ {", "('name',) def __str__(self): return self.name @register_snippet class IndustryTag(models.Model): name =", "-> models.QuerySet: qs = TopicPage.objects.live().specific().descendant_of(self) if live: qs = qs.live()", "[MEDIA_BLOCK, TEXT_BLOCK]: error_messages.append( ( 'This block must contain one Media", "page to allow for cleaner mapping of lessons (`DetailPage`s) to", "name = models.CharField(max_length=100, unique=True) panels = [FieldPanel('name')] class Meta: ordering", "old name company_name summary_context = models.CharField(max_length=255, blank=False, default='How we did", "classname='settings'), ] return TabbedInterface(panels).bind_to(model=cls) def get_template(self, request, *args, **kwargs): return", "= CMSGenericPage.content_panels + [ StreamFieldPanel('button'), ] class ListPage(CMSGenericPage): parent_page_types =", "= [MultiFieldPanel([FieldPanel('lesson'), FieldPanel('topic'), FieldPanel('module')])] threshold_tab = [ MultiFieldPanel( [ FieldPanel('threshold'),", "list page' verbose_name_plural = 'Automated list pages' def get_context(self, request,", "completion_status = get_lesson_completion_status(request.user) context['high_level_completion_progress'] = get_high_level_completion_progress( completion_status=completion_status, ) return context", "RICHTEXT_FEATURES__MINIMAL from core.context import get_context_provider from core.utils import PageTopicHelper, get_first_lesson", "any case study HS2 tag matches the first 2 digits", "), ), ('case_study', core_blocks.CaseStudyStaticBlock(icon='fa-book')), ( 'Step', core_blocks.StepByStepBlock(icon='cog'), ), ( 'fictional_example',", "related_name='trading_bloc_tagged_items' ) def _high_level_validation(value, error_messages): TEXT_BLOCK = 'text' # noqa", "any case study HS4 tag matches the first 4 digits", "the personalisation-relevant tags in separate # fields to aid lookup", "from wagtailmedia.models import Media from core import blocks as core_blocks,", "another page type... page_topic_helper = PageTopicHelper(self) next_lesson = page_topic_helper.get_next_lesson() context['current_lesson']", "StreamField( [ ( 'paragraph', blocks.StructBlock( [('paragraph', blocks.RichTextBlock())], template='core/struct_paragraph_block.html', icon='fa-font', ),", "validate it _backlink = self._get_backlink(request) if _backlink: context['backlink'] = _backlink", "bloc tag matches the any trading bloc that any of", "ObjectList(threshold_tab, heading='Threshold'), ] ) class Meta: verbose_name = 'Case Study", "if live: qs = qs.live() return qs @cached_property def count_topics(self):", "PageView(TimeStampedModel): page = models.ForeignKey(DetailPage, on_delete=models.CASCADE, related_name='page_views') list_page = models.ForeignKey(ListPage, on_delete=models.CASCADE,", "Meta: get_latest_by = 'modified' ordering = ( '-modified', '-created', )", "on_delete=models.CASCADE, related_name='country_tagged_items') class RegionTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationRegionTag, related_name='region_tagged_case_studies', on_delete=models.CASCADE", "( 'paragraph', blocks.RichTextBlock(options={'class': 'objectives'}), ), ('ListItem', core_blocks.Item()), ] ) body", "and a text node and that the media node has", "from modelcluster.contrib.taggit import ClusterTaggableManager from modelcluster.models import ClusterableModel, ParentalKey from", "match.', default=2, decimal_places=3, max_digits=5, ) country_exact = models.DecimalField( help_text=\"Score given", "Image.admin_form_fields + ('alt_text',) class Rendition(AbstractRendition): image = models.ForeignKey(AltTextImage, on_delete=models.CASCADE, related_name='renditions')", "RichTextField() image = models.ForeignKey( get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL, related_name='+' )", "already set if not self.slug: self.slug = slugify(self.name) super().save(*args, **kwargs)", "= models.DurationField(null=True, blank=True) parent_page_types = [ 'core.CuratedListPage', # TEMPORARY: remove", "), ( 'cons', blocks.StreamBlock( [ ( 'item', core_blocks.Item(icon='fa-arrow-right'), ) ]", "to obtain an ID for indexing self.update_modified = kwargs.pop('update_modified', getattr(self,", "error_messages = [] if value: error_messages = _high_level_validation(value, error_messages) error_messages", "######## content_panels = CMSGenericPage.content_panels + [ FieldPanel('heading'), ImageChooserPanel('image'), ] def", "case study \" 'unless there is also lesson match.', default=4,", "request): return self._redirect_to_parent_module() class DetailPage(CMSGenericPage): estimated_read_duration = models.DurationField(null=True, blank=True) parent_page_types", "section following it.' ) ) return error_messages def _low_level_validation(value, error_messages):", "self.title else self.summary_context return f'{display_name}' def save(self, **kwargs): # When", "the data twice completion_status = get_lesson_completion_status(request.user) context['module_completion_progress'] = get_module_completion_progress( completion_status=completion_status,", "allowed error_messages.append('Only one video may be used in a case", ") # old name company_name summary_context = models.CharField(max_length=255, blank=False, default='How", "slug = models.SlugField(max_length=100, unique=True) region = models.ForeignKey(Region, null=True, blank=True, on_delete=models.SET_NULL)", "# get this once, so we don't waste the network", "[ ('section', core_blocks.SectionBlock()), ('title', core_blocks.TitleBlock()), ('text', blocks.RichTextBlock(icon='openquote', helptext='Add a textblock')),", "company_name summary_context = models.CharField(max_length=255, blank=False, default='How we did it') #", "import reverse from django.utils.functional import cached_property from django.utils.safestring import mark_safe", "Unfortunately, because null=True needed to be added to create and", "import ugettext_lazy as _ from django_extensions.db.fields import CreationDateTimeField, ModificationDateTimeField from", "learning module this lesson belongs to\"\"\" return CuratedListPage.objects.live().specific().ancestor_of(self).first() @cached_property def", "this video, in VTT format', ) admin_form_fields = Media.admin_form_fields +", "ordering = ('name',) def save(self, *args, **kwargs): # Automatically set", "stop us accepting a backlink which # features a full", "template='core/struct_paragraph_block.html', icon='fa-font', ), ), ( 'video', blocks.StructBlock( [('video', core_blocks.VideoBlock())], template='core/struct_video_block.html',", "def save(self, **kwargs): self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified', True)) super().save(**kwargs)", "Page superclass and that's all we need here def _redirect_to_parent_module(self):", "return self.get_parent().title @cached_property def module(self): \"\"\"Gets the learning module this", "export plan, else ignore it.\"\"\" backlink_path = request.GET.get(BACKLINK_QUERYSTRING_NAME, '') if", "tags in separate # fields to aid lookup and make", "if next_lesson: context['next_lesson'] = next_lesson else: next_module = self.module.get_next_sibling() if", ") ######### # Panels ######### content_panels = CMSGenericPage.content_panels + [", "qs @cached_property def count_topics(self): return self.get_topics().count() @cached_property def count_detail_pages(self): count", "superclass and that's all we need here def _redirect_to_parent_module(self): dest", "return HttpResponseRedirect(dest) def serve_preview(self, request, mode_name='dummy'): # It doesn't matter", "of media node, which should be present here MEDIA_BLOCK =", "be a geographical string ('Europe') \"\"\" free_tagging = False class", "with field clash. \"\"\" created = CreationDateTimeField('created', null=True) modified =", "default=False, help_text='Should we record when a user views a page", "EXPORTPLAN_URL_MAP, ) # If we make a Redirect appear as", "panels = [ FieldPanel('title'), FieldPanel('content'), FieldPanel('tags'), ] def __str__(self): return", "the minimum score which a case study needs to have", "falls into unless there is an exact country or region", "'and/or Quote sections, then one Text section.' ), ) #", "= self._get_backlink_title(_backlink) if isinstance(self.get_parent().specific, TopicPage): # In a conditional because", "= RichTextField() button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True) image =", "to happen. return backlink_path return None # safe default def", "def serve(self, request): return self._redirect_to_parent_module() class LessonPlaceholderPage(mixins.AuthenticatedUserRequired, Page): \"\"\"Structural page", "personalisation. Tag value will be a geographical string ('Europe') \"\"\"", "related_name='steps') panels = [ FieldPanel('title'), FieldPanel('body'), FieldPanel('position'), FieldPanel('selector'), ] @register_snippet", "> 1: raise StreamBlockValidationError( non_block_errors=ValidationError('Only one image or video allowed", "on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='region_tagged_items') class TradingBlocTaggedCaseStudy(ItemBase): tag", "must come before a still image.') return error_messages def case_study_body_validation(value):", "that's all we need here def _redirect_to_parent_module(self): return HttpResponseRedirect(self.get_parent().url) def", "aren't ready when # models are imported if backlink_path and", "can sync it via Wagtail-Transfer register_snippet(Redirect) class GreatMedia(Media): transcript =", "models.CharField(max_length=255, blank=False, default='How we did it') # old name summary", "context def hero_singular_validation(value): if value and len(value) > 1: raise", "StreamField( [ ( 'paragraph', blocks.RichTextBlock(options={'class': 'objectives'}), ), ('ListItem', core_blocks.Item()), ]", "tag matches the first 4 digits of any of the", "MultiFieldPanel( [ InlinePanel('related_pages', label='Related pages'), ], heading='Related Lesson, Topic &", "InlinePanel('related_pages', label='Related pages'), ], heading='Related Lesson, Topic & Module, also", "models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.CASCADE, related_name='+') class AltTextImage(AbstractImage): alt_text = models.CharField(max_length=255,", "blank=True) admin_form_fields = Image.admin_form_fields + ('alt_text',) class Rendition(AbstractRendition): image =", "FieldPanel('position'), FieldPanel('selector'), ] @register_snippet class Product(models.Model): name = models.CharField(max_length=255) panels", "the export plan if we detect one and can validate", "__str__(self): display_name = self.title if self.title else self.summary_context return f'{display_name}'", "HS4 tag matches the first 4 digits of any of", "False class Meta: verbose_name = 'Country tag for personalisation' verbose_name_plural", "did it') # old name summary lead_title = models.TextField(blank=False) #", "__str__(self): return self.name @register_snippet class IndustryTag(models.Model): name = models.CharField(max_length=100, unique=True)", "( 'item', core_blocks.Item(), ) ] ), ), ], template='learn/recap.html', icon='fa-commenting-o',", "name = models.CharField(max_length=255) slug = models.SlugField(max_length=100, unique=True) region = models.ForeignKey(Region,", "verbose_name='Region tags' ) trading_bloc_code_tags = ClusterTaggableManager( through='core.TradingBlocTaggedCaseStudy', blank=True, verbose_name='Trading bloc", "context['module_completion_progress'] = get_module_completion_progress( completion_status=completion_status, module_page=self, ) context['high_level_completion_progress'] = get_high_level_completion_progress( completion_status=completion_status,", "null=True, blank=True, on_delete=models.CASCADE, related_name='+') class AltTextImage(AbstractImage): alt_text = models.CharField(max_length=255, blank=True)", "SECTION_SLUGS as EXPORTPLAN_SLUGS, SECTIONS as EXPORTPLAN_URL_MAP, ) # If we", "= self._get_backlink(request) if _backlink: context['backlink'] = _backlink context['backlink_title'] = self._get_backlink_title(_backlink)", "study. Supports personalised selection via its tags. The decision about", "tag = models.ForeignKey( PersonalisationRegionTag, related_name='region_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy',", "['core.CuratedListPage'] template_choices = (('learn/automated_list_page.html', 'Learn'),) record_read_progress = models.BooleanField( default=False, help_text='Should", "video must come before a still image.') return error_messages def", "name = models.CharField(max_length=255) panels = [ FieldPanel('name'), ] def __str__(self):", "URL as its OWN querystring param (eg a crafted attack", "we detect one and can validate it _backlink = self._get_backlink(request)", "from django.utils.safestring import mark_safe from django.utils.text import slugify from django.utils.translation", "FieldPanel('title'), FieldPanel('content'), FieldPanel('tags'), ] def __str__(self): return self.title class PersonalisationHSCodeTag(TagBase):", "'video', blocks.StructBlock( [('video', core_blocks.VideoBlock())], template='core/struct_video_block.html', icon='fa-play', ), ), ('case_study', core_blocks.CaseStudyStaticBlock(icon='fa-book')),", "\"\"\"Gets the learning module this lesson belongs to\"\"\" return CuratedListPage.objects.live().specific().ancestor_of(self).first()", "completion_status=completion_status, ) return context def hero_singular_validation(value): if value and len(value)", "fields ################ button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True) ######### #", "on base class method render_as_field 'obj_type': instance_obj.specific.__class__.__name__ if instance_obj else", "modules (`CuratedListPage`s). Not intented to be viewed by end users,", "= models.ForeignKey( PersonalisationHSCodeTag, related_name='hscode_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE,", "subnode_block_types[1] == VIDEO_BLOCK: # implicitly, [0] must be an image", "sources(self): return [ { 'src': self.url, 'type': mimetypes.guess_type(self.filename)[0] or 'application/octet-stream',", ") class ImageHash(AbstractObjectHash): image = models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.CASCADE, related_name='+')", "'unless there is also lesson or topic match.', default=2, decimal_places=3,", ") product_tab = [MultiFieldPanel([FieldPanel('product_hs6'), FieldPanel('product_hs4'), FieldPanel('product_hs2')])] market_tab = [ MultiFieldPanel([FieldPanel('country_exact'),", "personalisation' verbose_name_plural = 'Trading bloc tags for personalisation' # If", "] class InterstitialPage(CMSGenericPage): parent_page_types = ['core.LandingPage'] template_choices = (('learn/interstitial.html', 'Learn'),)", "verbose_name=_('English subtitles'), null=True, blank=True, help_text='English-language subtitles for this video, in", "within a full-page-width block', ), ), ] ) recap =", "we have to keep it registered as a Snippet to", "verbose_name='Trading bloc tags' ) created = CreationDateTimeField('created', null=True) modified =", "= models.TextField( verbose_name=_('English subtitles'), null=True, blank=True, help_text='English-language subtitles for this", "class CuratedListPage(CMSGenericPage): parent_page_types = ['core.ListPage'] subpage_types = [ 'core.TopicPage', ]", "get_high_level_completion_progress from domestic.helpers import get_lesson_completion_status context = super().get_context(request) if request.user.is_authenticated:", "= StreamField( [ ( 'media', blocks.StreamBlock( [ ('video', core_blocks.SimpleVideoBlock(template='core/includes/_case_study_video.html')), ('image',", "= RichTextField() tags = TaggableManager(through=ContentModuleTag, blank=True) panels = [ FieldPanel('title'),", "this once, so we don't waste the network call to", "blocks.StructBlock( [('video', core_blocks.VideoBlock())], template='core/struct_video_block.html', icon='fa-play', ), ), ('case_study', core_blocks.CaseStudyStaticBlock(icon='fa-book')), (", "InlinePanel, MultiFieldPanel, ObjectList, PageChooserPanel, StreamFieldPanel, TabbedInterface, ) from wagtail.contrib.redirects.models import", "Content fields ################ heading = RichTextField() image = models.ForeignKey( get_image_model_string(),", "'en', 'label': 'English', 'url': reverse('core:subtitles-serve', args=[self.id, 'en']), 'default': False, },", "django.template.loader import render_to_string from django.urls import reverse from django.utils.functional import", "error_messages): TEXT_BLOCK = 'text' # noqa N806 MEDIA_BLOCK = 'media'", "threshold = models.DecimalField( help_text='This is the minimum score which a", "tag matches the first 2 digits of any of the", "), ), ('choose_do_not_choose', core_blocks.ChooseDoNotChooseBlock()), ( 'image', core_blocks.ImageBlock( template='core/includes/_image_full_width.html', help_text='Image displayed", "'paragraph', blocks.StructBlock( [('paragraph', blocks.RichTextBlock())], template='core/struct_paragraph_block.html', icon='fa-font', ), ), ( 'video',", "sso_id=request.user.pk, ) def serve(self, request, *args, **kwargs): self.handle_page_view(request) return super().serve(request,", "be a HS6, HS4 or HS2 code\"\"\" # free_tagging =", "backlink_path is not None: backlink_path = unquote(backlink_path) if len(backlink_path.split('/')) >", "), ], template='learn/recap.html', icon='fa-commenting-o', ), ) ] ) ######### #", "[ ('title', blocks.CharBlock(icon='fa-header')), ( 'item', blocks.StreamBlock( [ ( 'item', core_blocks.Item(),", "the UX easier for editors hs_code_tags = ClusterTaggableManager(through='core.HSCodeTaggedCaseStudy', blank=True, verbose_name='HS-code", "MagnaPageChooserPanel('page', [DetailPage, CuratedListPage, TopicPage]), ] class Meta: unique_together = ['case_study',", "in EXPORTPLAN_SLUGS and '://' not in backlink_path ): # The", "allow for configuring and representing very simple to modules (`CuratedListPage`s).", "import ( SECTION_SLUGS as EXPORTPLAN_SLUGS, SECTIONS as EXPORTPLAN_URL_MAP, ) #", "CuratedListPage(CMSGenericPage): parent_page_types = ['core.ListPage'] subpage_types = [ 'core.TopicPage', ] template_choices", "StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True) ######### # Panels ######### content_panels =", "run 'core.TopicPage', ] template_choices = (('learn/detail_page.html', 'Learn'),) class Meta: verbose_name", "('name',) def __str__(self): return self.name @register_snippet class Country(models.Model): name =", "PersonalisationTradingBlocTag, related_name='trading_bloc_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey( to='core.CaseStudy', on_delete=models.CASCADE, related_name='trading_bloc_tagged_items'", "StreamBlockValidationError( non_block_errors=ValidationError('; '.join(error_messages), code='invalid'), ) class MagnaPageChooserPanel(PageChooserPanel): show_label = False", "module this lesson belongs to\"\"\" return CuratedListPage.objects.live().specific().ancestor_of(self).first() @cached_property def _export_plan_url_map(self):", "sso_id = models.TextField() class Meta: ordering = ['page__pk'] unique_together =", "class Tour(ClusterableModel): page = models.OneToOneField('wagtailcore.Page', on_delete=models.CASCADE, related_name='tour') title = models.CharField(max_length=255)", "backlinks that we KNOW are for the export plan, else", "class PersonalisationTradingBlocTag(TagBase): \"\"\"Custom tag for personalisation. Tag value will be", "settings_panels = [FieldPanel('slug')] + Page.settings_panels def __init__(self, *args, **kwargs): super().__init__(*args,", "case study HS4 tag matches the first 4 digits of", "of the user's products\", default=8, decimal_places=3, max_digits=5, ) product_hs4 =", "comes first so that it is displayed first) * Two", "**kwargs): self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified', True)) super().save(**kwargs) class Meta:", "redirect return self._redirect_to_parent_module() def serve(self, request): return self._redirect_to_parent_module() class LessonPlaceholderPage(mixins.AuthenticatedUserRequired,", "('DE') \"\"\" free_tagging = False class Meta: verbose_name = 'Country", "class PageView(TimeStampedModel): page = models.ForeignKey(DetailPage, on_delete=models.CASCADE, related_name='page_views') list_page = models.ForeignKey(ListPage,", "panels = [FieldPanel('name')] class Meta: ordering = ('name',) def __str__(self):", "default=2, decimal_places=3, max_digits=5, ) country_exact = models.DecimalField( help_text=\"Score given when", "marked as read list_page = ( ListPage.objects.ancestor_of(self) .filter(record_read_progress=True) .exclude(page_views_list__sso_id=request.user.pk, page_views_list__page=self)", "[ ( 'pros', blocks.StreamBlock( [ ( 'item', core_blocks.Item(icon='fa-arrow-right'), ) ]", "if [node.block_type for node in value if node.block_type != QUOTE_BLOCK]", "this collection?', ) class Meta: verbose_name = 'Automated list page'", "Meta: unique_together = ['case_study', 'page'] @register_snippet class CaseStudy(ClusterableModel): \"\"\"Dedicated snippet", "error_messages.append('The video must come before a still image.') return error_messages", "'-modified', '-created', ) @register_setting class CaseStudyScoringSettings(BaseSetting): threshold = models.DecimalField( help_text='This", "), ( 'video', blocks.StructBlock( [('video', core_blocks.VideoBlock())], template='core/struct_video_block.html', icon='fa-play', ), ),", "StreamFieldPanel('recap'), ] def handle_page_view(self, request): if request.user.is_authenticated: # checking if", "(ListPage) context['parent_page_url'] = self.get_parent().url if request.user.is_authenticated: # get this once,", "case study title', ) # old name company_name summary_context =", "context['high_level_completion_progress'] = get_high_level_completion_progress( completion_status=completion_status, ) return context def hero_singular_validation(value): if", "non_block_errors=ValidationError('Only one image or video allowed in Hero section', code='invalid'),", "present here MEDIA_BLOCK = 'media' # noqa N806 VIDEO_BLOCK =", "dest = CuratedListPage.objects.ancestor_of(self).first().url return HttpResponseRedirect(dest) def serve_preview(self, request, mode_name='dummy'): #", "of the user's products \" 'unless there is an HS6", "# Give the template a simple way to link back", "remove after topics refactor migration has run 'core.TopicPage', ] template_choices", "= ('name',) def save(self, *args, **kwargs): # Automatically set slug", "mode_name - we always redirect return self._redirect_to_parent_module() def serve(self, request):", "Region(models.Model): name = models.CharField(max_length=100, unique=True) panels = [FieldPanel('name')] class Meta:", "# If we make a Redirect appear as a Snippet,", "HS2 code\"\"\" # free_tagging = False # DISABLED until tag", "instance_obj, 'is_chosen': bool(instance_obj), # DEPRECATED - passed to templates for", "related_name='region_tagged_items') class TradingBlocTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationTradingBlocTag, related_name='trading_bloc_tagged_case_studies', on_delete=models.CASCADE )", "= models.CharField(max_length=255) position = models.CharField(max_length=255) selector = models.CharField(max_length=255) tour =", "ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='hs_code_tagged_items') class CountryTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationCountryTag, related_name='country_tagged_case_studies',", "need here def _redirect_to_parent_module(self): dest = CuratedListPage.objects.ancestor_of(self).first().url return HttpResponseRedirect(dest) def", "def _redirect_to_parent_module(self): dest = CuratedListPage.objects.ancestor_of(self).first().url return HttpResponseRedirect(dest) def serve_preview(self, request,", "import # because it features lazily-evaluated URLs that aren't ready", "case study \" 'unless there is also lesson or topic", "= ('name',) def __str__(self): return self.name @register_snippet class IndustryTag(models.Model): name", "template_choices = ( ('learn/landing_page.html', 'Learn'), ('core/generic_page.html', 'Generic'), ) ################ #", "context class PageView(TimeStampedModel): page = models.ForeignKey(DetailPage, on_delete=models.CASCADE, related_name='page_views') list_page =", "get_high_level_completion_progress( completion_status=completion_status, ) return context ################ # Content fields ################", "ContentModuleTag(TaggedItemBase): content_object = ParentalKey('core.ContentModule', on_delete=models.CASCADE, related_name='tagged_items') # TODO: deprecate and", "next_lesson = page_topic_helper.get_next_lesson() context['current_lesson'] = self context['current_module'] = page_topic_helper.module if", "ObjectList(product_tab, heading='Product'), ObjectList(market_tab, heading='Market'), ObjectList(lesson_tab, heading='Lesson'), ObjectList(threshold_tab, heading='Threshold'), ] )", "panels = [ MultiFieldPanel( [ FieldPanel('title'), FieldPanel('lead_title'), FieldPanel('summary_context'), StreamFieldPanel('body'), ],", "models.OneToOneField('wagtailcore.Page', on_delete=models.CASCADE, related_name='tour') title = models.CharField(max_length=255) body = models.CharField(max_length=255) button_text", "= ['core.TopicPage'] subpage_types = [] # No child pages allowed", "CS need to call create to obtain an ID for", "detect one and can validate it _backlink = self._get_backlink(request) if", "import Redirect from wagtail.contrib.settings.models import BaseSetting, register_setting from wagtail.core import", "section (with one or two items in it) ' 'and/or", "given when any case study HS6 tag matches the complete", "within a full-page-width block', ), ), ( 'video', core_blocks.SimpleVideoBlock( template='core/includes/_video_full_width.html',", "def serve_preview(self, request, mode_name='dummy'): # It doesn't matter what is", "Quote section, then one Text section following it.' ) )", "summary lead_title = models.TextField(blank=False) # Deliberately not rich-text / no", "modified = ModificationDateTimeField('modified', null=True) def save(self, **kwargs): self.update_modified = kwargs.pop('update_modified',", "# `title` comes from Page superclass and that's all we", "when user's lesson's topic is tagged in the case study", "one image or video allowed in Hero section', code='invalid'), )", "and ( backlink_path.split('/')[3] in EXPORTPLAN_SLUGS and '://' not in backlink_path", "wagtail.admin.edit_handlers import ( FieldPanel, InlinePanel, MultiFieldPanel, ObjectList, PageChooserPanel, StreamFieldPanel, TabbedInterface,", "validators=[case_study_body_validation], help_text=( 'This block must contain one Media section (with", "error_messages = _high_level_validation(value, error_messages) error_messages = _low_level_validation(value, error_messages) if error_messages:", "displayed within a full-page-width block', ), ), ( 'video', core_blocks.SimpleVideoBlock(", "' 'considered before being presented to users. ', default=10, decimal_places=3,", "= request.GET.get(BACKLINK_QUERYSTRING_NAME, '') if backlink_path is not None: backlink_path =", "models.CharField(max_length=255) panels = [ PageChooserPanel('page'), FieldPanel('title'), FieldPanel('body'), FieldPanel('button_text'), MultiFieldPanel([InlinePanel('steps')], heading='Steps'),", "indexing self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified', True)) super().save(**kwargs) update_cs_index(self) def", "video may be used in a case study.') elif subnode_block_types[1]", "[ FieldPanel('hs_code_tags'), FieldPanel('country_code_tags'), FieldPanel('region_code_tags'), FieldPanel('trading_bloc_code_tags'), ], heading='Case Study tags for", "topic = models.DecimalField( help_text=\"Score given when user's lesson's topic is", "product_hs6 = models.DecimalField( help_text='Score given when any case study HS6", ") class MagnaPageChooserPanel(PageChooserPanel): show_label = False field_template = 'admin/wagtailadmin/edit_handlers/field_panel_field.html' def", "validators=[hero_singular_validation], ) objective = StreamField( [ ( 'paragraph', blocks.RichTextBlock(options={'class': 'objectives'}),", "one and can validate it _backlink = self._get_backlink(request) if _backlink:", "= 'media' # noqa N806 VIDEO_BLOCK = 'video' # noqa", "but that's an acceptable limitation here and is very unlikely", "the case study \" 'unless there is also lesson match.',", "body = StreamField( [ ('section', core_blocks.SectionBlock()), ('title', core_blocks.TitleBlock()), ('text', blocks.RichTextBlock(icon='openquote',", "Code tag for personalisation' verbose_name_plural = 'HS Code tags for", "list_page = ( ListPage.objects.ancestor_of(self) .filter(record_read_progress=True) .exclude(page_views_list__sso_id=request.user.pk, page_views_list__page=self) .first() ) if", "template='core/struct_video_block.html', icon='fa-play', ), ), ('case_study', core_blocks.CaseStudyStaticBlock(icon='fa-book')), ( 'Step', core_blocks.StepByStepBlock(icon='cog'), ),", "class Meta: verbose_name = 'Region tag for personalisation' verbose_name_plural =", "class Meta: verbose_name = 'Trading bloc tag for personalisation' verbose_name_plural", "Topic & Module, also used for Personalisation', ), ] def", "from wagtail.core import blocks from wagtail.core.blocks.stream_block import StreamBlockValidationError from wagtail.core.fields", "# TODO: deprecate and remove class ContentModuleTag(TaggedItemBase): content_object = ParentalKey('core.ContentModule',", "FieldPanel('threshold'), ] ) ] edit_handler = TabbedInterface( [ ObjectList(product_tab, heading='Product'),", "# left null because was an existing field ) subtitles_en", "currently MAY be used as # a child of another", "panels = [ MagnaPageChooserPanel('page', [DetailPage, CuratedListPage, TopicPage]), ] class Meta:", "region tag matches the region of any of the user's", "Panels ######### settings_panels = CMSGenericPage.settings_panels + [FieldPanel('record_read_progress')] content_panels = CMSGenericPage.content_panels", "on_delete=models.CASCADE, related_name='tagged_items') # TODO: deprecate and remove @register_snippet class ContentModule(ClusterableModel):", "now, this is limited only to Export Plan pages/links. \"\"\"", "URL Slugs->title for all the Export Plan sections we have.\"\"\"", "# we need to be strict about presence and ordering", "= ClusterTaggableManager( through='core.RegionTaggedCaseStudy', blank=True, verbose_name='Region tags' ) trading_bloc_code_tags = ClusterTaggableManager(", "wagtail.core import blocks from wagtail.core.blocks.stream_block import StreamBlockValidationError from wagtail.core.fields import", "users. ', default=10, decimal_places=3, max_digits=5, ) lesson = models.DecimalField( help_text=\"Score", "items in it) and/or a Quote section, then one Text", "products\", default=8, decimal_places=3, max_digits=5, ) product_hs4 = models.DecimalField( help_text=\"Score given", "models.DecimalField( help_text='Score given when any case study trading bloc tag", "= [MultiFieldPanel([FieldPanel('product_hs6'), FieldPanel('product_hs4'), FieldPanel('product_hs2')])] market_tab = [ MultiFieldPanel([FieldPanel('country_exact'), FieldPanel('country_region'), FieldPanel('trading_blocs')])", "about presence and ordering of these nodes if [node.block_type for", "migration has run 'core.TopicPage', ] template_choices = (('learn/detail_page.html', 'Learn'),) class", "study \" 'unless there is also lesson or topic match.',", "simple way to link back to the parent # learning", "make a Redirect appear as a Snippet, we can sync", "from domestic.helpers import get_lesson_completion_status context = super().get_context(request) # Give the", "class LessonPlaceholderPage(mixins.AuthenticatedUserRequired, Page): \"\"\"Structural page to allow for configuring and", "import BaseSetting, register_setting from wagtail.core import blocks from wagtail.core.blocks.stream_block import", ") components = StreamField( [ ('route', core_blocks.RouteSectionBlock()), ], null=True, blank=True,", "] ), ), ], template='learn/pros_and_cons.html', icon='fa-arrow-right', ), ), ('choose_do_not_choose', core_blocks.ChooseDoNotChooseBlock()),", "admin_form_fields = Media.admin_form_fields + ( 'transcript', 'subtitles_en', ) @property def", "@cached_property def count_topics(self): return self.get_topics().count() @cached_property def count_detail_pages(self): count =", "elif subnode_block_types[1] == VIDEO_BLOCK: # implicitly, [0] must be an", "verbose_name_plural = 'HS Code tags for personalisation' class PersonalisationCountryTag(TagBase): \"\"\"Custom", "backlink_path return None # safe default def _get_backlink_title(self, backlink_path): \"\"\"For", "# TODO: deprecate and remove @register_snippet class ContentModule(ClusterableModel): title =", "], validators=[case_study_body_validation], help_text=( 'This block must contain one Media section", "super().delete(**kwargs) def get_cms_standalone_view_url(self): return reverse('cms_extras:case-study-view', args=[self.id]) class Meta: verbose_name_plural =", "(`CuratedListPage`s). Not intented to be viewed by end users, so", "Also, for the above reason, mixins.WagtailGA360Mixin and GA360Mixin are not", "[FieldPanel('template')] settings_panels = [FieldPanel('slug')] + Page.settings_panels def __init__(self, *args, **kwargs):", "[ ( 'item', core_blocks.Item(icon='fa-arrow-right'), ) ] ), ), ( 'cons',", "related_name='+' ) class ImageHash(AbstractObjectHash): image = models.ForeignKey('wagtailimages.Image', null=True, blank=True, on_delete=models.CASCADE,", "= 'Country tag for personalisation' verbose_name_plural = 'Country tags for", "brought us to this view. Only accepts backlinks that we", "export markets.\", default=4, decimal_places=3, max_digits=5, ) country_region = models.DecimalField( help_text=\"Score", "section', code='invalid'), ) class TopicPage(mixins.AuthenticatedUserRequired, Page): \"\"\"Structural page to allow", "template a simple way to link back to the parent", "PersonalisationRegionTag, related_name='region_tagged_case_studies', on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='region_tagged_items') class", "_low_level_validation(value, error_messages): # Check content of media node, which should", "else: next_module = self.module.get_next_sibling() if not next_module: return context context['next_module']", "+ ( 'transcript', 'subtitles_en', ) @property def sources(self): return [", "blank=False, null=True # left null because was an existing field", "max_digits=5, ) product_tab = [MultiFieldPanel([FieldPanel('product_hs6'), FieldPanel('product_hs4'), FieldPanel('product_hs2')])] market_tab = [", "heading='Market'), ObjectList(lesson_tab, heading='Lesson'), ObjectList(threshold_tab, heading='Threshold'), ] ) class Meta: verbose_name", "class Meta: verbose_name = 'Detail page' verbose_name_plural = 'Detail pages'", "GreatMedia(Media): transcript = models.TextField( verbose_name=_('Transcript'), blank=False, null=True # left null", "use as a case study. Supports personalised selection via its", "\"\"\" Generic page, freely inspired by Codered page \"\"\" class", "tags') country_code_tags = ClusterTaggableManager( through='core.CountryTaggedCaseStudy', blank=True, verbose_name='Country tags' ) region_code_tags", "AbstractRendition, Image from wagtail.snippets.models import register_snippet from wagtail.utils.decorators import cached_classmethod", "[] # TO COME: support for more than just English", "tag for personalisation. Tag value will be an ISO-2 Country", "here: # https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models class HSCodeTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationHSCodeTag, related_name='hscode_tagged_case_studies',", "abstract = True # Do not allow this page type", ") ) return error_messages def _low_level_validation(value, error_messages): # Check content", "the page attempts to render the relevant CaseStudyBlock. Note that", "if the page should record read progress # checking if", "export plan) from the querystring on the request that brought", "it registered as a Snippet to be able to transfer", "( 'item', blocks.StreamBlock( [ ( 'item', core_blocks.Item(), ) ] ),", "keeping the personalisation-relevant tags in separate # fields to aid", "for personalisation. Tag value will be an Trading blocs \"\"\"", "class Meta: ordering = ('name',) def __str__(self): return self.name @register_snippet", "page_views_list__page=self) .first() ) if list_page: PageView.objects.get_or_create( page=self, list_page=list_page, sso_id=request.user.pk, )", "= ClusterTaggableManager( through='core.CountryTaggedCaseStudy', blank=True, verbose_name='Country tags' ) region_code_tags = ClusterTaggableManager(", "alt(self): return self.image.alt_text @register_snippet class Tour(ClusterableModel): page = models.OneToOneField('wagtailcore.Page', on_delete=models.CASCADE,", "None: backlink_path = unquote(backlink_path) if len(backlink_path.split('/')) > 2 and (", "the network call to get the data twice completion_status =", "QUOTE_BLOCK] != [MEDIA_BLOCK, TEXT_BLOCK]: error_messages.append( ( 'This block must contain", "reverse('core:subtitles-serve', args=[self.id, 'en']), 'default': False, }, ) return output class", "'Learn'),) ################ # Content fields ################ heading = RichTextField() image", "image * (video must comes first so that it is", "module(self): \"\"\"Gets the learning module this lesson belongs to\"\"\" return", "'.join(error_messages), code='invalid'), ) class MagnaPageChooserPanel(PageChooserPanel): show_label = False field_template =", "happen when the page attempts to render the relevant CaseStudyBlock.", "verbose_name='Internal case study title', ) # old name company_name summary_context", "= { 'field': self.bound_field, self.object_type_name: instance_obj, 'is_chosen': bool(instance_obj), # DEPRECATED", "TourStep(Orderable): title = models.CharField(max_length=255) body = models.CharField(max_length=255) position = models.CharField(max_length=255)", "lesson_tab = [MultiFieldPanel([FieldPanel('lesson'), FieldPanel('topic'), FieldPanel('module')])] threshold_tab = [ MultiFieldPanel( [", "= models.BooleanField( default=False, help_text='Should we record when a user views", "on_delete=models.CASCADE, related_name='page_views_list') sso_id = models.TextField() class Meta: ordering = ['page__pk']", "default=4, decimal_places=3, max_digits=5, ) country_region = models.DecimalField( help_text=\"Score given when", "models.CharField(max_length=255) button_text = models.CharField(max_length=255) panels = [ PageChooserPanel('page'), FieldPanel('title'), FieldPanel('body'),", "limited only to Export Plan pages/links. \"\"\" # We have", "help_text=\"Score given when the user's lesson's module is tagged in", "matches one of the user's export markets.\", default=4, decimal_places=3, max_digits=5,", "has run 'core.TopicPage', ] template_choices = (('learn/detail_page.html', 'Learn'),) class Meta:", "get_topics(self, live=True) -> models.QuerySet: qs = TopicPage.objects.live().specific().descendant_of(self) if live: qs", "self.name @register_snippet class Country(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=100,", "products \" 'unless there is an HS6 or HS4 match.',", "class Meta: unique_together = ['case_study', 'page'] @register_snippet class CaseStudy(ClusterableModel): \"\"\"Dedicated", "ugettext_lazy as _ from django_extensions.db.fields import CreationDateTimeField, ModificationDateTimeField from great_components.mixins", "Panels ########## content_panels = Page.content_panels + [ StreamFieldPanel('hero'), StreamFieldPanel('objective'), StreamFieldPanel('body'),", "Export Plan sections we have.\"\"\" return {url: values['title'] for url,", "None # safe default def _get_backlink_title(self, backlink_path): \"\"\"For a given", "full URL as its OWN querystring param (eg a crafted", "video allowed in Hero section', code='invalid'), ) class TopicPage(mixins.AuthenticatedUserRequired, Page):", "we make a Redirect appear as a Snippet, we can", "# When we create a new CS need to call", "request): \"\"\"Try to extract a backlink (used for a link", "default='How we did it') # old name summary lead_title =", "'domestic.DomesticDashboard', ] template_choices = ( ('learn/landing_page.html', 'Learn'), ('core/generic_page.html', 'Generic'), )", "def get_context(self, request, *args, **kwargs): context = super().get_context(request) self.set_ga360_payload( page_id=self.id,", "# It doesn't matter what is passed as mode_name -", "# Check content of media node, which should be present", "= [ MagnaPageChooserPanel('page', [DetailPage, CuratedListPage, TopicPage]), ] class Meta: unique_together", "DocumentHash(AbstractObjectHash): document = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, on_delete=models.CASCADE, related_name='+' )", "to the export plan if we detect one and can", "presence and ordering of these nodes if [node.block_type for node", "######### # Panels ########## layout_panels = [FieldPanel('template')] settings_panels = [FieldPanel('slug')]", "count = 0 for topic in self.get_topics(): count += DetailPage.objects.live().descendant_of(topic).count()", "def __str__(self): return self.page.title class TourStep(Orderable): title = models.CharField(max_length=255) body", "- we always redirect return self._redirect_to_parent_module() def serve(self, request): return", "Meta: verbose_name_plural = 'Countries' ordering = ('name',) def save(self, *args,", "Panels ######## content_panels = CMSGenericPage.content_panels + [ FieldPanel('heading'), ImageChooserPanel('image'), ]", "self.get_topics(): count += DetailPage.objects.live().descendant_of(topic).count() return count def get_context(self, request, *args,", "image = models.ForeignKey(AltTextImage, on_delete=models.CASCADE, related_name='renditions') class Meta: unique_together = ('image',", "pages'), ], heading='Related Lesson, Topic & Module, also used for", "Deliberately not rich-text / no formatting body = StreamField( [", "= 'Region tags for personalisation' class PersonalisationTradingBlocTag(TagBase): \"\"\"Custom tag for", "related_name='tagged_items') # TODO: deprecate and remove @register_snippet class ContentModule(ClusterableModel): title", "), ), ( 'video', blocks.StructBlock( [('video', core_blocks.VideoBlock())], template='core/struct_video_block.html', icon='fa-play', ),", "import BACKLINK_QUERYSTRING_NAME, RICHTEXT_FEATURES__MINIMAL from core.context import get_context_provider from core.utils import", "# noqa N806 VIDEO_BLOCK = 'video' # noqa N806 for", "\"\"\"Structural page to allow for cleaner mapping of lessons (`DetailPage`s)", ") body = StreamField( [ ('section', core_blocks.SectionBlock()), ('title', core_blocks.TitleBlock()), ('text',", "True # Prepare backlink to the export plan if we", "# DEPRECATED - passed to templates for backwards compatibility only", "# old name company_name summary_context = models.CharField(max_length=255, blank=False, default='How we", "the user's products \" 'unless there is an HS6 match.',", "StreamFieldPanel('body'), StreamFieldPanel('recap'), ] def handle_page_view(self, request): if request.user.is_authenticated: # checking", "( 'item', core_blocks.Item(icon='fa-arrow-right'), ) ] ), ), ], template='learn/pros_and_cons.html', icon='fa-arrow-right',", "Panels ######### content_panels = CMSGenericPage.content_panels + [ FieldPanel('description'), StreamFieldPanel('button'), ImageChooserPanel('image'),", "= ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='hs_code_tagged_items') class CountryTaggedCaseStudy(ItemBase): tag = models.ForeignKey( PersonalisationCountryTag,", "'url': reverse('core:subtitles-serve', args=[self.id, 'en']), 'default': False, }, ) return output", "from domestic.helpers import get_lesson_completion_status context = super().get_context(request) if request.user.is_authenticated: completion_status", "StreamFieldPanel, TabbedInterface, ) from wagtail.contrib.redirects.models import Redirect from wagtail.contrib.settings.models import", "[ 'domestic.DomesticHomePage', # TODO: once we've restructured, remove this permission", "# Content models class CMSGenericPage( mixins.EnableTourMixin, mixins.AuthenticatedUserRequired, mixins.WagtailGA360Mixin, GA360Mixin, Page,", "error_messages def _low_level_validation(value, error_messages): # Check content of media node,", "media node has the following content: * One image, only", "via Wagtail's ModelAdmin, so appears in the sidebar, but we", "products \" 'unless there is an HS6 match.', default=4, decimal_places=3,", "blank=True, verbose_name='Trading bloc tags' ) created = CreationDateTimeField('created', null=True) modified", "template_choices = (('learn/detail_page.html', 'Learn'),) class Meta: verbose_name = 'Detail page'", "bloc tags' ) created = CreationDateTimeField('created', null=True) modified = ModificationDateTimeField('modified',", "ModificationDateTimeField('modified', null=True) panels = [ MultiFieldPanel( [ FieldPanel('title'), FieldPanel('lead_title'), FieldPanel('summary_context'),", "any of the user's products \" 'unless there is an", "render_as_field 'obj_type': instance_obj.specific.__class__.__name__ if instance_obj else None, } return mark_safe(render_to_string(self.field_template,", "tag for personalisation' verbose_name_plural = 'Trading bloc tags for personalisation'", "# video after image: not allowed error_messages.append('The video must come", ".exclude(page_views_list__sso_id=request.user.pk, page_views_list__page=self) .first() ) if list_page: PageView.objects.get_or_create( page=self, list_page=list_page, sso_id=request.user.pk,", "acceptable limitation here and is very unlikely # to happen.", "rich-text / no formatting body = StreamField( [ ( 'media',", "'video', core_blocks.SimpleVideoBlock( template='core/includes/_video_full_width.html', help_text='Video displayed within a full-page-width block', ),", "tags = TaggableManager(through=ContentModuleTag, blank=True) panels = [ FieldPanel('title'), FieldPanel('content'), FieldPanel('tags'),", "deprecate and remove class ContentModuleTag(TaggedItemBase): content_object = ParentalKey('core.ContentModule', on_delete=models.CASCADE, related_name='tagged_items')", "to keep it registered as a Snippet to be able", "on_delete=models.CASCADE ) content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='country_tagged_items') class RegionTaggedCaseStudy(ItemBase): tag", "tag for personalisation. Tag value will be a HS6, HS4", "class Meta: abstract = True content_hash = models.CharField(max_length=1000) @staticmethod def", "], heading='Case Study tags for Personalisation', ), MultiFieldPanel( [ InlinePanel('related_pages',", "fields to aid lookup and make the UX easier for", "mark_safe from django.utils.text import slugify from django.utils.translation import ugettext_lazy as", "@property def sources(self): return [ { 'src': self.url, 'type': mimetypes.guess_type(self.filename)[0]", "[ FieldPanel('title'), FieldPanel('body'), FieldPanel('position'), FieldPanel('selector'), ] @register_snippet class Product(models.Model): name", "backlink_path.split('/')[3] in EXPORTPLAN_SLUGS and '://' not in backlink_path ): #", "will redirect to the parent module if accessed. Also, for", "StreamField( [ ('section', core_blocks.SectionBlock()), ('title', core_blocks.TitleBlock()), ('text', blocks.RichTextBlock(icon='openquote', helptext='Add a", "if request.user.is_authenticated: # checking if the page should record read", "there is an HS6 or HS4 match.', default=2, decimal_places=3, max_digits=5,", "wagtail.utils.decorators import cached_classmethod from wagtailmedia.models import Media from core import", "to be viewed by end users, so will redirect to", "PageTopicHelper(self) next_lesson = page_topic_helper.get_next_lesson() context['current_lesson'] = self context['current_module'] = page_topic_helper.module", "\"\"\" class Meta: abstract = True # Do not allow", "context ################ # Content fields ################ description = RichTextField() button_label", "FieldPanel('button_text'), MultiFieldPanel([InlinePanel('steps')], heading='Steps'), ] def __str__(self): return self.page.title class TourStep(Orderable):", "'unless there is an HS6 match.', default=4, decimal_places=3, max_digits=5, )", "FieldPanel('title'), FieldPanel('body'), FieldPanel('position'), FieldPanel('selector'), ] @register_snippet class Product(models.Model): name =", "= 'HS Code tags for personalisation' class PersonalisationCountryTag(TagBase): \"\"\"Custom tag", "separate # fields to aid lookup and make the UX", "core_blocks.SimpleVideoBlock( template='core/includes/_video_full_width.html', help_text='Video displayed within a full-page-width block', ), ),", "DetailPage(CMSGenericPage): estimated_read_duration = models.DurationField(null=True, blank=True) parent_page_types = [ 'core.CuratedListPage', #", "super().__init__(*args, **kwargs) field = self._meta.get_field('template') field.choices = self.template_choices field.required =", "[0] must be an image # video after image: not", "models.CharField(max_length=255, blank=True) admin_form_fields = Image.admin_form_fields + ('alt_text',) class Rendition(AbstractRendition): image", "'Learn'),) ################ # Content fields ################ button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))],", "content_panels = Page.content_panels + [ StreamFieldPanel('hero'), StreamFieldPanel('objective'), StreamFieldPanel('body'), StreamFieldPanel('recap'), ]", "get_edit_handler(cls): # NOQA N805 panels = [ ObjectList(cls.content_panels, heading='Content'), ObjectList(cls.layout_panels,", "re-arrange EXPORT_PLAN_SECTION_TITLES_URLS after import # because it features lazily-evaluated URLs", "Personalisation', ), ] def __str__(self): display_name = self.title if self.title", "Plan sections we have.\"\"\" return {url: values['title'] for url, values", "region = models.ForeignKey(Region, null=True, blank=True, on_delete=models.SET_NULL) panels = [ FieldPanel('name'),", "or region match.\", default=2, decimal_places=3, max_digits=5, ) product_tab = [MultiFieldPanel([FieldPanel('product_hs6'),", "count += DetailPage.objects.live().descendant_of(topic).count() return count def get_context(self, request, *args, **kwargs):", "field clash. \"\"\" created = CreationDateTimeField('created', null=True) modified = ModificationDateTimeField('modified',", ") ] edit_handler = TabbedInterface( [ ObjectList(product_tab, heading='Product'), ObjectList(market_tab, heading='Market'),", "get_lesson_completion_status(request.user) context['module_completion_progress'] = get_module_completion_progress( completion_status=completion_status, module_page=self, ) context['high_level_completion_progress'] = get_high_level_completion_progress(", "None, } return mark_safe(render_to_string(self.field_template, context)) class CaseStudyRelatedPages(Orderable): case_study = ParentalKey(", "verbose_name = 'Region tag for personalisation' verbose_name_plural = 'Region tags", "from exportplan.core.data import ( SECTION_SLUGS as EXPORTPLAN_SLUGS, SECTIONS as EXPORTPLAN_URL_MAP,", "models.ForeignKey( get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) body = StreamField(", "'HS Code tag for personalisation' verbose_name_plural = 'HS Code tags", "'unless there is an exact country match.', default=2, decimal_places=3, max_digits=5,", "One image, only * One video, only * One video", "exact country or region match.\", default=2, decimal_places=3, max_digits=5, ) product_tab", "StreamField( [ ('Image', core_blocks.ImageBlock(template='core/includes/_hero_image.html')), ('Video', core_blocks.SimpleVideoBlock(template='core/includes/_hero_video.html')), ], null=True, blank=True, validators=[hero_singular_validation],", "backlink_path = unquote(backlink_path) if len(backlink_path.split('/')) > 2 and ( backlink_path.split('/')[3]", "help_text='Score given when any case study HS6 tag matches the", "get_context_provider from core.utils import PageTopicHelper, get_first_lesson from exportplan.core.data import (", "we need here def _redirect_to_parent_module(self): dest = CuratedListPage.objects.ancestor_of(self).first().url return HttpResponseRedirect(dest)", "only comes via data migration class Meta: verbose_name = 'HS", "able to transfer it with Wagtail-Transfer \"\"\" title = models.CharField(", "a textblock')), ('image', core_blocks.ImageBlock()), ], null=True, blank=True, ) components =", "in wagtail admin is_creatable = False template_choices = [] ###############", "template='core/includes/_video_full_width.html', help_text='Video displayed within a full-page-width block', ), ), ]", "HS6 tag matches the complete HS6 code of ' \"any", "if len(backlink_path.split('/')) > 2 and ( backlink_path.split('/')[3] in EXPORTPLAN_SLUGS and", "decision about the appropriate Case Study block to show will", "django.urls import reverse from django.utils.functional import cached_property from django.utils.safestring import", "topic_title(self): return self.get_parent().title @cached_property def module(self): \"\"\"Gets the learning module", "models.ForeignKey(ListPage, on_delete=models.CASCADE, related_name='page_views_list') sso_id = models.TextField() class Meta: ordering =", "topic match.', default=2, decimal_places=3, max_digits=5, ) product_hs6 = models.DecimalField( help_text='Score", "edit_handler = TabbedInterface( [ ObjectList(product_tab, heading='Product'), ObjectList(market_tab, heading='Market'), ObjectList(lesson_tab, heading='Lesson'),", "in the case study.\", default=8, decimal_places=3, max_digits=5, ) topic =", "self.bound_field, self.object_type_name: instance_obj, 'is_chosen': bool(instance_obj), # DEPRECATED - passed to", "backlink, see if we can get a title that goes", "'media' # noqa N806 VIDEO_BLOCK = 'video' # noqa N806", "StreamBlockValidationError( non_block_errors=ValidationError('Only one image or video allowed in Hero section',", "= CMSGenericPage.content_panels + [ FieldPanel('heading'), ImageChooserPanel('image'), ] def get_topics(self, live=True)", "page \"\"\" class Meta: abstract = True # Do not", "any case study country tag exactly matches one of the", "FieldPanel('name'), ] def __str__(self): return self.name @register_snippet class Region(models.Model): name", "django.conf import settings from django.core.exceptions import ValidationError from django.db import", "filehash = hashlib.md5() field_file.open() filehash.update(field_file.read()) field_file.close() return filehash.hexdigest() class DocumentHash(AbstractObjectHash):", "help_text=\"Score given when user's lesson is tagged in the case", ") def _high_level_validation(value, error_messages): TEXT_BLOCK = 'text' # noqa N806", "null=True) def save(self, **kwargs): self.update_modified = kwargs.pop('update_modified', getattr(self, 'update_modified', True))", "_high_level_validation(value, error_messages): TEXT_BLOCK = 'text' # noqa N806 MEDIA_BLOCK =", "################ description = RichTextField() button = StreamField([('button', core_blocks.ButtonBlock(icon='cog'))], null=True, blank=True)", "blank=True, verbose_name='HS-code tags') country_code_tags = ClusterTaggableManager( through='core.CountryTaggedCaseStudy', blank=True, verbose_name='Country tags'", "content_panels = CMSGenericPage.content_panels + [FieldPanel('description'), FieldPanel('button_label')] class CuratedListPage(CMSGenericPage): parent_page_types =", "not in backlink_path ): # The check for '://' will", "return f'{display_name}' def save(self, **kwargs): # When we create a", "if self.title else self.summary_context return f'{display_name}' def save(self, **kwargs): #", "[FieldPanel('slug')] + Page.settings_panels def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) field", "Only accepts backlinks that we KNOW are for the export", "next_module.specific context['next_lesson'] = get_first_lesson(next_module) return context class PageView(TimeStampedModel): page =", "True @cached_classmethod def get_edit_handler(cls): # NOQA N805 panels = [", "= _high_level_validation(value, error_messages) error_messages = _low_level_validation(value, error_messages) if error_messages: raise", "section.' ), ) # We are keeping the personalisation-relevant tags", "given when any case study country tag exactly matches one", "slug on save, if not already set if not self.slug:", "the case study.\", default=8, decimal_places=3, max_digits=5, ) topic = models.DecimalField(", "record when a user views a page in this collection?',", "and len(value) > 1: raise StreamBlockValidationError( non_block_errors=ValidationError('Only one image or", "topic_page.title if next_lesson: context['next_lesson'] = next_lesson else: next_module = self.module.get_next_sibling()", "\"any of the user's products\", default=8, decimal_places=3, max_digits=5, ) product_hs4", "def __str__(self): return self.title class PersonalisationHSCodeTag(TagBase): \"\"\"Custom tag for personalisation.", "components = StreamField( [ ('route', core_blocks.RouteSectionBlock()), ], null=True, blank=True, )", "study title', ) # old name company_name summary_context = models.CharField(max_length=255,", ") content_object = ParentalKey(to='core.CaseStudy', on_delete=models.CASCADE, related_name='country_tagged_items') class RegionTaggedCaseStudy(ItemBase): tag =", "it') # old name summary lead_title = models.TextField(blank=False) # Deliberately", "ObjectList(cls.settings_panels, heading='Settings', classname='settings'), ] return TabbedInterface(panels).bind_to(model=cls) def get_template(self, request, *args,", "= models.DecimalField( help_text=\"Score given when any case study HS2 tag", "template='learn/pros_and_cons.html', icon='fa-arrow-right', ), ), ('choose_do_not_choose', core_blocks.ChooseDoNotChooseBlock()), ( 'image', core_blocks.ImageBlock( template='core/includes/_image_full_width.html',", "'text', blocks.RichTextBlock( features=RICHTEXT_FEATURES__MINIMAL, ), ), ( 'quote', core_blocks.CaseStudyQuoteBlock(), ), ],", "its OWN querystring param (eg a crafted attack # URL),", "for personalisation' class PersonalisationCountryTag(TagBase): \"\"\"Custom tag for personalisation. Tag value", "import delete_cs_index, update_cs_index from core.constants import BACKLINK_QUERYSTRING_NAME, RICHTEXT_FEATURES__MINIMAL from core.context", "= [FieldPanel('name'), ImageChooserPanel('icon')] class Meta: ordering = ('name',) def __str__(self):", "be ' 'considered before being presented to users. ', default=10,", "is passed as mode_name - we always redirect return self._redirect_to_parent_module()", "we can sync it via Wagtail-Transfer register_snippet(Redirect) class GreatMedia(Media): transcript", "image: not allowed error_messages.append('The video must come before a still", "= qs.live() return qs @cached_property def count_topics(self): return self.get_topics().count() @cached_property", "Page.settings_panels def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) field = self._meta.get_field('template')", "(used for a link to the export plan) from the", "models.DecimalField( help_text=\"Score given when any case study HS2 tag matches", "to Export Plan pages/links. \"\"\" # We have to re-arrange", "core_blocks.ImageBlock(template='core/includes/_hero_image.html')), ('Video', core_blocks.SimpleVideoBlock(template='core/includes/_hero_video.html')), ], null=True, blank=True, validators=[hero_singular_validation], ) objective =", "null=True, blank=True) image = models.ForeignKey( get_image_model_string(), null=True, blank=True, on_delete=models.SET_NULL, related_name='+'", "######## # Panels ######## content_panels = CMSGenericPage.content_panels + [ FieldPanel('heading'),", "ignore it.\"\"\" backlink_path = request.GET.get(BACKLINK_QUERYSTRING_NAME, '') if backlink_path is not", "######### # Panels ######### settings_panels = CMSGenericPage.settings_panels + [FieldPanel('record_read_progress')] content_panels", "len(value) > 1: raise StreamBlockValidationError( non_block_errors=ValidationError('Only one image or video", "are imported if backlink_path and len(backlink_path.split('/')) > 3: _path =", "context['high_level_completion_progress'] = get_high_level_completion_progress( completion_status=completion_status, ) return context ################ # Content", "any case study region tag matches the region of any", "decimal_places=3, max_digits=5, ) trading_blocs = models.DecimalField( help_text='Score given when any", "TODO: deprecate and remove @register_snippet class ContentModule(ClusterableModel): title = models.CharField(max_length=255)", ") region_code_tags = ClusterTaggableManager( through='core.RegionTaggedCaseStudy', blank=True, verbose_name='Region tags' ) trading_bloc_code_tags", "content_object = ParentalKey( to='core.CaseStudy', on_delete=models.CASCADE, related_name='trading_bloc_tagged_items' ) def _high_level_validation(value, error_messages):", "################ # Content fields ################ description = RichTextField() button =", "= models.CharField(max_length=255, blank=True) admin_form_fields = Image.admin_form_fields + ('alt_text',) class Rendition(AbstractRendition):", "max_digits=5, ) lesson = models.DecimalField( help_text=\"Score given when user's lesson", "( '-modified', '-created', ) abstract = True # Content models" ]
[ "class Compose(AbstractTransform): \"\"\" Do transformation on input data with corresponding", "Default: True. Raises: TypeError: When 'transforms' is not a list.", "i.e, if height > width, then image will be rescaled", "``cv2.INTER_CUBIC``, bicubic interpolation \"\"\" def __init__(self, mode, size, interpolation=cv2.INTER_LINEAR): \"\"\"", "of size of the origin size cropped ratio (tuple): range", "to be cropped. scale (tuple): range of size of the", "If true, expands the output to make it large enough", "2.0 (the \"License\"); # you may not use this file", "size = tuple(size) self.size = size else: raise ValueError('Unknown inputs", "to make it large enough to hold the entire rotated", "interpolation: Default: cv2.INTER_CUBIC \"\"\" def __init__(self, mode, size, scale=(0.08, 1.0),", "3/4 to 4/3) of the original aspect ratio is made.", "(numpy ndarray): Image to be scaled. Returns: numpy ndarray: Rescaled", "used to train the Inception networks. Args: size: expected output", "contains data pre-processing or augmentation. Empty list means only reading", "'h', 'w']) for attempt in range(10): area = img.shape[0] *", "and len(size) == 2: if type(size) == list: size =", "shape of input data to all operations is [height, width,", "of the image will be matched to this number. i.e,", "w) to be passed to ``crop`` for a random sized", "given probability. Args: p (float): probability of the image being", "img (numpy ndarray): Image to be cropped and resized. Returns:", "= (-degrees, degrees) else: if len(degrees) != 2: raise ValueError(", "TypeError: When 'transforms' is not a list. ValueError: when the", "h, w = self.get_params(img, self.scale, self.ratio) return F.resized_crop(img, i, j,", "params_ret = collections.namedtuple('params_ret', ['i', 'j', 'h', 'w']) for attempt in", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "if type(size) == list: size = tuple(size) self.size = size", "Image to be flipped. Returns: numpy ndarray: Randomly flipped image.", "w, w) def __clas__(self, img): \"\"\" Args: img (numpy ndarray):", "area = img.shape[0] * img.shape[1] target_area = random.uniform(*scale) * area", "This crop is finally resized to given size. This is", "return params_ret(i, j, h, w) # Fallback w = min(img.shape[0],", "RandomRotation(AbstractTransform): \"\"\"Rotate the image by angle. Args: degrees (sequence or", "left corner. Default is the center of the image. \"\"\"", "ndarray: Randomly flipped image. \"\"\" if random.random() < self.prob: return", "the image being flipped. Default value is 0.5 \"\"\" def", "self.scale = scale self.ratio = ratio super().__init__(mode) def get_params(self, img,", "for a random sized crop. \"\"\" params_ret = collections.namedtuple('params_ret', ['i',", "image will be matched to this number. i.e, if height", "2: if type(size) == list: size = tuple(size) self.size =", "`filters`_ for more information. If omitted, or if the image", "scale: range of size of the origin size cropped ratio:", "\"\"\" init \"\"\" self.prob = prob super().__init__(mode) def __clas__(self, img):", "= op(im) return im @manager.TRANSFORMS.add_component class RandomHorizontalFlip(AbstractTransform): \"\"\"Horizontally flip the", "center of the image. \"\"\" def __init__(self, mode, degrees, center=None):", "'j', 'h', 'w']) for attempt in range(10): area = img.shape[0]", "and resized image. \"\"\" i, j, h, w = self.get_params(img,", "[height, width, channels]. Args: transforms (list): A list contains data", "(list): A list contains data pre-processing or augmentation. Empty list", "of the image. \"\"\" def __init__(self, mode, degrees, center=None): \"\"\"", "w = min(img.shape[0], img.shape[1]) i = (img.shape[0] - w) //", "int, smaller edge of the image will be matched to", "= int(round(math.sqrt(target_area / aspect_ratio))) if random.random() < 0.5: w, h", "If size is a sequence like (h, w), output size", "collections.Iterable) and len(size) == 2) if isinstance(size, int): self.size =", "max), the range of degrees will be (-degrees, +degrees). resample", "use this file except in compliance with the License. #", "height / width, size) interpolation (int, optional): Desired interpolation. Default", "to_rgb (bool, optional): If converting image to RGB color space.", "transforms must be a list!') self.transforms = transforms super().__init__(mode) def", "@manager.TRANSFORMS.add_component class RandomVerticalFlip(AbstractTransform): \"\"\"Vertically flip the given PIL Image randomly", "(numpy ndarray): Image to be cropped and resized. Returns: numpy", "if the image has mode \"1\" or \"P\", it is", "numpy as np import numbers import collections import random import", "be a list!') self.transforms = transforms super().__init__(mode) def __clas__(self, im):", "Randomly flipped image. \"\"\" if random.random() < self.prob: return F.hflip(img)", "collections.namedtuple('params_ret', ['i', 'j', 'h', 'w']) for attempt in range(10): area", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "image. \"\"\" if random.random() < self.prob: return F.vflip(img) return img", "License. # You may obtain a copy of the License", "original size and a random aspect ratio (default: of 3/4", "ratio cropped interpolation: Default: cv2.INTER_CUBIC \"\"\" def __init__(self, mode, size,", "0.5 \"\"\" def __init__(self, mode, prob=0.5): \"\"\" init \"\"\" self.prob", "cropped. scale (tuple): range of size of the origin size", "['i', 'j', 'h', 'w']) for attempt in range(10): area =", "img.shape[0] * img.shape[1] target_area = random.uniform(*scale) * area aspect_ratio =", "img.shape[1] - w) return params_ret(i, j, h, w) # Fallback", "for random rotation. \"\"\" angle = random.uniform(degrees[0], degrees[1]) return angle", "The shape of input data to all operations is [height,", "4. / 3.), interpolation=cv2.INTER_CUBIC): \"\"\" init \"\"\" self.size = (size,", "= tuple(size) self.size = size else: raise ValueError('Unknown inputs for", "flipped image. \"\"\" if random.random() < self.prob: return F.vflip(img) return", "information. If omitted, or if the image has mode \"1\"", "under the License is distributed on an \"AS IS\" BASIS,", "i, j, h, w = self.get_params(img, self.scale, self.ratio) return F.resized_crop(img,", "it must be positive.\") self.degrees = (-degrees, degrees) else: if", "finally resized to given size. This is popularly used to", "is [height, width, channels]. Args: transforms (list): A list contains", "License for the specific language governing permissions and # limitations", "to be passed to ``crop`` for a random sized crop.", "center (2-tuple, optional): Optional center of rotation. Origin is the", "= img.shape[0] * img.shape[1] target_area = random.uniform(*scale) * area aspect_ratio", "/ width, size) interpolation (int, optional): Desired interpolation. Default is", "2022 Baidu.com, Inc. All Rights Reserved # # Licensed under", "// 2 j = (img.shape[1] - w) // 2 return", "upper left corner. Default is the center of the image.", "of 3/4 to 4/3) of the original aspect ratio is", "train the Inception networks. Args: size: expected output size of", "Optional expansion flag. If true, expands the output to make", "class RandomVerticalFlip(AbstractTransform): \"\"\"Vertically flip the given PIL Image randomly with", "class RandomRotation(AbstractTransform): \"\"\"Rotate the image by angle. Args: degrees (sequence", "image path or image object. Returns: (np.array). Image after transformation.", "Returns: numpy ndarray: Randomly flipped image. \"\"\" if random.random() <", "/ 3.), interpolation=cv2.INTER_CUBIC): \"\"\" init \"\"\" self.size = (size, size)", "to be cropped and resized. Returns: numpy ndarray: Randomly cropped", "less than 1. \"\"\" def __init__(self, mode, transforms): if not", "This is popularly used to train the Inception networks. Args:", "to hold the entire rotated image. If false or omitted,", "ratio. A crop of random size (default: of 0.08 to", "ndarray): Image to be cropped. scale (tuple): range of size", "to RGB color space. Default: True. Raises: TypeError: When 'transforms'", "\"\"\"Crop the given numpy ndarray to random size and aspect", "1. \"\"\" def __init__(self, mode, transforms): if not isinstance(transforms, list):", "transforms (list): A list contains data pre-processing or augmentation. Empty", "transformation. \"\"\" for op in self.transforms: im = op(im) return", "to given size. This is popularly used to train the", "(tuple): range of size of the origin size cropped ratio", "sequence like (min, max), the range of degrees will be", "@staticmethod def get_params(degrees): \"\"\"Get parameters for ``rotate`` for a random", "self.get_params(self.degrees) return F.rotate(img, angle, self.center) @manager.TRANSFORMS.add_component class Resize(AbstractTransform): \"\"\"Resize the", "width, size) interpolation (int, optional): Desired interpolation. Default is ``cv2.INTER_CUBIC``,", "sized crop. Args: img (numpy ndarray): Image to be cropped.", "to random size and aspect ratio. A crop of random", "= collections.namedtuple('params_ret', ['i', 'j', 'h', 'w']) for attempt in range(10):", "\"P\", it is set to PIL.Image.NEAREST. expand (bool, optional): Optional", "the given size. Args: size (sequence or int): Desired output", "is a number instead of sequence like (min, max), the", "\"\"\" self.size = (size, size) self.interpolation = interpolation self.scale =", "in compliance with the License. # You may obtain a", "mode, prob=0.5): \"\"\" init \"\"\" self.prob = prob super().__init__(mode) def", "is either image path or image object. Returns: (np.array). Image", "Args: im (np.ndarray): It is either image path or image", "flipped. Default value is 0.5 \"\"\" def __init__(self, mode, prob=0.5):", "software # distributed under the License is distributed on an", "< 0: raise ValueError( \"If degrees is a single number,", "class Resize(AbstractTransform): \"\"\"Resize the input numpy ndarray to the given", "img (numpy ndarray): Image to be flipped. Returns: numpy ndarray:", "RandomVerticalFlip(AbstractTransform): \"\"\"Vertically flip the given PIL Image randomly with a", "= h, w if w <= img.shape[1] and h <=", "{}'.format(size)) self.interpolation = interpolation super().__init__(mode) def __clas__(self, img): \"\"\" Args:", "cropped ratio (tuple): range of aspect ratio of the origin", "<= img.shape[0]: i = random.randint(0, img.shape[0] - h) j =", "(min, max), the range of degrees will be (-degrees, +degrees).", "mode, transforms): if not isinstance(transforms, list): raise TypeError('The transforms must", "License. # ########################################################################## \"\"\" 数据变换器 \"\"\" import numpy as np", "j, h, w = self.get_params(img, self.scale, self.ratio) return F.resized_crop(img, i,", "isinstance(transforms, list): raise TypeError('The transforms must be a list!') self.transforms", "of random size (default: of 0.08 to 1.0) of the", "Returns: (np.array). Image after transformation. \"\"\" for op in self.transforms:", "true, expands the output to make it large enough to", "or (isinstance(size, collections.Iterable) and len(size) == 2) if isinstance(size, int):", "(h, w), output size will be matched to this. If", "cropped and resized image. \"\"\" i, j, h, w =", "4/3) of the original aspect ratio is made. This crop", "output to make it large enough to hold the entire", "to 1.0) of the original size and a random aspect", "degrees) else: if len(degrees) != 2: raise ValueError( \"If degrees", "\"\"\" # assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size)", "given numpy ndarray to random size and aspect ratio. A", "input numpy ndarray to the given size. Args: size (sequence", "channels]. Args: transforms (list): A list contains data pre-processing or", "prob=0.5): \"\"\" init \"\"\" self.prob = prob super().__init__(mode) def __clas__(self,", "cropped ratio: range of aspect ratio of the origin aspect", "# limitations under the License. # ########################################################################## \"\"\" 数据变换器 \"\"\"", "(img.shape[0] - w) // 2 j = (img.shape[1] - w)", "as np import numbers import collections import random import math", "center of rotation. Origin is the upper left corner. Default", "expansion flag. If true, expands the output to make it", "is not a list. ValueError: when the length of 'transforms'", "(tuple): range of aspect ratio of the origin aspect ratio", "Origin is the upper left corner. Default is the center", "When 'transforms' is not a list. ValueError: when the length", "scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.), interpolation=cv2.INTER_CUBIC): \"\"\"", "the origin size cropped ratio (tuple): range of aspect ratio", "is 0.5 \"\"\" def __init__(self, mode, prob=0.5): \"\"\" init \"\"\"", "import collections import random import math import cv2 from .", "is the upper left corner. Default is the center of", "(default: of 0.08 to 1.0) of the original size and", "degrees self.center = center super().__init__(mode) @staticmethod def get_params(degrees): \"\"\"Get parameters", "size of each edge scale: range of size of the", "will be matched to this. If size is an int,", "space. Default: True. Raises: TypeError: When 'transforms' is not a", "list means only reading images, no transformation. to_rgb (bool, optional):", "for op in self.transforms: im = op(im) return im @manager.TRANSFORMS.add_component", "########################################################################## # # Copyright (c) 2022 Baidu.com, Inc. All Rights", "class RandomResizedCrop(AbstractTransform): \"\"\"Crop the given numpy ndarray to random size", "in range(10): area = img.shape[0] * img.shape[1] target_area = random.uniform(*scale)", "numpy ndarray: Randomly cropped and resized image. \"\"\" i, j,", "isinstance(size, collections.abc.Iterable) and len(size) == 2: if type(size) == list:", "\"1\" or \"P\", it is set to PIL.Image.NEAREST. expand (bool,", "has mode \"1\" or \"P\", it is set to PIL.Image.NEAREST.", "flipped. Returns: numpy ndarray: Randomly flipped image. \"\"\" if random.random()", "or if the image has mode \"1\" or \"P\", it", "to train the Inception networks. Args: size: expected output size", "crop is finally resized to given size. This is popularly", "make it large enough to hold the entire rotated image.", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "of the origin size cropped ratio: range of aspect ratio", "be cropped. scale (tuple): range of size of the origin", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "if random.random() < 0.5: w, h = h, w if", "expand flag assumes rotation around the center and no translation.", "size is an int, smaller edge of the image will", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "# # Copyright (c) 2022 Baidu.com, Inc. All Rights Reserved", "the same size as the input image. Note that the", "to in writing, software # distributed under the License is", "if w <= img.shape[1] and h <= img.shape[0]: i =", "expand (bool, optional): Optional expansion flag. If true, expands the", "utf-8 -*- ########################################################################## # # Copyright (c) 2022 Baidu.com, Inc.", "the given PIL Image randomly with a given probability. Args:", "# See the License for the specific language governing permissions", "numpy ndarray to the given size. Args: size (sequence or", "(np.array). Image after transformation. \"\"\" for op in self.transforms: im", "If false or omitted, make the output image the same", "it must be of len 2.\") self.degrees = degrees self.center", "(numpy ndarray): Image to be cropped. scale (tuple): range of", "numpy ndarray: Randomly flipped image. \"\"\" if random.random() < self.prob:", "language governing permissions and # limitations under the License. #", "return img @manager.TRANSFORMS.add_component class RandomVerticalFlip(AbstractTransform): \"\"\"Vertically flip the given PIL", "or agreed to in writing, software # distributed under the", "and len(size) == 2) if isinstance(size, int): self.size = (size,", "\"\"\"Rotate the image by angle. Args: degrees (sequence or float", "size) elif isinstance(size, collections.abc.Iterable) and len(size) == 2: if type(size)", "Baidu.com, Inc. All Rights Reserved # # Licensed under the", "self.scale, self.ratio) return F.resized_crop(img, i, j, h, w, self.size, self.interpolation)", "required by applicable law or agreed to in writing, software", "list. ValueError: when the length of 'transforms' is less than", "w = int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio)))", "number, it must be positive.\") self.degrees = (-degrees, degrees) else:", "images, no transformation. to_rgb (bool, optional): If converting image to", "params_ret(i, j, w, w) def __clas__(self, img): \"\"\" Args: img", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "enough to hold the entire rotated image. If false or", "with the License. # You may obtain a copy of", "the original aspect ratio is made. This crop is finally", "= degrees self.center = center super().__init__(mode) @staticmethod def get_params(degrees): \"\"\"Get", "int): Range of degrees to select from. If degrees is", "Returns: numpy ndarray: Rotated image. \"\"\" angle = self.get_params(self.degrees) return", "image. If false or omitted, make the output image the", "return angle def __clas__(self, img): \"\"\" img (numpy ndarray): Image", "list): raise TypeError('The transforms must be a list!') self.transforms =", "origin aspect ratio cropped interpolation: Default: cv2.INTER_CUBIC \"\"\" def __init__(self,", "make the output image the same size as the input", "the upper left corner. Default is the center of the", "passed to ``crop`` for a random sized crop. \"\"\" params_ret", "area aspect_ratio = random.uniform(*ratio) w = int(round(math.sqrt(target_area * aspect_ratio))) h", "i = random.randint(0, img.shape[0] - h) j = random.randint(0, img.shape[1]", "Args: img (numpy ndarray): Image to be cropped and resized.", "mode, size, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.),", "being flipped. Default value is 0.5 \"\"\" def __init__(self, mode,", "of the original size and a random aspect ratio (default:", "size cropped ratio (tuple): range of aspect ratio of the", "resample ({cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_LANCZOS4}, optional): An optional resampling filter.", "list contains data pre-processing or augmentation. Empty list means only", "img.shape[1]) i = (img.shape[0] - w) // 2 j =", "or \"P\", it is set to PIL.Image.NEAREST. expand (bool, optional):", "= random.uniform(*scale) * area aspect_ratio = random.uniform(*ratio) w = int(round(math.sqrt(target_area", "sequence, it must be of len 2.\") self.degrees = degrees", "passed to ``rotate`` for random rotation. \"\"\" angle = random.uniform(degrees[0],", "compliance with the License. # You may obtain a copy", "len(size) == 2: if type(size) == list: size = tuple(size)", "agreed to in writing, software # distributed under the License", "around the center and no translation. center (2-tuple, optional): Optional", "h = int(round(math.sqrt(target_area / aspect_ratio))) if random.random() < 0.5: w,", "mode, size, interpolation=cv2.INTER_LINEAR): \"\"\" resize \"\"\" # assert isinstance(size, int)", "ndarray to the given size. Args: size (sequence or int):", "a random aspect ratio (default: of 3/4 to 4/3) of", "= random.uniform(degrees[0], degrees[1]) return angle def __clas__(self, img): \"\"\" img", "size, interpolation=cv2.INTER_LINEAR): \"\"\" resize \"\"\" # assert isinstance(size, int) or", "distributed under the License is distributed on an \"AS IS\"", "data with corresponding pre-processing and augmentation operations. The shape of", "\"\"\" 数据变换器 \"\"\" import numpy as np import numbers import", "Args: transforms (list): A list contains data pre-processing or augmentation.", "ndarray: Randomly cropped and resized image. \"\"\" i, j, h,", "2.\") self.degrees = degrees self.center = center super().__init__(mode) @staticmethod def", "cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_LANCZOS4}, optional): An optional resampling filter. See `filters`_", "target_area = random.uniform(*scale) * area aspect_ratio = random.uniform(*ratio) w =", "is a sequence, it must be of len 2.\") self.degrees", "- w) return params_ret(i, j, h, w) # Fallback w", "data to all operations is [height, width, channels]. Args: transforms", "single number, it must be positive.\") self.degrees = (-degrees, degrees)", "ratio cropped Returns: tuple: params (i, j, h, w) to", "h, w if w <= img.shape[1] and h <= img.shape[0]:", "np import numbers import collections import random import math import", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "path or image object. Returns: (np.array). Image after transformation. \"\"\"", "not use this file except in compliance with the License.", "img.shape[1] target_area = random.uniform(*scale) * area aspect_ratio = random.uniform(*ratio) w", "< self.prob: return F.vflip(img) return img @manager.TRANSFORMS.add_component class RandomResizedCrop(AbstractTransform): \"\"\"Crop", "= (img.shape[0] - w) // 2 j = (img.shape[1] -", "angle def __clas__(self, img): \"\"\" img (numpy ndarray): Image to", "image. Note that the expand flag assumes rotation around the", "super().__init__(mode) @staticmethod def get_params(degrees): \"\"\"Get parameters for ``rotate`` for a", "writing, software # distributed under the License is distributed on", "edge scale: range of size of the origin size cropped", "probability. Args: p (float): probability of the image being flipped.", "you may not use this file except in compliance with", "\"\"\" if random.random() < self.prob: return F.vflip(img) return img @manager.TRANSFORMS.add_component", "range of size of the origin size cropped ratio (tuple):", "(img.shape[1] - w) // 2 return params_ret(i, j, w, w)", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "with corresponding pre-processing and augmentation operations. The shape of input", "tuple(size) self.size = size else: raise ValueError('Unknown inputs for size:", "range of degrees will be (-degrees, +degrees). resample ({cv2.INTER_NEAREST, cv2.INTER_LINEAR,", "Image to be scaled. Returns: numpy ndarray: Rescaled image. \"\"\"", "or int): Desired output size. If size is a sequence", "w) return params_ret(i, j, h, w) # Fallback w =", "\"\"\" img (numpy ndarray): Image to be rotated. Returns: numpy", "self.get_params(img, self.scale, self.ratio) return F.resized_crop(img, i, j, h, w, self.size,", "__init__(self, mode, transforms): if not isinstance(transforms, list): raise TypeError('The transforms", "else: if len(degrees) != 2: raise ValueError( \"If degrees is", "len 2.\") self.degrees = degrees self.center = center super().__init__(mode) @staticmethod", "= prob super().__init__(mode) def __clas__(self, img): \"\"\" Args: img (numpy", "int(round(math.sqrt(target_area / aspect_ratio))) if random.random() < 0.5: w, h =", "\"\"\" Args: im (np.ndarray): It is either image path or", "im (np.ndarray): It is either image path or image object.", "of aspect ratio of the origin aspect ratio cropped Returns:", "aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio))) if random.random() < 0.5:", "it is set to PIL.Image.NEAREST. expand (bool, optional): Optional expansion", "= (size, size) self.interpolation = interpolation self.scale = scale self.ratio", "def __clas__(self, img): \"\"\" Args: img (numpy ndarray): Image to", "self.interpolation = interpolation super().__init__(mode) def __clas__(self, img): \"\"\" Args: img", "ratio is made. This crop is finally resized to given", "CONDITIONS OF ANY KIND, either express or implied. # See", "cv2.INTER_CUBIC \"\"\" def __init__(self, mode, size, scale=(0.08, 1.0), ratio=(3. /", "If converting image to RGB color space. Default: True. Raises:", "not a list. ValueError: when the length of 'transforms' is", "if random.random() < self.prob: return F.hflip(img) return img @manager.TRANSFORMS.add_component class", "resized. Returns: numpy ndarray: Randomly cropped and resized image. \"\"\"", "same size as the input image. Note that the expand", "If degrees is a number instead of sequence like (min,", "\"\"\" resize \"\"\" # assert isinstance(size, int) or (isinstance(size, collections.Iterable)", "resize \"\"\" # assert isinstance(size, int) or (isinstance(size, collections.Iterable) and", "!= 2: raise ValueError( \"If degrees is a sequence, it", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "@manager.TRANSFORMS.add_component class RandomResizedCrop(AbstractTransform): \"\"\"Crop the given numpy ndarray to random", "raise ValueError('Unknown inputs for size: {}'.format(size)) self.interpolation = interpolation super().__init__(mode)", "angle = self.get_params(self.degrees) return F.rotate(img, angle, self.center) @manager.TRANSFORMS.add_component class Resize(AbstractTransform):", "\"If degrees is a single number, it must be positive.\")", "output size of each edge scale: range of size of", "ndarray): Image to be scaled. Returns: numpy ndarray: Rescaled image.", "scale (tuple): range of size of the origin size cropped", "is popularly used to train the Inception networks. Args: size:", "size else: raise ValueError('Unknown inputs for size: {}'.format(size)) self.interpolation =", "ratio of the origin aspect ratio cropped interpolation: Default: cv2.INTER_CUBIC", "Image after transformation. \"\"\" for op in self.transforms: im =", "An optional resampling filter. See `filters`_ for more information. If", "ratio=(3. / 4., 4. / 3.), interpolation=cv2.INTER_CUBIC): \"\"\" init \"\"\"", "if degrees < 0: raise ValueError( \"If degrees is a", "super().__init__(mode) def __clas__(self, img): \"\"\" Args: img (numpy ndarray): Image", "\"\"\" Args: img (numpy ndarray): Image to be cropped and", "if random.random() < self.prob: return F.vflip(img) return img @manager.TRANSFORMS.add_component class", "of input data to all operations is [height, width, channels].", "\"\"\" for op in self.transforms: im = op(im) return im", "min(img.shape[0], img.shape[1]) i = (img.shape[0] - w) // 2 j", "params_ret(i, j, h, w) # Fallback w = min(img.shape[0], img.shape[1])", "self.interpolation = interpolation self.scale = scale self.ratio = ratio super().__init__(mode)", "be of len 2.\") self.degrees = degrees self.center = center", "for a random rotation. Returns: sequence: params to be passed", "img @manager.TRANSFORMS.add_component class RandomResizedCrop(AbstractTransform): \"\"\"Crop the given numpy ndarray to", "the length of 'transforms' is less than 1. \"\"\" def", "omitted, make the output image the same size as the", "center and no translation. center (2-tuple, optional): Optional center of", "no transformation. to_rgb (bool, optional): If converting image to RGB", "(sequence or int): Desired output size. If size is a", "parameters for ``crop`` for a random sized crop. Args: img", "Args: img (numpy ndarray): Image to be cropped. scale (tuple):", "If omitted, or if the image has mode \"1\" or", "({cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_LANCZOS4}, optional): An optional resampling filter. See", "\"\"\" def __init__(self, mode, size, scale=(0.08, 1.0), ratio=(3. / 4.,", "``rotate`` for random rotation. \"\"\" angle = random.uniform(degrees[0], degrees[1]) return", "image. \"\"\" angle = self.get_params(self.degrees) return F.rotate(img, angle, self.center) @manager.TRANSFORMS.add_component", "It is either image path or image object. Returns: (np.array).", "img @manager.TRANSFORMS.add_component class RandomVerticalFlip(AbstractTransform): \"\"\"Vertically flip the given PIL Image", "Image to be cropped and resized. Returns: numpy ndarray: Randomly", "= interpolation super().__init__(mode) def __clas__(self, img): \"\"\" Args: img (numpy", "ValueError('Unknown inputs for size: {}'.format(size)) self.interpolation = interpolation super().__init__(mode) def", "OR CONDITIONS OF ANY KIND, either express or implied. #", "given size. Args: size (sequence or int): Desired output size.", "j, w, w) def __clas__(self, img): \"\"\" Args: img (numpy", "is a sequence like (h, w), output size will be", "a sequence, it must be of len 2.\") self.degrees =", "or float or int): Range of degrees to select from.", "the License is distributed on an \"AS IS\" BASIS, #", "int) or (isinstance(size, collections.Iterable) and len(size) == 2) if isinstance(size,", "/ 4., 4. / 3.), interpolation=cv2.INTER_CUBIC): \"\"\" init \"\"\" self.size", "data pre-processing or augmentation. Empty list means only reading images,", "im): \"\"\" Args: im (np.ndarray): It is either image path", "= interpolation self.scale = scale self.ratio = ratio super().__init__(mode) def", "expands the output to make it large enough to hold", "pre-processing and augmentation operations. The shape of input data to", "angle = random.uniform(degrees[0], degrees[1]) return angle def __clas__(self, img): \"\"\"", "Returns: numpy ndarray: Randomly cropped and resized image. \"\"\" i,", "1.0), ratio=(3. / 4., 4. / 3.), interpolation=cv2.INTER_CUBIC): \"\"\" init", "collections import random import math import cv2 from . import", "size cropped ratio: range of aspect ratio of the origin", "h, w) # Fallback w = min(img.shape[0], img.shape[1]) i =", "tuple: params (i, j, h, w) to be passed to", "of the origin aspect ratio cropped Returns: tuple: params (i,", "range(10): area = img.shape[0] * img.shape[1] target_area = random.uniform(*scale) *", "this. If size is an int, smaller edge of the", "ValueError( \"If degrees is a single number, it must be", "- w) // 2 j = (img.shape[1] - w) //", "collections.abc.Iterable) and len(size) == 2: if type(size) == list: size", "math import cv2 from . import functional as F from", "a sequence like (h, w), output size will be matched", "import functional as F from easymia.core.abstract_transforms import AbstractTransform from easymia.libs", "interpolation \"\"\" def __init__(self, mode, size, interpolation=cv2.INTER_LINEAR): \"\"\" resize \"\"\"", "and no translation. center (2-tuple, optional): Optional center of rotation.", "Args: img (numpy ndarray): Image to be scaled. Returns: numpy", "# -*-coding utf-8 -*- ########################################################################## # # Copyright (c) 2022", "import AbstractTransform from easymia.libs import manager @manager.TRANSFORMS.add_component class Compose(AbstractTransform): \"\"\"", "list!') self.transforms = transforms super().__init__(mode) def __clas__(self, im): \"\"\" Args:", "crop. Args: img (numpy ndarray): Image to be cropped. scale", "as the input image. Note that the expand flag assumes", "aspect ratio cropped Returns: tuple: params (i, j, h, w)", "img.shape[0]: i = random.randint(0, img.shape[0] - h) j = random.randint(0,", "Args: size (sequence or int): Desired output size. If size", "import math import cv2 from . import functional as F", "law or agreed to in writing, software # distributed under", "like (min, max), the range of degrees will be (-degrees,", "an int, smaller edge of the image will be matched", "\"\"\" def __init__(self, mode, size, interpolation=cv2.INTER_LINEAR): \"\"\" resize \"\"\" #", "to select from. If degrees is a number instead of", "number instead of sequence like (min, max), the range of", "under the License. # ########################################################################## \"\"\" 数据变换器 \"\"\" import numpy", "or augmentation. Empty list means only reading images, no transformation.", "permissions and # limitations under the License. # ########################################################################## \"\"\"", "4., 4. / 3.), interpolation=cv2.INTER_CUBIC): \"\"\" init \"\"\" self.size =", "is a single number, it must be positive.\") self.degrees =", "Returns: tuple: params (i, j, h, w) to be passed", "self.size = size else: raise ValueError('Unknown inputs for size: {}'.format(size))", "is set to PIL.Image.NEAREST. expand (bool, optional): Optional expansion flag.", "\"\"\"Get parameters for ``crop`` for a random sized crop. Args:", "params (i, j, h, w) to be passed to ``crop``", "to PIL.Image.NEAREST. expand (bool, optional): Optional expansion flag. If true,", "* img.shape[1] target_area = random.uniform(*scale) * area aspect_ratio = random.uniform(*ratio)", "super().__init__(mode) def __clas__(self, im): \"\"\" Args: im (np.ndarray): It is", "if isinstance(size, int): self.size = (size, size) elif isinstance(size, collections.abc.Iterable)", "self.prob: return F.hflip(img) return img @manager.TRANSFORMS.add_component class RandomVerticalFlip(AbstractTransform): \"\"\"Vertically flip", "img (numpy ndarray): Image to be cropped. scale (tuple): range", "of sequence like (min, max), the range of degrees will", "of rotation. Origin is the upper left corner. Default is", "flipped image. \"\"\" if random.random() < self.prob: return F.hflip(img) return", "size of the origin size cropped ratio (tuple): range of", "to be flipped. Returns: numpy ndarray: Randomly flipped image. \"\"\"", "no translation. center (2-tuple, optional): Optional center of rotation. Origin", "self.prob = prob super().__init__(mode) def __clas__(self, img): \"\"\" Args: img", "a number instead of sequence like (min, max), the range", "pre-processing or augmentation. Empty list means only reading images, no", "* aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio))) if random.random() <", "number. i.e, if height > width, then image will be", "super().__init__(mode) def get_params(self, img, scale, ratio): \"\"\"Get parameters for ``crop``", "may obtain a copy of the License at # #", "Empty list means only reading images, no transformation. to_rgb (bool,", "if len(degrees) != 2: raise ValueError( \"If degrees is a", "Args: degrees (sequence or float or int): Range of degrees", "random rotation. \"\"\" angle = random.uniform(degrees[0], degrees[1]) return angle def", "of the origin aspect ratio cropped interpolation: Default: cv2.INTER_CUBIC \"\"\"", "(numpy ndarray): Image to be rotated. Returns: numpy ndarray: Rotated", "# Copyright (c) 2022 Baidu.com, Inc. All Rights Reserved #", "height > width, then image will be rescaled to (size", "ratio of the origin aspect ratio cropped Returns: tuple: params", "to be passed to ``rotate`` for random rotation. \"\"\" angle", "the input numpy ndarray to the given size. Args: size", "F.hflip(img) return img @manager.TRANSFORMS.add_component class RandomVerticalFlip(AbstractTransform): \"\"\"Vertically flip the given", "crop of random size (default: of 0.08 to 1.0) of", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "for attempt in range(10): area = img.shape[0] * img.shape[1] target_area", "(-degrees, +degrees). resample ({cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_LANCZOS4}, optional): An optional", "must be a list!') self.transforms = transforms super().__init__(mode) def __clas__(self,", "Default value is 0.5 \"\"\" def __init__(self, mode, prob=0.5): \"\"\"", "Randomly cropped and resized image. \"\"\" i, j, h, w", "center=None): \"\"\" init \"\"\" if isinstance(degrees, numbers.Number): if degrees <", "\"\"\" if random.random() < self.prob: return F.hflip(img) return img @manager.TRANSFORMS.add_component", "j = (img.shape[1] - w) // 2 return params_ret(i, j,", "elif isinstance(size, collections.abc.Iterable) and len(size) == 2: if type(size) ==", "may not use this file except in compliance with the", "aspect ratio is made. This crop is finally resized to", "cv2.INTER_LANCZOS4}, optional): An optional resampling filter. See `filters`_ for more", "length of 'transforms' is less than 1. \"\"\" def __init__(self,", "j = random.randint(0, img.shape[1] - w) return params_ret(i, j, h,", "false or omitted, make the output image the same size", "the center and no translation. center (2-tuple, optional): Optional center", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "and a random aspect ratio (default: of 3/4 to 4/3)", "this file except in compliance with the License. # You", "\"\"\" init \"\"\" if isinstance(degrees, numbers.Number): if degrees < 0:", "w) // 2 j = (img.shape[1] - w) // 2", "int): self.size = (size, size) elif isinstance(size, collections.abc.Iterable) and len(size)", "size. This is popularly used to train the Inception networks.", "= scale self.ratio = ratio super().__init__(mode) def get_params(self, img, scale,", "self.center = center super().__init__(mode) @staticmethod def get_params(degrees): \"\"\"Get parameters for", "corresponding pre-processing and augmentation operations. The shape of input data", "cv2 from . import functional as F from easymia.core.abstract_transforms import", "@manager.TRANSFORMS.add_component class Compose(AbstractTransform): \"\"\" Do transformation on input data with", "limitations under the License. # ########################################################################## \"\"\" 数据变换器 \"\"\" import", "expected output size of each edge scale: range of size", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "the origin aspect ratio cropped interpolation: Default: cv2.INTER_CUBIC \"\"\" def", "easymia.core.abstract_transforms import AbstractTransform from easymia.libs import manager @manager.TRANSFORMS.add_component class Compose(AbstractTransform):", "degrees[1]) return angle def __clas__(self, img): \"\"\" img (numpy ndarray):", "# # Licensed under the Apache License, Version 2.0 (the", "h, w, self.size, self.interpolation) @manager.TRANSFORMS.add_component class RandomRotation(AbstractTransform): \"\"\"Rotate the image", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "img, scale, ratio): \"\"\"Get parameters for ``crop`` for a random", "ratio super().__init__(mode) def get_params(self, img, scale, ratio): \"\"\"Get parameters for", "augmentation operations. The shape of input data to all operations", "0.5: w, h = h, w if w <= img.shape[1]", "aspect_ratio))) if random.random() < 0.5: w, h = h, w", "j, h, w) # Fallback w = min(img.shape[0], img.shape[1]) i", "instead of sequence like (min, max), the range of degrees", "of size of the origin size cropped ratio: range of", "op in self.transforms: im = op(im) return im @manager.TRANSFORMS.add_component class", "(sequence or float or int): Range of degrees to select", "Default is ``cv2.INTER_CUBIC``, bicubic interpolation \"\"\" def __init__(self, mode, size,", "else: raise ValueError('Unknown inputs for size: {}'.format(size)) self.interpolation = interpolation", "be passed to ``rotate`` for random rotation. \"\"\" angle =", "the Inception networks. Args: size: expected output size of each", "(isinstance(size, collections.Iterable) and len(size) == 2) if isinstance(size, int): self.size", "Note that the expand flag assumes rotation around the center", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "import cv2 from . import functional as F from easymia.core.abstract_transforms", "input data to all operations is [height, width, channels]. Args:", "random.uniform(*ratio) w = int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area /", "crop. \"\"\" params_ret = collections.namedtuple('params_ret', ['i', 'j', 'h', 'w']) for", "must be positive.\") self.degrees = (-degrees, degrees) else: if len(degrees)", "size) interpolation (int, optional): Desired interpolation. Default is ``cv2.INTER_CUBIC``, bicubic", "1.0) of the original size and a random aspect ratio", "PIL Image randomly with a given probability. Args: p (float):", "either image path or image object. Returns: (np.array). Image after", "class RandomHorizontalFlip(AbstractTransform): \"\"\"Horizontally flip the given PIL Image randomly with", "RandomHorizontalFlip(AbstractTransform): \"\"\"Horizontally flip the given PIL Image randomly with a", "select from. If degrees is a number instead of sequence", "more information. If omitted, or if the image has mode", "\"\"\" Args: img (numpy ndarray): Image to be scaled. Returns:", "the origin size cropped ratio: range of aspect ratio of", "j, h, w) to be passed to ``crop`` for a", "# Fallback w = min(img.shape[0], img.shape[1]) i = (img.shape[0] -", "'transforms' is not a list. ValueError: when the length of", "is less than 1. \"\"\" def __init__(self, mode, transforms): if", "(size, size) self.interpolation = interpolation self.scale = scale self.ratio =", "for more information. If omitted, or if the image has", "raise ValueError( \"If degrees is a single number, it must", "Returns: numpy ndarray: Rescaled image. \"\"\" return F.resize(img, self.size, self.interpolation)", "ratio): \"\"\"Get parameters for ``crop`` for a random sized crop.", "if height > width, then image will be rescaled to", "must be of len 2.\") self.degrees = degrees self.center =", "(2-tuple, optional): Optional center of rotation. Origin is the upper", "entire rotated image. If false or omitted, make the output", "is finally resized to given size. This is popularly used", "random sized crop. Args: img (numpy ndarray): Image to be", "__clas__(self, img): \"\"\" img (numpy ndarray): Image to be rotated.", "def get_params(self, img, scale, ratio): \"\"\"Get parameters for ``crop`` for", "(bool, optional): Optional expansion flag. If true, expands the output", "########################################################################## \"\"\" 数据变换器 \"\"\" import numpy as np import numbers", "Fallback w = min(img.shape[0], img.shape[1]) i = (img.shape[0] - w)", "of 'transforms' is less than 1. \"\"\" def __init__(self, mode,", "int): Desired output size. If size is a sequence like", "popularly used to train the Inception networks. Args: size: expected", "'transforms' is less than 1. \"\"\" def __init__(self, mode, transforms):", "(int, optional): Desired interpolation. Default is ``cv2.INTER_CUBIC``, bicubic interpolation \"\"\"", "(numpy ndarray): Image to be flipped. Returns: numpy ndarray: Randomly", "2 return params_ret(i, j, w, w) def __clas__(self, img): \"\"\"", "\"\"\"Horizontally flip the given PIL Image randomly with a given", "return params_ret(i, j, w, w) def __clas__(self, img): \"\"\" Args:", "optional resampling filter. See `filters`_ for more information. If omitted,", "be cropped and resized. Returns: numpy ndarray: Randomly cropped and", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "raise TypeError('The transforms must be a list!') self.transforms = transforms", "degrees to select from. If degrees is a number instead", "the entire rotated image. If false or omitted, make the", "# assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) ==", "random size and aspect ratio. A crop of random size", "params to be passed to ``rotate`` for random rotation. \"\"\"", "be flipped. Returns: numpy ndarray: Randomly flipped image. \"\"\" if", "and aspect ratio. A crop of random size (default: of", "(np.ndarray): It is either image path or image object. Returns:", "to the given size. Args: size (sequence or int): Desired", "or implied. # See the License for the specific language", "(c) 2022 Baidu.com, Inc. All Rights Reserved # # Licensed", "w) def __clas__(self, img): \"\"\" Args: img (numpy ndarray): Image", "(size, size) elif isinstance(size, collections.abc.Iterable) and len(size) == 2: if", "ndarray): Image to be flipped. Returns: numpy ndarray: Randomly flipped", "\"\"\" def __init__(self, mode, degrees, center=None): \"\"\" init \"\"\" if", "__clas__(self, img): \"\"\" Args: img (numpy ndarray): Image to be", "random.uniform(degrees[0], degrees[1]) return angle def __clas__(self, img): \"\"\" img (numpy", "will be rescaled to (size * height / width, size)", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "Desired interpolation. Default is ``cv2.INTER_CUBIC``, bicubic interpolation \"\"\" def __init__(self,", "return F.hflip(img) return img @manager.TRANSFORMS.add_component class RandomVerticalFlip(AbstractTransform): \"\"\"Vertically flip the", "original aspect ratio is made. This crop is finally resized", "def __clas__(self, im): \"\"\" Args: im (np.ndarray): It is either", "size and aspect ratio. A crop of random size (default:", "= self.get_params(img, self.scale, self.ratio) return F.resized_crop(img, i, j, h, w,", "output image the same size as the input image. Note", "== list: size = tuple(size) self.size = size else: raise", "= min(img.shape[0], img.shape[1]) i = (img.shape[0] - w) // 2", "random sized crop. \"\"\" params_ret = collections.namedtuple('params_ret', ['i', 'j', 'h',", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "origin aspect ratio cropped Returns: tuple: params (i, j, h,", "origin size cropped ratio: range of aspect ratio of the", "h = h, w if w <= img.shape[1] and h", "corner. Default is the center of the image. \"\"\" def", "scaled. Returns: numpy ndarray: Rescaled image. \"\"\" return F.resize(img, self.size,", "image. \"\"\" if random.random() < self.prob: return F.hflip(img) return img", "0: raise ValueError( \"If degrees is a single number, it", "(the \"License\"); # you may not use this file except", "matched to this. If size is an int, smaller edge", "manager @manager.TRANSFORMS.add_component class Compose(AbstractTransform): \"\"\" Do transformation on input data", "float or int): Range of degrees to select from. If", "for size: {}'.format(size)) self.interpolation = interpolation super().__init__(mode) def __clas__(self, img):", "# you may not use this file except in compliance", "\"\"\" def __init__(self, mode, prob=0.5): \"\"\" init \"\"\" self.prob =", "to be rotated. Returns: numpy ndarray: Rotated image. \"\"\" angle", "easymia.libs import manager @manager.TRANSFORMS.add_component class Compose(AbstractTransform): \"\"\" Do transformation on", "i = (img.shape[0] - w) // 2 j = (img.shape[1]", "cropped and resized. Returns: numpy ndarray: Randomly cropped and resized", "import manager @manager.TRANSFORMS.add_component class Compose(AbstractTransform): \"\"\" Do transformation on input", "random.randint(0, img.shape[0] - h) j = random.randint(0, img.shape[1] - w)", "self.transforms = transforms super().__init__(mode) def __clas__(self, im): \"\"\" Args: im", "-*-coding utf-8 -*- ########################################################################## # # Copyright (c) 2022 Baidu.com,", "im @manager.TRANSFORMS.add_component class RandomHorizontalFlip(AbstractTransform): \"\"\"Horizontally flip the given PIL Image", "PIL.Image.NEAREST. expand (bool, optional): Optional expansion flag. If true, expands", "from . import functional as F from easymia.core.abstract_transforms import AbstractTransform", "get_params(degrees): \"\"\"Get parameters for ``rotate`` for a random rotation. Returns:", "be rotated. Returns: numpy ndarray: Rotated image. \"\"\" angle =", "color space. Default: True. Raises: TypeError: When 'transforms' is not", "A list contains data pre-processing or augmentation. Empty list means", "of the original aspect ratio is made. This crop is", "\"\"\" init \"\"\" self.size = (size, size) self.interpolation = interpolation", "Image to be cropped. scale (tuple): range of size of", "image has mode \"1\" or \"P\", it is set to", "center super().__init__(mode) @staticmethod def get_params(degrees): \"\"\"Get parameters for ``rotate`` for", "the origin aspect ratio cropped Returns: tuple: params (i, j,", "to ``crop`` for a random sized crop. \"\"\" params_ret =", "operations. The shape of input data to all operations is", "Args: img (numpy ndarray): Image to be flipped. Returns: numpy", "== 2: if type(size) == list: size = tuple(size) self.size", "value is 0.5 \"\"\" def __init__(self, mode, prob=0.5): \"\"\" init", "\"\"\"Resize the input numpy ndarray to the given size. Args:", "import numbers import collections import random import math import cv2", "flag assumes rotation around the center and no translation. center", "# # Unless required by applicable law or agreed to", "@manager.TRANSFORMS.add_component class RandomRotation(AbstractTransform): \"\"\"Rotate the image by angle. Args: degrees", "aspect ratio (default: of 3/4 to 4/3) of the original", "/ aspect_ratio))) if random.random() < 0.5: w, h = h,", "for ``rotate`` for a random rotation. Returns: sequence: params to", "networks. Args: size: expected output size of each edge scale:", "like (h, w), output size will be matched to this.", "// 2 return params_ret(i, j, w, w) def __clas__(self, img):", "return F.vflip(img) return img @manager.TRANSFORMS.add_component class RandomResizedCrop(AbstractTransform): \"\"\"Crop the given", "ndarray): Image to be rotated. Returns: numpy ndarray: Rotated image.", "ndarray: Rotated image. \"\"\" angle = self.get_params(self.degrees) return F.rotate(img, angle,", "size (default: of 0.08 to 1.0) of the original size", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "mode, degrees, center=None): \"\"\" init \"\"\" if isinstance(degrees, numbers.Number): if", "sequence: params to be passed to ``rotate`` for random rotation.", "\"\"\" if isinstance(degrees, numbers.Number): if degrees < 0: raise ValueError(", "ratio (default: of 3/4 to 4/3) of the original aspect", "- h) j = random.randint(0, img.shape[1] - w) return params_ret(i,", "sequence like (h, w), output size will be matched to", "aspect ratio cropped interpolation: Default: cv2.INTER_CUBIC \"\"\" def __init__(self, mode,", "Version 2.0 (the \"License\"); # you may not use this", "RandomResizedCrop(AbstractTransform): \"\"\"Crop the given numpy ndarray to random size and", "= self.get_params(self.degrees) return F.rotate(img, angle, self.center) @manager.TRANSFORMS.add_component class Resize(AbstractTransform): \"\"\"Resize", "of aspect ratio of the origin aspect ratio cropped interpolation:", "2 j = (img.shape[1] - w) // 2 return params_ret(i,", "\"\"\"Get parameters for ``rotate`` for a random rotation. Returns: sequence:", "randomly with a given probability. Args: p (float): probability of", "the expand flag assumes rotation around the center and no", "will be (-degrees, +degrees). resample ({cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_LANCZOS4}, optional):", "Returns: sequence: params to be passed to ``rotate`` for random", "Range of degrees to select from. If degrees is a", "output size. If size is a sequence like (h, w),", "probability of the image being flipped. Default value is 0.5", "and # limitations under the License. # ########################################################################## \"\"\" 数据变换器", "w, self.size, self.interpolation) @manager.TRANSFORMS.add_component class RandomRotation(AbstractTransform): \"\"\"Rotate the image by", "random.random() < 0.5: w, h = h, w if w", "interpolation super().__init__(mode) def __clas__(self, img): \"\"\" Args: img (numpy ndarray):", "optional): Desired interpolation. Default is ``cv2.INTER_CUBIC``, bicubic interpolation \"\"\" def", "degrees is a single number, it must be positive.\") self.degrees", "Default: cv2.INTER_CUBIC \"\"\" def __init__(self, mode, size, scale=(0.08, 1.0), ratio=(3.", "implied. # See the License for the specific language governing", "to this. If size is an int, smaller edge of", "and augmentation operations. The shape of input data to all", "under the Apache License, Version 2.0 (the \"License\"); # you", "interpolation=cv2.INTER_LINEAR): \"\"\" resize \"\"\" # assert isinstance(size, int) or (isinstance(size,", "F from easymia.core.abstract_transforms import AbstractTransform from easymia.libs import manager @manager.TRANSFORMS.add_component", "def __init__(self, mode, size, scale=(0.08, 1.0), ratio=(3. / 4., 4.", "be positive.\") self.degrees = (-degrees, degrees) else: if len(degrees) !=", "random size (default: of 0.08 to 1.0) of the original", "as F from easymia.core.abstract_transforms import AbstractTransform from easymia.libs import manager", "``crop`` for a random sized crop. Args: img (numpy ndarray):", "init \"\"\" if isinstance(degrees, numbers.Number): if degrees < 0: raise", "def __clas__(self, img): \"\"\" img (numpy ndarray): Image to be", "angle. Args: degrees (sequence or float or int): Range of", "'w']) for attempt in range(10): area = img.shape[0] * img.shape[1]", "rotated image. If false or omitted, make the output image", "is an int, smaller edge of the image will be", "inputs for size: {}'.format(size)) self.interpolation = interpolation super().__init__(mode) def __clas__(self,", "optional): An optional resampling filter. See `filters`_ for more information.", "cropped interpolation: Default: cv2.INTER_CUBIC \"\"\" def __init__(self, mode, size, scale=(0.08,", "positive.\") self.degrees = (-degrees, degrees) else: if len(degrees) != 2:", "after transformation. \"\"\" for op in self.transforms: im = op(im)", "by applicable law or agreed to in writing, software #", "+degrees). resample ({cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_LANCZOS4}, optional): An optional resampling", "* height / width, size) interpolation (int, optional): Desired interpolation.", "Image randomly with a given probability. Args: p (float): probability", "w) # Fallback w = min(img.shape[0], img.shape[1]) i = (img.shape[0]", "smaller edge of the image will be matched to this", "numbers.Number): if degrees < 0: raise ValueError( \"If degrees is", "from. If degrees is a number instead of sequence like", "@manager.TRANSFORMS.add_component class Resize(AbstractTransform): \"\"\"Resize the input numpy ndarray to the", "return img @manager.TRANSFORMS.add_component class RandomResizedCrop(AbstractTransform): \"\"\"Crop the given numpy ndarray", "img): \"\"\" Args: img (numpy ndarray): Image to be scaled.", "h) j = random.randint(0, img.shape[1] - w) return params_ret(i, j,", "return F.resized_crop(img, i, j, h, w, self.size, self.interpolation) @manager.TRANSFORMS.add_component class", "numbers import collections import random import math import cv2 from", "assumes rotation around the center and no translation. center (2-tuple,", "F.rotate(img, angle, self.center) @manager.TRANSFORMS.add_component class Resize(AbstractTransform): \"\"\"Resize the input numpy", "transforms super().__init__(mode) def __clas__(self, im): \"\"\" Args: im (np.ndarray): It", "(default: of 3/4 to 4/3) of the original aspect ratio", "img.shape[0] - h) j = random.randint(0, img.shape[1] - w) return", "only reading images, no transformation. to_rgb (bool, optional): If converting", "img): \"\"\" Args: img (numpy ndarray): Image to be flipped.", "degrees (sequence or float or int): Range of degrees to", "ratio: range of aspect ratio of the origin aspect ratio", "Optional center of rotation. Origin is the upper left corner.", "Randomly flipped image. \"\"\" if random.random() < self.prob: return F.vflip(img)", "random.randint(0, img.shape[1] - w) return params_ret(i, j, h, w) #", "int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio))) if random.random()", "image. \"\"\" i, j, h, w = self.get_params(img, self.scale, self.ratio)", "be rescaled to (size * height / width, size) interpolation", "of the image being flipped. Default value is 0.5 \"\"\"", "(size * height / width, size) interpolation (int, optional): Desired", "F.resized_crop(img, i, j, h, w, self.size, self.interpolation) @manager.TRANSFORMS.add_component class RandomRotation(AbstractTransform):", "degrees, center=None): \"\"\" init \"\"\" if isinstance(degrees, numbers.Number): if degrees", "be scaled. Returns: numpy ndarray: Rescaled image. \"\"\" return F.resize(img,", "AbstractTransform from easymia.libs import manager @manager.TRANSFORMS.add_component class Compose(AbstractTransform): \"\"\" Do", "means only reading images, no transformation. to_rgb (bool, optional): If", "size and a random aspect ratio (default: of 3/4 to", "random.random() < self.prob: return F.vflip(img) return img @manager.TRANSFORMS.add_component class RandomResizedCrop(AbstractTransform):", "on input data with corresponding pre-processing and augmentation operations. The", "made. This crop is finally resized to given size. This", "- w) // 2 return params_ret(i, j, w, w) def", "def get_params(degrees): \"\"\"Get parameters for ``rotate`` for a random rotation.", "with a given probability. Args: p (float): probability of the", "assert isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)", "get_params(self, img, scale, ratio): \"\"\"Get parameters for ``crop`` for a", "for a random sized crop. Args: img (numpy ndarray): Image", "be passed to ``crop`` for a random sized crop. \"\"\"", "return F.rotate(img, angle, self.center) @manager.TRANSFORMS.add_component class Resize(AbstractTransform): \"\"\"Resize the input", "that the expand flag assumes rotation around the center and", "w, h = h, w if w <= img.shape[1] and", "ValueError( \"If degrees is a sequence, it must be of", "self.size = (size, size) elif isinstance(size, collections.abc.Iterable) and len(size) ==", "< 0.5: w, h = h, w if w <=", "interpolation=cv2.INTER_CUBIC): \"\"\" init \"\"\" self.size = (size, size) self.interpolation =", "img.shape[1] and h <= img.shape[0]: i = random.randint(0, img.shape[0] -", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "degrees < 0: raise ValueError( \"If degrees is a single", "img): \"\"\" img (numpy ndarray): Image to be rotated. Returns:", "than 1. \"\"\" def __init__(self, mode, transforms): if not isinstance(transforms,", "ValueError: when the length of 'transforms' is less than 1.", "\"\"\" i, j, h, w = self.get_params(img, self.scale, self.ratio) return", "Rights Reserved # # Licensed under the Apache License, Version", "Unless required by applicable law or agreed to in writing,", "given PIL Image randomly with a given probability. Args: p", "when the length of 'transforms' is less than 1. \"\"\"", "set to PIL.Image.NEAREST. expand (bool, optional): Optional expansion flag. If", "size: {}'.format(size)) self.interpolation = interpolation super().__init__(mode) def __clas__(self, img): \"\"\"", "(float): probability of the image being flipped. Default value is", ". import functional as F from easymia.core.abstract_transforms import AbstractTransform from", "be matched to this. If size is an int, smaller", "operations is [height, width, channels]. Args: transforms (list): A list", "interpolation self.scale = scale self.ratio = ratio super().__init__(mode) def get_params(self,", "img (numpy ndarray): Image to be scaled. Returns: numpy ndarray:", "optional): Optional center of rotation. Origin is the upper left", "of len 2.\") self.degrees = degrees self.center = center super().__init__(mode)", "to this number. i.e, if height > width, then image", "size) self.interpolation = interpolation self.scale = scale self.ratio = ratio", "scale, ratio): \"\"\"Get parameters for ``crop`` for a random sized", "isinstance(degrees, numbers.Number): if degrees < 0: raise ValueError( \"If degrees", "cropped Returns: tuple: params (i, j, h, w) to be", "the image will be matched to this number. i.e, if", "degrees will be (-degrees, +degrees). resample ({cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_LANCZOS4},", "the specific language governing permissions and # limitations under the", "Image to be rotated. Returns: numpy ndarray: Rotated image. \"\"\"", "self.transforms: im = op(im) return im @manager.TRANSFORMS.add_component class RandomHorizontalFlip(AbstractTransform): \"\"\"Horizontally", "governing permissions and # limitations under the License. # ##########################################################################", "A crop of random size (default: of 0.08 to 1.0)", "be matched to this number. i.e, if height > width,", "origin size cropped ratio (tuple): range of aspect ratio of", "applicable law or agreed to in writing, software # distributed", "rotation. Origin is the upper left corner. Default is the", "input image. Note that the expand flag assumes rotation around", "# ########################################################################## \"\"\" 数据变换器 \"\"\" import numpy as np import", "rotated. Returns: numpy ndarray: Rotated image. \"\"\" angle = self.get_params(self.degrees)", "mode \"1\" or \"P\", it is set to PIL.Image.NEAREST. expand", "interpolation. Default is ``cv2.INTER_CUBIC``, bicubic interpolation \"\"\" def __init__(self, mode,", "size is a sequence like (h, w), output size will", "def __init__(self, mode, size, interpolation=cv2.INTER_LINEAR): \"\"\" resize \"\"\" # assert", "self.degrees = degrees self.center = center super().__init__(mode) @staticmethod def get_params(degrees):", "from easymia.libs import manager @manager.TRANSFORMS.add_component class Compose(AbstractTransform): \"\"\" Do transformation", "self.size = (size, size) self.interpolation = interpolation self.scale = scale", "rotation. Returns: sequence: params to be passed to ``rotate`` for", "rotation. \"\"\" angle = random.uniform(degrees[0], degrees[1]) return angle def __clas__(self,", "for ``crop`` for a random sized crop. Args: img (numpy", "self.ratio = ratio super().__init__(mode) def get_params(self, img, scale, ratio): \"\"\"Get", "a single number, it must be positive.\") self.degrees = (-degrees,", "in writing, software # distributed under the License is distributed", "= (img.shape[1] - w) // 2 return params_ret(i, j, w,", "large enough to hold the entire rotated image. If false", "RGB color space. Default: True. Raises: TypeError: When 'transforms' is", "to 4/3) of the original aspect ratio is made. This", "@manager.TRANSFORMS.add_component class RandomHorizontalFlip(AbstractTransform): \"\"\"Horizontally flip the given PIL Image randomly", "size will be matched to this. If size is an", "import numpy as np import numbers import collections import random", "\"\"\" Do transformation on input data with corresponding pre-processing and", "size: expected output size of each edge scale: range of", "image being flipped. Default value is 0.5 \"\"\" def __init__(self,", "matched to this number. i.e, if height > width, then", "of 0.08 to 1.0) of the original size and a", "self.prob: return F.vflip(img) return img @manager.TRANSFORMS.add_component class RandomResizedCrop(AbstractTransform): \"\"\"Crop the", "image to RGB color space. Default: True. Raises: TypeError: When", "or omitted, make the output image the same size as", "p (float): probability of the image being flipped. Default value", "3.), interpolation=cv2.INTER_CUBIC): \"\"\" init \"\"\" self.size = (size, size) self.interpolation", "Rotated image. \"\"\" angle = self.get_params(self.degrees) return F.rotate(img, angle, self.center)", "width, then image will be rescaled to (size * height", "interpolation (int, optional): Desired interpolation. Default is ``cv2.INTER_CUBIC``, bicubic interpolation", "bicubic interpolation \"\"\" def __init__(self, mode, size, interpolation=cv2.INTER_LINEAR): \"\"\" resize", "it large enough to hold the entire rotated image. If", "of degrees to select from. If degrees is a number", "img (numpy ndarray): Image to be rotated. Returns: numpy ndarray:", "to all operations is [height, width, channels]. Args: transforms (list):", "transformation on input data with corresponding pre-processing and augmentation operations.", "a list. ValueError: when the length of 'transforms' is less", "image by angle. Args: degrees (sequence or float or int):", "isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2) if", "= ratio super().__init__(mode) def get_params(self, img, scale, ratio): \"\"\"Get parameters", "a random rotation. Returns: sequence: params to be passed to", "isinstance(size, int): self.size = (size, size) elif isinstance(size, collections.abc.Iterable) and", "2) if isinstance(size, int): self.size = (size, size) elif isinstance(size,", "init \"\"\" self.size = (size, size) self.interpolation = interpolation self.scale", "w) // 2 return params_ret(i, j, w, w) def __clas__(self,", "(bool, optional): If converting image to RGB color space. Default:", "the range of degrees will be (-degrees, +degrees). resample ({cv2.INTER_NEAREST,", "type(size) == list: size = tuple(size) self.size = size else:", "the image has mode \"1\" or \"P\", it is set", "a given probability. Args: p (float): probability of the image", "is made. This crop is finally resized to given size.", "omitted, or if the image has mode \"1\" or \"P\",", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "= transforms super().__init__(mode) def __clas__(self, im): \"\"\" Args: im (np.ndarray):", "then image will be rescaled to (size * height /", "raise ValueError( \"If degrees is a sequence, it must be", "License, Version 2.0 (the \"License\"); # you may not use", "the output to make it large enough to hold the", "数据变换器 \"\"\" import numpy as np import numbers import collections", "\"\"\"Vertically flip the given PIL Image randomly with a given", "# You may obtain a copy of the License at", "0.08 to 1.0) of the original size and a random", "See `filters`_ for more information. If omitted, or if the", "w = self.get_params(img, self.scale, self.ratio) return F.resized_crop(img, i, j, h,", "init \"\"\" self.prob = prob super().__init__(mode) def __clas__(self, img): \"\"\"", "self.size, self.interpolation) @manager.TRANSFORMS.add_component class RandomRotation(AbstractTransform): \"\"\"Rotate the image by angle.", "= (size, size) elif isinstance(size, collections.abc.Iterable) and len(size) == 2:", "transforms): if not isinstance(transforms, list): raise TypeError('The transforms must be", "the input image. Note that the expand flag assumes rotation", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "ndarray): Image to be cropped and resized. Returns: numpy ndarray:", "object. Returns: (np.array). Image after transformation. \"\"\" for op in", "def __init__(self, mode, prob=0.5): \"\"\" init \"\"\" self.prob = prob", "resampling filter. See `filters`_ for more information. If omitted, or", "aspect ratio of the origin aspect ratio cropped interpolation: Default:", "transformation. to_rgb (bool, optional): If converting image to RGB color", "op(im) return im @manager.TRANSFORMS.add_component class RandomHorizontalFlip(AbstractTransform): \"\"\"Horizontally flip the given", "resized image. \"\"\" i, j, h, w = self.get_params(img, self.scale,", "= center super().__init__(mode) @staticmethod def get_params(degrees): \"\"\"Get parameters for ``rotate``", "random import math import cv2 from . import functional as", "optional): Optional expansion flag. If true, expands the output to", "\"If degrees is a sequence, it must be of len", "= random.randint(0, img.shape[0] - h) j = random.randint(0, img.shape[1] -", "self.interpolation) @manager.TRANSFORMS.add_component class RandomRotation(AbstractTransform): \"\"\"Rotate the image by angle. Args:", "Reserved # # Licensed under the Apache License, Version 2.0", "cv2.INTER_CUBIC, cv2.INTER_LANCZOS4}, optional): An optional resampling filter. See `filters`_ for", "the original size and a random aspect ratio (default: of", "the License for the specific language governing permissions and #", "be (-degrees, +degrees). resample ({cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_LANCZOS4}, optional): An", "TypeError('The transforms must be a list!') self.transforms = transforms super().__init__(mode)", "to (size * height / width, size) interpolation (int, optional):", "Apache License, Version 2.0 (the \"License\"); # you may not", "-*- ########################################################################## # # Copyright (c) 2022 Baidu.com, Inc. All", "F.vflip(img) return img @manager.TRANSFORMS.add_component class RandomResizedCrop(AbstractTransform): \"\"\"Crop the given numpy", "either express or implied. # See the License for the", "> width, then image will be rescaled to (size *", "edge of the image will be matched to this number.", "w if w <= img.shape[1] and h <= img.shape[0]: i", "will be matched to this number. i.e, if height >", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "scale self.ratio = ratio super().__init__(mode) def get_params(self, img, scale, ratio):", "def __init__(self, mode, degrees, center=None): \"\"\" init \"\"\" if isinstance(degrees,", "__init__(self, mode, degrees, center=None): \"\"\" init \"\"\" if isinstance(degrees, numbers.Number):", "Resize(AbstractTransform): \"\"\"Resize the input numpy ndarray to the given size.", "If size is an int, smaller edge of the image", "len(size) == 2) if isinstance(size, int): self.size = (size, size)", "from easymia.core.abstract_transforms import AbstractTransform from easymia.libs import manager @manager.TRANSFORMS.add_component class", "by angle. Args: degrees (sequence or float or int): Range", "all operations is [height, width, channels]. Args: transforms (list): A", "``rotate`` for a random rotation. Returns: sequence: params to be", "augmentation. Empty list means only reading images, no transformation. to_rgb", "< self.prob: return F.hflip(img) return img @manager.TRANSFORMS.add_component class RandomVerticalFlip(AbstractTransform): \"\"\"Vertically", "not isinstance(transforms, list): raise TypeError('The transforms must be a list!')", "sized crop. \"\"\" params_ret = collections.namedtuple('params_ret', ['i', 'j', 'h', 'w'])", "range of size of the origin size cropped ratio: range", "is the center of the image. \"\"\" def __init__(self, mode,", "image object. Returns: (np.array). Image after transformation. \"\"\" for op", "Args: p (float): probability of the image being flipped. Default", "size, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.), interpolation=cv2.INTER_CUBIC):", "filter. See `filters`_ for more information. If omitted, or if", "this number. i.e, if height > width, then image will", "width, channels]. Args: transforms (list): A list contains data pre-processing", "size. Args: size (sequence or int): Desired output size. If", "import random import math import cv2 from . import functional", "and h <= img.shape[0]: i = random.randint(0, img.shape[0] - h)", "output size will be matched to this. If size is", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "aspect_ratio = random.uniform(*ratio) w = int(round(math.sqrt(target_area * aspect_ratio))) h =", "if not isinstance(transforms, list): raise TypeError('The transforms must be a", "or image object. Returns: (np.array). Image after transformation. \"\"\" for", "image the same size as the input image. Note that", "if isinstance(degrees, numbers.Number): if degrees < 0: raise ValueError( \"If", "= random.randint(0, img.shape[1] - w) return params_ret(i, j, h, w)", "def __init__(self, mode, transforms): if not isinstance(transforms, list): raise TypeError('The", "size (sequence or int): Desired output size. If size is", "of degrees will be (-degrees, +degrees). resample ({cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC,", "range of aspect ratio of the origin aspect ratio cropped", "2: raise ValueError( \"If degrees is a sequence, it must", "optional): If converting image to RGB color space. Default: True.", "* area aspect_ratio = random.uniform(*ratio) w = int(round(math.sqrt(target_area * aspect_ratio)))", "aspect ratio of the origin aspect ratio cropped Returns: tuple:", "attempt in range(10): area = img.shape[0] * img.shape[1] target_area =", "flip the given PIL Image randomly with a given probability.", "__init__(self, mode, prob=0.5): \"\"\" init \"\"\" self.prob = prob super().__init__(mode)", "random aspect ratio (default: of 3/4 to 4/3) of the", "``crop`` for a random sized crop. \"\"\" params_ret = collections.namedtuple('params_ret',", "random rotation. Returns: sequence: params to be passed to ``rotate``", "each edge scale: range of size of the origin size", "size. If size is a sequence like (h, w), output", "Inc. All Rights Reserved # # Licensed under the Apache", "w), output size will be matched to this. If size", "rescaled to (size * height / width, size) interpolation (int,", "ratio (tuple): range of aspect ratio of the origin aspect", "flag. If true, expands the output to make it large", "size as the input image. Note that the expand flag", "degrees is a number instead of sequence like (min, max),", "= size else: raise ValueError('Unknown inputs for size: {}'.format(size)) self.interpolation", "reading images, no transformation. to_rgb (bool, optional): If converting image", "self.degrees = (-degrees, degrees) else: if len(degrees) != 2: raise", "Copyright (c) 2022 Baidu.com, Inc. All Rights Reserved # #", "input data with corresponding pre-processing and augmentation operations. The shape", "given size. This is popularly used to train the Inception", "w <= img.shape[1] and h <= img.shape[0]: i = random.randint(0,", "\"License\"); # you may not use this file except in", "All Rights Reserved # # Licensed under the Apache License,", "Compose(AbstractTransform): \"\"\" Do transformation on input data with corresponding pre-processing", "\"\"\" angle = random.uniform(degrees[0], degrees[1]) return angle def __clas__(self, img):", "ndarray to random size and aspect ratio. A crop of", "\"\"\" angle = self.get_params(self.degrees) return F.rotate(img, angle, self.center) @manager.TRANSFORMS.add_component class", "self.center) @manager.TRANSFORMS.add_component class Resize(AbstractTransform): \"\"\"Resize the input numpy ndarray to", "numpy ndarray: Rotated image. \"\"\" angle = self.get_params(self.degrees) return F.rotate(img,", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "of each edge scale: range of size of the origin", "\"\"\" self.prob = prob super().__init__(mode) def __clas__(self, img): \"\"\" Args:", "Raises: TypeError: When 'transforms' is not a list. ValueError: when", "= int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area / aspect_ratio))) if", "== 2) if isinstance(size, int): self.size = (size, size) elif", "rotation around the center and no translation. center (2-tuple, optional):", "# distributed under the License is distributed on an \"AS", "__init__(self, mode, size, interpolation=cv2.INTER_LINEAR): \"\"\" resize \"\"\" # assert isinstance(size,", "angle, self.center) @manager.TRANSFORMS.add_component class Resize(AbstractTransform): \"\"\"Resize the input numpy ndarray", "to ``rotate`` for random rotation. \"\"\" angle = random.uniform(degrees[0], degrees[1])", "and resized. Returns: numpy ndarray: Randomly cropped and resized image.", "# Unless required by applicable law or agreed to in", "random.uniform(*scale) * area aspect_ratio = random.uniform(*ratio) w = int(round(math.sqrt(target_area *", "translation. center (2-tuple, optional): Optional center of rotation. Origin is", "i, j, h, w, self.size, self.interpolation) @manager.TRANSFORMS.add_component class RandomRotation(AbstractTransform): \"\"\"Rotate", "the output image the same size as the input image.", "image. \"\"\" def __init__(self, mode, degrees, center=None): \"\"\" init \"\"\"", "self.ratio) return F.resized_crop(img, i, j, h, w, self.size, self.interpolation) @manager.TRANSFORMS.add_component", "random.random() < self.prob: return F.hflip(img) return img @manager.TRANSFORMS.add_component class RandomVerticalFlip(AbstractTransform):", "the License. # ########################################################################## \"\"\" 数据变换器 \"\"\" import numpy as", "functional as F from easymia.core.abstract_transforms import AbstractTransform from easymia.libs import", "the image by angle. Args: degrees (sequence or float or", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "a random sized crop. \"\"\" params_ret = collections.namedtuple('params_ret', ['i', 'j',", "hold the entire rotated image. If false or omitted, make", "Inception networks. Args: size: expected output size of each edge", "prob super().__init__(mode) def __clas__(self, img): \"\"\" Args: img (numpy ndarray):", "the image. \"\"\" def __init__(self, mode, degrees, center=None): \"\"\" init", "\"\"\" params_ret = collections.namedtuple('params_ret', ['i', 'j', 'h', 'w']) for attempt", "degrees is a sequence, it must be of len 2.\")", "in self.transforms: im = op(im) return im @manager.TRANSFORMS.add_component class RandomHorizontalFlip(AbstractTransform):", "__init__(self, mode, size, scale=(0.08, 1.0), ratio=(3. / 4., 4. /", "You may obtain a copy of the License at #", "\"\"\" import numpy as np import numbers import collections import", "the given numpy ndarray to random size and aspect ratio.", "(-degrees, degrees) else: if len(degrees) != 2: raise ValueError( \"If", "j, h, w, self.size, self.interpolation) @manager.TRANSFORMS.add_component class RandomRotation(AbstractTransform): \"\"\"Rotate the", "Do transformation on input data with corresponding pre-processing and augmentation", "Args: size: expected output size of each edge scale: range", "size of the origin size cropped ratio: range of aspect", "= random.uniform(*ratio) w = int(round(math.sqrt(target_area * aspect_ratio))) h = int(round(math.sqrt(target_area", "the center of the image. \"\"\" def __init__(self, mode, degrees,", "is ``cv2.INTER_CUBIC``, bicubic interpolation \"\"\" def __init__(self, mode, size, interpolation=cv2.INTER_LINEAR):", "a random sized crop. Args: img (numpy ndarray): Image to", "a list!') self.transforms = transforms super().__init__(mode) def __clas__(self, im): \"\"\"", "parameters for ``rotate`` for a random rotation. Returns: sequence: params", "Default is the center of the image. \"\"\" def __init__(self,", "im = op(im) return im @manager.TRANSFORMS.add_component class RandomHorizontalFlip(AbstractTransform): \"\"\"Horizontally flip", "h, w) to be passed to ``crop`` for a random", "to be scaled. Returns: numpy ndarray: Rescaled image. \"\"\" return", "img): \"\"\" Args: img (numpy ndarray): Image to be cropped", "\"\"\" def __init__(self, mode, transforms): if not isinstance(transforms, list): raise", "Desired output size. If size is a sequence like (h,", "len(degrees) != 2: raise ValueError( \"If degrees is a sequence,", "list: size = tuple(size) self.size = size else: raise ValueError('Unknown", "converting image to RGB color space. Default: True. Raises: TypeError:", "True. Raises: TypeError: When 'transforms' is not a list. ValueError:", "of the origin size cropped ratio (tuple): range of aspect", "h <= img.shape[0]: i = random.randint(0, img.shape[0] - h) j", "the Apache License, Version 2.0 (the \"License\"); # you may", "\"\"\" Args: img (numpy ndarray): Image to be flipped. Returns:", "__clas__(self, im): \"\"\" Args: im (np.ndarray): It is either image", "<= img.shape[1] and h <= img.shape[0]: i = random.randint(0, img.shape[0]", "numpy ndarray to random size and aspect ratio. A crop", "(i, j, h, w) to be passed to ``crop`` for", "return im @manager.TRANSFORMS.add_component class RandomHorizontalFlip(AbstractTransform): \"\"\"Horizontally flip the given PIL", "or int): Range of degrees to select from. If degrees", "image will be rescaled to (size * height / width,", "aspect ratio. A crop of random size (default: of 0.08", "resized to given size. This is popularly used to train" ]
[ "in serialized_deposit assert serialized_deposit['mesh_terms'] == [ { 'data': {'source': 'MeSH',", "create_record( { 'terms': [ {'source': 'MeSH', 'value': 'Cognitive Neuroscience'}, {'source':", "serialize_terms_for_edit_ui(deposit) assert 'terms' not in serialized_deposit assert serialized_deposit['mesh_terms'] == []", "'terms' not in serialized_deposit assert serialized_deposit['mesh_terms'] == [] assert serialized_deposit['fast_terms']", "2018-present NU,FSM,GHSL. # # menRva is free software; you can", "Neuroscience'} } ] assert serialized_deposit['fast_terms'] == [ { 'data': {'source':", "} ] assert serialized_deposit['fast_terms'] == [ { 'data': {'source': 'FAST',", "'value': 'Cognitive Neuroscience'} } ] assert serialized_deposit['fast_terms'] == [ {", "# -*- coding: utf-8 -*- # # This file is", "can redistribute it and/or modify it # under the terms", "'data': {'source': 'MeSH', 'value': 'Cognitive Neuroscience'} } ] assert serialized_deposit['fast_terms']", "'value': 'Border terrier'} ] }, published=False ) serialized_deposit = serialize_terms_for_edit_ui(deposit)", "{'source': 'MeSH', 'value': 'Cognitive Neuroscience'}, {'source': 'FAST', 'value': 'Border terrier'}", "[ {'source': 'MeSH', 'value': 'Cognitive Neuroscience'}, {'source': 'FAST', 'value': 'Border", "import serialize_terms_for_edit_ui def test_serialize_terms_for_edit_ui(create_record): deposit = create_record( { 'terms': [", "assert 'terms' not in serialized_deposit assert serialized_deposit['mesh_terms'] == [] assert", "serialized_deposit['mesh_terms'] == [ { 'data': {'source': 'MeSH', 'value': 'Cognitive Neuroscience'}", "free software; you can redistribute it and/or modify it #", "serialized_deposit['fast_terms'] == [ { 'data': {'source': 'FAST', 'value': 'Border terrier'}", "more details. \"\"\"Test terms views.py\"\"\" from cd2h_repo_project.modules.terms.views import serialize_terms_for_edit_ui def", "= create_record( { 'terms': [ {'source': 'MeSH', 'value': 'Cognitive Neuroscience'},", "'Cognitive Neuroscience'}, {'source': 'FAST', 'value': 'Border terrier'} ] }, published=False", "'FAST', 'value': 'Border terrier'} } ] def test_serialize_terms_for_edit_ui_no_terms(create_record): deposit =", "not in serialized_deposit assert serialized_deposit['mesh_terms'] == [] assert serialized_deposit['fast_terms'] ==", "serialize_terms_for_edit_ui def test_serialize_terms_for_edit_ui(create_record): deposit = create_record( { 'terms': [ {'source':", "'MeSH', 'value': 'Cognitive Neuroscience'} } ] assert serialized_deposit['fast_terms'] == [", "} ] def test_serialize_terms_for_edit_ui_no_terms(create_record): deposit = create_record(published=False) serialized_deposit = serialize_terms_for_edit_ui(deposit)", "terrier'} ] }, published=False ) serialized_deposit = serialize_terms_for_edit_ui(deposit) assert 'terms'", "== [ { 'data': {'source': 'MeSH', 'value': 'Cognitive Neuroscience'} }", "'Cognitive Neuroscience'} } ] assert serialized_deposit['fast_terms'] == [ { 'data':", "LICENSE file for more details. \"\"\"Test terms views.py\"\"\" from cd2h_repo_project.modules.terms.views", "under the terms of the MIT License; see LICENSE file", "'terms': [ {'source': 'MeSH', 'value': 'Cognitive Neuroscience'}, {'source': 'FAST', 'value':", "License; see LICENSE file for more details. \"\"\"Test terms views.py\"\"\"", "you can redistribute it and/or modify it # under the", "of menRva. # Copyright (C) 2018-present NU,FSM,GHSL. # # menRva", "] }, published=False ) serialized_deposit = serialize_terms_for_edit_ui(deposit) assert 'terms' not", "test_serialize_terms_for_edit_ui(create_record): deposit = create_record( { 'terms': [ {'source': 'MeSH', 'value':", "file is part of menRva. # Copyright (C) 2018-present NU,FSM,GHSL.", "utf-8 -*- # # This file is part of menRva.", "serialize_terms_for_edit_ui(deposit) assert 'terms' not in serialized_deposit assert serialized_deposit['mesh_terms'] == [", "coding: utf-8 -*- # # This file is part of", "file for more details. \"\"\"Test terms views.py\"\"\" from cd2h_repo_project.modules.terms.views import", "MIT License; see LICENSE file for more details. \"\"\"Test terms", "NU,FSM,GHSL. # # menRva is free software; you can redistribute", "'Border terrier'} ] }, published=False ) serialized_deposit = serialize_terms_for_edit_ui(deposit) assert", "menRva. # Copyright (C) 2018-present NU,FSM,GHSL. # # menRva is", "(C) 2018-present NU,FSM,GHSL. # # menRva is free software; you", "# Copyright (C) 2018-present NU,FSM,GHSL. # # menRva is free", "-*- coding: utf-8 -*- # # This file is part", "serialized_deposit = serialize_terms_for_edit_ui(deposit) assert 'terms' not in serialized_deposit assert serialized_deposit['mesh_terms']", "is free software; you can redistribute it and/or modify it", "'terms' not in serialized_deposit assert serialized_deposit['mesh_terms'] == [ { 'data':", "assert serialized_deposit['mesh_terms'] == [ { 'data': {'source': 'MeSH', 'value': 'Cognitive", "\"\"\"Test terms views.py\"\"\" from cd2h_repo_project.modules.terms.views import serialize_terms_for_edit_ui def test_serialize_terms_for_edit_ui(create_record): deposit", "def test_serialize_terms_for_edit_ui(create_record): deposit = create_record( { 'terms': [ {'source': 'MeSH',", "from cd2h_repo_project.modules.terms.views import serialize_terms_for_edit_ui def test_serialize_terms_for_edit_ui(create_record): deposit = create_record( {", "{ 'data': {'source': 'FAST', 'value': 'Border terrier'} } ] def", "= serialize_terms_for_edit_ui(deposit) assert 'terms' not in serialized_deposit assert serialized_deposit['mesh_terms'] ==", "software; you can redistribute it and/or modify it # under", "it and/or modify it # under the terms of the", "Neuroscience'}, {'source': 'FAST', 'value': 'Border terrier'} ] }, published=False )", "serialized_deposit assert serialized_deposit['mesh_terms'] == [ { 'data': {'source': 'MeSH', 'value':", "Copyright (C) 2018-present NU,FSM,GHSL. # # menRva is free software;", "# # This file is part of menRva. # Copyright", "assert serialized_deposit['fast_terms'] == [ { 'data': {'source': 'FAST', 'value': 'Border", "the MIT License; see LICENSE file for more details. \"\"\"Test", "{ 'data': {'source': 'MeSH', 'value': 'Cognitive Neuroscience'} } ] assert", "}, published=False ) serialized_deposit = serialize_terms_for_edit_ui(deposit) assert 'terms' not in", "see LICENSE file for more details. \"\"\"Test terms views.py\"\"\" from", "def test_serialize_terms_for_edit_ui_no_terms(create_record): deposit = create_record(published=False) serialized_deposit = serialize_terms_for_edit_ui(deposit) assert 'terms'", "deposit = create_record( { 'terms': [ {'source': 'MeSH', 'value': 'Cognitive", "# menRva is free software; you can redistribute it and/or", "the terms of the MIT License; see LICENSE file for", "# This file is part of menRva. # Copyright (C)", "{'source': 'FAST', 'value': 'Border terrier'} ] }, published=False ) serialized_deposit", "# # menRva is free software; you can redistribute it", "'data': {'source': 'FAST', 'value': 'Border terrier'} } ] def test_serialize_terms_for_edit_ui_no_terms(create_record):", "redistribute it and/or modify it # under the terms of", "[ { 'data': {'source': 'FAST', 'value': 'Border terrier'} } ]", "'value': 'Border terrier'} } ] def test_serialize_terms_for_edit_ui_no_terms(create_record): deposit = create_record(published=False)", "and/or modify it # under the terms of the MIT", "'MeSH', 'value': 'Cognitive Neuroscience'}, {'source': 'FAST', 'value': 'Border terrier'} ]", "{'source': 'MeSH', 'value': 'Cognitive Neuroscience'} } ] assert serialized_deposit['fast_terms'] ==", "it # under the terms of the MIT License; see", "views.py\"\"\" from cd2h_repo_project.modules.terms.views import serialize_terms_for_edit_ui def test_serialize_terms_for_edit_ui(create_record): deposit = create_record(", "'Border terrier'} } ] def test_serialize_terms_for_edit_ui_no_terms(create_record): deposit = create_record(published=False) serialized_deposit", "cd2h_repo_project.modules.terms.views import serialize_terms_for_edit_ui def test_serialize_terms_for_edit_ui(create_record): deposit = create_record( { 'terms':", ") serialized_deposit = serialize_terms_for_edit_ui(deposit) assert 'terms' not in serialized_deposit assert", "details. \"\"\"Test terms views.py\"\"\" from cd2h_repo_project.modules.terms.views import serialize_terms_for_edit_ui def test_serialize_terms_for_edit_ui(create_record):", "[ { 'data': {'source': 'MeSH', 'value': 'Cognitive Neuroscience'} } ]", "terms views.py\"\"\" from cd2h_repo_project.modules.terms.views import serialize_terms_for_edit_ui def test_serialize_terms_for_edit_ui(create_record): deposit =", "create_record(published=False) serialized_deposit = serialize_terms_for_edit_ui(deposit) assert 'terms' not in serialized_deposit assert", "] assert serialized_deposit['fast_terms'] == [ { 'data': {'source': 'FAST', 'value':", "] def test_serialize_terms_for_edit_ui_no_terms(create_record): deposit = create_record(published=False) serialized_deposit = serialize_terms_for_edit_ui(deposit) assert", "'value': 'Cognitive Neuroscience'}, {'source': 'FAST', 'value': 'Border terrier'} ] },", "terrier'} } ] def test_serialize_terms_for_edit_ui_no_terms(create_record): deposit = create_record(published=False) serialized_deposit =", "for more details. \"\"\"Test terms views.py\"\"\" from cd2h_repo_project.modules.terms.views import serialize_terms_for_edit_ui", "== [ { 'data': {'source': 'FAST', 'value': 'Border terrier'} }", "assert 'terms' not in serialized_deposit assert serialized_deposit['mesh_terms'] == [ {", "= create_record(published=False) serialized_deposit = serialize_terms_for_edit_ui(deposit) assert 'terms' not in serialized_deposit", "of the MIT License; see LICENSE file for more details.", "menRva is free software; you can redistribute it and/or modify", "not in serialized_deposit assert serialized_deposit['mesh_terms'] == [ { 'data': {'source':", "test_serialize_terms_for_edit_ui_no_terms(create_record): deposit = create_record(published=False) serialized_deposit = serialize_terms_for_edit_ui(deposit) assert 'terms' not", "deposit = create_record(published=False) serialized_deposit = serialize_terms_for_edit_ui(deposit) assert 'terms' not in", "-*- # # This file is part of menRva. #", "part of menRva. # Copyright (C) 2018-present NU,FSM,GHSL. # #", "in serialized_deposit assert serialized_deposit['mesh_terms'] == [] assert serialized_deposit['fast_terms'] == []", "terms of the MIT License; see LICENSE file for more", "published=False ) serialized_deposit = serialize_terms_for_edit_ui(deposit) assert 'terms' not in serialized_deposit", "'FAST', 'value': 'Border terrier'} ] }, published=False ) serialized_deposit =", "This file is part of menRva. # Copyright (C) 2018-present", "{ 'terms': [ {'source': 'MeSH', 'value': 'Cognitive Neuroscience'}, {'source': 'FAST',", "{'source': 'FAST', 'value': 'Border terrier'} } ] def test_serialize_terms_for_edit_ui_no_terms(create_record): deposit", "modify it # under the terms of the MIT License;", "# under the terms of the MIT License; see LICENSE", "is part of menRva. # Copyright (C) 2018-present NU,FSM,GHSL. #" ]
[ "def test_site(search: str): \"\"\"please enter site name with http information\"\"\"", "def bing_search(search: str): webbrowser.open_new_tab(f\"https://www.bing.com/search?q={search}\") def duck_search(search: str): webbrowser.open_new_tab(f\"https://duckduckgo.com/?q={search}\") def yahoo_search(search:", "name with http information\"\"\" try: r = requests.get(search) except Exception", "def yahoo_search(search: str): webbrowser.open_new_tab(f\"https://search.yahoo.com/search?p={search}\") def ask_search(search: str): webbrowser.open_new_tab(f\"https://www.ask.com/web?q={search}\") def yandex_search(search:", "str, lang='en', sentence=1): try: wikipedia.set_lang(lang) print(wikipedia.summary(search, sentences=sentence)) except Exception as", "import requests def yt_search(search: str): webbrowser.open_new_tab(f\"https://www.youtube.com/results?search_query={search}\") def google_search(search: str): webbrowser.open_new_tab(f\"https://www.google.com/search?q={search}\")", "enter site name with http information\"\"\" try: r = requests.get(search)", "webbrowser.open_new_tab(f\"https://search.yahoo.com/search?p={search}\") def ask_search(search: str): webbrowser.open_new_tab(f\"https://www.ask.com/web?q={search}\") def yandex_search(search: str): webbrowser.open_new_tab(f\"https://yandex.com/search/?text={search}\") def", "str): webbrowser.open_new_tab(f\"https://en.wikipedia.org/wiki/{search}\") def test_site(search: str): \"\"\"please enter site name with", "def yt_search(search: str): webbrowser.open_new_tab(f\"https://www.youtube.com/results?search_query={search}\") def google_search(search: str): webbrowser.open_new_tab(f\"https://www.google.com/search?q={search}\") def bing_search(search:", "str): webbrowser.open_new_tab(f\"https://mail.google.com/mail/u/0/#search/{search}\") def wiki_web_search(search: str): webbrowser.open_new_tab(f\"https://en.wikipedia.org/wiki/{search}\") def test_site(search: str): \"\"\"please", "site name with http information\"\"\" try: r = requests.get(search) except", "webbrowser.open_new_tab(f\"https://www.ask.com/web?q={search}\") def yandex_search(search: str): webbrowser.open_new_tab(f\"https://yandex.com/search/?text={search}\") def ecosia_search(search: str): webbrowser.open_new_tab(f\"https://www.ecosia.org/search?q={search}\") def", "wikipedia.set_lang(lang) print(wikipedia.summary(search, sentences=sentence)) except Exception as error: print(error) return error", "information\"\"\" try: r = requests.get(search) except Exception as error: print(error)", "wiki_terminal_search(search: str, lang='en', sentence=1): try: wikipedia.set_lang(lang) print(wikipedia.summary(search, sentences=sentence)) except Exception", "except Exception as error: print(error) return error def mail_search(search: str):", "mail_search(search: str): webbrowser.open_new_tab(f\"https://mail.google.com/mail/u/0/#search/{search}\") def wiki_web_search(search: str): webbrowser.open_new_tab(f\"https://en.wikipedia.org/wiki/{search}\") def test_site(search: str):", "google_search(search: str): webbrowser.open_new_tab(f\"https://www.google.com/search?q={search}\") def bing_search(search: str): webbrowser.open_new_tab(f\"https://www.bing.com/search?q={search}\") def duck_search(search: str):", "def ask_search(search: str): webbrowser.open_new_tab(f\"https://www.ask.com/web?q={search}\") def yandex_search(search: str): webbrowser.open_new_tab(f\"https://yandex.com/search/?text={search}\") def ecosia_search(search:", "as error: print(error) return \"site not working\" if r.status_code ==", "Exception as error: print(error) return error def mail_search(search: str): webbrowser.open_new_tab(f\"https://mail.google.com/mail/u/0/#search/{search}\")", "working\" if r.status_code == 200: print(\"site working\") return \"site working\"", "def mail_search(search: str): webbrowser.open_new_tab(f\"https://mail.google.com/mail/u/0/#search/{search}\") def wiki_web_search(search: str): webbrowser.open_new_tab(f\"https://en.wikipedia.org/wiki/{search}\") def test_site(search:", "return \"site not working\" if r.status_code == 200: print(\"site working\")", "webbrowser.open_new_tab(f\"https://mail.google.com/mail/u/0/#search/{search}\") def wiki_web_search(search: str): webbrowser.open_new_tab(f\"https://en.wikipedia.org/wiki/{search}\") def test_site(search: str): \"\"\"please enter", "str): webbrowser.open_new_tab(f\"https://duckduckgo.com/?q={search}\") def yahoo_search(search: str): webbrowser.open_new_tab(f\"https://search.yahoo.com/search?p={search}\") def ask_search(search: str): webbrowser.open_new_tab(f\"https://www.ask.com/web?q={search}\")", "print(error) return \"site not working\" if r.status_code == 200: print(\"site", "str): webbrowser.open_new_tab(f\"https://www.ecosia.org/search?q={search}\") def fb_search(search: str): webbrowser.open_new_tab(f\"https://www.facebook.com/search/top/?q={search}\") def wiki_terminal_search(search: str, lang='en',", "print(wikipedia.summary(search, sentences=sentence)) except Exception as error: print(error) return error def", "try: r = requests.get(search) except Exception as error: print(error) return", "r = requests.get(search) except Exception as error: print(error) return \"site", "yahoo_search(search: str): webbrowser.open_new_tab(f\"https://search.yahoo.com/search?p={search}\") def ask_search(search: str): webbrowser.open_new_tab(f\"https://www.ask.com/web?q={search}\") def yandex_search(search: str):", "def wiki_web_search(search: str): webbrowser.open_new_tab(f\"https://en.wikipedia.org/wiki/{search}\") def test_site(search: str): \"\"\"please enter site", "return error def mail_search(search: str): webbrowser.open_new_tab(f\"https://mail.google.com/mail/u/0/#search/{search}\") def wiki_web_search(search: str): webbrowser.open_new_tab(f\"https://en.wikipedia.org/wiki/{search}\")", "bing_search(search: str): webbrowser.open_new_tab(f\"https://www.bing.com/search?q={search}\") def duck_search(search: str): webbrowser.open_new_tab(f\"https://duckduckgo.com/?q={search}\") def yahoo_search(search: str):", "str): webbrowser.open_new_tab(f\"https://yandex.com/search/?text={search}\") def ecosia_search(search: str): webbrowser.open_new_tab(f\"https://www.ecosia.org/search?q={search}\") def fb_search(search: str): webbrowser.open_new_tab(f\"https://www.facebook.com/search/top/?q={search}\")", "test_site(search: str): \"\"\"please enter site name with http information\"\"\" try:", "\"\"\"please enter site name with http information\"\"\" try: r =", "error def mail_search(search: str): webbrowser.open_new_tab(f\"https://mail.google.com/mail/u/0/#search/{search}\") def wiki_web_search(search: str): webbrowser.open_new_tab(f\"https://en.wikipedia.org/wiki/{search}\") def", "try: wikipedia.set_lang(lang) print(wikipedia.summary(search, sentences=sentence)) except Exception as error: print(error) return", "wiki_web_search(search: str): webbrowser.open_new_tab(f\"https://en.wikipedia.org/wiki/{search}\") def test_site(search: str): \"\"\"please enter site name", "= requests.get(search) except Exception as error: print(error) return \"site not", "str): webbrowser.open_new_tab(f\"https://www.facebook.com/search/top/?q={search}\") def wiki_terminal_search(search: str, lang='en', sentence=1): try: wikipedia.set_lang(lang) print(wikipedia.summary(search,", "print(error) return error def mail_search(search: str): webbrowser.open_new_tab(f\"https://mail.google.com/mail/u/0/#search/{search}\") def wiki_web_search(search: str):", "requests.get(search) except Exception as error: print(error) return \"site not working\"", "import wikipedia import requests def yt_search(search: str): webbrowser.open_new_tab(f\"https://www.youtube.com/results?search_query={search}\") def google_search(search:", "def yandex_search(search: str): webbrowser.open_new_tab(f\"https://yandex.com/search/?text={search}\") def ecosia_search(search: str): webbrowser.open_new_tab(f\"https://www.ecosia.org/search?q={search}\") def fb_search(search:", "webbrowser.open_new_tab(f\"https://www.youtube.com/results?search_query={search}\") def google_search(search: str): webbrowser.open_new_tab(f\"https://www.google.com/search?q={search}\") def bing_search(search: str): webbrowser.open_new_tab(f\"https://www.bing.com/search?q={search}\") def", "sentences=sentence)) except Exception as error: print(error) return error def mail_search(search:", "error: print(error) return \"site not working\" if r.status_code == 200:", "duck_search(search: str): webbrowser.open_new_tab(f\"https://duckduckgo.com/?q={search}\") def yahoo_search(search: str): webbrowser.open_new_tab(f\"https://search.yahoo.com/search?p={search}\") def ask_search(search: str):", "requests def yt_search(search: str): webbrowser.open_new_tab(f\"https://www.youtube.com/results?search_query={search}\") def google_search(search: str): webbrowser.open_new_tab(f\"https://www.google.com/search?q={search}\") def", "not working\" if r.status_code == 200: print(\"site working\") return \"site", "str): webbrowser.open_new_tab(f\"https://www.youtube.com/results?search_query={search}\") def google_search(search: str): webbrowser.open_new_tab(f\"https://www.google.com/search?q={search}\") def bing_search(search: str): webbrowser.open_new_tab(f\"https://www.bing.com/search?q={search}\")", "str): webbrowser.open_new_tab(f\"https://www.ask.com/web?q={search}\") def yandex_search(search: str): webbrowser.open_new_tab(f\"https://yandex.com/search/?text={search}\") def ecosia_search(search: str): webbrowser.open_new_tab(f\"https://www.ecosia.org/search?q={search}\")", "with http information\"\"\" try: r = requests.get(search) except Exception as", "webbrowser.open_new_tab(f\"https://www.bing.com/search?q={search}\") def duck_search(search: str): webbrowser.open_new_tab(f\"https://duckduckgo.com/?q={search}\") def yahoo_search(search: str): webbrowser.open_new_tab(f\"https://search.yahoo.com/search?p={search}\") def", "def duck_search(search: str): webbrowser.open_new_tab(f\"https://duckduckgo.com/?q={search}\") def yahoo_search(search: str): webbrowser.open_new_tab(f\"https://search.yahoo.com/search?p={search}\") def ask_search(search:", "str): webbrowser.open_new_tab(f\"https://search.yahoo.com/search?p={search}\") def ask_search(search: str): webbrowser.open_new_tab(f\"https://www.ask.com/web?q={search}\") def yandex_search(search: str): webbrowser.open_new_tab(f\"https://yandex.com/search/?text={search}\")", "def fb_search(search: str): webbrowser.open_new_tab(f\"https://www.facebook.com/search/top/?q={search}\") def wiki_terminal_search(search: str, lang='en', sentence=1): try:", "str): webbrowser.open_new_tab(f\"https://www.bing.com/search?q={search}\") def duck_search(search: str): webbrowser.open_new_tab(f\"https://duckduckgo.com/?q={search}\") def yahoo_search(search: str): webbrowser.open_new_tab(f\"https://search.yahoo.com/search?p={search}\")", "<gh_stars>1-10 import webbrowser import wikipedia import requests def yt_search(search: str):", "webbrowser.open_new_tab(f\"https://en.wikipedia.org/wiki/{search}\") def test_site(search: str): \"\"\"please enter site name with http", "webbrowser.open_new_tab(f\"https://yandex.com/search/?text={search}\") def ecosia_search(search: str): webbrowser.open_new_tab(f\"https://www.ecosia.org/search?q={search}\") def fb_search(search: str): webbrowser.open_new_tab(f\"https://www.facebook.com/search/top/?q={search}\") def", "sentence=1): try: wikipedia.set_lang(lang) print(wikipedia.summary(search, sentences=sentence)) except Exception as error: print(error)", "lang='en', sentence=1): try: wikipedia.set_lang(lang) print(wikipedia.summary(search, sentences=sentence)) except Exception as error:", "yt_search(search: str): webbrowser.open_new_tab(f\"https://www.youtube.com/results?search_query={search}\") def google_search(search: str): webbrowser.open_new_tab(f\"https://www.google.com/search?q={search}\") def bing_search(search: str):", "yandex_search(search: str): webbrowser.open_new_tab(f\"https://yandex.com/search/?text={search}\") def ecosia_search(search: str): webbrowser.open_new_tab(f\"https://www.ecosia.org/search?q={search}\") def fb_search(search: str):", "wikipedia import requests def yt_search(search: str): webbrowser.open_new_tab(f\"https://www.youtube.com/results?search_query={search}\") def google_search(search: str):", "fb_search(search: str): webbrowser.open_new_tab(f\"https://www.facebook.com/search/top/?q={search}\") def wiki_terminal_search(search: str, lang='en', sentence=1): try: wikipedia.set_lang(lang)", "error: print(error) return error def mail_search(search: str): webbrowser.open_new_tab(f\"https://mail.google.com/mail/u/0/#search/{search}\") def wiki_web_search(search:", "def ecosia_search(search: str): webbrowser.open_new_tab(f\"https://www.ecosia.org/search?q={search}\") def fb_search(search: str): webbrowser.open_new_tab(f\"https://www.facebook.com/search/top/?q={search}\") def wiki_terminal_search(search:", "ecosia_search(search: str): webbrowser.open_new_tab(f\"https://www.ecosia.org/search?q={search}\") def fb_search(search: str): webbrowser.open_new_tab(f\"https://www.facebook.com/search/top/?q={search}\") def wiki_terminal_search(search: str,", "except Exception as error: print(error) return \"site not working\" if", "Exception as error: print(error) return \"site not working\" if r.status_code", "webbrowser.open_new_tab(f\"https://duckduckgo.com/?q={search}\") def yahoo_search(search: str): webbrowser.open_new_tab(f\"https://search.yahoo.com/search?p={search}\") def ask_search(search: str): webbrowser.open_new_tab(f\"https://www.ask.com/web?q={search}\") def", "webbrowser.open_new_tab(f\"https://www.facebook.com/search/top/?q={search}\") def wiki_terminal_search(search: str, lang='en', sentence=1): try: wikipedia.set_lang(lang) print(wikipedia.summary(search, sentences=sentence))", "str): \"\"\"please enter site name with http information\"\"\" try: r", "webbrowser import wikipedia import requests def yt_search(search: str): webbrowser.open_new_tab(f\"https://www.youtube.com/results?search_query={search}\") def", "as error: print(error) return error def mail_search(search: str): webbrowser.open_new_tab(f\"https://mail.google.com/mail/u/0/#search/{search}\") def", "str): webbrowser.open_new_tab(f\"https://www.google.com/search?q={search}\") def bing_search(search: str): webbrowser.open_new_tab(f\"https://www.bing.com/search?q={search}\") def duck_search(search: str): webbrowser.open_new_tab(f\"https://duckduckgo.com/?q={search}\")", "import webbrowser import wikipedia import requests def yt_search(search: str): webbrowser.open_new_tab(f\"https://www.youtube.com/results?search_query={search}\")", "\"site not working\" if r.status_code == 200: print(\"site working\") return", "def google_search(search: str): webbrowser.open_new_tab(f\"https://www.google.com/search?q={search}\") def bing_search(search: str): webbrowser.open_new_tab(f\"https://www.bing.com/search?q={search}\") def duck_search(search:", "webbrowser.open_new_tab(f\"https://www.google.com/search?q={search}\") def bing_search(search: str): webbrowser.open_new_tab(f\"https://www.bing.com/search?q={search}\") def duck_search(search: str): webbrowser.open_new_tab(f\"https://duckduckgo.com/?q={search}\") def", "def wiki_terminal_search(search: str, lang='en', sentence=1): try: wikipedia.set_lang(lang) print(wikipedia.summary(search, sentences=sentence)) except", "http information\"\"\" try: r = requests.get(search) except Exception as error:", "ask_search(search: str): webbrowser.open_new_tab(f\"https://www.ask.com/web?q={search}\") def yandex_search(search: str): webbrowser.open_new_tab(f\"https://yandex.com/search/?text={search}\") def ecosia_search(search: str):", "webbrowser.open_new_tab(f\"https://www.ecosia.org/search?q={search}\") def fb_search(search: str): webbrowser.open_new_tab(f\"https://www.facebook.com/search/top/?q={search}\") def wiki_terminal_search(search: str, lang='en', sentence=1):" ]
[ "66), lambda : key_by_guess(10, 67, 'y'), lambda : key_by_space(10, 68),", "ch_index) def key_by_guess(ct_index, ch_index, guess=' '): return strxor(MSGS_DECODED[ct_index][ch_index], guess) def", "max_len = 0 for i1, i2, c in comb: if", "for (x, y) in zip(a[:len(b)], b)])) #.encode('hex') else: return (\"\".join([chr(ord(x)", "in c: html += '<td>' html += '%02d' % ord(ch)", "s5 = '3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070' s6 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4' s7 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce' s8", "html += '<th></th>' for i in xrange(max_len): html += '<th>'", "lambda : key_by_space(10, 33), lambda : key_by_space(8, 34), lambda :", "in combinations(MSGS, 2)] html = '<html><body>' html += '<table style=\"white-space:nowrap\"", "key_by_guess(3, 53, 'm'), lambda : key_by_space(4, 54), lambda : key_by_space(1,", "MSGS] def combinations(iterable, r): indices = range(r) n = len(iterable)", "9), lambda : key_by_space(10, 10), lambda : key_by_space(1, 11), lambda", "key_by_space(10, 27), lambda : key_by_space(3, 28), lambda : key_by_space(9, 29),", "= [(i1, i2, strxor(s1.decode('hex'), s2.decode('hex'))) for i1, i2, (s1,s2) in", "44), lambda : key_by_guess(7, 45, 'y'), lambda : key_by_space(7, 46),", "'271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027' s10 = '466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83' s11 = '32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904' def strxor(a, b):", "+= '%02d' % ord(ch) if ch in string.printable: html +=", "key_by_guess(10, 82, 'e'), lambda : key_by_guess(6, 83, 'c'), lambda :", "html += '<th>' + str(i) + '</th>' html += '</tr>'", "html += '</td>' html += '</tr>' html += '<tr>' html", "= [s.decode('hex') for s in MSGS] def combinations(iterable, r): indices", "html += '<tr>' html += '<th></th>' for i in xrange(max_len):", "key_by_guess(3, 51, 't'), lambda : key_by_guess(3, 52, 'h'), lambda :", "ord(ch) html += '</td>' html += '</tr>' html += '<tr>'", "lambda : key_by_guess(3, 52, 'h'), lambda : key_by_guess(3, 53, 'm'),", "return strxor(MSGS_DECODED[ct_index][ch_index], guess) def main(): output_combinations_table() key = [ lambda", "lambda : key_by_space(8, 1), lambda : key_by_space(0, 2), lambda :", "+= '</tr>' html += '</thead>' for i1, i2, c in", ": key_by_guess(10, 75, 'h'), lambda : key_by_guess(10, 76, 'a'), lambda", "= '<html><body>' html += '<table style=\"white-space:nowrap\" border=\"1\">' html += '<thead>'", "return (\"\".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)]))", ": key_by_space(6, 22), lambda : key_by_space(4, 23), lambda : key_by_space(0,", "(x, y) in zip(a, b[:len(a)])])) #.encode('hex') def random(size=16): return open(\"/dev/urandom\").read(size)", "lambda : key_by_space(9, 59), lambda : key_by_space(3, 60), lambda :", "'e'), lambda : key_by_guess(3, 80, 'x'), lambda : key_by_guess(3, 81,", "'</html>' with open('combinations.html', 'w') as f: f.write(html) def key_by_space(ct_index, ch_index):", "key_by_space(4, 23), lambda : key_by_space(0, 24), lambda : key_by_guess(1, 25,", "36), lambda : key_by_space(5, 37), lambda : key_by_space(7, 38), lambda", "def key_by_space(ct_index, ch_index): return key_by_guess(ct_index, ch_index) def key_by_guess(ct_index, ch_index, guess='", "b[:len(a)])])) #.encode('hex') def random(size=16): return open(\"/dev/urandom\").read(size) def encrypt(key, msg): c", "lambda : key_by_guess(3, 81, 't'), lambda : key_by_guess(10, 82, 'e'),", "# a = a.decode('hex') # b = b.decode('hex') if len(a)", "max_len = max(combinations, key=lambda x: len(x)) max_len = 0 for", "'c'), lambda : key_by_guess(6, 84, 'e'), # lambda : key_by_guess(6,", "1] + 1 break else: return # def main(): #", "+= '<table style=\"white-space:nowrap\" border=\"1\">' html += '<thead>' html += '<tr>'", "= 0 for i1, i2, c in comb: if len(c)", "html += '</thead>' for i1, i2, c in comb: html", "lambda : key_by_guess(3, 43, 'n'), lambda : key_by_space(4, 44), lambda", "'32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904' def strxor(a, b): # xor two strings of different", "string.printable: html += '<br />' html += '&#%d;' % ord(ch)", "open(\"/dev/urandom\").read(size) def encrypt(key, msg): c = strxor(key, msg) print print", "i): indices[i] = indices[i] + 1 for j in range(i", "68, 't'), ] for i, s in enumerate(MSGS): print '%2d:", "key_by_space(4, 44), lambda : key_by_guess(7, 45, 'y'), lambda : key_by_space(7,", "lambda : key_by_space(9, 4), lambda : key_by_space(6, 5), lambda :", "lambda : key_by_space(6, 5), lambda : key_by_space(7, 6), lambda :", "lambda : key_by_guess(7, 45, 'y'), lambda : key_by_space(7, 46), lambda", ": key_by_space(10, 56), lambda : key_by_space(1, 57), lambda : key_by_space(0,", "s7 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce' s8 = '315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3' s9 = '271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027' s10", ": key_by_guess(10, 67, 'y'), lambda : key_by_space(10, 68), lambda :", "'466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83' s11 = '32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904' def strxor(a, b): # xor two", "'<td>(%s, %s)</td>' % (i1 + 1, i2 + 1) for", "1, r): indices[j] = indices[j - 1] + 1 break", "def random(size=16): return open(\"/dev/urandom\").read(size) def encrypt(key, msg): c = strxor(key,", "'32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4' s7 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce' s8 = '315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3' s9 = '271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027'", "(s1,s2) in combinations(MSGS, 2)] html = '<html><body>' html += '<table", "lambda : key_by_space(5, 66), lambda : key_by_guess(10, 67, 'y'), lambda", "28), lambda : key_by_space(9, 29), lambda : key_by_space(7, 30), lambda", "key_by_guess(3, 80, 'x'), lambda : key_by_guess(3, 81, 't'), lambda :", "54), lambda : key_by_space(1, 55), lambda : key_by_space(10, 56), lambda", "as f: f.write(html) def key_by_space(ct_index, ch_index): return key_by_guess(ct_index, ch_index) def", "42), lambda : key_by_guess(3, 43, 'n'), lambda : key_by_space(4, 44),", "key_by_space(ct_index, ch_index): return key_by_guess(ct_index, ch_index) def key_by_guess(ct_index, ch_index, guess=' '):", "73), lambda : key_by_space(0, 74), lambda : key_by_guess(10, 75, 'h'),", "lambda : key_by_guess(6, 83, 'c'), lambda : key_by_guess(6, 84, 'e'),", "lambda : key_by_guess(0, 62, 'o'), lambda : key_by_space(0, 63), lambda", "+= '<td>(%s, %s)</td>' % (i1 + 1, i2 + 1)", ": key_by_guess(1, 25, 'y'), lambda : key_by_space(7, 26), lambda :", "c in comb: if len(c) > max_len: max_len = len(c)", "in indices),) for i in reversed(range(r)): if indices[i] < n", "return open(\"/dev/urandom\").read(size) def encrypt(key, msg): c = strxor(key, msg) print", "[s.decode('hex') for s in MSGS] def combinations(iterable, r): indices =", "key_by_space(10, 35), lambda : key_by_space(9, 36), lambda : key_by_space(5, 37),", ": key_by_guess(10, 48, 'r'), lambda : key_by_space(7, 49), lambda :", "in indices) + (tuple(iterable[i] for i in indices),) for i", "in enumerate(MSGS): print '%2d: %s' % (i + 1, ''.join([strxor(k(),", "key_by_space(7, 69), lambda : key_by_space(1, 70), lambda : key_by_space(3, 71),", "1), lambda : key_by_space(0, 2), lambda : key_by_space(4, 3), lambda", "k, ch in itertools.izip(key, s.decode('hex'))])) if __name__ == \"__main__\": main()", "22), lambda : key_by_space(4, 23), lambda : key_by_space(0, 24), lambda", "61), lambda : key_by_guess(0, 62, 'o'), lambda : key_by_space(0, 63),", ": key_by_space(5, 42), lambda : key_by_guess(3, 43, 'n'), lambda :", "MSGS = (s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11) MSGS_DECODED = [s.decode('hex') for s in MSGS]", "in range(i + 1, r): indices[j] = indices[j - 1]", "'t'), lambda : key_by_guess(10, 82, 'e'), lambda : key_by_guess(6, 83,", "random(size=16): return open(\"/dev/urandom\").read(size) def encrypt(key, msg): c = strxor(key, msg)", "open('combinations.html', 'w') as f: f.write(html) def key_by_space(ct_index, ch_index): return key_by_guess(ct_index,", "key_by_space(8, 16), lambda : key_by_space(4, 17), lambda : key_by_space(10, 18),", ": key_by_space(7, 6), lambda : key_by_guess(4, 7, '\\''), #??? lambda", "key=lambda x: len(x)) max_len = 0 for i1, i2, c", "lambda : key_by_space(6, 19), lambda : key_by_space(7, 20), lambda :", "key_by_space(1, 57), lambda : key_by_space(0, 58), lambda : key_by_space(9, 59),", "+ 1, i2 + 1) for ch in c: html", "^ ord(y)) for (x, y) in zip(a, b[:len(a)])])) #.encode('hex') def", "35), lambda : key_by_space(9, 36), lambda : key_by_space(5, 37), lambda", "= '32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904' def strxor(a, b): # xor two strings of", "def output_combinations_table(): comb = [(i1, i2, strxor(s1.decode('hex'), s2.decode('hex'))) for i1,", "16), lambda : key_by_space(4, 17), lambda : key_by_space(10, 18), lambda", ": key_by_space(4, 17), lambda : key_by_space(10, 18), lambda : key_by_space(6,", "lambda : key_by_space(5, 42), lambda : key_by_guess(3, 43, 'n'), lambda", "+= '<th>' + str(i) + '</th>' html += '</tr>' html", "MSGS_DECODED = [s.decode('hex') for s in MSGS] def combinations(iterable, r):", "lambda : key_by_space(1, 70), lambda : key_by_space(3, 71), lambda :", ": key_by_space(9, 4), lambda : key_by_space(6, 5), lambda : key_by_space(7,", "indices) + (tuple(iterable[i] for i in indices),) for i in", "6), lambda : key_by_guess(4, 7, '\\''), #??? lambda : key_by_space(2,", "f.write(html) def key_by_space(ct_index, ch_index): return key_by_guess(ct_index, ch_index) def key_by_guess(ct_index, ch_index,", "for i in indices),) for i in reversed(range(r)): if indices[i]", "18), lambda : key_by_space(6, 19), lambda : key_by_space(7, 20), lambda", ": key_by_space(0, 63), lambda : key_by_space(10, 64), lambda : key_by_guess(6,", "'</th>' html += '</tr>' html += '</thead>' for i1, i2,", "timeit import itertools s1 = '<KEY>' s2 = '<KEY>' s3", "+= '</thead>' for i1, i2, c in comb: html +=", "'</table>' html += '</body>' html += '</html>' with open('combinations.html', 'w')", ": key_by_space(1, 55), lambda : key_by_space(10, 56), lambda : key_by_space(1,", "key_by_space(3, 60), lambda : key_by_space(7, 61), lambda : key_by_guess(0, 62,", ": key_by_space(10, 64), lambda : key_by_guess(6, 65, 't'), lambda :", "ord(ch) if ch in string.printable: html += '<br />' html", "key_by_guess(6, 84, 'e'), # lambda : key_by_guess(6, 68, 't'), ]", "for (x, y) in zip(a, b[:len(a)])])) #.encode('hex') def random(size=16): return", "if indices[i] < n - (r - i): indices[i] =", "5), lambda : key_by_space(7, 6), lambda : key_by_guess(4, 7, '\\''),", "8), lambda : key_by_space(6, 9), lambda : key_by_space(10, 10), lambda", "return # def main(): # for c in combinations('ABCD', 2):", "of different lengths # a = a.decode('hex') # b =", "'t'), ] for i, s in enumerate(MSGS): print '%2d: %s'", "html += '&#%d;' % ord(ch) html += '</td>' html +=", "= (s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11) MSGS_DECODED = [s.decode('hex') for s in MSGS] def", "lambda : key_by_space(4, 44), lambda : key_by_guess(7, 45, 'y'), lambda", "'32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce' s8 = '315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3' s9 = '271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027' s10 = '466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83'", "# xor two strings of different lengths # a =", ": key_by_space(2, 8), lambda : key_by_space(6, 9), lambda : key_by_space(10,", ": key_by_space(6, 19), lambda : key_by_space(7, 20), lambda : key_by_space(4,", "% ord(ch) if ch in string.printable: html += '<br />'", "lambda : key_by_space(1, 57), lambda : key_by_space(0, 58), lambda :", "key_by_guess(3, 50, 'i'), lambda : key_by_guess(3, 51, 't'), lambda :", "lambda : key_by_space(9, 0), lambda : key_by_space(8, 1), lambda :", "main(): output_combinations_table() key = [ lambda : key_by_space(9, 0), lambda", "(x, y) in zip(a[:len(b)], b)])) #.encode('hex') else: return (\"\".join([chr(ord(x) ^", "'</tr>' html += '</table>' html += '</body>' html += '</html>'", "key_by_space(8, 1), lambda : key_by_space(0, 2), lambda : key_by_space(4, 3),", "'m'), lambda : key_by_space(4, 54), lambda : key_by_space(1, 55), lambda", "if ch in string.printable: html += '<br />' html +=", "+ '</th>' html += '</tr>' html += '</thead>' for i1,", "n = len(iterable) while True: yield tuple(i for i in", "for c in combinations('ABCD', 2): # print c def output_combinations_table():", "7, '\\''), #??? lambda : key_by_space(2, 8), lambda : key_by_space(6,", "33), lambda : key_by_space(8, 34), lambda : key_by_space(10, 35), lambda", "b.decode('hex') if len(a) > len(b): return (\"\".join([chr(ord(x) ^ ord(y)) for", "s11 = '32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904' def strxor(a, b): # xor two strings", "def strxor(a, b): # xor two strings of different lengths", "<reponame>ptsurko/coursera_crypt<filename>hw1.py import string from timeit import itertools s1 = '<KEY>'", "74), lambda : key_by_guess(10, 75, 'h'), lambda : key_by_guess(10, 76,", "import string from timeit import itertools s1 = '<KEY>' s2", "key_by_space(2, 72), lambda : key_by_space(1, 73), lambda : key_by_space(0, 74),", "14), lambda : key_by_space(8, 15), lambda : key_by_space(8, 16), lambda", "15), lambda : key_by_space(8, 16), lambda : key_by_space(4, 17), lambda", "''.join([strxor(k(), ch) for k, ch in itertools.izip(key, s.decode('hex'))])) if __name__", "'</tr>' html += '<tr>' html += '<th></th>' for i in", "lambda : key_by_space(8, 15), lambda : key_by_space(8, 16), lambda :", "2)] html = '<html><body>' html += '<table style=\"white-space:nowrap\" border=\"1\">' html", "+= '</body>' html += '</html>' with open('combinations.html', 'w') as f:", "in combinations('ABCD', 2): # print c def output_combinations_table(): comb =", "comb: html += '<tr>' html += '<td>(%s, %s)</td>' % (i1", "% ord(ch) html += '</td>' html += '</tr>' html +=", "break else: return # def main(): # for c in", "s2.decode('hex'))) for i1, i2, (s1,s2) in combinations(MSGS, 2)] html =", "1 break else: return # def main(): # for c", "52, 'h'), lambda : key_by_guess(3, 53, 'm'), lambda : key_by_space(4,", "lambda : key_by_space(9, 12), lambda : key_by_space(6, 13), lambda :", "26), lambda : key_by_space(10, 27), lambda : key_by_space(3, 28), lambda", "- i): indices[i] = indices[i] + 1 for j in", "'<tr>' html += '<td>(%s, %s)</td>' % (i1 + 1, i2", ": key_by_guess(6, 84, 'e'), # lambda : key_by_guess(6, 68, 't'),", ": key_by_space(4, 3), lambda : key_by_space(9, 4), lambda : key_by_space(6,", "xrange(max_len): html += '<th>' + str(i) + '</th>' html +=", "'<th>' + str(i) + '</th>' html += '</tr>' html +=", "key_by_space(7, 46), lambda : key_by_guess(10, 47, 'e'), lambda : key_by_guess(10,", "print '%2d: %s' % (i + 1, ''.join([strxor(k(), ch) for", "+= '<td>' html += '%02d' % ord(ch) if ch in", "# WTF??? # max_len = max(combinations, key=lambda x: len(x)) max_len", "for i1, i2, c in comb: html += '<tr>' html", "lambda : key_by_space(0, 58), lambda : key_by_space(9, 59), lambda :", "two strings of different lengths # a = a.decode('hex') #", "key_by_space(6, 5), lambda : key_by_space(7, 6), lambda : key_by_guess(4, 7,", "> len(b): return (\"\".join([chr(ord(x) ^ ord(y)) for (x, y) in", "49), lambda : key_by_guess(3, 50, 'i'), lambda : key_by_guess(3, 51,", "key_by_space(10, 33), lambda : key_by_space(8, 34), lambda : key_by_space(10, 35),", "key_by_guess(6, 68, 't'), ] for i, s in enumerate(MSGS): print", "40), lambda : key_by_space(8, 41), lambda : key_by_space(5, 42), lambda", "key_by_space(0, 24), lambda : key_by_guess(1, 25, 'y'), lambda : key_by_space(7,", "= '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce' s8 = '315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3' s9 = '271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027' s10 =", "% (i1 + 1, i2 + 1) for ch in", "in comb: if len(c) > max_len: max_len = len(c) #", "'%02d' % ord(ch) if ch in string.printable: html += '<br", "key_by_space(1, 73), lambda : key_by_space(0, 74), lambda : key_by_guess(10, 75,", "lambda : key_by_space(7, 26), lambda : key_by_space(10, 27), lambda :", "key_by_space(1, 39), lambda : key_by_space(0, 40), lambda : key_by_space(8, 41),", ": key_by_space(5, 66), lambda : key_by_guess(10, 67, 'y'), lambda :", "while True: yield tuple(i for i in indices) + (tuple(iterable[i]", "lambda : key_by_space(0, 32), lambda : key_by_space(10, 33), lambda :", "html += '<table style=\"white-space:nowrap\" border=\"1\">' html += '<thead>' html +=", "key_by_space(10, 64), lambda : key_by_guess(6, 65, 't'), lambda : key_by_space(5,", "= '<KEY>' s3 = '32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb' s4 = '32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa' s5 =", "> max_len: max_len = len(c) # print max_len html +=", ": key_by_space(6, 9), lambda : key_by_space(10, 10), lambda : key_by_space(1,", "(r - i): indices[i] = indices[i] + 1 for j", "60), lambda : key_by_space(7, 61), lambda : key_by_guess(0, 62, 'o'),", ": key_by_space(0, 24), lambda : key_by_guess(1, 25, 'y'), lambda :", "69), lambda : key_by_space(1, 70), lambda : key_by_space(3, 71), lambda", "def main(): output_combinations_table() key = [ lambda : key_by_space(9, 0),", "different lengths # a = a.decode('hex') # b = b.decode('hex')", "key_by_guess(10, 76, 'a'), lambda : key_by_guess(10, 77, 'n'), lambda :", "lambda : key_by_guess(3, 79, 'e'), lambda : key_by_guess(3, 80, 'x'),", "c #.encode('hex') return c MSGS = (s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11) MSGS_DECODED = [s.decode('hex')", "43, 'n'), lambda : key_by_space(4, 44), lambda : key_by_guess(7, 45,", "lambda : key_by_space(6, 22), lambda : key_by_space(4, 23), lambda :", "len(iterable) while True: yield tuple(i for i in indices) +", ": key_by_space(1, 57), lambda : key_by_space(0, 58), lambda : key_by_space(9,", "50, 'i'), lambda : key_by_guess(3, 51, 't'), lambda : key_by_guess(3,", "'h'), lambda : key_by_guess(3, 53, 'm'), lambda : key_by_space(4, 54),", "'3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070' s6 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4' s7 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce' s8 = '315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3'", "lambda : key_by_space(3, 71), lambda : key_by_space(2, 72), lambda :", "key_by_guess(10, 67, 'y'), lambda : key_by_space(10, 68), lambda : key_by_space(7,", "+ 1 break else: return # def main(): # for", "i1, i2, c in comb: if len(c) > max_len: max_len", "'i'), lambda : key_by_guess(3, 51, 't'), lambda : key_by_guess(3, 52,", ": key_by_space(7, 26), lambda : key_by_space(10, 27), lambda : key_by_space(3,", "ch in c: html += '<td>' html += '%02d' %", "30), lambda : key_by_space(1, 31), lambda : key_by_space(0, 32), lambda", "html += '<td>' html += '%02d' % ord(ch) if ch", "lengths # a = a.decode('hex') # b = b.decode('hex') if", "lambda : key_by_space(8, 16), lambda : key_by_space(4, 17), lambda :", ": key_by_space(7, 49), lambda : key_by_guess(3, 50, 'i'), lambda :", "key_by_space(8, 34), lambda : key_by_space(10, 35), lambda : key_by_space(9, 36),", "+ 1 for j in range(i + 1, r): indices[j]", "64), lambda : key_by_guess(6, 65, 't'), lambda : key_by_space(5, 66),", "'a'), lambda : key_by_guess(10, 77, 'n'), lambda : key_by_space(10, 78),", "= '315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3' s9 = '271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027' s10 = '466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83' s11 =", "%s)</td>' % (i1 + 1, i2 + 1) for ch", "n - (r - i): indices[i] = indices[i] + 1", "lambda : key_by_space(0, 2), lambda : key_by_space(4, 3), lambda :", "key_by_space(8, 41), lambda : key_by_space(5, 42), lambda : key_by_guess(3, 43,", "lambda : key_by_space(5, 37), lambda : key_by_space(7, 38), lambda :", "71), lambda : key_by_space(2, 72), lambda : key_by_space(1, 73), lambda", "'<KEY>' s2 = '<KEY>' s3 = '32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb' s4 = '32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa'", "print c #.encode('hex') return c MSGS = (s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11) MSGS_DECODED =", "+= '</tr>' html += '</table>' html += '</body>' html +=", "key_by_space(7, 30), lambda : key_by_space(1, 31), lambda : key_by_space(0, 32),", "lambda : key_by_space(1, 73), lambda : key_by_space(0, 74), lambda :", "+ str(i) + '</th>' html += '</tr>' html += '</thead>'", "1, ''.join([strxor(k(), ch) for k, ch in itertools.izip(key, s.decode('hex'))])) if", "key_by_space(1, 31), lambda : key_by_space(0, 32), lambda : key_by_space(10, 33),", "39), lambda : key_by_space(0, 40), lambda : key_by_space(8, 41), lambda", ": key_by_guess(10, 76, 'a'), lambda : key_by_guess(10, 77, 'n'), lambda", "html += '</table>' html += '</body>' html += '</html>' with", "strings of different lengths # a = a.decode('hex') # b", "3), lambda : key_by_space(9, 4), lambda : key_by_space(6, 5), lambda", "key_by_guess(3, 81, 't'), lambda : key_by_guess(10, 82, 'e'), lambda :", ": key_by_space(9, 12), lambda : key_by_space(6, 13), lambda : key_by_space(4,", ": key_by_space(0, 40), lambda : key_by_space(8, 41), lambda : key_by_space(5,", "for j in range(i + 1, r): indices[j] = indices[j", "78), lambda : key_by_guess(3, 79, 'e'), lambda : key_by_guess(3, 80,", "lambda : key_by_space(1, 55), lambda : key_by_space(10, 56), lambda :", "= '32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb' s4 = '32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa' s5 = '3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070' s6 =", "29), lambda : key_by_space(7, 30), lambda : key_by_space(1, 31), lambda", "key_by_space(9, 0), lambda : key_by_space(8, 1), lambda : key_by_space(0, 2),", "key_by_space(7, 6), lambda : key_by_guess(4, 7, '\\''), #??? lambda :", "+= '<tr>' html += '<td>(%s, %s)</td>' % (i1 + 1,", "lambda : key_by_guess(10, 77, 'n'), lambda : key_by_space(10, 78), lambda", "in string.printable: html += '<br />' html += '&#%d;' %", "s in MSGS] def combinations(iterable, r): indices = range(r) n", "'<td>' html += '%02d' % ord(ch) if ch in string.printable:", "lambda : key_by_guess(3, 51, 't'), lambda : key_by_guess(3, 52, 'h'),", "True: yield tuple(i for i in indices) + (tuple(iterable[i] for", "max_len: max_len = len(c) # print max_len html += '<th></th>'", "key_by_space(4, 54), lambda : key_by_space(1, 55), lambda : key_by_space(10, 56),", "(\"\".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])) #.encode('hex')", "lambda : key_by_space(7, 30), lambda : key_by_space(1, 31), lambda :", ": key_by_space(2, 72), lambda : key_by_space(1, 73), lambda : key_by_space(0,", "%s' % (i + 1, ''.join([strxor(k(), ch) for k, ch", "s4 = '32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa' s5 = '3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070' s6 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4' s7", "key_by_guess(6, 83, 'c'), lambda : key_by_guess(6, 84, 'e'), # lambda", "tuple(i for i in indices) + (tuple(iterable[i] for i in", "key_by_space(9, 59), lambda : key_by_space(3, 60), lambda : key_by_space(7, 61),", "comb: if len(c) > max_len: max_len = len(c) # print", "key_by_guess(ct_index, ch_index, guess=' '): return strxor(MSGS_DECODED[ct_index][ch_index], guess) def main(): output_combinations_table()", "79, 'e'), lambda : key_by_guess(3, 80, 'x'), lambda : key_by_guess(3,", "84, 'e'), # lambda : key_by_guess(6, 68, 't'), ] for", ": key_by_guess(10, 47, 'e'), lambda : key_by_guess(10, 48, 'r'), lambda", "j in range(i + 1, r): indices[j] = indices[j -", "(i + 1, ''.join([strxor(k(), ch) for k, ch in itertools.izip(key,", "ch in string.printable: html += '<br />' html += '&#%d;'", "lambda : key_by_space(8, 41), lambda : key_by_space(5, 42), lambda :", "key_by_space(7, 49), lambda : key_by_guess(3, 50, 'i'), lambda : key_by_guess(3,", "strxor(a, b): # xor two strings of different lengths #", "print print c #.encode('hex') return c MSGS = (s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11) MSGS_DECODED", "border=\"1\">' html += '<thead>' html += '<tr>' # WTF??? #", "76, 'a'), lambda : key_by_guess(10, 77, 'n'), lambda : key_by_space(10,", "lambda : key_by_guess(10, 48, 'r'), lambda : key_by_space(7, 49), lambda", "key_by_space(7, 61), lambda : key_by_guess(0, 62, 'o'), lambda : key_by_space(0,", "if len(a) > len(b): return (\"\".join([chr(ord(x) ^ ord(y)) for (x,", "in reversed(range(r)): if indices[i] < n - (r - i):", "- (r - i): indices[i] = indices[i] + 1 for", "key_by_space(5, 42), lambda : key_by_guess(3, 43, 'n'), lambda : key_by_space(4,", "32), lambda : key_by_space(10, 33), lambda : key_by_space(8, 34), lambda", ": key_by_guess(7, 45, 'y'), lambda : key_by_space(7, 46), lambda :", ": key_by_space(1, 39), lambda : key_by_space(0, 40), lambda : key_by_space(8,", "^ ord(y)) for (x, y) in zip(a[:len(b)], b)])) #.encode('hex') else:", "4), lambda : key_by_space(6, 5), lambda : key_by_space(7, 6), lambda", "key_by_guess(7, 45, 'y'), lambda : key_by_space(7, 46), lambda : key_by_guess(10,", "# b = b.decode('hex') if len(a) > len(b): return (\"\".join([chr(ord(x)", "(i1 + 1, i2 + 1) for ch in c:", "import itertools s1 = '<KEY>' s2 = '<KEY>' s3 =", "yield tuple(i for i in indices) + (tuple(iterable[i] for i", "ord(y)) for (x, y) in zip(a, b[:len(a)])])) #.encode('hex') def random(size=16):", "+= '</td>' html += '</tr>' html += '<tr>' html +=", "main(): # for c in combinations('ABCD', 2): # print c", "'): return strxor(MSGS_DECODED[ct_index][ch_index], guess) def main(): output_combinations_table() key = [", "for k, ch in itertools.izip(key, s.decode('hex'))])) if __name__ == \"__main__\":", "for i in reversed(range(r)): if indices[i] < n - (r", "lambda : key_by_space(7, 49), lambda : key_by_guess(3, 50, 'i'), lambda", "'</thead>' for i1, i2, c in comb: html += '<tr>'", "html += '</tr>' html += '</thead>' for i1, i2, c", "in comb: html += '<tr>' html += '<td>(%s, %s)</td>' %", ": key_by_space(10, 33), lambda : key_by_space(8, 34), lambda : key_by_space(10,", "key_by_guess(1, 25, 'y'), lambda : key_by_space(7, 26), lambda : key_by_space(10,", "'32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb' s4 = '32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa' s5 = '3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070' s6 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4'", "in zip(a[:len(b)], b)])) #.encode('hex') else: return (\"\".join([chr(ord(x) ^ ord(y)) for", "key_by_space(6, 13), lambda : key_by_space(4, 14), lambda : key_by_space(8, 15),", ": key_by_space(9, 29), lambda : key_by_space(7, 30), lambda : key_by_space(1,", "19), lambda : key_by_space(7, 20), lambda : key_by_space(4, 21), lambda", "82, 'e'), lambda : key_by_guess(6, 83, 'c'), lambda : key_by_guess(6,", ": key_by_space(9, 59), lambda : key_by_space(3, 60), lambda : key_by_space(7,", "'<table style=\"white-space:nowrap\" border=\"1\">' html += '<thead>' html += '<tr>' #", "s9 = '271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027' s10 = '466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83' s11 = '32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904' def", "lambda : key_by_space(4, 23), lambda : key_by_space(0, 24), lambda :", "key_by_space(9, 36), lambda : key_by_space(5, 37), lambda : key_by_space(7, 38),", "'x'), lambda : key_by_guess(3, 81, 't'), lambda : key_by_guess(10, 82,", "x: len(x)) max_len = 0 for i1, i2, c in", "lambda : key_by_space(7, 20), lambda : key_by_space(4, 21), lambda :", ": key_by_space(10, 68), lambda : key_by_space(7, 69), lambda : key_by_space(1,", "ord(y)) for (x, y) in zip(a[:len(b)], b)])) #.encode('hex') else: return", "style=\"white-space:nowrap\" border=\"1\">' html += '<thead>' html += '<tr>' # WTF???", ": key_by_guess(3, 51, 't'), lambda : key_by_guess(3, 52, 'h'), lambda", "max_len = len(c) # print max_len html += '<th></th>' for", "key_by_space(7, 38), lambda : key_by_space(1, 39), lambda : key_by_space(0, 40),", "'</td>' html += '</tr>' html += '<tr>' html += '<th></th>'", "b): # xor two strings of different lengths # a", "key_by_space(2, 8), lambda : key_by_space(6, 9), lambda : key_by_space(10, 10),", "key_by_space(7, 20), lambda : key_by_space(4, 21), lambda : key_by_space(6, 22),", "17), lambda : key_by_space(10, 18), lambda : key_by_space(6, 19), lambda", "key_by_space(6, 19), lambda : key_by_space(7, 20), lambda : key_by_space(4, 21),", ": key_by_guess(10, 82, 'e'), lambda : key_by_guess(6, 83, 'c'), lambda", "key_by_space(8, 15), lambda : key_by_space(8, 16), lambda : key_by_space(4, 17),", "in xrange(max_len): html += '<th>' + str(i) + '</th>' html", "+ 1) for ch in c: html += '<td>' html", "2), lambda : key_by_space(4, 3), lambda : key_by_space(9, 4), lambda", "12), lambda : key_by_space(6, 13), lambda : key_by_space(4, 14), lambda", "23), lambda : key_by_space(0, 24), lambda : key_by_guess(1, 25, 'y'),", "html += '<br />' html += '&#%d;' % ord(ch) html", ": key_by_space(10, 18), lambda : key_by_space(6, 19), lambda : key_by_space(7,", ": key_by_space(3, 28), lambda : key_by_space(9, 29), lambda : key_by_space(7,", "- 1] + 1 break else: return # def main():", "'w') as f: f.write(html) def key_by_space(ct_index, ch_index): return key_by_guess(ct_index, ch_index)", "80, 'x'), lambda : key_by_guess(3, 81, 't'), lambda : key_by_guess(10,", "lambda : key_by_space(7, 6), lambda : key_by_guess(4, 7, '\\''), #???", "46), lambda : key_by_guess(10, 47, 'e'), lambda : key_by_guess(10, 48,", "c MSGS = (s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11) MSGS_DECODED = [s.decode('hex') for s in", "strxor(key, msg) print print c #.encode('hex') return c MSGS =", "key_by_space(6, 22), lambda : key_by_space(4, 23), lambda : key_by_space(0, 24),", ": key_by_guess(3, 50, 'i'), lambda : key_by_guess(3, 51, 't'), lambda", ": key_by_space(8, 15), lambda : key_by_space(8, 16), lambda : key_by_space(4,", "indices[j - 1] + 1 break else: return # def", "lambda : key_by_guess(1, 25, 'y'), lambda : key_by_space(7, 26), lambda", "41), lambda : key_by_space(5, 42), lambda : key_by_guess(3, 43, 'n'),", ": key_by_space(5, 37), lambda : key_by_space(7, 38), lambda : key_by_space(1,", "c in combinations('ABCD', 2): # print c def output_combinations_table(): comb", "key_by_guess(4, 7, '\\''), #??? lambda : key_by_space(2, 8), lambda :", "#??? lambda : key_by_space(2, 8), lambda : key_by_space(6, 9), lambda", "'<th></th>' for i in xrange(max_len): html += '<th>' + str(i)", "key_by_guess(10, 77, 'n'), lambda : key_by_space(10, 78), lambda : key_by_guess(3,", "lambda : key_by_guess(6, 84, 'e'), # lambda : key_by_guess(6, 68,", ": key_by_guess(3, 52, 'h'), lambda : key_by_guess(3, 53, 'm'), lambda", "lambda : key_by_guess(4, 7, '\\''), #??? lambda : key_by_space(2, 8),", "= '466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83' s11 = '32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904' def strxor(a, b): # xor", "key_by_guess(10, 47, 'e'), lambda : key_by_guess(10, 48, 'r'), lambda :", ": key_by_space(7, 20), lambda : key_by_space(4, 21), lambda : key_by_space(6,", "lambda : key_by_guess(10, 67, 'y'), lambda : key_by_space(10, 68), lambda", "67, 'y'), lambda : key_by_space(10, 68), lambda : key_by_space(7, 69),", ": key_by_guess(0, 62, 'o'), lambda : key_by_space(0, 63), lambda :", "lambda : key_by_space(3, 28), lambda : key_by_space(9, 29), lambda :", "key_by_space(4, 14), lambda : key_by_space(8, 15), lambda : key_by_space(8, 16),", "key_by_space(0, 40), lambda : key_by_space(8, 41), lambda : key_by_space(5, 42),", "i2 + 1) for ch in c: html += '<td>'", "+= '<tr>' html += '<th></th>' for i in xrange(max_len): html", "< n - (r - i): indices[i] = indices[i] +", "'y'), lambda : key_by_space(7, 26), lambda : key_by_space(10, 27), lambda", "i1, i2, c in comb: html += '<tr>' html +=", ": key_by_space(4, 21), lambda : key_by_space(6, 22), lambda : key_by_space(4,", "20), lambda : key_by_space(4, 21), lambda : key_by_space(6, 22), lambda", "if len(c) > max_len: max_len = len(c) # print max_len", "'&#%d;' % ord(ch) html += '</td>' html += '</tr>' html", "= indices[i] + 1 for j in range(i + 1,", "'<tr>' html += '<th></th>' for i in xrange(max_len): html +=", "lambda : key_by_space(10, 68), lambda : key_by_space(7, 69), lambda :", "r): indices = range(r) n = len(iterable) while True: yield", "+= '</html>' with open('combinations.html', 'w') as f: f.write(html) def key_by_space(ct_index,", "lambda : key_by_space(1, 31), lambda : key_by_space(0, 32), lambda :", ": key_by_space(4, 44), lambda : key_by_guess(7, 45, 'y'), lambda :", "lambda : key_by_guess(6, 65, 't'), lambda : key_by_space(5, 66), lambda", "len(x)) max_len = 0 for i1, i2, c in comb:", ": key_by_space(4, 14), lambda : key_by_space(8, 15), lambda : key_by_space(8,", "lambda : key_by_space(2, 72), lambda : key_by_space(1, 73), lambda :", "'32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa' s5 = '3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070' s6 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4' s7 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce'", "'</tr>' html += '</thead>' for i1, i2, c in comb:", "combinations('ABCD', 2): # print c def output_combinations_table(): comb = [(i1,", "for ch in c: html += '<td>' html += '%02d'", "= '32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa' s5 = '3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070' s6 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4' s7 =", "range(i + 1, r): indices[j] = indices[j - 1] +", "lambda : key_by_space(10, 18), lambda : key_by_space(6, 19), lambda :", "for i1, i2, c in comb: if len(c) > max_len:", "i, s in enumerate(MSGS): print '%2d: %s' % (i +", "= '<KEY>' s2 = '<KEY>' s3 = '32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb' s4 =", "# def main(): # for c in combinations('ABCD', 2): #", "html += '<tr>' html += '<td>(%s, %s)</td>' % (i1 +", "print max_len html += '<th></th>' for i in xrange(max_len): html", "= a.decode('hex') # b = b.decode('hex') if len(a) > len(b):", "lambda : key_by_space(4, 54), lambda : key_by_space(1, 55), lambda :", "i2, c in comb: if len(c) > max_len: max_len =", ": key_by_space(7, 38), lambda : key_by_space(1, 39), lambda : key_by_space(0,", "strxor(s1.decode('hex'), s2.decode('hex'))) for i1, i2, (s1,s2) in combinations(MSGS, 2)] html", "55), lambda : key_by_space(10, 56), lambda : key_by_space(1, 57), lambda", "return key_by_guess(ct_index, ch_index) def key_by_guess(ct_index, ch_index, guess=' '): return strxor(MSGS_DECODED[ct_index][ch_index],", "(s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11) MSGS_DECODED = [s.decode('hex') for s in MSGS] def combinations(iterable,", "48, 'r'), lambda : key_by_space(7, 49), lambda : key_by_guess(3, 50,", "[ lambda : key_by_space(9, 0), lambda : key_by_space(8, 1), lambda", "lambda : key_by_space(4, 21), lambda : key_by_space(6, 22), lambda :", "38), lambda : key_by_space(1, 39), lambda : key_by_space(0, 40), lambda", "r): indices[j] = indices[j - 1] + 1 break else:", ": key_by_space(7, 61), lambda : key_by_guess(0, 62, 'o'), lambda :", "lambda : key_by_space(6, 9), lambda : key_by_space(10, 10), lambda :", "max(combinations, key=lambda x: len(x)) max_len = 0 for i1, i2,", "key_by_space(0, 2), lambda : key_by_space(4, 3), lambda : key_by_space(9, 4),", "2): # print c def output_combinations_table(): comb = [(i1, i2,", "'o'), lambda : key_by_space(0, 63), lambda : key_by_space(10, 64), lambda", "= range(r) n = len(iterable) while True: yield tuple(i for", "key_by_space(9, 12), lambda : key_by_space(6, 13), lambda : key_by_space(4, 14),", "lambda : key_by_space(10, 78), lambda : key_by_guess(3, 79, 'e'), lambda", "guess) def main(): output_combinations_table() key = [ lambda : key_by_space(9,", ": key_by_space(0, 74), lambda : key_by_guess(10, 75, 'h'), lambda :", "key_by_space(4, 21), lambda : key_by_space(6, 22), lambda : key_by_space(4, 23),", "= strxor(key, msg) print print c #.encode('hex') return c MSGS", "key_by_guess(10, 48, 'r'), lambda : key_by_space(7, 49), lambda : key_by_guess(3,", ": key_by_guess(3, 80, 'x'), lambda : key_by_guess(3, 81, 't'), lambda", "# lambda : key_by_guess(6, 68, 't'), ] for i, s", "83, 'c'), lambda : key_by_guess(6, 84, 'e'), # lambda :", "= b.decode('hex') if len(a) > len(b): return (\"\".join([chr(ord(x) ^ ord(y))", "63), lambda : key_by_space(10, 64), lambda : key_by_guess(6, 65, 't'),", "0), lambda : key_by_space(8, 1), lambda : key_by_space(0, 2), lambda", "+ str(i) + '</th>' html += '</tr>' html += '</table>'", "'e'), lambda : key_by_guess(10, 48, 'r'), lambda : key_by_space(7, 49),", "s2 = '<KEY>' s3 = '32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb' s4 = '32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa' s5", "= [ lambda : key_by_space(9, 0), lambda : key_by_space(8, 1),", "lambda : key_by_guess(6, 68, 't'), ] for i, s in", "html += '</tr>' html += '<tr>' html += '<th></th>' for", "key_by_guess(ct_index, ch_index) def key_by_guess(ct_index, ch_index, guess=' '): return strxor(MSGS_DECODED[ct_index][ch_index], guess)", ": key_by_space(0, 2), lambda : key_by_space(4, 3), lambda : key_by_space(9,", "'h'), lambda : key_by_guess(10, 76, 'a'), lambda : key_by_guess(10, 77,", "key_by_space(10, 56), lambda : key_by_space(1, 57), lambda : key_by_space(0, 58),", "key_by_space(0, 32), lambda : key_by_space(10, 33), lambda : key_by_space(8, 34),", "57), lambda : key_by_space(0, 58), lambda : key_by_space(9, 59), lambda", "68), lambda : key_by_space(7, 69), lambda : key_by_space(1, 70), lambda", ": key_by_space(0, 58), lambda : key_by_space(9, 59), lambda : key_by_space(3,", ": key_by_space(4, 54), lambda : key_by_space(1, 55), lambda : key_by_space(10,", "62, 'o'), lambda : key_by_space(0, 63), lambda : key_by_space(10, 64),", "# for c in combinations('ABCD', 2): # print c def", "c def output_combinations_table(): comb = [(i1, i2, strxor(s1.decode('hex'), s2.decode('hex'))) for", ": key_by_space(7, 30), lambda : key_by_space(1, 31), lambda : key_by_space(0,", ": key_by_space(3, 71), lambda : key_by_space(2, 72), lambda : key_by_space(1,", "lambda : key_by_space(4, 14), lambda : key_by_space(8, 15), lambda :", ": key_by_space(1, 70), lambda : key_by_space(3, 71), lambda : key_by_space(2,", "key_by_space(3, 71), lambda : key_by_space(2, 72), lambda : key_by_space(1, 73),", "indices[j] = indices[j - 1] + 1 break else: return", "lambda : key_by_guess(10, 82, 'e'), lambda : key_by_guess(6, 83, 'c'),", ": key_by_guess(3, 43, 'n'), lambda : key_by_space(4, 44), lambda :", "'y'), lambda : key_by_space(7, 46), lambda : key_by_guess(10, 47, 'e'),", "# print max_len html += '<th></th>' for i in xrange(max_len):", ": key_by_guess(6, 68, 't'), ] for i, s in enumerate(MSGS):", "lambda : key_by_space(2, 8), lambda : key_by_space(6, 9), lambda :", "key_by_space(0, 58), lambda : key_by_space(9, 59), lambda : key_by_space(3, 60),", ": key_by_space(0, 32), lambda : key_by_space(10, 33), lambda : key_by_space(8,", "37), lambda : key_by_space(7, 38), lambda : key_by_space(1, 39), lambda", "'<thead>' html += '<tr>' # WTF??? # max_len = max(combinations,", ": key_by_space(10, 78), lambda : key_by_guess(3, 79, 'e'), lambda :", "range(r) n = len(iterable) while True: yield tuple(i for i", "'<tr>' # WTF??? # max_len = max(combinations, key=lambda x: len(x))", "lambda : key_by_space(10, 56), lambda : key_by_space(1, 57), lambda :", "75, 'h'), lambda : key_by_guess(10, 76, 'a'), lambda : key_by_guess(10,", "key = [ lambda : key_by_space(9, 0), lambda : key_by_space(8,", "21), lambda : key_by_space(6, 22), lambda : key_by_space(4, 23), lambda", ": key_by_space(10, 35), lambda : key_by_space(9, 36), lambda : key_by_space(5,", "65, 't'), lambda : key_by_space(5, 66), lambda : key_by_guess(10, 67,", "# print c def output_combinations_table(): comb = [(i1, i2, strxor(s1.decode('hex'),", "% (i + 1, ''.join([strxor(k(), ch) for k, ch in", "(\"\".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])) #.encode('hex')", "key_by_space(4, 3), lambda : key_by_space(9, 4), lambda : key_by_space(6, 5),", ": key_by_space(1, 31), lambda : key_by_space(0, 32), lambda : key_by_space(10,", "lambda : key_by_space(0, 24), lambda : key_by_guess(1, 25, 'y'), lambda", "lambda : key_by_space(3, 60), lambda : key_by_space(7, 61), lambda :", "lambda : key_by_space(7, 69), lambda : key_by_space(1, 70), lambda :", "= len(iterable) while True: yield tuple(i for i in indices)", "indices[i] + 1 for j in range(i + 1, r):", "# max_len = max(combinations, key=lambda x: len(x)) max_len = 0", "output_combinations_table() key = [ lambda : key_by_space(9, 0), lambda :", "output_combinations_table(): comb = [(i1, i2, strxor(s1.decode('hex'), s2.decode('hex'))) for i1, i2,", "comb = [(i1, i2, strxor(s1.decode('hex'), s2.decode('hex'))) for i1, i2, (s1,s2)", "for s in MSGS] def combinations(iterable, r): indices = range(r)", "a = a.decode('hex') # b = b.decode('hex') if len(a) >", "msg): c = strxor(key, msg) print print c #.encode('hex') return", "59), lambda : key_by_space(3, 60), lambda : key_by_space(7, 61), lambda", "key_by_guess(10, 75, 'h'), lambda : key_by_guess(10, 76, 'a'), lambda :", "len(a) > len(b): return (\"\".join([chr(ord(x) ^ ord(y)) for (x, y)", "guess=' '): return strxor(MSGS_DECODED[ct_index][ch_index], guess) def main(): output_combinations_table() key =", "70), lambda : key_by_space(3, 71), lambda : key_by_space(2, 72), lambda", "+= '<th></th>' for i in xrange(max_len): html += '<th>' +", "key_by_guess(3, 43, 'n'), lambda : key_by_space(4, 44), lambda : key_by_guess(7,", "= '3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070' s6 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4' s7 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce' s8 =", "lambda : key_by_space(1, 39), lambda : key_by_space(0, 40), lambda :", "lambda : key_by_space(10, 35), lambda : key_by_space(9, 36), lambda :", "+= '</table>' html += '</body>' html += '</html>' with open('combinations.html',", "html += '</html>' with open('combinations.html', 'w') as f: f.write(html) def", "lambda : key_by_space(7, 46), lambda : key_by_guess(10, 47, 'e'), lambda", "for i in xrange(max_len): html += '<th>' + str(i) +", "1) for ch in c: html += '<td>' html +=", "y) in zip(a[:len(b)], b)])) #.encode('hex') else: return (\"\".join([chr(ord(x) ^ ord(y))", ": key_by_guess(6, 83, 'c'), lambda : key_by_guess(6, 84, 'e'), #", "(tuple(iterable[i] for i in indices),) for i in reversed(range(r)): if", "html += '%02d' % ord(ch) if ch in string.printable: html", "def combinations(iterable, r): indices = range(r) n = len(iterable) while", "b)])) #.encode('hex') else: return (\"\".join([chr(ord(x) ^ ord(y)) for (x, y)", ": key_by_guess(6, 65, 't'), lambda : key_by_space(5, 66), lambda :", "return c MSGS = (s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11) MSGS_DECODED = [s.decode('hex') for s", "f: f.write(html) def key_by_space(ct_index, ch_index): return key_by_guess(ct_index, ch_index) def key_by_guess(ct_index,", "strxor(MSGS_DECODED[ct_index][ch_index], guess) def main(): output_combinations_table() key = [ lambda :", "lambda : key_by_space(0, 40), lambda : key_by_space(8, 41), lambda :", "max_len html += '<th></th>' for i in xrange(max_len): html +=", "'t'), lambda : key_by_space(5, 66), lambda : key_by_guess(10, 67, 'y'),", "lambda : key_by_space(8, 34), lambda : key_by_space(10, 35), lambda :", "i in indices),) for i in reversed(range(r)): if indices[i] <", "+ '</th>' html += '</tr>' html += '</table>' html +=", ": key_by_space(10, 10), lambda : key_by_space(1, 11), lambda : key_by_space(9,", "key_by_space(9, 4), lambda : key_by_space(6, 5), lambda : key_by_space(7, 6),", "'315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3' s9 = '271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027' s10 = '466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83' s11 = '32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904'", "#.encode('hex') return c MSGS = (s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11) MSGS_DECODED = [s.decode('hex') for", "combinations(iterable, r): indices = range(r) n = len(iterable) while True:", "ch) for k, ch in itertools.izip(key, s.decode('hex'))])) if __name__ ==", "key_by_space(7, 26), lambda : key_by_space(10, 27), lambda : key_by_space(3, 28),", "+= '<br />' html += '&#%d;' % ord(ch) html +=", ": key_by_space(1, 11), lambda : key_by_space(9, 12), lambda : key_by_space(6,", "'%2d: %s' % (i + 1, ''.join([strxor(k(), ch) for k,", ": key_by_space(6, 5), lambda : key_by_space(7, 6), lambda : key_by_guess(4,", "combinations(MSGS, 2)] html = '<html><body>' html += '<table style=\"white-space:nowrap\" border=\"1\">'", "'\\''), #??? lambda : key_by_space(2, 8), lambda : key_by_space(6, 9),", "xor two strings of different lengths # a = a.decode('hex')", "47, 'e'), lambda : key_by_guess(10, 48, 'r'), lambda : key_by_space(7,", "i in indices) + (tuple(iterable[i] for i in indices),) for", ": key_by_space(3, 60), lambda : key_by_space(7, 61), lambda : key_by_guess(0,", "lambda : key_by_guess(3, 80, 'x'), lambda : key_by_guess(3, 81, 't'),", "enumerate(MSGS): print '%2d: %s' % (i + 1, ''.join([strxor(k(), ch)", ": key_by_space(9, 36), lambda : key_by_space(5, 37), lambda : key_by_space(7,", "+= '</tr>' html += '<tr>' html += '<th></th>' for i", "key_by_space(10, 78), lambda : key_by_guess(3, 79, 'e'), lambda : key_by_guess(3,", ": key_by_space(8, 41), lambda : key_by_space(5, 42), lambda : key_by_guess(3,", "key_by_space(10, 18), lambda : key_by_space(6, 19), lambda : key_by_space(7, 20),", "lambda : key_by_guess(3, 53, 'm'), lambda : key_by_space(4, 54), lambda", "len(c) # print max_len html += '<th></th>' for i in", "key_by_space(1, 11), lambda : key_by_space(9, 12), lambda : key_by_space(6, 13),", "lambda : key_by_space(10, 64), lambda : key_by_guess(6, 65, 't'), lambda", "s1 = '<KEY>' s2 = '<KEY>' s3 = '32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb' s4", "key_by_space(1, 55), lambda : key_by_space(10, 56), lambda : key_by_space(1, 57),", "1, i2 + 1) for ch in c: html +=", "def key_by_guess(ct_index, ch_index, guess=' '): return strxor(MSGS_DECODED[ct_index][ch_index], guess) def main():", "key_by_space(4, 17), lambda : key_by_space(10, 18), lambda : key_by_space(6, 19),", "itertools s1 = '<KEY>' s2 = '<KEY>' s3 = '32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb'", "key_by_space(0, 74), lambda : key_by_guess(10, 75, 'h'), lambda : key_by_guess(10,", "def encrypt(key, msg): c = strxor(key, msg) print print c", "from timeit import itertools s1 = '<KEY>' s2 = '<KEY>'", "s6 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4' s7 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce' s8 = '315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3' s9", "html += '<td>(%s, %s)</td>' % (i1 + 1, i2 +", ": key_by_space(10, 27), lambda : key_by_space(3, 28), lambda : key_by_space(9,", "key_by_space(5, 66), lambda : key_by_guess(10, 67, 'y'), lambda : key_by_space(10,", "len(c) > max_len: max_len = len(c) # print max_len html", "i2, (s1,s2) in combinations(MSGS, 2)] html = '<html><body>' html +=", "'r'), lambda : key_by_space(7, 49), lambda : key_by_guess(3, 50, 'i'),", "= len(c) # print max_len html += '<th></th>' for i", "lambda : key_by_space(1, 11), lambda : key_by_space(9, 12), lambda :", "lambda : key_by_guess(10, 75, 'h'), lambda : key_by_guess(10, 76, 'a'),", "lambda : key_by_space(7, 61), lambda : key_by_guess(0, 62, 'o'), lambda", "+ 1, r): indices[j] = indices[j - 1] + 1", "lambda : key_by_space(4, 3), lambda : key_by_space(9, 4), lambda :", "msg) print print c #.encode('hex') return c MSGS = (s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11)", "+ (tuple(iterable[i] for i in indices),) for i in reversed(range(r)):", "'<br />' html += '&#%d;' % ord(ch) html += '</td>'", ": key_by_space(8, 34), lambda : key_by_space(10, 35), lambda : key_by_space(9,", "'y'), lambda : key_by_space(10, 68), lambda : key_by_space(7, 69), lambda", "lambda : key_by_space(7, 38), lambda : key_by_space(1, 39), lambda :", "key_by_guess(0, 62, 'o'), lambda : key_by_space(0, 63), lambda : key_by_space(10,", "key_by_space(3, 28), lambda : key_by_space(9, 29), lambda : key_by_space(7, 30),", "56), lambda : key_by_space(1, 57), lambda : key_by_space(0, 58), lambda", "i in reversed(range(r)): if indices[i] < n - (r -", "45, 'y'), lambda : key_by_space(7, 46), lambda : key_by_guess(10, 47,", "+= '<thead>' html += '<tr>' # WTF??? # max_len =", "= '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd2061bbde24eb76a19d84aba34d8de287be84d07e7e9a30ee714979c7e1123a8bd9822a33ecaf512472e8e8f8db3f9635c1949e640c621854eba0d79eccf52ff111284b4cc61d11902aebc66f2b2e436434eacc0aba938220b084800c2ca4e693522643573b2c4ce35050b0cf774201f0fe52ac9f26d71b6cf61a711cc229f77ace7aa88a2f19983122b11be87a59c355d25f8e4' s7 = '32510bfbacfbb9befd54415da243e1695ecabd58c519cd4bd90f1fa6ea5ba47b01c909ba7696cf606ef40c04afe1ac0aa8148dd066592ded9f8774b529c7ea125d298e8883f5e9305f4b44f915cb2bd05af51373fd9b4af511039fa2d96f83414aaaf261bda2e97b170fb5cce2a53e675c154c0d9681596934777e2275b381ce2e40582afe67650b13e72287ff2270abcf73bb028932836fbdecfecee0a3b894473c1bbeb6b4913a536ce4f9b13f1efff71ea313c8661dd9a4ce' s8 = '315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3' s9 =", "c in comb: html += '<tr>' html += '<td>(%s, %s)</td>'", "indices),) for i in reversed(range(r)): if indices[i] < n -", "lambda : key_by_guess(3, 50, 'i'), lambda : key_by_guess(3, 51, 't'),", "72), lambda : key_by_space(1, 73), lambda : key_by_space(0, 74), lambda", "'t'), lambda : key_by_guess(3, 52, 'h'), lambda : key_by_guess(3, 53,", "/>' html += '&#%d;' % ord(ch) html += '</td>' html", "html += '</body>' html += '</html>' with open('combinations.html', 'w') as", "31), lambda : key_by_space(0, 32), lambda : key_by_space(10, 33), lambda", "html = '<html><body>' html += '<table style=\"white-space:nowrap\" border=\"1\">' html +=", "b = b.decode('hex') if len(a) > len(b): return (\"\".join([chr(ord(x) ^", "0 for i1, i2, c in comb: if len(c) >", "lambda : key_by_guess(10, 47, 'e'), lambda : key_by_guess(10, 48, 'r'),", "in zip(a, b[:len(a)])])) #.encode('hex') def random(size=16): return open(\"/dev/urandom\").read(size) def encrypt(key,", "s10 = '466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83' s11 = '32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904' def strxor(a, b): #", ": key_by_space(7, 69), lambda : key_by_space(1, 70), lambda : key_by_space(3,", "reversed(range(r)): if indices[i] < n - (r - i): indices[i]", "WTF??? # max_len = max(combinations, key=lambda x: len(x)) max_len =", "] for i, s in enumerate(MSGS): print '%2d: %s' %", "27), lambda : key_by_space(3, 28), lambda : key_by_space(9, 29), lambda", ": key_by_guess(3, 53, 'm'), lambda : key_by_space(4, 54), lambda :", "str(i) + '</th>' html += '</tr>' html += '</table>' html", "lambda : key_by_space(6, 13), lambda : key_by_space(4, 14), lambda :", "= '271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027' s10 = '466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83' s11 = '32510ba9babebbbefd001547a810e67149caee11d945cd7fc81a05e9f85aac650e9052ba6a8cd8257bf14d13e6f0a803b54fde9e77472dbff89d71b57bddef121336cb85ccb8f3315f4b52e301d16e9f52f904' def strxor(a,", "c = strxor(key, msg) print print c #.encode('hex') return c", "ch_index): return key_by_guess(ct_index, ch_index) def key_by_guess(ct_index, ch_index, guess=' '): return", ": key_by_space(9, 0), lambda : key_by_space(8, 1), lambda : key_by_space(0,", "for i in indices) + (tuple(iterable[i] for i in indices),)", "lambda : key_by_space(10, 27), lambda : key_by_space(3, 28), lambda :", "print c def output_combinations_table(): comb = [(i1, i2, strxor(s1.decode('hex'), s2.decode('hex')))", "return (\"\".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])]))", ": key_by_space(1, 73), lambda : key_by_space(0, 74), lambda : key_by_guess(10,", "string from timeit import itertools s1 = '<KEY>' s2 =", "indices = range(r) n = len(iterable) while True: yield tuple(i", ": key_by_guess(3, 79, 'e'), lambda : key_by_guess(3, 80, 'x'), lambda", "lambda : key_by_space(0, 63), lambda : key_by_space(10, 64), lambda :", "[(i1, i2, strxor(s1.decode('hex'), s2.decode('hex'))) for i1, i2, (s1,s2) in combinations(MSGS,", "i in xrange(max_len): html += '<th>' + str(i) + '</th>'", "13), lambda : key_by_space(4, 14), lambda : key_by_space(8, 15), lambda", "str(i) + '</th>' html += '</tr>' html += '</thead>' for", ": key_by_space(7, 46), lambda : key_by_guess(10, 47, 'e'), lambda :", "indices[i] = indices[i] + 1 for j in range(i +", "s3 = '32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb' s4 = '32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa' s5 = '3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070' s6", "key_by_space(6, 9), lambda : key_by_space(10, 10), lambda : key_by_space(1, 11),", "a.decode('hex') # b = b.decode('hex') if len(a) > len(b): return", "key_by_guess(3, 52, 'h'), lambda : key_by_guess(3, 53, 'm'), lambda :", "html += '<tr>' # WTF??? # max_len = max(combinations, key=lambda", "#.encode('hex') def random(size=16): return open(\"/dev/urandom\").read(size) def encrypt(key, msg): c =", "lambda : key_by_guess(10, 76, 'a'), lambda : key_by_guess(10, 77, 'n'),", "'e'), # lambda : key_by_guess(6, 68, 't'), ] for i,", "+= '&#%d;' % ord(ch) html += '</td>' html += '</tr>'", ": key_by_space(8, 1), lambda : key_by_space(0, 2), lambda : key_by_space(4,", ": key_by_space(6, 13), lambda : key_by_space(4, 14), lambda : key_by_space(8,", "def main(): # for c in combinations('ABCD', 2): # print", "'<KEY>' s3 = '32510ba9a7b2bba9b8005d43a304b5714cc0bb0c8a34884dd91304b8ad40b62b07df44ba6e9d8a2368e51d04e0e7b207b70b9b8261112bacb6c866a232dfe257527dc29398f5f3251a0d47e503c66e935de81230b59b7afb5f41afa8d661cb' s4 = '32510ba9aab2a8a4fd06414fb517b5605cc0aa0dc91a8908c2064ba8ad5ea06a029056f47a8ad3306ef5021eafe1ac01a81197847a5c68a1b78769a37bc8f4575432c198ccb4ef63590256e305cd3a9544ee4160ead45aef520489e7da7d835402bca670bda8eb775200b8dabbba246b130f040d8ec6447e2c767f3d30ed81ea2e4c1404e1315a1010e7229be6636aaa' s5 = '3f561ba9adb4b6ebec54424ba317b564418fac0dd35f8c08d31a1fe9e24fe56808c213f17c81d9607cee021dafe1e001b21ade877a5e68bea88d61b93ac5ee0d562e8e9582f5ef375f0a4ae20ed86e935de81230b59b73fb4302cd95d770c65b40aaa065f2a5e33a5a0bb5dcaba43722130f042f8ec85b7c2070'", "'e'), lambda : key_by_guess(6, 83, 'c'), lambda : key_by_guess(6, 84,", "for i, s in enumerate(MSGS): print '%2d: %s' % (i", "key_by_space(0, 63), lambda : key_by_space(10, 64), lambda : key_by_guess(6, 65,", "'<html><body>' html += '<table style=\"white-space:nowrap\" border=\"1\">' html += '<thead>' html", "with open('combinations.html', 'w') as f: f.write(html) def key_by_space(ct_index, ch_index): return", "indices[i] < n - (r - i): indices[i] = indices[i]", "key_by_space(5, 37), lambda : key_by_space(7, 38), lambda : key_by_space(1, 39),", ": key_by_guess(10, 77, 'n'), lambda : key_by_space(10, 78), lambda :", "1 for j in range(i + 1, r): indices[j] =", "lambda : key_by_space(10, 10), lambda : key_by_space(1, 11), lambda :", "11), lambda : key_by_space(9, 12), lambda : key_by_space(6, 13), lambda", "53, 'm'), lambda : key_by_space(4, 54), lambda : key_by_space(1, 55),", "key_by_space(10, 68), lambda : key_by_space(7, 69), lambda : key_by_space(1, 70),", "encrypt(key, msg): c = strxor(key, msg) print print c #.encode('hex')", "y) in zip(a, b[:len(a)])])) #.encode('hex') def random(size=16): return open(\"/dev/urandom\").read(size) def", "58), lambda : key_by_space(9, 59), lambda : key_by_space(3, 60), lambda", "81, 't'), lambda : key_by_guess(10, 82, 'e'), lambda : key_by_guess(6,", "= indices[j - 1] + 1 break else: return #", "zip(a[:len(b)], b)])) #.encode('hex') else: return (\"\".join([chr(ord(x) ^ ord(y)) for (x,", "s8 = '315c4eeaa8b5f8bffd11155ea506b56041c6a00c8a08854dd21a4bbde54ce56801d943ba708b8a3574f40c00fff9e00fa1439fd0654327a3bfc860b92f89ee04132ecb9298f5fd2d5e4b45e40ecc3b9d59e9417df7c95bba410e9aa2ca24c5474da2f276baa3ac325918b2daada43d6712150441c2e04f6565517f317da9d3' s9 = '271946f9bbb2aeadec111841a81abc300ecaa01bd8069d5cc91005e9fe4aad6e04d513e96d99de2569bc5e50eeeca709b50a8a987f4264edb6896fb537d0a716132ddc938fb0f836480e06ed0fcd6e9759f40462f9cf57f4564186a2c1778f1543efa270bda5e933421cbe88a4a52222190f471e9bd15f652b653b7071aec59a2705081ffe72651d08f822c9ed6d76e48b63ab15d0208573a7eef027' s10 = '466d06ece998b7a2fb1d464fed2ced7641ddaa3cc31c9941cf110abbf409ed39598005b3399ccfafb61d0315fca0a314be138a9f32503bedac8067f03adbf3575c3b8edc9ba7f537530541ab0f9f3cd04ff50d66f1d559ba520e89a2cb2a83' s11", "key_by_guess(6, 65, 't'), lambda : key_by_space(5, 66), lambda : key_by_guess(10,", "s in enumerate(MSGS): print '%2d: %s' % (i + 1,", "34), lambda : key_by_space(10, 35), lambda : key_by_space(9, 36), lambda", "lambda : key_by_space(0, 74), lambda : key_by_guess(10, 75, 'h'), lambda", "in MSGS] def combinations(iterable, r): indices = range(r) n =", "77, 'n'), lambda : key_by_space(10, 78), lambda : key_by_guess(3, 79,", "51, 't'), lambda : key_by_guess(3, 52, 'h'), lambda : key_by_guess(3,", "key_by_guess(3, 79, 'e'), lambda : key_by_guess(3, 80, 'x'), lambda :", "ch_index, guess=' '): return strxor(MSGS_DECODED[ct_index][ch_index], guess) def main(): output_combinations_table() key", "'n'), lambda : key_by_space(10, 78), lambda : key_by_guess(3, 79, 'e'),", "#.encode('hex') else: return (\"\".join([chr(ord(x) ^ ord(y)) for (x, y) in", "else: return # def main(): # for c in combinations('ABCD',", "c: html += '<td>' html += '%02d' % ord(ch) if", "html += '<thead>' html += '<tr>' # WTF??? # max_len", ": key_by_guess(4, 7, '\\''), #??? lambda : key_by_space(2, 8), lambda", "html += '</tr>' html += '</table>' html += '</body>' html", "lambda : key_by_space(9, 36), lambda : key_by_space(5, 37), lambda :", "10), lambda : key_by_space(1, 11), lambda : key_by_space(9, 12), lambda", "key_by_space(1, 70), lambda : key_by_space(3, 71), lambda : key_by_space(2, 72),", "key_by_space(9, 29), lambda : key_by_space(7, 30), lambda : key_by_space(1, 31),", ": key_by_guess(3, 81, 't'), lambda : key_by_guess(10, 82, 'e'), lambda", "24), lambda : key_by_guess(1, 25, 'y'), lambda : key_by_space(7, 26),", "'n'), lambda : key_by_space(4, 44), lambda : key_by_guess(7, 45, 'y'),", "+= '<tr>' # WTF??? # max_len = max(combinations, key=lambda x:", "key_by_space(10, 10), lambda : key_by_space(1, 11), lambda : key_by_space(9, 12),", "i1, i2, (s1,s2) in combinations(MSGS, 2)] html = '<html><body>' html", "i2, c in comb: html += '<tr>' html += '<td>(%s,", "zip(a, b[:len(a)])])) #.encode('hex') def random(size=16): return open(\"/dev/urandom\").read(size) def encrypt(key, msg):", "len(b): return (\"\".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)],", "+ 1, ''.join([strxor(k(), ch) for k, ch in itertools.izip(key, s.decode('hex'))]))", "= max(combinations, key=lambda x: len(x)) max_len = 0 for i1,", "'</th>' html += '</tr>' html += '</table>' html += '</body>'", "for i1, i2, (s1,s2) in combinations(MSGS, 2)] html = '<html><body>'", ": key_by_space(8, 16), lambda : key_by_space(4, 17), lambda : key_by_space(10,", "lambda : key_by_space(9, 29), lambda : key_by_space(7, 30), lambda :", "lambda : key_by_space(4, 17), lambda : key_by_space(10, 18), lambda :", ": key_by_space(4, 23), lambda : key_by_space(0, 24), lambda : key_by_guess(1,", "25, 'y'), lambda : key_by_space(7, 26), lambda : key_by_space(10, 27),", "'</body>' html += '</html>' with open('combinations.html', 'w') as f: f.write(html)", "i2, strxor(s1.decode('hex'), s2.decode('hex'))) for i1, i2, (s1,s2) in combinations(MSGS, 2)]", "else: return (\"\".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a," ]
[ "ValueError('arms_sampled is empty!') unsampled_arm_name_list = [name for name, sampled_arm in", "we have three arms (arm1, arm2, and arm3) with expected", "the optimal arms arm1 and arm2. ``{arm1: 0.5, arm2: 0.5,", "in arms_sampled.iteritems() if sampled_arm.total == 0] return frozenset(unsampled_arm_name_list) @abstractmethod def", "set of names of the unsampled arms :rtype: frozenset(str) :raise:", "running bandit ``subtype`` endpoint. Computes the allocation to each arm", "optimal arms. For example, if we have three arms (arm1,", "allocation) key-value pairs :rtype: a dictionary of (str, float64) pairs", "``{arm1: 0.5, arm2: 0.5, arm3: 0.0}`` :return: the dictionary of", "Works with k-armed bandits (k >= 1). The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf", "subtype of the UCB bandit algorithm (default: None) :type subtype:", "arms_sampled = self._historical_info.arms_sampled if not arms_sampled: raise ValueError('sample_arms are empty!')", "# -*- coding: utf-8 -*- \"\"\"Classes (Python) to compute the", "to encapsulate the computation of bandit UCB. The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf", "a tie, the method will split the allocation among the", "all arms are pulled at least once, this method will", "[(self.get_ucb_payoff(sampled_arm, number_sampled), arm_name) for arm_name, sampled_arm in arms_sampled.iteritems()] return get_winning_arm_names_from_payoff_arm_name_list(ucb_payoff_arm_name_list)", "r\"\"\"Implementation of the constructor of UCB (Upper Confidence Bound) and", "is empty!') unsampled_arm_name_list = [name for name, sampled_arm in arms_sampled.iteritems()", "1). The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf If there is at least one", "number_sampled: int :return: ucb payoff :rtype: float64 :raise: ValueError when", "are multiple unsampled arms). If all arms are pulled at", "multiple unsampled arms). If all arms are pulled at least", "details) :param subtype: subtype of the UCB bandit algorithm (default:", "\"\"\" def __init__( self, historical_info, subtype=None, ): \"\"\"Construct a UCB", "\"\"\" pass def allocate_arms(self): r\"\"\"Compute the allocation to each arm", "unsampled arms unsampled_arm_names = self.get_unsampled_arm_names(arms_sampled) if unsampled_arm_names: return unsampled_arm_names number_sampled", "a UCB object. :param historical_info: a dictionary of arms sampled", "(Upper Confidence Bound) arm allocation and choosing the arm to", "import get_winning_arm_names_from_payoff_arm_name_list, get_equal_arm_allocations class UCBInterface(BanditInterface): r\"\"\"Implementation of the constructor of", ":class:`moe.bandit.data_containers.SampleArm` :type arms_sampled: dictionary of (str, SampleArm()) pairs :return: set", ":param number_sampled: the overall number of pulls so far :type", "unsampled arm (randomly choose an unsampled arm if there are", ":type number_sampled: int :return: ucb payoff :rtype: float64 :raise: ValueError", "the dictionary of (arm, allocation) key-value pairs :rtype: a dictionary", ":rtype: frozenset(str) :raise: ValueError when ``arms_sampled`` are empty. \"\"\" if", "ValueError('arms_sampled is empty!') # If there exists an unsampled arm,", "names based on the given ``arms_sampled``.. Throws an exception when", "arms_sampled: dictionary of (str, SampleArm()) pairs :return: set of names", "pull the optimal arm (best expected upper confidence bound payoff).", "See :mod:`moe.bandit.bandit_interface` docs for further details. \"\"\" def __init__( self,", "to each arm based on the given subtype, and, historical", "Confidence Bound) and method allocate_arms. The method get_ucb_payoff is implemented", "The method get_ucb_payoff is implemented in subclass. A class to", "of the constructor of UCB (Upper Confidence Bound) and method", "k-armed bandits (k >= 1). The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf If there", "\"\"\" if not arms_sampled: raise ValueError('arms_sampled is empty!') # If", "(randomly choose an unsampled arm if there are multiple unsampled", "a dictionary of arm name to :class:`moe.bandit.data_containers.SampleArm` :type arms_sampled: dictionary", "of a tie, the method will split the allocation among", "copy from abc import abstractmethod from moe.bandit.bandit_interface import BanditInterface from", "pairs :rtype: a dictionary of (str, float64) pairs :raise: ValueError", "a dictionary of arms sampled :type historical_info: dictionary of (str,", "The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf If there is at least one unsampled", "of (arm, allocation) key-value pairs :rtype: a dictionary of (str,", "arms_sampled: raise ValueError('sample_arms are empty!') return get_equal_arm_allocations(arms_sampled, self.get_winning_arm_names(arms_sampled)) def get_winning_arm_names(self,", "will split the allocation among the optimal arms. For example,", ":mod:`moe.bandit.bandit_interface` for further details on bandit. \"\"\" import copy from", "are pulled at least once, this method will pull the", "will pull the optimal arm (best expected upper confidence bound", "arm2: 0.5, arm3: 0.0}`` :return: the dictionary of (arm, allocation)", "historical_info: dictionary of (str, SampleArm()) pairs (see :class:`moe.bandit.data_containers.SampleArm` for more", "an unsampled arm, return the names of the unsampled arms", "unsampled arm, return the names of the unsampled arms unsampled_arm_names", "optimal arm (best expected upper confidence bound payoff). See :func:`moe.bandit.ucb.ucb_interface.UCBInterface.get_ucb_payoff`", "number_sampled: the overall number of pulls so far :type number_sampled:", "(Upper Confidence Bound) and method allocate_arms. The method get_ucb_payoff is", "bandits (k >= 1). The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf If there is", "See :func:`moe.bandit.ucb.ucb_interface.UCBInterface.get_ucb_payoff` for details on how to compute the expected", "each arm based on the given subtype, and, historical info.", "Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf To inherit this class, a subclass needs to", "in subclasses for details. :param sampled_arm: a sampled arm :type", "inherit this class, a subclass needs to implement get_ucb_payoff (see", "encapsulate the computation of bandit UCB. The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf To", "key-value pairs :rtype: a dictionary of (str, float64) pairs :raise:", "expected upper confidence bound payoff using the UCB subtype formula.", "the allocation among the optimal arms. For example, if we", "\"\"\"Classes (Python) to compute the Bandit UCB (Upper Confidence Bound)", "SampleArm()) pairs (see :class:`moe.bandit.data_containers.SampleArm` for more details) :param subtype: subtype", "(best expected upper confidence bound payoff). See :func:`moe.bandit.ucb.ucb_interface.UCBInterface.get_ucb_payoff` for details", "pull next. See :mod:`moe.bandit.bandit_interface` for further details on bandit. \"\"\"", "the winning arms :rtype: frozenset(str) :raise: ValueError when ``arms_sampled`` are", "number_sampled = sum([sampled_arm.total for sampled_arm in arms_sampled.itervalues()]) ucb_payoff_arm_name_list = [(self.get_ucb_payoff(sampled_arm,", "will choose to pull the unsampled arm (randomly choose an", "``arms_sampled`` are empty. \"\"\" if not arms_sampled: raise ValueError('arms_sampled is", "dictionary of arm name to :class:`moe.bandit.data_containers.SampleArm` :type arms_sampled: dictionary of", "and, historical info. Works with k-armed bandits (k >= 1).", "is implemented in subclass. A class to encapsulate the computation", "coding: utf-8 -*- \"\"\"Classes (Python) to compute the Bandit UCB", "further details. \"\"\" def __init__( self, historical_info, subtype=None, ): \"\"\"Construct", "once, this method will pull the optimal arm (best expected", "A class to encapsulate the computation of bandit UCB. The", "dictionary of (str, float64) pairs :raise: ValueError when ``sample_arms`` are", "exception when arms_sampled is empty. :param arms_sampled: a dictionary of", "of the winning arms :rtype: frozenset(str) :raise: ValueError when ``arms_sampled``", "an exception when arms_sampled is empty. :param arms_sampled: a dictionary", "upper confidence bound payoff using the UCB subtype formula. See", "-*- coding: utf-8 -*- \"\"\"Classes (Python) to compute the Bandit", "UCB (Upper Confidence Bound) and method allocate_arms. The method get_ucb_payoff", "(arm1, arm2, and arm3) with expected UCB payoff 0.5, 0.5,", "far :type number_sampled: int :return: ucb payoff :rtype: float64 :raise:", "compute the Bandit UCB (Upper Confidence Bound) arm allocation and", "= subtype @staticmethod def get_unsampled_arm_names(arms_sampled): r\"\"\"Compute the set of unsampled", "the method will split the allocation among the optimal arms.", "arms (arm1, arm2, and arm3) with expected UCB payoff 0.5,", "arms_sampled is empty. :param arms_sampled: a dictionary of arm name", "on bandit. \"\"\" import copy from abc import abstractmethod from", "to implement get_ucb_payoff (see :func:`moe.bandit.ucb.ucb1.UCB1.get_ucb_payoff` for an example), everything else", "def get_winning_arm_names(self, arms_sampled): r\"\"\"Compute the set of winning arm names", "arm (best expected upper confidence bound payoff). See :func:`moe.bandit.ucb.ucb_interface.UCBInterface.get_ucb_payoff` for", "overall number of pulls so far :type number_sampled: int :return:", "``sampled_arm`` is empty. \"\"\" pass def allocate_arms(self): r\"\"\"Compute the allocation", "import BanditInterface from moe.bandit.utils import get_winning_arm_names_from_payoff_arm_name_list, get_equal_arm_allocations class UCBInterface(BanditInterface): r\"\"\"Implementation", "get_unsampled_arm_names(arms_sampled): r\"\"\"Compute the set of unsampled arm names based on", "moe.bandit.bandit_interface import BanditInterface from moe.bandit.utils import get_winning_arm_names_from_payoff_arm_name_list, get_equal_arm_allocations class UCBInterface(BanditInterface):", ":rtype: a dictionary of (str, float64) pairs :raise: ValueError when", "ucb_payoff_arm_name_list = [(self.get_ucb_payoff(sampled_arm, number_sampled), arm_name) for arm_name, sampled_arm in arms_sampled.iteritems()]", "to pull next. See :mod:`moe.bandit.bandit_interface` for further details on bandit.", "definition in subclasses for details. :param sampled_arm: a sampled arm", "are empty. \"\"\" arms_sampled = self._historical_info.arms_sampled if not arms_sampled: raise", "implemented. See :mod:`moe.bandit.bandit_interface` docs for further details. \"\"\" def __init__(", "of bandit UCB. The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf To inherit this class,", "return unsampled_arm_names number_sampled = sum([sampled_arm.total for sampled_arm in arms_sampled.itervalues()]) ucb_payoff_arm_name_list", "arm2. ``{arm1: 0.5, arm2: 0.5, arm3: 0.0}`` :return: the dictionary", "this method will pull the optimal arm (best expected upper", "copy.deepcopy(historical_info) self._subtype = subtype @staticmethod def get_unsampled_arm_names(arms_sampled): r\"\"\"Compute the set", "def get_unsampled_arm_names(arms_sampled): r\"\"\"Compute the set of unsampled arm names based", "= self.get_unsampled_arm_names(arms_sampled) if unsampled_arm_names: return unsampled_arm_names number_sampled = sum([sampled_arm.total for", "``arms_sampled``.. Throws an exception when arms_sampled is empty. :param arms_sampled:", "unsampled arm if there are multiple unsampled arms). If all", "expected upper confidence bound payoff). See :func:`moe.bandit.ucb.ucb_interface.UCBInterface.get_ucb_payoff` for details on", "the unsampled arm (randomly choose an unsampled arm if there", "bandit algorithm (default: None) :type subtype: str \"\"\" self._historical_info =", "expected UCB payoff 0.5, 0.5, and 0.1 respectively. We split", "None) :type subtype: str \"\"\" self._historical_info = copy.deepcopy(historical_info) self._subtype =", "0.1 respectively. We split the allocation between the optimal arms", "have three arms (arm1, arm2, and arm3) with expected UCB", "0.5, arm2: 0.5, arm3: 0.0}`` :return: the dictionary of (arm,", "= sum([sampled_arm.total for sampled_arm in arms_sampled.itervalues()]) ucb_payoff_arm_name_list = [(self.get_ucb_payoff(sampled_arm, number_sampled),", "the computation of bandit UCB. The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf To inherit", "the given subtype, and, historical info. Works with k-armed bandits", "of arm name to :class:`moe.bandit.data_containers.SampleArm` :type arms_sampled: dictionary of (str,", "and choosing the arm to pull next. See :mod:`moe.bandit.bandit_interface` for", "method allocate_arms. The method get_ucb_payoff is implemented in subclass. A", "get_equal_arm_allocations(arms_sampled, self.get_winning_arm_names(arms_sampled)) def get_winning_arm_names(self, arms_sampled): r\"\"\"Compute the set of winning", "ValueError('sample_arms are empty!') return get_equal_arm_allocations(arms_sampled, self.get_winning_arm_names(arms_sampled)) def get_winning_arm_names(self, arms_sampled): r\"\"\"Compute", "of the UCB bandit algorithm (default: None) :type subtype: str", "method will choose to pull the unsampled arm (randomly choose", "bandit. \"\"\" import copy from abc import abstractmethod from moe.bandit.bandit_interface", "float64) pairs :raise: ValueError when ``sample_arms`` are empty. \"\"\" arms_sampled", "0.5, and 0.1 respectively. We split the allocation between the", "UCBInterface(BanditInterface): r\"\"\"Implementation of the constructor of UCB (Upper Confidence Bound)", "subtype: str \"\"\" self._historical_info = copy.deepcopy(historical_info) self._subtype = subtype @staticmethod", ":mod:`moe.bandit.bandit_interface` docs for further details. \"\"\" def __init__( self, historical_info,", "self, historical_info, subtype=None, ): \"\"\"Construct a UCB object. :param historical_info:", "SampleArm()) pairs :return: set of names of the unsampled arms", "0] return frozenset(unsampled_arm_name_list) @abstractmethod def get_ucb_payoff(self, sampled_arm, number_sampled): r\"\"\"Compute the", "arms arm1 and arm2. ``{arm1: 0.5, arm2: 0.5, arm3: 0.0}``", "To inherit this class, a subclass needs to implement get_ucb_payoff", "using the UCB subtype formula. See definition in subclasses for", "bandit ``subtype`` endpoint. Computes the allocation to each arm based", "sampled arm :type sampled_arm: :class:`moe.bandit.data_containers.SampleArm` :param number_sampled: the overall number", "from abc import abstractmethod from moe.bandit.bandit_interface import BanditInterface from moe.bandit.utils", "The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf To inherit this class, a subclass needs", "subtype, and, historical info. Works with k-armed bandits (k >=", "expected upper confidence bound payoff (expected UCB payoff) In case", "implement get_ucb_payoff (see :func:`moe.bandit.ucb.ucb1.UCB1.get_ucb_payoff` for an example), everything else is", "self._subtype = subtype @staticmethod def get_unsampled_arm_names(arms_sampled): r\"\"\"Compute the set of", "there exists an unsampled arm, return the names of the", "example, if we have three arms (arm1, arm2, and arm3)", "get_equal_arm_allocations class UCBInterface(BanditInterface): r\"\"\"Implementation of the constructor of UCB (Upper", "method will pull the optimal arm (best expected upper confidence", "dictionary of (arm, allocation) key-value pairs :rtype: a dictionary of", "constructor of UCB (Upper Confidence Bound) and method allocate_arms. The", "abc import abstractmethod from moe.bandit.bandit_interface import BanditInterface from moe.bandit.utils import", "subclass needs to implement get_ucb_payoff (see :func:`moe.bandit.ucb.ucb1.UCB1.get_ucb_payoff` for an example),", "with k-armed bandits (k >= 1). The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf If", "(Python) to compute the Bandit UCB (Upper Confidence Bound) arm", "a sampled arm :type sampled_arm: :class:`moe.bandit.data_containers.SampleArm` :param number_sampled: the overall", "Throws an exception when arms_sampled is empty. :param arms_sampled: a", "frozenset(unsampled_arm_name_list) @abstractmethod def get_ucb_payoff(self, sampled_arm, number_sampled): r\"\"\"Compute the expected upper", "(str, SampleArm()) pairs :return: set of names of the winning", "r\"\"\"Compute the expected upper confidence bound payoff using the UCB", "number_sampled): r\"\"\"Compute the expected upper confidence bound payoff using the", "In case of a tie, the method will split the", "split the allocation between the optimal arms arm1 and arm2.", "UCB. The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf To inherit this class, a subclass", "how to compute the expected upper confidence bound payoff (expected", "each arm given ``historical_info``, running bandit ``subtype`` endpoint. Computes the", "arms are pulled at least once, this method will pull", "UCB subtype formula. See definition in subclasses for details. :param", "(k >= 1). The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf If there is at", "an unsampled arm if there are multiple unsampled arms). If", "pairs :raise: ValueError when ``sample_arms`` are empty. \"\"\" arms_sampled =", "a subclass needs to implement get_ucb_payoff (see :func:`moe.bandit.ucb.ucb1.UCB1.get_ucb_payoff` for an", "empty. \"\"\" if not arms_sampled: raise ValueError('arms_sampled is empty!') #", "\"\"\"Construct a UCB object. :param historical_info: a dictionary of arms", "to compute the Bandit UCB (Upper Confidence Bound) arm allocation", "details. \"\"\" def __init__( self, historical_info, subtype=None, ): \"\"\"Construct a", "0.5, arm3: 0.0}`` :return: the dictionary of (arm, allocation) key-value", ":class:`moe.bandit.data_containers.SampleArm` for more details) :param subtype: subtype of the UCB", "def __init__( self, historical_info, subtype=None, ): \"\"\"Construct a UCB object.", "method get_ucb_payoff is implemented in subclass. A class to encapsulate", "BanditInterface from moe.bandit.utils import get_winning_arm_names_from_payoff_arm_name_list, get_equal_arm_allocations class UCBInterface(BanditInterface): r\"\"\"Implementation of", "to pull the unsampled arm (randomly choose an unsampled arm", "get_ucb_payoff is implemented in subclass. A class to encapsulate the", ":type arms_sampled: dictionary of (str, SampleArm()) pairs :return: set of", "further details on bandit. \"\"\" import copy from abc import", "\"\"\" arms_sampled = self._historical_info.arms_sampled if not arms_sampled: raise ValueError('sample_arms are", "formula. See definition in subclasses for details. :param sampled_arm: a", "Bound) and method allocate_arms. The method get_ucb_payoff is implemented in", "historical_info: a dictionary of arms sampled :type historical_info: dictionary of", "subtype @staticmethod def get_unsampled_arm_names(arms_sampled): r\"\"\"Compute the set of unsampled arm", "sampled_arm: :class:`moe.bandit.data_containers.SampleArm` :param number_sampled: the overall number of pulls so", "arm2, and arm3) with expected UCB payoff 0.5, 0.5, and", "get_winning_arm_names_from_payoff_arm_name_list, get_equal_arm_allocations class UCBInterface(BanditInterface): r\"\"\"Implementation of the constructor of UCB", "arms_sampled.itervalues()]) ucb_payoff_arm_name_list = [(self.get_ucb_payoff(sampled_arm, number_sampled), arm_name) for arm_name, sampled_arm in", "arm3) with expected UCB payoff 0.5, 0.5, and 0.1 respectively.", "unsampled_arm_names = self.get_unsampled_arm_names(arms_sampled) if unsampled_arm_names: return unsampled_arm_names number_sampled = sum([sampled_arm.total", "payoff 0.5, 0.5, and 0.1 respectively. We split the allocation", "Confidence Bound) arm allocation and choosing the arm to pull", "arms unsampled_arm_names = self.get_unsampled_arm_names(arms_sampled) if unsampled_arm_names: return unsampled_arm_names number_sampled =", "when ``arms_sampled`` are empty. \"\"\" if not arms_sampled: raise ValueError('arms_sampled", ":return: the dictionary of (arm, allocation) key-value pairs :rtype: a", "subtype formula. See definition in subclasses for details. :param sampled_arm:", "Bandit UCB (Upper Confidence Bound) arm allocation and choosing the", "the constructor of UCB (Upper Confidence Bound) and method allocate_arms.", "get_ucb_payoff (see :func:`moe.bandit.ucb.ucb1.UCB1.get_ucb_payoff` for an example), everything else is already", "arm, return the names of the unsampled arms unsampled_arm_names =", "empty. \"\"\" pass def allocate_arms(self): r\"\"\"Compute the allocation to each", "details on bandit. \"\"\" import copy from abc import abstractmethod", "http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf If there is at least one unsampled arm, this", "@abstractmethod def get_ucb_payoff(self, sampled_arm, number_sampled): r\"\"\"Compute the expected upper confidence", "unsampled arm, this method will choose to pull the unsampled", "the allocation to each arm given ``historical_info``, running bandit ``subtype``", "Bound) arm allocation and choosing the arm to pull next.", "when ``sample_arms`` are empty. \"\"\" arms_sampled = self._historical_info.arms_sampled if not", "empty!') # If there exists an unsampled arm, return the", "arm if there are multiple unsampled arms). If all arms", "upper confidence bound payoff). See :func:`moe.bandit.ucb.ucb_interface.UCBInterface.get_ucb_payoff` for details on how", "arm given ``historical_info``, running bandit ``subtype`` endpoint. Computes the allocation", "r\"\"\"Compute the set of unsampled arm names based on the", "if there are multiple unsampled arms). If all arms are", "names of the unsampled arms :rtype: frozenset(str) :raise: ValueError when", "allocation between the optimal arms arm1 and arm2. ``{arm1: 0.5,", "pairs (see :class:`moe.bandit.data_containers.SampleArm` for more details) :param subtype: subtype of", "UCB payoff) In case of a tie, the method will", "payoff :rtype: float64 :raise: ValueError when ``sampled_arm`` is empty. \"\"\"", "UCB (Upper Confidence Bound) arm allocation and choosing the arm", "``subtype`` endpoint. Computes the allocation to each arm based on", "sampled_arm, number_sampled): r\"\"\"Compute the expected upper confidence bound payoff using", "ucb payoff :rtype: float64 :raise: ValueError when ``sampled_arm`` is empty.", "For example, if we have three arms (arm1, arm2, and", "self.get_unsampled_arm_names(arms_sampled) if unsampled_arm_names: return unsampled_arm_names number_sampled = sum([sampled_arm.total for sampled_arm", "== 0] return frozenset(unsampled_arm_name_list) @abstractmethod def get_ucb_payoff(self, sampled_arm, number_sampled): r\"\"\"Compute", "the allocation to each arm based on the given subtype,", "pulls so far :type number_sampled: int :return: ucb payoff :rtype:", "computation of bandit UCB. The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf To inherit this", "int :return: ucb payoff :rtype: float64 :raise: ValueError when ``sampled_arm``", "allocation to each arm given ``historical_info``, running bandit ``subtype`` endpoint.", "everything else is already implemented. See :mod:`moe.bandit.bandit_interface` docs for further", "If there is at least one unsampled arm, this method", "arm to pull next. See :mod:`moe.bandit.bandit_interface` for further details on", "docs for further details. \"\"\" def __init__( self, historical_info, subtype=None,", "endpoint. Computes the allocation to each arm based on the", "details on how to compute the expected upper confidence bound", "the expected upper confidence bound payoff (expected UCB payoff) In", ":func:`moe.bandit.ucb.ucb_interface.UCBInterface.get_ucb_payoff` for details on how to compute the expected upper", "sampled_arm: a sampled arm :type sampled_arm: :class:`moe.bandit.data_containers.SampleArm` :param number_sampled: the", "str \"\"\" self._historical_info = copy.deepcopy(historical_info) self._subtype = subtype @staticmethod def", "payoff using the UCB subtype formula. See definition in subclasses", "and method allocate_arms. The method get_ucb_payoff is implemented in subclass.", "needs to implement get_ucb_payoff (see :func:`moe.bandit.ucb.ucb1.UCB1.get_ucb_payoff` for an example), everything", "arms_sampled: raise ValueError('arms_sampled is empty!') unsampled_arm_name_list = [name for name,", "between the optimal arms arm1 and arm2. ``{arm1: 0.5, arm2:", "arms :rtype: frozenset(str) :raise: ValueError when ``arms_sampled`` are empty. \"\"\"", "based on the given subtype, and, historical info. Works with", "not arms_sampled: raise ValueError('arms_sampled is empty!') # If there exists", "confidence bound payoff using the UCB subtype formula. See definition", "for further details on bandit. \"\"\" import copy from abc", "details. :param sampled_arm: a sampled arm :type sampled_arm: :class:`moe.bandit.data_containers.SampleArm` :param", "of (str, float64) pairs :raise: ValueError when ``sample_arms`` are empty.", "the UCB subtype formula. See definition in subclasses for details.", ":func:`moe.bandit.ucb.ucb1.UCB1.get_ucb_payoff` for an example), everything else is already implemented. See", "when ``sampled_arm`` is empty. \"\"\" pass def allocate_arms(self): r\"\"\"Compute the", "is empty. \"\"\" pass def allocate_arms(self): r\"\"\"Compute the allocation to", "the unsampled arms :rtype: frozenset(str) :raise: ValueError when ``arms_sampled`` are", "if not arms_sampled: raise ValueError('arms_sampled is empty!') unsampled_arm_name_list = [name", "for sampled_arm in arms_sampled.itervalues()]) ucb_payoff_arm_name_list = [(self.get_ucb_payoff(sampled_arm, number_sampled), arm_name) for", "of the unsampled arms :rtype: frozenset(str) :raise: ValueError when ``arms_sampled``", "self.get_winning_arm_names(arms_sampled)) def get_winning_arm_names(self, arms_sampled): r\"\"\"Compute the set of winning arm", "(arm, allocation) key-value pairs :rtype: a dictionary of (str, float64)", ":type sampled_arm: :class:`moe.bandit.data_containers.SampleArm` :param number_sampled: the overall number of pulls", "allocation to each arm based on the given subtype, and,", "empty. \"\"\" arms_sampled = self._historical_info.arms_sampled if not arms_sampled: raise ValueError('sample_arms", "class UCBInterface(BanditInterface): r\"\"\"Implementation of the constructor of UCB (Upper Confidence", "= [(self.get_ucb_payoff(sampled_arm, number_sampled), arm_name) for arm_name, sampled_arm in arms_sampled.iteritems()] return", "return get_equal_arm_allocations(arms_sampled, self.get_winning_arm_names(arms_sampled)) def get_winning_arm_names(self, arms_sampled): r\"\"\"Compute the set of", "pulled at least once, this method will pull the optimal", "example), everything else is already implemented. See :mod:`moe.bandit.bandit_interface` docs for", "arms_sampled: a dictionary of arm name to :class:`moe.bandit.data_containers.SampleArm` :type arms_sampled:", "(str, SampleArm()) pairs (see :class:`moe.bandit.data_containers.SampleArm` for more details) :param subtype:", "Computes the allocation to each arm based on the given", "method will split the allocation among the optimal arms. For", "of UCB (Upper Confidence Bound) and method allocate_arms. The method", "among the optimal arms. For example, if we have three", ":return: set of names of the winning arms :rtype: frozenset(str)", "of the unsampled arms unsampled_arm_names = self.get_unsampled_arm_names(arms_sampled) if unsampled_arm_names: return", "class, a subclass needs to implement get_ucb_payoff (see :func:`moe.bandit.ucb.ucb1.UCB1.get_ucb_payoff` for", "names of the winning arms :rtype: frozenset(str) :raise: ValueError when", "when arms_sampled is empty. :param arms_sampled: a dictionary of arm", "Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf If there is at least one unsampled arm,", "object. :param historical_info: a dictionary of arms sampled :type historical_info:", "[name for name, sampled_arm in arms_sampled.iteritems() if sampled_arm.total == 0]", "choose an unsampled arm if there are multiple unsampled arms).", "sampled :type historical_info: dictionary of (str, SampleArm()) pairs (see :class:`moe.bandit.data_containers.SampleArm`", "of names of the winning arms :rtype: frozenset(str) :raise: ValueError", "info. Works with k-armed bandits (k >= 1). The Algorithm:", "(default: None) :type subtype: str \"\"\" self._historical_info = copy.deepcopy(historical_info) self._subtype", "choose to pull the unsampled arm (randomly choose an unsampled", "subclass. A class to encapsulate the computation of bandit UCB.", "arms sampled :type historical_info: dictionary of (str, SampleArm()) pairs (see", "arm based on the given subtype, and, historical info. Works", "self._historical_info.arms_sampled if not arms_sampled: raise ValueError('sample_arms are empty!') return get_equal_arm_allocations(arms_sampled,", "in subclass. A class to encapsulate the computation of bandit", "bound payoff). See :func:`moe.bandit.ucb.ucb_interface.UCBInterface.get_ucb_payoff` for details on how to compute", "for details. :param sampled_arm: a sampled arm :type sampled_arm: :class:`moe.bandit.data_containers.SampleArm`", ">= 1). The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf If there is at least", "allocation among the optimal arms. For example, if we have", "0.0}`` :return: the dictionary of (arm, allocation) key-value pairs :rtype:", "the optimal arms. For example, if we have three arms", "See definition in subclasses for details. :param sampled_arm: a sampled", "an example), everything else is already implemented. See :mod:`moe.bandit.bandit_interface` docs", "to :class:`moe.bandit.data_containers.SampleArm` :type arms_sampled: dictionary of (str, SampleArm()) pairs :return:", "empty. \"\"\" if not arms_sampled: raise ValueError('arms_sampled is empty!') unsampled_arm_name_list", "\"\"\" import copy from abc import abstractmethod from moe.bandit.bandit_interface import", "unsampled_arm_name_list = [name for name, sampled_arm in arms_sampled.iteritems() if sampled_arm.total", "choosing the arm to pull next. See :mod:`moe.bandit.bandit_interface` for further", "raise ValueError('arms_sampled is empty!') # If there exists an unsampled", "given subtype, and, historical info. Works with k-armed bandits (k", "of winning arm names based on the given ``arms_sampled``.. Throws", "the optimal arm (best expected upper confidence bound payoff). See", "is empty. :param arms_sampled: a dictionary of arm name to", "historical info. Works with k-armed bandits (k >= 1). The", "if unsampled_arm_names: return unsampled_arm_names number_sampled = sum([sampled_arm.total for sampled_arm in", "See :mod:`moe.bandit.bandit_interface` for further details on bandit. \"\"\" import copy", "payoff). See :func:`moe.bandit.ucb.ucb_interface.UCBInterface.get_ucb_payoff` for details on how to compute the", "for details on how to compute the expected upper confidence", "dictionary of (str, SampleArm()) pairs :return: set of names of", "are empty!') return get_equal_arm_allocations(arms_sampled, self.get_winning_arm_names(arms_sampled)) def get_winning_arm_names(self, arms_sampled): r\"\"\"Compute the", ":class:`moe.bandit.data_containers.SampleArm` :param number_sampled: the overall number of pulls so far", "__init__( self, historical_info, subtype=None, ): \"\"\"Construct a UCB object. :param", "is already implemented. See :mod:`moe.bandit.bandit_interface` docs for further details. \"\"\"", "return the names of the unsampled arms unsampled_arm_names = self.get_unsampled_arm_names(arms_sampled)", "the allocation between the optimal arms arm1 and arm2. ``{arm1:", "(str, SampleArm()) pairs :return: set of names of the unsampled", "arms_sampled.iteritems() if sampled_arm.total == 0] return frozenset(unsampled_arm_name_list) @abstractmethod def get_ucb_payoff(self,", "not arms_sampled: raise ValueError('arms_sampled is empty!') unsampled_arm_name_list = [name for", "arms). If all arms are pulled at least once, this", "for more details) :param subtype: subtype of the UCB bandit", "name, sampled_arm in arms_sampled.iteritems() if sampled_arm.total == 0] return frozenset(unsampled_arm_name_list)", "sampled_arm in arms_sampled.iteritems() if sampled_arm.total == 0] return frozenset(unsampled_arm_name_list) @abstractmethod", "if not arms_sampled: raise ValueError('arms_sampled is empty!') # If there", "UCB object. :param historical_info: a dictionary of arms sampled :type", "allocation and choosing the arm to pull next. See :mod:`moe.bandit.bandit_interface`", "class to encapsulate the computation of bandit UCB. The Algorithm:", "for an example), everything else is already implemented. See :mod:`moe.bandit.bandit_interface`", "the arm to pull next. See :mod:`moe.bandit.bandit_interface` for further details", "from moe.bandit.bandit_interface import BanditInterface from moe.bandit.utils import get_winning_arm_names_from_payoff_arm_name_list, get_equal_arm_allocations class", "UCB payoff 0.5, 0.5, and 0.1 respectively. We split the", "subtype: subtype of the UCB bandit algorithm (default: None) :type", "for further details. \"\"\" def __init__( self, historical_info, subtype=None, ):", "bandit UCB. The Algorithm: http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf To inherit this class, a", ":type subtype: str \"\"\" self._historical_info = copy.deepcopy(historical_info) self._subtype = subtype", "confidence bound payoff). See :func:`moe.bandit.ucb.ucb_interface.UCBInterface.get_ucb_payoff` for details on how to", "= [name for name, sampled_arm in arms_sampled.iteritems() if sampled_arm.total ==", "for name, sampled_arm in arms_sampled.iteritems() if sampled_arm.total == 0] return", "ValueError when ``arms_sampled`` are empty. \"\"\" if not arms_sampled: raise", "this method will choose to pull the unsampled arm (randomly", ":raise: ValueError when ``sample_arms`` are empty. \"\"\" arms_sampled = self._historical_info.arms_sampled", "arm, this method will choose to pull the unsampled arm", "sum([sampled_arm.total for sampled_arm in arms_sampled.itervalues()]) ucb_payoff_arm_name_list = [(self.get_ucb_payoff(sampled_arm, number_sampled), arm_name)", "else is already implemented. See :mod:`moe.bandit.bandit_interface` docs for further details.", ":param arms_sampled: a dictionary of arm name to :class:`moe.bandit.data_containers.SampleArm` :type", "pass def allocate_arms(self): r\"\"\"Compute the allocation to each arm given", "the UCB bandit algorithm (default: None) :type subtype: str \"\"\"", "r\"\"\"Compute the set of winning arm names based on the", "of (str, SampleArm()) pairs (see :class:`moe.bandit.data_containers.SampleArm` for more details) :param", "= copy.deepcopy(historical_info) self._subtype = subtype @staticmethod def get_unsampled_arm_names(arms_sampled): r\"\"\"Compute the", "if sampled_arm.total == 0] return frozenset(unsampled_arm_name_list) @abstractmethod def get_ucb_payoff(self, sampled_arm,", ":raise: ValueError when ``arms_sampled`` are empty. \"\"\" if not arms_sampled:", "from moe.bandit.utils import get_winning_arm_names_from_payoff_arm_name_list, get_equal_arm_allocations class UCBInterface(BanditInterface): r\"\"\"Implementation of the", "of pulls so far :type number_sampled: int :return: ucb payoff", "get_ucb_payoff(self, sampled_arm, number_sampled): r\"\"\"Compute the expected upper confidence bound payoff", "(see :func:`moe.bandit.ucb.ucb1.UCB1.get_ucb_payoff` for an example), everything else is already implemented.", "(expected UCB payoff) In case of a tie, the method", "of arms sampled :type historical_info: dictionary of (str, SampleArm()) pairs", "allocate_arms(self): r\"\"\"Compute the allocation to each arm given ``historical_info``, running", "We split the allocation between the optimal arms arm1 and", "empty!') unsampled_arm_name_list = [name for name, sampled_arm in arms_sampled.iteritems() if", "algorithm (default: None) :type subtype: str \"\"\" self._historical_info = copy.deepcopy(historical_info)", "def get_ucb_payoff(self, sampled_arm, number_sampled): r\"\"\"Compute the expected upper confidence bound", "arm3: 0.0}`` :return: the dictionary of (arm, allocation) key-value pairs", "unsampled arm names based on the given ``arms_sampled``.. Throws an", "confidence bound payoff (expected UCB payoff) In case of a", "allocate_arms. The method get_ucb_payoff is implemented in subclass. A class", "0.5, 0.5, and 0.1 respectively. We split the allocation between", "unsampled arms :rtype: frozenset(str) :raise: ValueError when ``arms_sampled`` are empty.", "raise ValueError('sample_arms are empty!') return get_equal_arm_allocations(arms_sampled, self.get_winning_arm_names(arms_sampled)) def get_winning_arm_names(self, arms_sampled):", "arm allocation and choosing the arm to pull next. See", "r\"\"\"Compute the allocation to each arm given ``historical_info``, running bandit", "to each arm given ``historical_info``, running bandit ``subtype`` endpoint. Computes", ":param sampled_arm: a sampled arm :type sampled_arm: :class:`moe.bandit.data_containers.SampleArm` :param number_sampled:", "there is at least one unsampled arm, this method will", "case of a tie, the method will split the allocation", "bound payoff using the UCB subtype formula. See definition in", "import abstractmethod from moe.bandit.bandit_interface import BanditInterface from moe.bandit.utils import get_winning_arm_names_from_payoff_arm_name_list,", "arm1 and arm2. ``{arm1: 0.5, arm2: 0.5, arm3: 0.0}`` :return:", "historical_info, subtype=None, ): \"\"\"Construct a UCB object. :param historical_info: a", "one unsampled arm, this method will choose to pull the", "already implemented. See :mod:`moe.bandit.bandit_interface` docs for further details. \"\"\" def", "is at least one unsampled arm, this method will choose", "the names of the unsampled arms unsampled_arm_names = self.get_unsampled_arm_names(arms_sampled) if", "of (str, SampleArm()) pairs :return: set of names of the", "the Bandit UCB (Upper Confidence Bound) arm allocation and choosing", "``sample_arms`` are empty. \"\"\" arms_sampled = self._historical_info.arms_sampled if not arms_sampled:", "upper confidence bound payoff (expected UCB payoff) In case of", "a dictionary of (str, float64) pairs :raise: ValueError when ``sample_arms``", "respectively. We split the allocation between the optimal arms arm1", "float64 :raise: ValueError when ``sampled_arm`` is empty. \"\"\" pass def", "SampleArm()) pairs :return: set of names of the winning arms", "def allocate_arms(self): r\"\"\"Compute the allocation to each arm given ``historical_info``,", "utf-8 -*- \"\"\"Classes (Python) to compute the Bandit UCB (Upper", "(see :class:`moe.bandit.data_containers.SampleArm` for more details) :param subtype: subtype of the", "the set of winning arm names based on the given", "there are multiple unsampled arms). If all arms are pulled", "are empty. \"\"\" if not arms_sampled: raise ValueError('arms_sampled is empty!')", "bound payoff (expected UCB payoff) In case of a tie,", "tie, the method will split the allocation among the optimal", "If all arms are pulled at least once, this method", ":return: ucb payoff :rtype: float64 :raise: ValueError when ``sampled_arm`` is", "compute the expected upper confidence bound payoff (expected UCB payoff)", "arm (randomly choose an unsampled arm if there are multiple", "on the given subtype, and, historical info. Works with k-armed", "If there exists an unsampled arm, return the names of", "given ``arms_sampled``.. Throws an exception when arms_sampled is empty. :param", "ValueError when ``sampled_arm`` is empty. \"\"\" pass def allocate_arms(self): r\"\"\"Compute", "of unsampled arm names based on the given ``arms_sampled``.. Throws", "number of pulls so far :type number_sampled: int :return: ucb", "\"\"\" if not arms_sampled: raise ValueError('arms_sampled is empty!') unsampled_arm_name_list =", ":raise: ValueError when ``sampled_arm`` is empty. \"\"\" pass def allocate_arms(self):", "on the given ``arms_sampled``.. Throws an exception when arms_sampled is", "at least one unsampled arm, this method will choose to", "``historical_info``, running bandit ``subtype`` endpoint. Computes the allocation to each", "payoff (expected UCB payoff) In case of a tie, the", "given ``historical_info``, running bandit ``subtype`` endpoint. Computes the allocation to", "dictionary of arms sampled :type historical_info: dictionary of (str, SampleArm())", "optimal arms arm1 and arm2. ``{arm1: 0.5, arm2: 0.5, arm3:", "exists an unsampled arm, return the names of the unsampled", "unsampled_arm_names: return unsampled_arm_names number_sampled = sum([sampled_arm.total for sampled_arm in arms_sampled.itervalues()])", "pairs :return: set of names of the winning arms :rtype:", "arm name to :class:`moe.bandit.data_containers.SampleArm` :type arms_sampled: dictionary of (str, SampleArm())", "sampled_arm.total == 0] return frozenset(unsampled_arm_name_list) @abstractmethod def get_ucb_payoff(self, sampled_arm, number_sampled):", "with expected UCB payoff 0.5, 0.5, and 0.1 respectively. We", "ValueError when ``sample_arms`` are empty. \"\"\" arms_sampled = self._historical_info.arms_sampled if", "unsampled arms). If all arms are pulled at least once,", "arm :type sampled_arm: :class:`moe.bandit.data_containers.SampleArm` :param number_sampled: the overall number of", "least one unsampled arm, this method will choose to pull", "frozenset(str) :raise: ValueError when ``arms_sampled`` are empty. \"\"\" if not", "import copy from abc import abstractmethod from moe.bandit.bandit_interface import BanditInterface", "subclasses for details. :param sampled_arm: a sampled arm :type sampled_arm:", "UCB bandit algorithm (default: None) :type subtype: str \"\"\" self._historical_info", "and arm3) with expected UCB payoff 0.5, 0.5, and 0.1", "self._historical_info = copy.deepcopy(historical_info) self._subtype = subtype @staticmethod def get_unsampled_arm_names(arms_sampled): r\"\"\"Compute", "and 0.1 respectively. We split the allocation between the optimal", ":rtype: float64 :raise: ValueError when ``sampled_arm`` is empty. \"\"\" pass", "in arms_sampled.itervalues()]) ucb_payoff_arm_name_list = [(self.get_ucb_payoff(sampled_arm, number_sampled), arm_name) for arm_name, sampled_arm", "based on the given ``arms_sampled``.. Throws an exception when arms_sampled", "the set of unsampled arm names based on the given", "set of unsampled arm names based on the given ``arms_sampled``..", "arms_sampled): r\"\"\"Compute the set of winning arm names based on", "empty. :param arms_sampled: a dictionary of arm name to :class:`moe.bandit.data_containers.SampleArm`", "winning arms :rtype: frozenset(str) :raise: ValueError when ``arms_sampled`` are empty.", "is empty!') # If there exists an unsampled arm, return", "unsampled_arm_names number_sampled = sum([sampled_arm.total for sampled_arm in arms_sampled.itervalues()]) ucb_payoff_arm_name_list =", "if we have three arms (arm1, arm2, and arm3) with", "pairs :return: set of names of the unsampled arms :rtype:", "the expected upper confidence bound payoff using the UCB subtype", "to compute the expected upper confidence bound payoff (expected UCB", "the unsampled arms unsampled_arm_names = self.get_unsampled_arm_names(arms_sampled) if unsampled_arm_names: return unsampled_arm_names", "\"\"\" self._historical_info = copy.deepcopy(historical_info) self._subtype = subtype @staticmethod def get_unsampled_arm_names(arms_sampled):", "the given ``arms_sampled``.. Throws an exception when arms_sampled is empty.", "-*- \"\"\"Classes (Python) to compute the Bandit UCB (Upper Confidence", "names of the unsampled arms unsampled_arm_names = self.get_unsampled_arm_names(arms_sampled) if unsampled_arm_names:", ":type historical_info: dictionary of (str, SampleArm()) pairs (see :class:`moe.bandit.data_containers.SampleArm` for", "this class, a subclass needs to implement get_ucb_payoff (see :func:`moe.bandit.ucb.ucb1.UCB1.get_ucb_payoff`", "the overall number of pulls so far :type number_sampled: int", "sampled_arm in arms_sampled.itervalues()]) ucb_payoff_arm_name_list = [(self.get_ucb_payoff(sampled_arm, number_sampled), arm_name) for arm_name,", "three arms (arm1, arm2, and arm3) with expected UCB payoff", "if not arms_sampled: raise ValueError('sample_arms are empty!') return get_equal_arm_allocations(arms_sampled, self.get_winning_arm_names(arms_sampled))", "set of names of the winning arms :rtype: frozenset(str) :raise:", "on how to compute the expected upper confidence bound payoff", "http://moodle.technion.ac.il/pluginfile.php/192340/mod_resource/content/0/UCB.pdf To inherit this class, a subclass needs to implement", "abstractmethod from moe.bandit.bandit_interface import BanditInterface from moe.bandit.utils import get_winning_arm_names_from_payoff_arm_name_list, get_equal_arm_allocations", "next. See :mod:`moe.bandit.bandit_interface` for further details on bandit. \"\"\" import", "split the allocation among the optimal arms. For example, if", "pull the unsampled arm (randomly choose an unsampled arm if", "arms. For example, if we have three arms (arm1, arm2,", "so far :type number_sampled: int :return: ucb payoff :rtype: float64", "winning arm names based on the given ``arms_sampled``.. Throws an", "least once, this method will pull the optimal arm (best", "# If there exists an unsampled arm, return the names", "raise ValueError('arms_sampled is empty!') unsampled_arm_name_list = [name for name, sampled_arm", "moe.bandit.utils import get_winning_arm_names_from_payoff_arm_name_list, get_equal_arm_allocations class UCBInterface(BanditInterface): r\"\"\"Implementation of the constructor", "set of winning arm names based on the given ``arms_sampled``..", "empty!') return get_equal_arm_allocations(arms_sampled, self.get_winning_arm_names(arms_sampled)) def get_winning_arm_names(self, arms_sampled): r\"\"\"Compute the set", "get_winning_arm_names(self, arms_sampled): r\"\"\"Compute the set of winning arm names based", "of names of the unsampled arms :rtype: frozenset(str) :raise: ValueError", ":param subtype: subtype of the UCB bandit algorithm (default: None)", "return frozenset(unsampled_arm_name_list) @abstractmethod def get_ucb_payoff(self, sampled_arm, number_sampled): r\"\"\"Compute the expected", "arms_sampled: raise ValueError('arms_sampled is empty!') # If there exists an", "dictionary of (str, SampleArm()) pairs (see :class:`moe.bandit.data_containers.SampleArm` for more details)", "and arm2. ``{arm1: 0.5, arm2: 0.5, arm3: 0.0}`` :return: the", "not arms_sampled: raise ValueError('sample_arms are empty!') return get_equal_arm_allocations(arms_sampled, self.get_winning_arm_names(arms_sampled)) def", "implemented in subclass. A class to encapsulate the computation of", "(str, float64) pairs :raise: ValueError when ``sample_arms`` are empty. \"\"\"", "@staticmethod def get_unsampled_arm_names(arms_sampled): r\"\"\"Compute the set of unsampled arm names", "): \"\"\"Construct a UCB object. :param historical_info: a dictionary of", "payoff) In case of a tie, the method will split", "subtype=None, ): \"\"\"Construct a UCB object. :param historical_info: a dictionary", ":param historical_info: a dictionary of arms sampled :type historical_info: dictionary", ":return: set of names of the unsampled arms :rtype: frozenset(str)", "= self._historical_info.arms_sampled if not arms_sampled: raise ValueError('sample_arms are empty!') return", "name to :class:`moe.bandit.data_containers.SampleArm` :type arms_sampled: dictionary of (str, SampleArm()) pairs", "more details) :param subtype: subtype of the UCB bandit algorithm", "at least once, this method will pull the optimal arm", "arm names based on the given ``arms_sampled``.. Throws an exception" ]
[ "') if text.strip() == \"\": continue result, error = Hedge.run('<stdin>',", "while True: text = input('Hedge > ') if text.strip() ==", "Hedge while True: text = input('Hedge > ') if text.strip()", "import Hedge while True: text = input('Hedge > ') if", "Hedge.run('<stdin>', text) if (error): print(error.asString()) elif result: if len(result.elements) ==", "input('Hedge > ') if text.strip() == \"\": continue result, error", "result, error = Hedge.run('<stdin>', text) if (error): print(error.asString()) elif result:", "= input('Hedge > ') if text.strip() == \"\": continue result,", "continue result, error = Hedge.run('<stdin>', text) if (error): print(error.asString()) elif", "== \"\": continue result, error = Hedge.run('<stdin>', text) if (error):", "print(error.asString()) elif result: if len(result.elements) == 1: print(repr(result.elements[0])) else: print(repr(result))", "True: text = input('Hedge > ') if text.strip() == \"\":", "error = Hedge.run('<stdin>', text) if (error): print(error.asString()) elif result: if", "if (error): print(error.asString()) elif result: if len(result.elements) == 1: print(repr(result.elements[0]))", "= Hedge.run('<stdin>', text) if (error): print(error.asString()) elif result: if len(result.elements)", "text = input('Hedge > ') if text.strip() == \"\": continue", "\"\": continue result, error = Hedge.run('<stdin>', text) if (error): print(error.asString())", "<reponame>RonaldoAPSD/Hedge import Hedge while True: text = input('Hedge > ')", "if text.strip() == \"\": continue result, error = Hedge.run('<stdin>', text)", "(error): print(error.asString()) elif result: if len(result.elements) == 1: print(repr(result.elements[0])) else:", "text) if (error): print(error.asString()) elif result: if len(result.elements) == 1:", "> ') if text.strip() == \"\": continue result, error =", "text.strip() == \"\": continue result, error = Hedge.run('<stdin>', text) if" ]
[ "* g.dds.prod(dtype=\"f8\") yield (ptype, field), data[mask] class IOHandlerPacked2D(IOHandlerPackedHDF5): _dataset_type =", "ftype, fname = field fsize = size rv[field] = np.empty(fsize,", "field): f = h5py.File(grid.filename, mode=\"r\") ds = f[\"/Grid%08i/%s\" % (grid.id,", "None for g in chunk.objs: if g.filename is None: continue", "for g in chunk.objs: if g.filename is None: continue if", "pds is not None: break else: raise RuntimeError( \"Could not", "dtype=h5_dtype) yield field, obj, self._read_obj_field(obj, field, (fid, data)) if fid", "g.NumberOfActiveParticles[ptype] == 0: continue pds = ds elif not g.NumberOfActiveParticles[ptype]:", "ds, ghost_zones=3): self.ds = ds import enzo self.enzo = enzo", "add_io: fields.append((\"io\", str(name))) elif add_dm: fields.append((\"DarkMatter\", str(name))) else: fields.append((\"enzo\", str(name)))", "for g in chunk.objs: # We want a *hard error*", "not hasattr(v, \"shape\") or v.dtype == \"O\": continue elif len(v.dims)", "== 0: continue ds = f.get(\"/Grid%08i\" % g.id) for ptype,", "f.close() def io_iter(self, chunks, fields): h5_dtype = self._field_dtype for chunk", "**kwargs)[self._base] class IOHandlerInMemory(BaseIOHandler): _dataset_type = \"enzo_inline\" def __init__(self, ds, ghost_zones=3):", "0: continue for ptype in sorted(ptf): x, y, z =", "some reason I don't understand. This does *not* need #", "= ds.get(f\"{pname}/{ptype}\") if pds is not None: break else: raise", "# Note one really important thing here: even if we", "others, nope. Doesn't seem to be a version thing. #", "print(\"Opening (read) %s\" % g.filename) f = h5py.File(g.filename, mode=\"r\") nap", "if g.NumberOfActiveParticles[ptype] == 0: continue pds = ds elif not", "the call is made from # _read_particle_coords. yield ptype, (x,", "fid is not None: fid.close() def _read_obj_field(self, obj, field, fid_data):", "add_dm = \"DarkMatter\" in grid.ds.particle_types for name, v in group.items():", "fields: ftype, fname = field fsize = size rv[field] =", "for ptype, field_list in sorted(ptf.items()): if ptype == \"io\": if", "None: fid_data = (None, None) fid, data = fid_data if", "if fname == \"Dark_Matter_Density\": data[:] = 0 return data.T raise", "name, v in self.grids_in_memory[grid.id].items(): # NOTE: This won't work with", "= g.select(selector, ds, rv[field], ind) # caches ind += nd", "yt.geometry.selection_routines import GridSelector from yt.utilities.io_handler import BaseIOHandler from yt.utilities.logger import", "[] add_io = \"io\" in grid.ds.particle_types for name, v in", "fields.append((\"enzo\", str(name))) elif add_io: fields.append((\"io\", str(name))) else: fields.append((\"enzo\", str(name))) return", "fields @property def _read_exception(self): return (KeyError,) def _read_particle_coords(self, chunks, ptf):", "= ( self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"], ) yield ptype, (x, y,", "len(dtypes) == 1: # Now, if everything we saw was", "_convert_mass: data *= g.dds.prod(dtype=\"f8\") yield (ptype, field), data[mask] if f:", "None: fid.close() fid = h5py.h5f.open( obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY ) filename =", "ng, ) ind = 0 for chunk in chunks: for", "is None: continue if f is None: # print(\"Opening (read)", "(slice(NGZ, -NGZ), slice(NGZ, -NGZ), slice(NGZ, -NGZ)) def _read_obj_field(self, *args, **kwargs):", "= g.select(selector, data_view, rv[field], ind) ind += nd assert ind", "is None: data = np.empty(obj.ActiveDimensions[::-1], dtype=self._field_dtype) ftype, fname = field", "g in chunk.objs: if g.id not in self.grids_in_memory: continue nap", "\"io\": if g.NumberOfParticles == 0: continue pds = ds elif", "fid_data is None: fid_data = (None, None) fid, data =", "cells of %s fields in %s grids\", size, [f2 for", "{} class IOHandlerPackedHDF5(BaseIOHandler): _dataset_type = \"enzo_packed_3d\" _base = slice(None) _field_dtype", "fields = [] dtypes = set() add_io = \"io\" in", "# print(\"Opening (read) %s\" % g.filename) f = h5py.File(g.filename, mode=\"r\")", "h5py.File(grid.filename, mode=\"r\") ds = f[\"/Grid%08i/%s\" % (grid.id, field)][:] f.close() return", "= np.atleast_3d(gds.get(fname)[()].transpose()) f.close() return rv if size is None: size", "= h5py.File(g.filename, mode=\"r\") gds = f.get(\"/Grid%08i\" % g.id) if gds", "fields = [] add_io = \"io\" in grid.ds.particle_types for name,", "fname in fields: rv[(ftype, fname)] = self.grids_in_memory[g.id][fname].swapaxes(0, 2) return rv", "v.ndim == 1: if grid.ds.dimensionality == 1: fields.append((\"enzo\", str(name))) elif", "h5py.File(g.filename, mode=\"r\") nap = sum(g.NumberOfActiveParticles.values()) if g.NumberOfParticles == 0 and", "f: f.close() def io_iter(self, chunks, fields): h5_dtype = self._field_dtype for", "fields.append((\"enzo\", str(name))) dtypes.add(v.dtype) if len(dtypes) == 1: # Now, if", "# These should be organized by grid filename f =", "= {} # Now we have to do something unpleasant", "we can go ahead and # set it here. We", "== 0: continue for ptype, field_list in sorted(ptf.items()): x, y,", "selector is None: # This only ever happens if the", "0 for chunk in chunks: f = None for g", "chunks: f = None for g in chunk.objs: if f", "z = ( np.asarray(pds.get(pn % ax)[()], dtype=\"=f8\") for ax in", "in chunk.objs) for field in fields: ftype, fname = field", "== \"O\": continue elif len(v.dims) == 1: if grid.ds.dimensionality ==", "# This only ever happens if the call is made", "fid_data): if fid_data is None: fid_data = (None, None) fid,", "# caches ind += nd f.close() return rv class IOHandlerPacked1D(IOHandlerPackedHDF5):", "don't know why, but on some installations of h5py this", "should be organized by grid filename for g in chunk.objs:", "for ftype, fname in fields: rv[(ftype, fname)] = self.grids_in_memory[g.id][fname].swapaxes(0, 2)", "dtype=\"float64\") ng = sum(len(c.objs) for c in chunks) mylog.debug( \"Reading", "data[mask] class IOHandlerPacked2D(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_2d\" _particle_reader = False def", "y, z = ( np.asarray(pds.get(pn % ax)[()], dtype=\"=f8\") for ax", "IOHandlerPackedHDF5(BaseIOHandler): _dataset_type = \"enzo_packed_3d\" _base = slice(None) _field_dtype = \"float64\"", "np.empty(fsize, dtype=\"float64\") ng = sum(len(c.objs) for c in chunks) mylog.debug(", "in fields: rv[(ftype, fname)] = np.atleast_3d(gds.get(fname)[()].transpose()) f.close() return rv if", "1D datasets or references. # For all versions of Enzo", "of the same size. So, let's grab one. if not", "list(chunks) if isinstance(selector, GridSelector): if not (len(chunks) == len(chunks[0].objs) ==", "\"enzo_packed_1d\" _particle_reader = False def _read_data_set(self, grid, field): f =", "0 and nap == 0: continue for ptype in sorted(ptf):", "selector.select_points(x, y, z, 0.0) if mask is None: continue for", "in fields: ftype, fname = field data_view = self.grids_in_memory[g.id][fname][ self.my_slice", "obj.filename for field in fields: nodal_flag = self.ds.field_info[field].nodal_flag dims =", "= f fields = [] dtypes = set() add_io =", "is not None: fid.close() def _read_obj_field(self, obj, field, fid_data): if", "break else: raise RuntimeError( \"Could not find active particle group", "chunk in chunks: # These should be organized by grid", "is None: continue for field in field_list: data = self.grids_in_memory[g.id][field]", "mode=\"r\") gds = f.get(\"/Grid%08i\" % g.id) if gds is None:", "fields def _read_fluid_selection(self, chunks, selector, fields, size): rv = {}", "g.dds.prod(dtype=\"f8\") yield (ptype, field), data[mask] class IOHandlerPacked2D(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_2d\"", "**kwargs): return super()._read_obj_field(*args, **kwargs)[self._base] class IOHandlerInMemory(BaseIOHandler): _dataset_type = \"enzo_inline\" def", "-- it just needs to be # okay for now.", "happens if the call is made from # _read_particle_coords. yield", "else: fields.append((\"enzo\", str(name))) return fields def _read_fluid_selection(self, chunks, selector, fields,", "%s cells of %s fields in %s grids\", size, [f2", "close = True fid = h5py.h5f.open(obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY) else: close =", "I know about, we can assume all floats # are", "all versions of Enzo I know about, we can assume", "None: continue if f is None: # print(\"Opening (read) %s\"", "not find active particle group in data.\" ) pn =", "def _read_fluid_selection(self, chunks, selector, fields, size): rv = {} #", "ax in \"xyz\" ) if selector is None: # This", "\"enzo_inline\" def __init__(self, ds, ghost_zones=3): self.ds = ds import enzo", "on others, nope. Doesn't seem to be a version thing.", "0 and nap == 0: continue ds = f.get(\"/Grid%08i\" %", "grid.id] except KeyError: group = f fields = [] dtypes", "fid = h5py.h5f.open( obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY ) filename = obj.filename for", "does *not* need # to be correct -- it will", "= [] add_io = \"io\" in grid.ds.particle_types for name, v", "def _read_obj_field(self, obj, field, fid_data): if fid_data is None: fid_data", "str(name))) elif add_io: fields.append((\"io\", str(name))) else: fields.append((\"enzo\", str(name))) return fields", "f = h5py.File(g.filename, mode=\"r\") gds = f.get(\"/Grid%08i\" % g.id) if", "obj.filename != filename: # Note one really important thing here:", "continue else: for pname in [\"Active Particles\", \"Particles\"]: pds =", "= size rv[field] = np.empty(fsize, dtype=\"float64\") ng = sum(len(c.objs) for", "ind += nd f.close() return rv class IOHandlerPacked1D(IOHandlerPackedHDF5): _dataset_type =", "but # on others, nope. Doesn't seem to be a", "len(chunks[0].objs) == 1): raise RuntimeError g = chunks[0].objs[0] for ftype,", "class IOHandlerPackedHDF5(BaseIOHandler): _dataset_type = \"enzo_packed_3d\" _base = slice(None) _field_dtype =", "= f[\"/Grid%08i/%s\" % (grid.id, field)][:] f.close() return ds.transpose()[:, None, None]", "y, z) continue mask = selector.select_points(x, y, z, 0.0) if", "np.empty(dims, dtype=h5_dtype) yield field, obj, self._read_obj_field(obj, field, (fid, data)) if", "ever happens if the call is made from # _read_particle_coords.", "f = None for g in chunk.objs: if g.filename is", "from yt.geometry.selection_routines import GridSelector from yt.utilities.io_handler import BaseIOHandler from yt.utilities.logger", "nd assert ind == fsize return rv def _read_particle_coords(self, chunks,", "caches ind += nd f.close() return rv class IOHandlerPacked1D(IOHandlerPackedHDF5): _dataset_type", "data = self.grids_in_memory[g.id][field] if field in _convert_mass: data = data", "here. We do this because it is a HUGE savings", "continue nap = sum(g.NumberOfActiveParticles.values()) if g.NumberOfParticles == 0 and nap", "group.items(): # NOTE: This won't work with 1D datasets or", "for 32 bit # floats, since our numpy copying/casting is", "return ds.transpose()[:, :, None] def _read_fluid_selection(self, chunks, selector, fields, size):", "field try: node = \"/Grid%08i/%s\" % (obj.id, fname) dg =", "ftype, fname in fields: rv[(ftype, fname)] = np.atleast_3d(gds.get(fname)[()].transpose()) f.close() return", "elif add_dm: fields.append((\"DarkMatter\", str(name))) else: fields.append((\"enzo\", str(name))) dtypes.add(v.dtype) if len(dtypes)", "same dtype, we can go ahead and # set it", "elif add_io: fields.append((\"io\", str(name))) elif add_dm: fields.append((\"DarkMatter\", str(name))) else: fields.append((\"enzo\",", "chunk in chunks: f = None for g in chunk.objs:", "continue elif len(v.dims) == 1: if grid.ds.dimensionality == 1: fields.append((\"enzo\",", "= f[\"/Grid%08i\" % grid.id] except KeyError: group = f fields", "field_list: data = np.asarray(pds.get(field)[()], \"=f8\") if field in _convert_mass: data", "field, obj, self._read_obj_field(obj, field, (fid, data)) if fid is not", "add_dm: fields.append((\"DarkMatter\", str(name))) else: fields.append((\"enzo\", str(name))) dtypes.add(v.dtype) if len(dtypes) ==", "# h5py's, for some reason I don't understand. This does", "== 1: fields.append((\"enzo\", str(name))) elif add_io: fields.append((\"io\", str(name))) else: fields.append((\"enzo\",", "ind) ind += nd assert ind == fsize return rv", "= self.grids_in_memory[g.id][field] if field in _convert_mass: data = data *", "is not None: fid.close() fid = h5py.h5f.open( obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY )", "nap == 0: continue ds = f.get(\"/Grid%08i\" % g.id) for", "from self._read_particle_fields(chunks, ptf, None) def _read_particle_fields(self, chunks, ptf, selector): chunks", "h5py.h5s.ALL, data) # I don't know why, but on some", "version thing. # dg.close() if close: fid.close() return data.T class", "IOHandlerPacked1D(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_1d\" _particle_reader = False def _read_data_set(self, grid,", "and nap == 0: continue for ptype in sorted(ptf): x,", "it is a HUGE savings for 32 bit # floats,", "self.grids_in_memory[g.id][\"particle_position_z\"], ) yield ptype, (x, y, z) def _read_particle_fields(self, chunks,", "fid_data if fid is None: close = True fid =", "def __init__(self, ds, ghost_zones=3): self.ds = ds import enzo self.enzo", "chunks = list(chunks) if isinstance(selector, GridSelector): if not (len(chunks) ==", "\"O\": continue elif len(v.dims) == 1: if grid.ds.dimensionality == 1:", "h5py's, for some reason I don't understand. This does *not*", "_read_data_set(self, grid, field): f = h5py.File(grid.filename, mode=\"r\") ds = f[\"/Grid%08i/%s\"", "str(name))) elif add_io: fields.append((\"io\", str(name))) elif add_dm: fields.append((\"DarkMatter\", str(name))) else:", "grid): if grid.filename is None: return [] f = h5py.File(grid.filename,", "h5py this works, but # on others, nope. Doesn't seem", "# Now, if everything we saw was the same dtype,", "_read_particle_fields(self, chunks, ptf, selector): chunks = list(chunks) for chunk in", "{} # Now we have to do something unpleasant chunks", "r\"particle_position_%s\") x, y, z = ( np.asarray(pds.get(pn % ax)[()], dtype=\"=f8\")", "a # problem, but one we can return to. if", "*args, **kwargs): return super()._read_obj_field(*args, **kwargs)[self._base] class IOHandlerInMemory(BaseIOHandler): _dataset_type = \"enzo_inline\"", "ds elif ptype == \"DarkMatter\": if g.NumberOfActiveParticles[ptype] == 0: continue", "IOHandlerInMemory(BaseIOHandler): _dataset_type = \"enzo_inline\" def __init__(self, ds, ghost_zones=3): self.ds =", "floats, since our numpy copying/casting is way faster than #", "= f.get(\"/Grid%08i\" % g.id) if gds is None: gds =", "works, but # on others, nope. Doesn't seem to be", "nd = g.select(selector, data_view, rv[field], ind) ind += nd assert", "can return to. if fid is not None: fid.close() fid", "data.T raise dg.read(h5py.h5s.ALL, h5py.h5s.ALL, data) # I don't know why,", "chunks, fields): h5_dtype = self._field_dtype for chunk in chunks: fid", "= obj.filename for field in fields: nodal_flag = self.ds.field_info[field].nodal_flag dims", "= enzo self.grids_in_memory = enzo.grid_data self.old_grids_in_memory = enzo.old_grid_data self.my_slice =", "0: continue pds = ds elif not g.NumberOfActiveParticles[ptype]: continue else:", "fid = h5py.h5f.open(obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY) else: close = False if data", "in field_list: data = np.asarray(pds.get(field)[()], \"=f8\") if field in _convert_mass:", ") mask = selector.select_points(x, y, z, 0.0) if mask is", "fname)] = np.atleast_3d(gds.get(fname)[()].transpose()) f.close() return rv if size is None:", "still be doing file opening and whatnot. This is a", "dtypes.add(v.dtype) if len(dtypes) == 1: # Now, if everything we", "will get fixed later -- it just needs to be", "problem, but one we can return to. if fid is", "be a version thing. # dg.close() if close: fid.close() return", "mode=\"r\") try: group = f[\"/Grid%08i\" % grid.id] except KeyError: group", "== \"DarkMatter\": if g.NumberOfActiveParticles[ptype] == 0: continue pds = ds", "hasattr(v, \"shape\") or v.dtype == \"O\": continue elif v.ndim ==", "(ptype, field), data[mask] if f: f.close() def io_iter(self, chunks, fields):", "chunks[0].objs[0] for ftype, fname in fields: rv[(ftype, fname)] = self.grids_in_memory[g.id][fname].swapaxes(0,", "# print(\"Opening (count) %s\" % g.filename) f = h5py.File(g.filename, mode=\"r\")", "organized by grid filename f = None for g in", "data[:] = 0 return data.T raise dg.read(h5py.h5s.ALL, h5py.h5s.ALL, data) #", "np.empty(obj.ActiveDimensions[::-1], dtype=self._field_dtype) ftype, fname = field try: node = \"/Grid%08i/%s\"", "if fid is not None: fid.close() fid = h5py.h5f.open( obj.filename.encode(\"latin-1\"),", "def _read_field_names(self, grid): fields = [] add_io = \"io\" in", "y, z = ( self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"], ) mask =", "f is None: # print(\"Opening (count) %s\" % g.filename) f", "print(\"Opening (count) %s\" % g.filename) f = h5py.File(g.filename, mode=\"r\") gds", "def _read_particle_fields(self, chunks, ptf, selector): chunks = list(chunks) for chunk", "ind = 0 for chunk in chunks: f = None", "== 0: continue for ptype in sorted(ptf): x, y, z", "_h5py as h5py _convert_mass = (\"particle_mass\", \"mass\") _particle_position_names = {}", "== 0 and nap == 0: continue for ptype in", "\"io\" in grid.ds.particle_types for name, v in self.grids_in_memory[grid.id].items(): # NOTE:", "This won't work with 1D datasets or references. # For", "if ptype == \"io\": if g.NumberOfParticles == 0: continue pds", "yield field, obj, self._read_obj_field(obj, field, (fid, data)) if fid is", "nd = g.select(selector, ds, rv[field], ind) # caches ind +=", "super()._read_obj_field(*args, **kwargs)[self._base] class IOHandlerInMemory(BaseIOHandler): _dataset_type = \"enzo_inline\" def __init__(self, ds,", "implement LRU caching in the _read_obj_field function, # we'll still", "= \"io\" in grid.ds.particle_types add_dm = \"DarkMatter\" in grid.ds.particle_types for", "for ftype, fname in fields: rv[(ftype, fname)] = np.atleast_3d(gds.get(fname)[()].transpose()) f.close()", "self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"], ) mask = selector.select_points(x, y, z, 0.0)", "class IOHandlerPacked1D(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_1d\" _particle_reader = False def _read_data_set(self,", "obj, field, fid_data): if fid_data is None: fid_data = (None,", "self._read_obj_field(obj, field, (fid, data)) if fid is not None: fid.close()", "(\"particle_mass\", \"mass\") _particle_position_names = {} class IOHandlerPackedHDF5(BaseIOHandler): _dataset_type = \"enzo_packed_3d\"", "g in chunk.objs: # We want a *hard error* here.", "in self.grids_in_memory: continue for field in fields: ftype, fname =", "np from yt.geometry.selection_routines import GridSelector from yt.utilities.io_handler import BaseIOHandler from", "*args, **kwargs): super().__init__(*args, **kwargs) NGZ = self.ds.parameters.get(\"NumberOfGhostZones\", 3) self._base =", "list(chunks) for chunk in chunks: # These should be organized", "be organized by grid filename for g in chunk.objs: if", "something unpleasant chunks = list(chunks) if isinstance(selector, GridSelector): if not", "_read_particle_coords(self, chunks, ptf): yield from self._read_particle_fields(chunks, ptf, None) def _read_particle_fields(self,", "reason I don't understand. This does *not* need # to", "work with 1D datasets or references. if not hasattr(v, \"shape\")", "Now we have to do something unpleasant chunks = list(chunks)", "self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"], ) yield ptype, (x, y, z) def", "not None: fid.close() fid = h5py.h5f.open( obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY ) filename", "except KeyError: if fname == \"Dark_Matter_Density\": data[:] = 0 return", "chunks: fid = None filename = -1 for obj in", ") yield ptype, (x, y, z) def _read_particle_fields(self, chunks, ptf,", "be organized by grid filename f = None for g", "import _h5py as h5py _convert_mass = (\"particle_mass\", \"mass\") _particle_position_names =", "_dataset_type = \"enzo_inline\" def __init__(self, ds, ghost_zones=3): self.ds = ds", "in _convert_mass: data = data * g.dds.prod(dtype=\"f8\") yield (ptype, field),", "add_io = \"io\" in grid.ds.particle_types add_dm = \"DarkMatter\" in grid.ds.particle_types", "super().__init__(*args, **kwargs) NGZ = self.ds.parameters.get(\"NumberOfGhostZones\", 3) self._base = (slice(NGZ, -NGZ),", "hasattr(v, \"shape\") or v.dtype == \"O\": continue elif len(v.dims) ==", "# implement LRU caching in the _read_obj_field function, # we'll", "chunk in chunks: fid = None filename = -1 for", "function, # we'll still be doing file opening and whatnot.", "opening and whatnot. This is a # problem, but one", "import ytLogger as mylog from yt.utilities.on_demand_imports import _h5py as h5py", "if fid_data is None: fid_data = (None, None) fid, data", "\"io\" in grid.ds.particle_types add_dm = \"DarkMatter\" in grid.ds.particle_types for name,", "try: group = f[\"/Grid%08i\" % grid.id] except KeyError: group =", "close = False if data is None: data = np.empty(obj.ActiveDimensions[::-1],", "(fid, data)) if fid is not None: fid.close() def _read_obj_field(self,", "fname == \"Dark_Matter_Density\": data[:] = 0 return data.T raise dg.read(h5py.h5s.ALL,", "for field in fields: nodal_flag = self.ds.field_info[field].nodal_flag dims = obj.ActiveDimensions[::-1]", "enzo self.grids_in_memory = enzo.grid_data self.old_grids_in_memory = enzo.old_grid_data self.my_slice = (", "yield ptype, (x, y, z) continue mask = selector.select_points(x, y,", "for obj in chunk.objs: if obj.filename is None: continue if", "for ax in \"xyz\" ) if selector is None: #", "nope. Doesn't seem to be a version thing. # dg.close()", "ds = np.atleast_3d(gds.get(fname)[()].transpose()) nd = g.select(selector, ds, rv[field], ind) #", "-ghost_zones), slice(ghost_zones, -ghost_zones), slice(ghost_zones, -ghost_zones), ) BaseIOHandler.__init__(self, ds) def _read_field_names(self,", "should be organized by grid filename f = None for", "continue ds = f.get(\"/Grid%08i\" % g.id) for ptype, field_list in", "for field in fields: ftype, fname = field data_view =", "-1 for obj in chunk.objs: if obj.filename is None: continue", "y, z) def _read_particle_fields(self, chunks, ptf, selector): chunks = list(chunks)", "fields, size): rv = {} # Now we have to", "= \"enzo_packed_2d\" _particle_reader = False def _read_data_set(self, grid, field): f", "v.dtype == \"O\": continue elif v.ndim == 1: if grid.ds.dimensionality", "str(name))) dtypes.add(v.dtype) if len(dtypes) == 1: # Now, if everything", "as mylog from yt.utilities.on_demand_imports import _h5py as h5py _convert_mass =", "-- it will get fixed later -- it just needs", "doing file opening and whatnot. This is a # problem,", "do this because it is a HUGE savings for 32", "rv[(ftype, fname)] = self.grids_in_memory[g.id][fname].swapaxes(0, 2) return rv if size is", "chunks) mylog.debug( \"Reading %s cells of %s fields in %s", "= list(chunks) if isinstance(selector, GridSelector): if not (len(chunks) == len(chunks[0].objs)", "These should be organized by grid filename f = None", "+ nodal_flag[::-1] data = np.empty(dims, dtype=h5_dtype) yield field, obj, self._read_obj_field(obj,", "None: return [] f = h5py.File(grid.filename, mode=\"r\") try: group =", "continue for field in field_list: data = np.asarray(pds.get(field)[()], \"=f8\") if", "nodal_flag = self.ds.field_info[field].nodal_flag dims = obj.ActiveDimensions[::-1] + nodal_flag[::-1] data =", "== fsize return rv def _read_particle_coords(self, chunks, ptf): chunks =", "sum(g.NumberOfActiveParticles.values()) if g.NumberOfParticles == 0 and nap == 0: continue", "_read_fluid_selection(self, chunks, selector, fields, size): rv = {} # Now", "g.NumberOfParticles == 0 and nap == 0: continue for ptype", "ds.transpose()[:, :, None] def _read_fluid_selection(self, chunks, selector, fields, size): rv", "data_view = self.grids_in_memory[g.id][fname][ self.my_slice ].swapaxes(0, 2) nd = g.select(selector, data_view,", "32 bit # floats, since our numpy copying/casting is way", "None: size = sum(g.count(selector) for chunk in chunks for g", "% grid.id] except KeyError: group = f fields = []", "\"DarkMatter\" in grid.ds.particle_types for name, v in group.items(): # NOTE:", "go ahead and # set it here. We do this", "know about, we can assume all floats # are of", "g in chunk.objs: if f is None: # print(\"Opening (count)", "add_io = \"io\" in grid.ds.particle_types for name, v in self.grids_in_memory[grid.id].items():", "for chunk in chunks: for g in chunk.objs: # We", "if selector is None: # This only ever happens if", "rv[(ftype, fname)] = np.atleast_3d(gds.get(fname)[()].transpose()) f.close() return rv if size is", "for chunk in chunks: f = None for g in", "in chunks) mylog.debug( \"Reading %s cells of %s fields in", "3) self._base = (slice(NGZ, -NGZ), slice(NGZ, -NGZ), slice(NGZ, -NGZ)) def", "== \"O\": continue elif v.ndim == 1: if grid.ds.dimensionality ==", "= self.grids_in_memory[g.id][fname][ self.my_slice ].swapaxes(0, 2) nd = g.select(selector, data_view, rv[field],", "BaseIOHandler from yt.utilities.logger import ytLogger as mylog from yt.utilities.on_demand_imports import", "z, 0.0) if mask is None: continue for field in", "ftype, fname = field data_view = self.grids_in_memory[g.id][fname][ self.my_slice ].swapaxes(0, 2)", "we have to do something unpleasant chunks = list(chunks) if", "+= nd f.close() return rv class IOHandlerPacked1D(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_1d\"", "g.NumberOfParticles == 0 and nap == 0: continue ds =", "= h5py.File(g.filename, mode=\"r\") nap = sum(g.NumberOfActiveParticles.values()) if g.NumberOfParticles == 0", "savings for 32 bit # floats, since our numpy copying/casting", "why, but on some installations of h5py this works, but", "Note one really important thing here: even if we do", "z = ( self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"], ) mask = selector.select_points(x,", "we can return to. if fid is not None: fid.close()", "Doesn't seem to be a version thing. # dg.close() if", "we can assume all floats # are of the same", "# We want a *hard error* here. # if g.id", "f is None: # print(\"Opening (read) %s\" % g.filename) f", "continue for field in field_list: data = self.grids_in_memory[g.id][field] if field", "with 1D datasets or references. if not hasattr(v, \"shape\") or", "get fixed later -- it just needs to be #", "GridSelector from yt.utilities.io_handler import BaseIOHandler from yt.utilities.logger import ytLogger as", "\"enzo_packed_3d_gz\" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) NGZ = self.ds.parameters.get(\"NumberOfGhostZones\",", "isinstance(selector, GridSelector): if not (len(chunks) == len(chunks[0].objs) == 1): raise", "g.filename is None: continue if f is None: # print(\"Opening", "sorted(ptf.items()): if ptype == \"io\": if g.NumberOfParticles == 0: continue", "from # _read_particle_coords. yield ptype, (x, y, z) continue mask", "I don't understand. This does *not* need # to be", "fid_data = (None, None) fid, data = fid_data if fid", "chunks: # These should be organized by grid filename for", "f.get(\"/Grid%08i\" % g.id) if gds is None: gds = f", "self.enzo = enzo self.grids_in_memory = enzo.grid_data self.old_grids_in_memory = enzo.old_grid_data self.my_slice", "fields in %s grids\", size, [f2 for f1, f2 in", "not in self.grids_in_memory: continue nap = sum(g.NumberOfActiveParticles.values()) if g.NumberOfParticles ==", "faster than # h5py's, for some reason I don't understand.", "sorted(ptf): x, y, z = ( self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"], )", "[] dtypes = set() add_io = \"io\" in grid.ds.particle_types add_dm", "\"float64\" def _read_field_names(self, grid): if grid.filename is None: return []", "slice(ghost_zones, -ghost_zones), slice(ghost_zones, -ghost_zones), ) BaseIOHandler.__init__(self, ds) def _read_field_names(self, grid):", "is not None: break else: raise RuntimeError( \"Could not find", "NGZ = self.ds.parameters.get(\"NumberOfGhostZones\", 3) self._base = (slice(NGZ, -NGZ), slice(NGZ, -NGZ),", "# if g.id not in self.grids_in_memory: continue for field in", "know why, but on some installations of h5py this works,", "if g.NumberOfParticles == 0 and nap == 0: continue ds", "% g.filename) f = h5py.File(g.filename, mode=\"r\") nap = sum(g.NumberOfActiveParticles.values()) if", "( slice(ghost_zones, -ghost_zones), slice(ghost_zones, -ghost_zones), slice(ghost_zones, -ghost_zones), ) BaseIOHandler.__init__(self, ds)", "\"/Grid%08i/%s\" % (obj.id, fname) dg = h5py.h5d.open(fid, node.encode(\"latin-1\")) except KeyError:", "if g.id not in self.grids_in_memory: continue for field in fields:", "__init__(self, *args, **kwargs): super().__init__(*args, **kwargs) NGZ = self.ds.parameters.get(\"NumberOfGhostZones\", 3) self._base", "raise RuntimeError g = chunks[0].objs[0] for ftype, fname in fields:", "do something unpleasant chunks = list(chunks) if isinstance(selector, GridSelector): if", "as h5py _convert_mass = (\"particle_mass\", \"mass\") _particle_position_names = {} class", "(read) %s\" % g.filename) f = h5py.File(g.filename, mode=\"r\") nap =", "fid is None: close = True fid = h5py.h5f.open(obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY)", "yt.utilities.logger import ytLogger as mylog from yt.utilities.on_demand_imports import _h5py as", "for now. self._field_dtype = list(dtypes)[0] f.close() return fields @property def", "fields.append((\"io\", str(name))) elif add_dm: fields.append((\"DarkMatter\", str(name))) else: fields.append((\"enzo\", str(name))) dtypes.add(v.dtype)", "fname = field try: node = \"/Grid%08i/%s\" % (obj.id, fname)", "g.select(selector, ds, rv[field], ind) # caches ind += nd f.close()", "= 0 for chunk in chunks: f = None for", "chunks for g in chunk.objs) for field in fields: ftype,", "def _read_particle_coords(self, chunks, ptf): chunks = list(chunks) for chunk in", "z = ( self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"], ) yield ptype, (x,", "data = np.empty(dims, dtype=h5_dtype) yield field, obj, self._read_obj_field(obj, field, (fid,", "== \"io\": if g.NumberOfParticles == 0: continue pds = ds", "= obj.ActiveDimensions[::-1] + nodal_flag[::-1] data = np.empty(dims, dtype=h5_dtype) yield field,", "gds is None: gds = f for field in fields:", "data)) if fid is not None: fid.close() def _read_obj_field(self, obj,", "if not hasattr(v, \"shape\") or v.dtype == \"O\": continue elif", "= sum(len(c.objs) for c in chunks) mylog.debug( \"Reading %s cells", "else: fields.append((\"enzo\", str(name))) dtypes.add(v.dtype) if len(dtypes) == 1: # Now,", "None) def _read_particle_fields(self, chunks, ptf, selector): chunks = list(chunks) for", "= -1 for obj in chunk.objs: if obj.filename is None:", "enzo self.enzo = enzo self.grids_in_memory = enzo.grid_data self.old_grids_in_memory = enzo.old_grid_data", "self._read_particle_fields(chunks, ptf, None) def _read_particle_fields(self, chunks, ptf, selector): chunks =", "to be # okay for now. self._field_dtype = list(dtypes)[0] f.close()", "for field in fields: ftype, fname = field ds =", "chunk.objs: if g.filename is None: continue if f is None:", "= 0 for chunk in chunks: for g in chunk.objs:", "in chunk.objs: if g.filename is None: continue if f is", "important thing here: even if we do # implement LRU", "if grid.ds.dimensionality == 1: fields.append((\"enzo\", str(name))) elif add_io: fields.append((\"io\", str(name)))", "mylog from yt.utilities.on_demand_imports import _h5py as h5py _convert_mass = (\"particle_mass\",", "one really important thing here: even if we do #", "mode=\"r\") gds = f.get(\"/Grid%08i\" % g.id) for ftype, fname in", "in fields: ftype, fname = field fsize = size rv[field]", "= enzo.grid_data self.old_grids_in_memory = enzo.old_grid_data self.my_slice = ( slice(ghost_zones, -ghost_zones),", "needs to be # okay for now. self._field_dtype = list(dtypes)[0]", "slice(ghost_zones, -ghost_zones), ) BaseIOHandler.__init__(self, ds) def _read_field_names(self, grid): fields =", "These should be organized by grid filename for g in", "or v.dtype == \"O\": continue elif len(v.dims) == 1: if", "set() add_io = \"io\" in grid.ds.particle_types add_dm = \"DarkMatter\" in", "in grid.ds.particle_types for name, v in group.items(): # NOTE: This", "obj, self._read_obj_field(obj, field, (fid, data)) if fid is not None:", "g.dds.prod(dtype=\"f8\") yield (ptype, field), data[mask] if f: f.close() def io_iter(self,", "**kwargs): super().__init__(*args, **kwargs) NGZ = self.ds.parameters.get(\"NumberOfGhostZones\", 3) self._base = (slice(NGZ,", "= ( slice(ghost_zones, -ghost_zones), slice(ghost_zones, -ghost_zones), slice(ghost_zones, -ghost_zones), ) BaseIOHandler.__init__(self,", "and # set it here. We do this because it", "= sum(g.NumberOfActiveParticles.values()) if g.NumberOfParticles == 0 and nap == 0:", "% (obj.id, fname) dg = h5py.h5d.open(fid, node.encode(\"latin-1\")) except KeyError: if", "z) def _read_particle_fields(self, chunks, ptf, selector): chunks = list(chunks) for", "0: continue ds = f.get(\"/Grid%08i\" % g.id) for ptype, field_list", "since our numpy copying/casting is way faster than # h5py's,", "not g.NumberOfActiveParticles[ptype]: continue else: for pname in [\"Active Particles\", \"Particles\"]:", "is a HUGE savings for 32 bit # floats, since", "chunk.objs) for field in fields: ftype, fname = field fsize", "def _read_field_names(self, grid): if grid.filename is None: return [] f", "= ds import enzo self.enzo = enzo self.grids_in_memory = enzo.grid_data", "LRU caching in the _read_obj_field function, # we'll still be", "understand. This does *not* need # to be correct --", "elif not g.NumberOfActiveParticles[ptype]: continue else: for pname in [\"Active Particles\",", "data_view, rv[field], ind) ind += nd assert ind == fsize", "in sorted(ptf.items()): x, y, z = ( self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"],", "than # h5py's, for some reason I don't understand. This", "# Now we have to do something unpleasant chunks =", "*not* need # to be correct -- it will get", "field in fields: ftype, fname = field ds = np.atleast_3d(gds.get(fname)[()].transpose())", "= np.empty(fsize, dtype=\"float64\") ng = sum(len(c.objs) for c in chunks)", "np.asarray(pds.get(pn % ax)[()], dtype=\"=f8\") for ax in \"xyz\" ) if", "won't work with 1D datasets or references. # For all", "for c in chunks) mylog.debug( \"Reading %s cells of %s", "yield ptype, (x, y, z) def _read_particle_fields(self, chunks, ptf, selector):", "we do # implement LRU caching in the _read_obj_field function,", "fname = field data_view = self.grids_in_memory[g.id][fname][ self.my_slice ].swapaxes(0, 2) nd", "= self.ds.field_info[field].nodal_flag dims = obj.ActiveDimensions[::-1] + nodal_flag[::-1] data = np.empty(dims,", "We do this because it is a HUGE savings for", "need # to be correct -- it will get fixed", "if isinstance(selector, GridSelector): if not (len(chunks) == len(chunks[0].objs) == 1):", "this because it is a HUGE savings for 32 bit", "if f is None: # print(\"Opening (read) %s\" % g.filename)", "def _read_particle_coords(self, chunks, ptf): yield from self._read_particle_fields(chunks, ptf, None) def", "ds = f.get(\"/Grid%08i\" % g.id) for ptype, field_list in sorted(ptf.items()):", "rv if size is None: size = sum(g.count(selector) for chunk", "is None: # This only ever happens if the call", "self.ds = ds import enzo self.enzo = enzo self.grids_in_memory =", "later -- it just needs to be # okay for", "_base = slice(None) _field_dtype = \"float64\" def _read_field_names(self, grid): if", "in the _read_obj_field function, # we'll still be doing file", "_convert_mass = (\"particle_mass\", \"mass\") _particle_position_names = {} class IOHandlerPackedHDF5(BaseIOHandler): _dataset_type", "# For all versions of Enzo I know about, we", "NOTE: This won't work with 1D datasets or references. if", "yield from self._read_particle_fields(chunks, ptf, None) def _read_particle_fields(self, chunks, ptf, selector):", "if mask is None: continue for field in field_list: data", "in _convert_mass: data *= g.dds.prod(dtype=\"f8\") yield (ptype, field), data[mask] if", "grid filename f = None for g in chunk.objs: if", "_particle_reader = False def _read_data_set(self, grid, field): f = h5py.File(grid.filename,", "pname in [\"Active Particles\", \"Particles\"]: pds = ds.get(f\"{pname}/{ptype}\") if pds", "\"enzo_packed_3d\" _base = slice(None) _field_dtype = \"float64\" def _read_field_names(self, grid):", "to do something unpleasant chunks = list(chunks) if isinstance(selector, GridSelector):", "np.atleast_3d(gds.get(fname)[()].transpose()) f.close() return rv if size is None: size =", "None for g in chunk.objs: if f is None: #", "mode=\"r\") ds = f[\"/Grid%08i/%s\" % (grid.id, field)][:] f.close() return ds.transpose()[:,", "only ever happens if the call is made from #", "grid.ds.particle_types for name, v in group.items(): # NOTE: This won't", "for pname in [\"Active Particles\", \"Particles\"]: pds = ds.get(f\"{pname}/{ptype}\") if", "f = h5py.File(grid.filename, mode=\"r\") ds = f[\"/Grid%08i/%s\" % (grid.id, field)][:]", "our numpy copying/casting is way faster than # h5py's, for", "== 0 and nap == 0: continue ds = f.get(\"/Grid%08i\"", "@property def _read_exception(self): return (KeyError,) def _read_particle_coords(self, chunks, ptf): yield", "in self.grids_in_memory: continue nap = sum(g.NumberOfActiveParticles.values()) if g.NumberOfParticles == 0", "= 0 return data.T raise dg.read(h5py.h5s.ALL, h5py.h5s.ALL, data) # I", "in %s grids\", size, [f2 for f1, f2 in fields],", "self.my_slice ].swapaxes(0, 2) nd = g.select(selector, data_view, rv[field], ind) ind", "(x, y, z) def _read_particle_fields(self, chunks, ptf, selector): chunks =", "= ( self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"], ) mask = selector.select_points(x, y,", "seem to be a version thing. # dg.close() if close:", "ptype, (x, y, z) continue mask = selector.select_points(x, y, z,", "and nap == 0: continue for ptype, field_list in sorted(ptf.items()):", "2) nd = g.select(selector, data_view, rv[field], ind) ind += nd", "about, we can assume all floats # are of the", "one. if not hasattr(v, \"shape\") or v.dtype == \"O\": continue", "it will get fixed later -- it just needs to", "node = \"/Grid%08i/%s\" % (obj.id, fname) dg = h5py.h5d.open(fid, node.encode(\"latin-1\"))", "x, y, z = ( np.asarray(pds.get(pn % ax)[()], dtype=\"=f8\") for", "not None: break else: raise RuntimeError( \"Could not find active", "Now, if everything we saw was the same dtype, we", "copying/casting is way faster than # h5py's, for some reason", "h5py.File(g.filename, mode=\"r\") gds = f.get(\"/Grid%08i\" % g.id) for ftype, fname", "= h5py.File(grid.filename, mode=\"r\") try: group = f[\"/Grid%08i\" % grid.id] except", "0 return data.T raise dg.read(h5py.h5s.ALL, h5py.h5s.ALL, data) # I don't", "if fid is None: close = True fid = h5py.h5f.open(obj.filename.encode(\"latin-1\"),", "RuntimeError g = chunks[0].objs[0] f = h5py.File(g.filename, mode=\"r\") gds =", "rv[field], ind) ind += nd assert ind == fsize return", "g.id) for ftype, fname in fields: rv[(ftype, fname)] = np.atleast_3d(gds.get(fname)[()].transpose())", "if fid is not None: fid.close() def _read_obj_field(self, obj, field,", "grid.filename is None: return [] f = h5py.File(grid.filename, mode=\"r\") try:", "made from # _read_particle_coords. yield ptype, (x, y, z) continue", "in fields: ftype, fname = field ds = np.atleast_3d(gds.get(fname)[()].transpose()) nd", "for chunk in chunks: # These should be organized by", "0.0) if mask is None: continue for field in field_list:", "= False if data is None: data = np.empty(obj.ActiveDimensions[::-1], dtype=self._field_dtype)", "= False def _read_data_set(self, grid, field): f = h5py.File(grid.filename, mode=\"r\")", "selector, fields, size): rv = {} # Now we have", "rv def _read_particle_coords(self, chunks, ptf): chunks = list(chunks) for chunk", "group in data.\" ) pn = _particle_position_names.get(ptype, r\"particle_position_%s\") x, y,", "field), data[mask] if f: f.close() def io_iter(self, chunks, fields): h5_dtype", "elif v.ndim == 1: if grid.ds.dimensionality == 1: fields.append((\"enzo\", str(name)))", "grab one. if not hasattr(v, \"shape\") or v.dtype == \"O\":", "= selector.select_points(x, y, z, 0.0) if mask is None: continue", "data * g.dds.prod(dtype=\"f8\") yield (ptype, field), data[mask] class IOHandlerPacked2D(IOHandlerPackedHDF5): _dataset_type", "= \"enzo_packed_3d\" _base = slice(None) _field_dtype = \"float64\" def _read_field_names(self,", "if f: f.close() def io_iter(self, chunks, fields): h5_dtype = self._field_dtype", "_read_field_names(self, grid): if grid.filename is None: return [] f =", "v in self.grids_in_memory[grid.id].items(): # NOTE: This won't work with 1D", "in chunks for g in chunk.objs) for field in fields:", "data = data * g.dds.prod(dtype=\"f8\") yield (ptype, field), data[mask] class", "in fields: rv[(ftype, fname)] = self.grids_in_memory[g.id][fname].swapaxes(0, 2) return rv if", "pn = _particle_position_names.get(ptype, r\"particle_position_%s\") x, y, z = ( np.asarray(pds.get(pn", "_dataset_type = \"enzo_packed_1d\" _particle_reader = False def _read_data_set(self, grid, field):", "for field in fields: ftype, fname = field fsize =", "if close: fid.close() return data.T class IOHandlerPackedHDF5GhostZones(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_3d_gz\"", "= field try: node = \"/Grid%08i/%s\" % (obj.id, fname) dg", "fields: ftype, fname = field ds = np.atleast_3d(gds.get(fname)[()].transpose()) nd =", "if obj.filename is None: continue if obj.filename != filename: #", "( np.asarray(pds.get(pn % ax)[()], dtype=\"=f8\") for ax in \"xyz\" )", "for some reason I don't understand. This does *not* need", "if g.id not in self.grids_in_memory: continue nap = sum(g.NumberOfActiveParticles.values()) if", "is None: return [] f = h5py.File(grid.filename, mode=\"r\") try: group", "unpleasant chunks = list(chunks) if isinstance(selector, GridSelector): if not (len(chunks)", "For all versions of Enzo I know about, we can", "Enzo I know about, we can assume all floats #", "None) fid, data = fid_data if fid is None: close", "fields], ng, ) ind = 0 for chunk in chunks:", "for field in field_list: data = self.grids_in_memory[g.id][field] if field in", "None: continue for field in field_list: data = self.grids_in_memory[g.id][field] if", "of h5py this works, but # on others, nope. Doesn't", "fid.close() fid = h5py.h5f.open( obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY ) filename = obj.filename", "by grid filename for g in chunk.objs: if g.id not", "None: break else: raise RuntimeError( \"Could not find active particle", "g in chunk.objs) for field in fields: ftype, fname =", "datasets or references. if not hasattr(v, \"shape\") or v.dtype ==", "continue mask = selector.select_points(x, y, z, 0.0) if mask is", "is None: # print(\"Opening (read) %s\" % g.filename) f =", "rv[field], ind) # caches ind += nd f.close() return rv", "fields: rv[(ftype, fname)] = np.atleast_3d(gds.get(fname)[()].transpose()) f.close() return rv if size", "= np.empty(obj.ActiveDimensions[::-1], dtype=self._field_dtype) ftype, fname = field try: node =", "= (slice(NGZ, -NGZ), slice(NGZ, -NGZ), slice(NGZ, -NGZ)) def _read_obj_field(self, *args,", "False def _read_data_set(self, grid, field): f = h5py.File(grid.filename, mode=\"r\") ds", "return fields @property def _read_exception(self): return (KeyError,) def _read_particle_coords(self, chunks,", "slice(NGZ, -NGZ), slice(NGZ, -NGZ)) def _read_obj_field(self, *args, **kwargs): return super()._read_obj_field(*args,", "a HUGE savings for 32 bit # floats, since our", "active particle group in data.\" ) pn = _particle_position_names.get(ptype, r\"particle_position_%s\")", "for g in chunk.objs) for field in fields: ftype, fname", "We want a *hard error* here. # if g.id not", "else: for pname in [\"Active Particles\", \"Particles\"]: pds = ds.get(f\"{pname}/{ptype}\")", "ftype, fname = field try: node = \"/Grid%08i/%s\" % (obj.id,", "elif len(v.dims) == 1: if grid.ds.dimensionality == 1: fields.append((\"enzo\", str(name)))", "= self.ds.parameters.get(\"NumberOfGhostZones\", 3) self._base = (slice(NGZ, -NGZ), slice(NGZ, -NGZ), slice(NGZ,", "g = chunks[0].objs[0] for ftype, fname in fields: rv[(ftype, fname)]", "= fid_data if fid is None: close = True fid", "size rv[field] = np.empty(fsize, dtype=\"float64\") ng = sum(len(c.objs) for c", "f = h5py.File(g.filename, mode=\"r\") nap = sum(g.NumberOfActiveParticles.values()) if g.NumberOfParticles ==", "find active particle group in data.\" ) pn = _particle_position_names.get(ptype,", "NOTE: This won't work with 1D datasets or references. #", "not (len(chunks) == len(chunks[0].objs) == 1): raise RuntimeError g =", "continue for ptype in sorted(ptf): x, y, z = (", "ptype in sorted(ptf): x, y, z = ( self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"],", "IOHandlerPacked2D(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_2d\" _particle_reader = False def _read_data_set(self, grid,", "here. # if g.id not in self.grids_in_memory: continue for field", "len(chunks[0].objs) == 1): raise RuntimeError g = chunks[0].objs[0] f =", "we saw was the same dtype, we can go ahead", "enzo.old_grid_data self.my_slice = ( slice(ghost_zones, -ghost_zones), slice(ghost_zones, -ghost_zones), slice(ghost_zones, -ghost_zones),", "= \"DarkMatter\" in grid.ds.particle_types for name, v in group.items(): #", "return [] f = h5py.File(grid.filename, mode=\"r\") try: group = f[\"/Grid%08i\"", "in sorted(ptf.items()): if ptype == \"io\": if g.NumberOfParticles == 0:", "\"Particles\"]: pds = ds.get(f\"{pname}/{ptype}\") if pds is not None: break", "KeyError: if fname == \"Dark_Matter_Density\": data[:] = 0 return data.T", "data = np.empty(obj.ActiveDimensions[::-1], dtype=self._field_dtype) ftype, fname = field try: node", "field ds = np.atleast_3d(gds.get(fname)[()].transpose()) nd = g.select(selector, ds, rv[field], ind)", "ahead and # set it here. We do this because", "with 1D datasets or references. # For all versions of", "size. So, let's grab one. if not hasattr(v, \"shape\") or", "field in fields: nodal_flag = self.ds.field_info[field].nodal_flag dims = obj.ActiveDimensions[::-1] +", "close: fid.close() return data.T class IOHandlerPackedHDF5GhostZones(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_3d_gz\" def", "is made from # _read_particle_coords. yield ptype, (x, y, z)", "if g.NumberOfParticles == 0 and nap == 0: continue for", "rv class IOHandlerPacked1D(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_1d\" _particle_reader = False def", "filename for g in chunk.objs: if g.id not in self.grids_in_memory:", "assume all floats # are of the same size. So,", "really important thing here: even if we do # implement", "return data.T class IOHandlerPackedHDF5GhostZones(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_3d_gz\" def __init__(self, *args,", "as np from yt.geometry.selection_routines import GridSelector from yt.utilities.io_handler import BaseIOHandler", "(x, y, z) continue mask = selector.select_points(x, y, z, 0.0)", "str(name))) else: fields.append((\"enzo\", str(name))) dtypes.add(v.dtype) if len(dtypes) == 1: #", "file opening and whatnot. This is a # problem, but", "None: continue for field in field_list: data = np.asarray(pds.get(field)[()], \"=f8\")", "self.grids_in_memory[g.id][\"particle_position_z\"], ) mask = selector.select_points(x, y, z, 0.0) if mask", "continue elif v.ndim == 1: if grid.ds.dimensionality == 1: fields.append((\"enzo\",", "fname = field ds = np.atleast_3d(gds.get(fname)[()].transpose()) nd = g.select(selector, ds,", "call is made from # _read_particle_coords. yield ptype, (x, y,", "self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"], ) mask = selector.select_points(x, y, z, 0.0) if", "in chunk.objs: # We want a *hard error* here. #", "f.close() return rv class IOHandlerPacked1D(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_1d\" _particle_reader =", "# dg.close() if close: fid.close() return data.T class IOHandlerPackedHDF5GhostZones(IOHandlerPackedHDF5): _dataset_type", "the same size. So, let's grab one. if not hasattr(v,", "group = f fields = [] dtypes = set() add_io", "mask is None: continue for field in field_list: data =", "== 0: continue pds = ds elif not g.NumberOfActiveParticles[ptype]: continue", "if f is None: # print(\"Opening (count) %s\" % g.filename)", ") filename = obj.filename for field in fields: nodal_flag =", "saw was the same dtype, we can go ahead and", "# floats, since our numpy copying/casting is way faster than", "a version thing. # dg.close() if close: fid.close() return data.T", "== len(chunks[0].objs) == 1): raise RuntimeError g = chunks[0].objs[0] f", "field), data[mask] class IOHandlerPacked2D(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_2d\" _particle_reader = False", "% g.id) for ptype, field_list in sorted(ptf.items()): if ptype ==", "= field data_view = self.grids_in_memory[g.id][fname][ self.my_slice ].swapaxes(0, 2) nd =", "in field_list: data = self.grids_in_memory[g.id][field] if field in _convert_mass: data", "1: fields.append((\"enzo\", str(name))) elif add_io: fields.append((\"io\", str(name))) elif add_dm: fields.append((\"DarkMatter\",", "ds.get(f\"{pname}/{ptype}\") if pds is not None: break else: raise RuntimeError(", "f.get(\"/Grid%08i\" % g.id) for ptype, field_list in sorted(ptf.items()): if ptype", "in grid.ds.particle_types add_dm = \"DarkMatter\" in grid.ds.particle_types for name, v", "fields.append((\"io\", str(name))) else: fields.append((\"enzo\", str(name))) return fields def _read_fluid_selection(self, chunks,", "references. # For all versions of Enzo I know about,", "ax)[()], dtype=\"=f8\") for ax in \"xyz\" ) if selector is", "a *hard error* here. # if g.id not in self.grids_in_memory:", "it just needs to be # okay for now. self._field_dtype", "self.grids_in_memory[grid.id].items(): # NOTE: This won't work with 1D datasets or", "= list(chunks) for chunk in chunks: # These should be", "g.filename) f = h5py.File(g.filename, mode=\"r\") nap = sum(g.NumberOfActiveParticles.values()) if g.NumberOfParticles", "# NOTE: This won't work with 1D datasets or references.", "size is None: size = sum(g.count(selector) for chunk in chunks", ") if selector is None: # This only ever happens", "pds = ds elif not g.NumberOfActiveParticles[ptype]: continue else: for pname", "is a # problem, but one we can return to.", "is way faster than # h5py's, for some reason I", "0 and nap == 0: continue for ptype, field_list in", "filename = -1 for obj in chunk.objs: if obj.filename is", "chunks, selector, fields, size): rv = {} # Now we", "fid.close() def _read_obj_field(self, obj, field, fid_data): if fid_data is None:", "ind = 0 for chunk in chunks: for g in", "ds, rv[field], ind) # caches ind += nd f.close() return", "np.atleast_3d(gds.get(fname)[()].transpose()) nd = g.select(selector, ds, rv[field], ind) # caches ind", "1): raise RuntimeError g = chunks[0].objs[0] for ftype, fname in", "= chunks[0].objs[0] for ftype, fname in fields: rv[(ftype, fname)] =", "continue if obj.filename != filename: # Note one really important", "ptf, selector): chunks = list(chunks) for chunk in chunks: #", "fid.close() return data.T class IOHandlerPackedHDF5GhostZones(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_3d_gz\" def __init__(self,", "else: raise RuntimeError( \"Could not find active particle group in", "# I don't know why, but on some installations of", "= \"io\" in grid.ds.particle_types for name, v in self.grids_in_memory[grid.id].items(): #", "1: fields.append((\"enzo\", str(name))) elif add_io: fields.append((\"io\", str(name))) else: fields.append((\"enzo\", str(name)))", "error* here. # if g.id not in self.grids_in_memory: continue for", "ftype, fname = field ds = np.atleast_3d(gds.get(fname)[()].transpose()) nd = g.select(selector,", "= (\"particle_mass\", \"mass\") _particle_position_names = {} class IOHandlerPackedHDF5(BaseIOHandler): _dataset_type =", "ptf, None) def _read_particle_fields(self, chunks, ptf, selector): chunks = list(chunks)", "= h5py.h5d.open(fid, node.encode(\"latin-1\")) except KeyError: if fname == \"Dark_Matter_Density\": data[:]", "\"O\": continue elif v.ndim == 1: if grid.ds.dimensionality == 1:", "grid): fields = [] add_io = \"io\" in grid.ds.particle_types for", "whatnot. This is a # problem, but one we can", "field_list: data = self.grids_in_memory[g.id][field] if field in _convert_mass: data =", "chunks[0].objs[0] f = h5py.File(g.filename, mode=\"r\") gds = f.get(\"/Grid%08i\" % g.id)", "if not (len(chunks) == len(chunks[0].objs) == 1): raise RuntimeError g", "add_io: fields.append((\"io\", str(name))) else: fields.append((\"enzo\", str(name))) return fields def _read_fluid_selection(self,", "the _read_obj_field function, # we'll still be doing file opening", "False if data is None: data = np.empty(obj.ActiveDimensions[::-1], dtype=self._field_dtype) ftype,", "f = None for g in chunk.objs: if f is", "self.grids_in_memory = enzo.grid_data self.old_grids_in_memory = enzo.old_grid_data self.my_slice = ( slice(ghost_zones,", "self._field_dtype for chunk in chunks: fid = None filename =", "2) return rv if size is None: size = sum(g.count(selector)", "ind == fsize return rv def _read_particle_coords(self, chunks, ptf): chunks", "def io_iter(self, chunks, fields): h5_dtype = self._field_dtype for chunk in", "or v.dtype == \"O\": continue elif v.ndim == 1: if", "def _read_exception(self): return (KeyError,) def _read_particle_coords(self, chunks, ptf): yield from", "0 for chunk in chunks: for g in chunk.objs: #", "f.close() return ds.transpose()[:, :, None] def _read_fluid_selection(self, chunks, selector, fields,", "chunks, ptf, selector): chunks = list(chunks) for chunk in chunks:", "if size is None: size = sum(g.count(selector) for chunk in", "do # implement LRU caching in the _read_obj_field function, #", "numpy copying/casting is way faster than # h5py's, for some", "is None: gds = f for field in fields: ftype,", "chunks: # These should be organized by grid filename f", "elif ptype == \"DarkMatter\": if g.NumberOfActiveParticles[ptype] == 0: continue pds", "RuntimeError( \"Could not find active particle group in data.\" )", "# These should be organized by grid filename for g", "size): rv = {} # Now we have to do", "data.\" ) pn = _particle_position_names.get(ptype, r\"particle_position_%s\") x, y, z =", "= h5py.File(grid.filename, mode=\"r\") ds = f[\"/Grid%08i/%s\" % (grid.id, field)][:] f.close()", "= \"enzo_inline\" def __init__(self, ds, ghost_zones=3): self.ds = ds import", "].swapaxes(0, 2) nd = g.select(selector, data_view, rv[field], ind) ind +=", "%s grids\", size, [f2 for f1, f2 in fields], ng,", "fields.append((\"enzo\", str(name))) elif add_io: fields.append((\"io\", str(name))) elif add_dm: fields.append((\"DarkMatter\", str(name)))", "0: continue for ptype, field_list in sorted(ptf.items()): x, y, z", "f2 in fields], ng, ) ind = 0 for chunk", "chunk in chunks for g in chunk.objs) for field in", "def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) NGZ = self.ds.parameters.get(\"NumberOfGhostZones\", 3)", "\"DarkMatter\": if g.NumberOfActiveParticles[ptype] == 0: continue pds = ds elif", "data is None: data = np.empty(obj.ActiveDimensions[::-1], dtype=self._field_dtype) ftype, fname =", "\"=f8\") if field in _convert_mass: data *= g.dds.prod(dtype=\"f8\") yield (ptype,", "for ptype, field_list in sorted(ptf.items()): x, y, z = (", "z) continue mask = selector.select_points(x, y, z, 0.0) if mask", "selector): chunks = list(chunks) for chunk in chunks: # These", "-NGZ)) def _read_obj_field(self, *args, **kwargs): return super()._read_obj_field(*args, **kwargs)[self._base] class IOHandlerInMemory(BaseIOHandler):", "sum(g.count(selector) for chunk in chunks for g in chunk.objs) for", "return data.T raise dg.read(h5py.h5s.ALL, h5py.h5s.ALL, data) # I don't know", "v in group.items(): # NOTE: This won't work with 1D", "here: even if we do # implement LRU caching in", "_read_obj_field function, # we'll still be doing file opening and", "raise dg.read(h5py.h5s.ALL, h5py.h5s.ALL, data) # I don't know why, but", "-ghost_zones), ) BaseIOHandler.__init__(self, ds) def _read_field_names(self, grid): fields = []", "or references. if not hasattr(v, \"shape\") or v.dtype == \"O\":", "ind) # caches ind += nd f.close() return rv class", "ptf): yield from self._read_particle_fields(chunks, ptf, None) def _read_particle_fields(self, chunks, ptf,", "= list(dtypes)[0] f.close() return fields @property def _read_exception(self): return (KeyError,)", "if everything we saw was the same dtype, we can", "field)][:] f.close() return ds.transpose()[:, :, None] def _read_fluid_selection(self, chunks, selector,", "# are of the same size. So, let's grab one.", "*= g.dds.prod(dtype=\"f8\") yield (ptype, field), data[mask] if f: f.close() def", "even if we do # implement LRU caching in the", "in sorted(ptf): x, y, z = ( self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"],", ") ind = 0 for chunk in chunks: for g", "None] def _read_fluid_selection(self, chunks, selector, fields, size): rv = {}", "if len(dtypes) == 1: # Now, if everything we saw", "fields): h5_dtype = self._field_dtype for chunk in chunks: fid =", "nodal_flag[::-1] data = np.empty(dims, dtype=h5_dtype) yield field, obj, self._read_obj_field(obj, field,", "won't work with 1D datasets or references. if not hasattr(v,", "if field in _convert_mass: data = data * g.dds.prod(dtype=\"f8\") yield", "fid is not None: fid.close() fid = h5py.h5f.open( obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY", "list(dtypes)[0] f.close() return fields @property def _read_exception(self): return (KeyError,) def", "# to be correct -- it will get fixed later", "import enzo self.enzo = enzo self.grids_in_memory = enzo.grid_data self.old_grids_in_memory =", "self.ds.field_info[field].nodal_flag dims = obj.ActiveDimensions[::-1] + nodal_flag[::-1] data = np.empty(dims, dtype=h5_dtype)", "% g.filename) f = h5py.File(g.filename, mode=\"r\") gds = f.get(\"/Grid%08i\" %", "raise RuntimeError g = chunks[0].objs[0] f = h5py.File(g.filename, mode=\"r\") gds", "gds = f.get(\"/Grid%08i\" % g.id) if gds is None: gds", "dtype=\"=f8\") for ax in \"xyz\" ) if selector is None:", "bit # floats, since our numpy copying/casting is way faster", "field, fid_data): if fid_data is None: fid_data = (None, None)", "1D datasets or references. if not hasattr(v, \"shape\") or v.dtype", "data = np.asarray(pds.get(field)[()], \"=f8\") if field in _convert_mass: data *=", "= None filename = -1 for obj in chunk.objs: if", "= f.get(\"/Grid%08i\" % g.id) for ptype, field_list in sorted(ptf.items()): if", "from yt.utilities.io_handler import BaseIOHandler from yt.utilities.logger import ytLogger as mylog", "because it is a HUGE savings for 32 bit #", "chunk.objs: if g.id not in self.grids_in_memory: continue nap = sum(g.NumberOfActiveParticles.values())", "way faster than # h5py's, for some reason I don't", "in chunk.objs: if obj.filename is None: continue if obj.filename !=", "= [] dtypes = set() add_io = \"io\" in grid.ds.particle_types", "if field in _convert_mass: data *= g.dds.prod(dtype=\"f8\") yield (ptype, field),", "ptype == \"DarkMatter\": if g.NumberOfActiveParticles[ptype] == 0: continue pds =", "= ( np.asarray(pds.get(pn % ax)[()], dtype=\"=f8\") for ax in \"xyz\"", ") BaseIOHandler.__init__(self, ds) def _read_field_names(self, grid): fields = [] add_io", "fid, data = fid_data if fid is None: close =", "h5py.h5f.ACC_RDONLY) else: close = False if data is None: data", "= \"enzo_packed_1d\" _particle_reader = False def _read_data_set(self, grid, field): f", "return fields def _read_fluid_selection(self, chunks, selector, fields, size): rv =", "import numpy as np from yt.geometry.selection_routines import GridSelector from yt.utilities.io_handler", "return (KeyError,) def _read_particle_coords(self, chunks, ptf): yield from self._read_particle_fields(chunks, ptf,", "ds import enzo self.enzo = enzo self.grids_in_memory = enzo.grid_data self.old_grids_in_memory", "or references. # For all versions of Enzo I know", "obj.filename is None: continue if obj.filename != filename: # Note", "from yt.utilities.on_demand_imports import _h5py as h5py _convert_mass = (\"particle_mass\", \"mass\")", "class IOHandlerPackedHDF5GhostZones(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_3d_gz\" def __init__(self, *args, **kwargs): super().__init__(*args,", "== 1): raise RuntimeError g = chunks[0].objs[0] f = h5py.File(g.filename,", "(KeyError,) def _read_particle_coords(self, chunks, ptf): yield from self._read_particle_fields(chunks, ptf, None)", "None: continue if obj.filename != filename: # Note one really", "obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY ) filename = obj.filename for field in fields:", "ptype, field_list in sorted(ptf.items()): x, y, z = ( self.grids_in_memory[g.id][\"particle_position_x\"],", "None: # This only ever happens if the call is", "chunks = list(chunks) for chunk in chunks: # These should", "fsize = size rv[field] = np.empty(fsize, dtype=\"float64\") ng = sum(len(c.objs)", "ptf): chunks = list(chunks) for chunk in chunks: # These", "if the call is made from # _read_particle_coords. yield ptype,", "_convert_mass: data = data * g.dds.prod(dtype=\"f8\") yield (ptype, field), data[mask]", "set it here. We do this because it is a", "field_list in sorted(ptf.items()): x, y, z = ( self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"],", "!= filename: # Note one really important thing here: even", "_dataset_type = \"enzo_packed_3d\" _base = slice(None) _field_dtype = \"float64\" def", "else: close = False if data is None: data =", "data) # I don't know why, but on some installations", "to. if fid is not None: fid.close() fid = h5py.h5f.open(", "None: # print(\"Opening (count) %s\" % g.filename) f = h5py.File(g.filename,", "field_list in sorted(ptf.items()): if ptype == \"io\": if g.NumberOfParticles ==", "g.NumberOfActiveParticles[ptype]: continue else: for pname in [\"Active Particles\", \"Particles\"]: pds", "it here. We do this because it is a HUGE", "= f[\"/Grid%08i/%s\" % (grid.id, field)][:] f.close() return ds.transpose()[:, :, None]", "== 1): raise RuntimeError g = chunks[0].objs[0] for ftype, fname", ":, None] def _read_fluid_selection(self, chunks, selector, fields, size): rv =", "Particles\", \"Particles\"]: pds = ds.get(f\"{pname}/{ptype}\") if pds is not None:", ") pn = _particle_position_names.get(ptype, r\"particle_position_%s\") x, y, z = (", "was the same dtype, we can go ahead and #", "# we'll still be doing file opening and whatnot. This", "thing. # dg.close() if close: fid.close() return data.T class IOHandlerPackedHDF5GhostZones(IOHandlerPackedHDF5):", "= {} class IOHandlerPackedHDF5(BaseIOHandler): _dataset_type = \"enzo_packed_3d\" _base = slice(None)", "0: continue pds = ds elif ptype == \"DarkMatter\": if", "f fields = [] dtypes = set() add_io = \"io\"", "datasets or references. # For all versions of Enzo I", "import BaseIOHandler from yt.utilities.logger import ytLogger as mylog from yt.utilities.on_demand_imports", "dtypes = set() add_io = \"io\" in grid.ds.particle_types add_dm =", "rv = {} # Now we have to do something", "g.id) for ptype, field_list in sorted(ptf.items()): if ptype == \"io\":", "field in field_list: data = self.grids_in_memory[g.id][field] if field in _convert_mass:", "in data.\" ) pn = _particle_position_names.get(ptype, r\"particle_position_%s\") x, y, z", "= np.atleast_3d(gds.get(fname)[()].transpose()) nd = g.select(selector, ds, rv[field], ind) # caches", "fname) dg = h5py.h5d.open(fid, node.encode(\"latin-1\")) except KeyError: if fname ==", "== 0: continue pds = ds elif ptype == \"DarkMatter\":", "# on others, nope. Doesn't seem to be a version", "for chunk in chunks for g in chunk.objs) for field", "This is a # problem, but one we can return", "# problem, but one we can return to. if fid", "elif add_io: fields.append((\"io\", str(name))) else: fields.append((\"enzo\", str(name))) return fields def", "= \"enzo_packed_3d_gz\" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) NGZ =", "raise RuntimeError( \"Could not find active particle group in data.\"", "= self._field_dtype for chunk in chunks: fid = None filename", "except KeyError: group = f fields = [] dtypes =", ") ind = 0 for chunk in chunks: f =", "caching in the _read_obj_field function, # we'll still be doing", "g.NumberOfParticles == 0 and nap == 0: continue for ptype,", "assert ind == fsize return rv def _read_particle_coords(self, chunks, ptf):", "% g.id) for ftype, fname in fields: rv[(ftype, fname)] =", "% g.id) if gds is None: gds = f for", "pds = ds.get(f\"{pname}/{ptype}\") if pds is not None: break else:", "just needs to be # okay for now. self._field_dtype =", "[\"Active Particles\", \"Particles\"]: pds = ds.get(f\"{pname}/{ptype}\") if pds is not", "everything we saw was the same dtype, we can go", "is None: continue for field in field_list: data = np.asarray(pds.get(field)[()],", "= np.empty(dims, dtype=h5_dtype) yield field, obj, self._read_obj_field(obj, field, (fid, data))", "field data_view = self.grids_in_memory[g.id][fname][ self.my_slice ].swapaxes(0, 2) nd = g.select(selector,", "g.id) if gds is None: gds = f for field", "mode=\"r\") nap = sum(g.NumberOfActiveParticles.values()) if g.NumberOfParticles == 0 and nap", "True fid = h5py.h5f.open(obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY) else: close = False if", "= ds elif not g.NumberOfActiveParticles[ptype]: continue else: for pname in", "gds = f for field in fields: ftype, fname =", "ptype == \"io\": if g.NumberOfParticles == 0: continue pds =", "\"Reading %s cells of %s fields in %s grids\", size,", "1: # Now, if everything we saw was the same", "import GridSelector from yt.utilities.io_handler import BaseIOHandler from yt.utilities.logger import ytLogger", "(None, None) fid, data = fid_data if fid is None:", "for chunk in chunks: fid = None filename = -1", "chunks: for g in chunk.objs: # We want a *hard", "RuntimeError g = chunks[0].objs[0] for ftype, fname in fields: rv[(ftype,", "organized by grid filename for g in chunk.objs: if g.id", "( self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"], ) yield ptype, (x, y, z)", "references. if not hasattr(v, \"shape\") or v.dtype == \"O\": continue", "_particle_position_names = {} class IOHandlerPackedHDF5(BaseIOHandler): _dataset_type = \"enzo_packed_3d\" _base =", "1): raise RuntimeError g = chunks[0].objs[0] f = h5py.File(g.filename, mode=\"r\")", "% (grid.id, field)][:] f.close() return ds.transpose()[:, :, None] def _read_fluid_selection(self,", "None: fid.close() def _read_obj_field(self, obj, field, fid_data): if fid_data is", "g in chunk.objs: if g.filename is None: continue if f", "dg = h5py.h5d.open(fid, node.encode(\"latin-1\")) except KeyError: if fname == \"Dark_Matter_Density\":", "None: close = True fid = h5py.h5f.open(obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY) else: close", "(count) %s\" % g.filename) f = h5py.File(g.filename, mode=\"r\") gds =", "= f for field in fields: ftype, fname = field", "grid.ds.dimensionality == 1: fields.append((\"enzo\", str(name))) elif add_io: fields.append((\"io\", str(name))) elif", "f = h5py.File(grid.filename, mode=\"r\") try: group = f[\"/Grid%08i\" % grid.id]", "filename = obj.filename for field in fields: nodal_flag = self.ds.field_info[field].nodal_flag", "dtype, we can go ahead and # set it here.", "\"Could not find active particle group in data.\" ) pn", "is None: continue if obj.filename != filename: # Note one", "return to. if fid is not None: fid.close() fid =", "in chunk.objs: if f is None: # print(\"Opening (count) %s\"", "== \"Dark_Matter_Density\": data[:] = 0 return data.T raise dg.read(h5py.h5s.ALL, h5py.h5s.ALL,", "== len(chunks[0].objs) == 1): raise RuntimeError g = chunks[0].objs[0] for", "= field ds = np.atleast_3d(gds.get(fname)[()].transpose()) nd = g.select(selector, ds, rv[field],", "class IOHandlerInMemory(BaseIOHandler): _dataset_type = \"enzo_inline\" def __init__(self, ds, ghost_zones=3): self.ds", "data *= g.dds.prod(dtype=\"f8\") yield (ptype, field), data[mask] if f: f.close()", "= None for g in chunk.objs: if f is None:", "g = chunks[0].objs[0] f = h5py.File(g.filename, mode=\"r\") gds = f.get(\"/Grid%08i\"", "not None: fid.close() def _read_obj_field(self, obj, field, fid_data): if fid_data", "dg.close() if close: fid.close() return data.T class IOHandlerPackedHDF5GhostZones(IOHandlerPackedHDF5): _dataset_type =", "= None for g in chunk.objs: if g.filename is None:", "in chunks: for g in chunk.objs: # We want a", "[] f = h5py.File(grid.filename, mode=\"r\") try: group = f[\"/Grid%08i\" %", "(grid.id, field)][:] f.close() return ds.transpose()[:, :, None] def _read_fluid_selection(self, chunks,", "fields: rv[(ftype, fname)] = self.grids_in_memory[g.id][fname].swapaxes(0, 2) return rv if size", "I don't know why, but on some installations of h5py", "ftype, fname in fields: rv[(ftype, fname)] = self.grids_in_memory[g.id][fname].swapaxes(0, 2) return", "= enzo.old_grid_data self.my_slice = ( slice(ghost_zones, -ghost_zones), slice(ghost_zones, -ghost_zones), slice(ghost_zones,", "[f2 for f1, f2 in fields], ng, ) ind =", "self.grids_in_memory[g.id][field] if field in _convert_mass: data = data * g.dds.prod(dtype=\"f8\")", "grid filename for g in chunk.objs: if g.id not in", "str(name))) return fields def _read_fluid_selection(self, chunks, selector, fields, size): rv", "_read_exception(self): return (KeyError,) def _read_particle_coords(self, chunks, ptf): yield from self._read_particle_fields(chunks,", "_read_field_names(self, grid): fields = [] add_io = \"io\" in grid.ds.particle_types", "== 0 and nap == 0: continue for ptype, field_list", "dtype=self._field_dtype) ftype, fname = field try: node = \"/Grid%08i/%s\" %", "numpy as np from yt.geometry.selection_routines import GridSelector from yt.utilities.io_handler import", "versions of Enzo I know about, we can assume all", "= _particle_position_names.get(ptype, r\"particle_position_%s\") x, y, z = ( np.asarray(pds.get(pn %", "h5py _convert_mass = (\"particle_mass\", \"mass\") _particle_position_names = {} class IOHandlerPackedHDF5(BaseIOHandler):", "_read_particle_coords. yield ptype, (x, y, z) continue mask = selector.select_points(x,", "size, [f2 for f1, f2 in fields], ng, ) ind", "nd f.close() return rv class IOHandlerPacked1D(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_1d\" _particle_reader", "This won't work with 1D datasets or references. if not", "if obj.filename != filename: # Note one really important thing", "h5py.h5f.ACC_RDONLY ) filename = obj.filename for field in fields: nodal_flag", "ds = f[\"/Grid%08i/%s\" % (grid.id, field)][:] f.close() return ds.transpose()[:, :,", "yt.utilities.io_handler import BaseIOHandler from yt.utilities.logger import ytLogger as mylog from", "= slice(None) _field_dtype = \"float64\" def _read_field_names(self, grid): if grid.filename", "now. self._field_dtype = list(dtypes)[0] f.close() return fields @property def _read_exception(self):", "+= nd assert ind == fsize return rv def _read_particle_coords(self,", "h5py.h5f.open(obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY) else: close = False if data is None:", "and whatnot. This is a # problem, but one we", "is None: # print(\"Opening (count) %s\" % g.filename) f =", "_read_obj_field(self, *args, **kwargs): return super()._read_obj_field(*args, **kwargs)[self._base] class IOHandlerInMemory(BaseIOHandler): _dataset_type =", "don't understand. This does *not* need # to be correct", "self.ds.parameters.get(\"NumberOfGhostZones\", 3) self._base = (slice(NGZ, -NGZ), slice(NGZ, -NGZ), slice(NGZ, -NGZ))", "obj in chunk.objs: if obj.filename is None: continue if obj.filename", "in chunks: f = None for g in chunk.objs: if", "str(name))) elif add_dm: fields.append((\"DarkMatter\", str(name))) else: fields.append((\"enzo\", str(name))) dtypes.add(v.dtype) if", "%s\" % g.filename) f = h5py.File(g.filename, mode=\"r\") gds = f.get(\"/Grid%08i\"", "_read_particle_coords(self, chunks, ptf): chunks = list(chunks) for chunk in chunks:", "fname)] = self.grids_in_memory[g.id][fname].swapaxes(0, 2) return rv if size is None:", "chunk in chunks: for g in chunk.objs: # We want", "This only ever happens if the call is made from", "rv[field] = np.empty(fsize, dtype=\"float64\") ng = sum(len(c.objs) for c in", "class IOHandlerPacked2D(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_2d\" _particle_reader = False def _read_data_set(self,", "self.grids_in_memory[g.id][fname][ self.my_slice ].swapaxes(0, 2) nd = g.select(selector, data_view, rv[field], ind)", "on some installations of h5py this works, but # on", "# _read_particle_coords. yield ptype, (x, y, z) continue mask =", "have to do something unpleasant chunks = list(chunks) if isinstance(selector,", "can go ahead and # set it here. We do", "(ptype, field), data[mask] class IOHandlerPacked2D(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_2d\" _particle_reader =", "nap = sum(g.NumberOfActiveParticles.values()) if g.NumberOfParticles == 0 and nap ==", "y, z = ( self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"], ) yield ptype,", "return super()._read_obj_field(*args, **kwargs)[self._base] class IOHandlerInMemory(BaseIOHandler): _dataset_type = \"enzo_inline\" def __init__(self,", "\"xyz\" ) if selector is None: # This only ever", "work with 1D datasets or references. # For all versions", "(len(chunks) == len(chunks[0].objs) == 1): raise RuntimeError g = chunks[0].objs[0]", "f1, f2 in fields], ng, ) ind = 0 for", "field in _convert_mass: data = data * g.dds.prod(dtype=\"f8\") yield (ptype,", "-NGZ), slice(NGZ, -NGZ)) def _read_obj_field(self, *args, **kwargs): return super()._read_obj_field(*args, **kwargs)[self._base]", "fsize return rv def _read_particle_coords(self, chunks, ptf): chunks = list(chunks)", "in chunks: # These should be organized by grid filename", "chunks, ptf): chunks = list(chunks) for chunk in chunks: #", "self.grids_in_memory[g.id][fname].swapaxes(0, 2) return rv if size is None: size =", "not in self.grids_in_memory: continue for field in fields: ftype, fname", "def _read_obj_field(self, *args, **kwargs): return super()._read_obj_field(*args, **kwargs)[self._base] class IOHandlerInMemory(BaseIOHandler): _dataset_type", "= self.grids_in_memory[g.id][fname].swapaxes(0, 2) return rv if size is None: size", "def _read_data_set(self, grid, field): f = h5py.File(grid.filename, mode=\"r\") ds =", "dims = obj.ActiveDimensions[::-1] + nodal_flag[::-1] data = np.empty(dims, dtype=h5_dtype) yield", "field in fields: ftype, fname = field fsize = size", "g.select(selector, data_view, rv[field], ind) ind += nd assert ind ==", "( self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"], ) mask = selector.select_points(x, y, z,", "of %s fields in %s grids\", size, [f2 for f1,", "data = fid_data if fid is None: close = True", "fid = None filename = -1 for obj in chunk.objs:", "to be correct -- it will get fixed later --", "-NGZ), slice(NGZ, -NGZ), slice(NGZ, -NGZ)) def _read_obj_field(self, *args, **kwargs): return", "g.id not in self.grids_in_memory: continue nap = sum(g.NumberOfActiveParticles.values()) if g.NumberOfParticles", "nap == 0: continue for ptype, field_list in sorted(ptf.items()): x,", "chunks, ptf): yield from self._read_particle_fields(chunks, ptf, None) def _read_particle_fields(self, chunks,", "ds elif not g.NumberOfActiveParticles[ptype]: continue else: for pname in [\"Active", "but on some installations of h5py this works, but #", "chunk.objs: if f is None: # print(\"Opening (count) %s\" %", "= chunks[0].objs[0] f = h5py.File(g.filename, mode=\"r\") gds = f.get(\"/Grid%08i\" %", "fname = field fsize = size rv[field] = np.empty(fsize, dtype=\"float64\")", "for f1, f2 in fields], ng, ) ind = 0", "this works, but # on others, nope. Doesn't seem to", "data.T class IOHandlerPackedHDF5GhostZones(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_3d_gz\" def __init__(self, *args, **kwargs):", "IOHandlerPackedHDF5GhostZones(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_3d_gz\" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)", "_dataset_type = \"enzo_packed_3d_gz\" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) NGZ", "is None: close = True fid = h5py.h5f.open(obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY) else:", "= \"/Grid%08i/%s\" % (obj.id, fname) dg = h5py.h5d.open(fid, node.encode(\"latin-1\")) except", "grid, field): f = h5py.File(grid.filename, mode=\"r\") ds = f[\"/Grid%08i/%s\" %", "same size. So, let's grab one. if not hasattr(v, \"shape\")", "if pds is not None: break else: raise RuntimeError( \"Could", "f[\"/Grid%08i\" % grid.id] except KeyError: group = f fields =", "self._base = (slice(NGZ, -NGZ), slice(NGZ, -NGZ), slice(NGZ, -NGZ)) def _read_obj_field(self,", "\"shape\") or v.dtype == \"O\": continue elif len(v.dims) == 1:", "ds) def _read_field_names(self, grid): fields = [] add_io = \"io\"", "self._field_dtype = list(dtypes)[0] f.close() return fields @property def _read_exception(self): return", "can assume all floats # are of the same size.", "in fields: nodal_flag = self.ds.field_info[field].nodal_flag dims = obj.ActiveDimensions[::-1] + nodal_flag[::-1]", "in chunks: fid = None filename = -1 for obj", "_particle_position_names.get(ptype, r\"particle_position_%s\") x, y, z = ( np.asarray(pds.get(pn % ax)[()],", "fname in fields: rv[(ftype, fname)] = np.atleast_3d(gds.get(fname)[()].transpose()) f.close() return rv", "(obj.id, fname) dg = h5py.h5d.open(fid, node.encode(\"latin-1\")) except KeyError: if fname", "KeyError: group = f fields = [] dtypes = set()", "h5py.File(grid.filename, mode=\"r\") try: group = f[\"/Grid%08i\" % grid.id] except KeyError:", "== 1: fields.append((\"enzo\", str(name))) elif add_io: fields.append((\"io\", str(name))) elif add_dm:", "grid.ds.dimensionality == 1: fields.append((\"enzo\", str(name))) elif add_io: fields.append((\"io\", str(name))) else:", "field in field_list: data = np.asarray(pds.get(field)[()], \"=f8\") if field in", "sum(len(c.objs) for c in chunks) mylog.debug( \"Reading %s cells of", "x, y, z = ( self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"], ) yield", "if gds is None: gds = f for field in", "c in chunks) mylog.debug( \"Reading %s cells of %s fields", "GridSelector): if not (len(chunks) == len(chunks[0].objs) == 1): raise RuntimeError", "h5py.h5d.open(fid, node.encode(\"latin-1\")) except KeyError: if fname == \"Dark_Matter_Density\": data[:] =", "field, (fid, data)) if fid is not None: fid.close() def", "ptype, (x, y, z) def _read_particle_fields(self, chunks, ptf, selector): chunks", "__init__(self, ds, ghost_zones=3): self.ds = ds import enzo self.enzo =", "_field_dtype = \"float64\" def _read_field_names(self, grid): if grid.filename is None:", "fields: ftype, fname = field data_view = self.grids_in_memory[g.id][fname][ self.my_slice ].swapaxes(0,", "f = h5py.File(g.filename, mode=\"r\") gds = f.get(\"/Grid%08i\" % g.id) for", "f.close() return rv if size is None: size = sum(g.count(selector)", "g.NumberOfParticles == 0: continue pds = ds elif ptype ==", "1: if grid.ds.dimensionality == 1: fields.append((\"enzo\", str(name))) elif add_io: fields.append((\"io\",", "group = f[\"/Grid%08i\" % grid.id] except KeyError: group = f", "dg.read(h5py.h5s.ALL, h5py.h5s.ALL, data) # I don't know why, but on", "%s fields in %s grids\", size, [f2 for f1, f2", "\"mass\") _particle_position_names = {} class IOHandlerPackedHDF5(BaseIOHandler): _dataset_type = \"enzo_packed_3d\" _base", "So, let's grab one. if not hasattr(v, \"shape\") or v.dtype", "be # okay for now. self._field_dtype = list(dtypes)[0] f.close() return", "yt.utilities.on_demand_imports import _h5py as h5py _convert_mass = (\"particle_mass\", \"mass\") _particle_position_names", "continue pds = ds elif not g.NumberOfActiveParticles[ptype]: continue else: for", "in [\"Active Particles\", \"Particles\"]: pds = ds.get(f\"{pname}/{ptype}\") if pds is", "_read_obj_field(self, obj, field, fid_data): if fid_data is None: fid_data =", "size = sum(g.count(selector) for chunk in chunks for g in", "field in fields: ftype, fname = field data_view = self.grids_in_memory[g.id][fname][", "in chunk.objs: if g.id not in self.grids_in_memory: continue nap =", "grids\", size, [f2 for f1, f2 in fields], ng, )", "for name, v in group.items(): # NOTE: This won't work", "None filename = -1 for obj in chunk.objs: if obj.filename", "we'll still be doing file opening and whatnot. This is", "self.my_slice = ( slice(ghost_zones, -ghost_zones), slice(ghost_zones, -ghost_zones), slice(ghost_zones, -ghost_zones), )", "# set it here. We do this because it is", "**kwargs) NGZ = self.ds.parameters.get(\"NumberOfGhostZones\", 3) self._base = (slice(NGZ, -NGZ), slice(NGZ,", "= h5py.h5f.open( obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY ) filename = obj.filename for field", "yield (ptype, field), data[mask] if f: f.close() def io_iter(self, chunks,", "\"Dark_Matter_Density\": data[:] = 0 return data.T raise dg.read(h5py.h5s.ALL, h5py.h5s.ALL, data)", "ng, ) ind = 0 for chunk in chunks: f", "sorted(ptf.items()): x, y, z = ( self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"], )", "chunk.objs: if obj.filename is None: continue if obj.filename != filename:", "BaseIOHandler.__init__(self, ds) def _read_field_names(self, grid): fields = [] add_io =", "ptype, field_list in sorted(ptf.items()): if ptype == \"io\": if g.NumberOfParticles", "v.dtype == \"O\": continue elif len(v.dims) == 1: if grid.ds.dimensionality", "slice(None) _field_dtype = \"float64\" def _read_field_names(self, grid): if grid.filename is", "HUGE savings for 32 bit # floats, since our numpy", "*hard error* here. # if g.id not in self.grids_in_memory: continue", "= h5py.h5f.open(obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY) else: close = False if data is", "by grid filename f = None for g in chunk.objs:", "%s\" % g.filename) f = h5py.File(g.filename, mode=\"r\") nap = sum(g.NumberOfActiveParticles.values())", "= h5py.File(g.filename, mode=\"r\") gds = f.get(\"/Grid%08i\" % g.id) for ftype,", "for ptype in sorted(ptf): x, y, z = ( self.grids_in_memory[g.id][\"particle_position_x\"],", "h5py.File(g.filename, mode=\"r\") gds = f.get(\"/Grid%08i\" % g.id) if gds is", "\"enzo_packed_2d\" _particle_reader = False def _read_data_set(self, grid, field): f =", "not hasattr(v, \"shape\") or v.dtype == \"O\": continue elif v.ndim", "str(name))) else: fields.append((\"enzo\", str(name))) return fields def _read_fluid_selection(self, chunks, selector,", "obj.ActiveDimensions[::-1] + nodal_flag[::-1] data = np.empty(dims, dtype=h5_dtype) yield field, obj,", "node.encode(\"latin-1\")) except KeyError: if fname == \"Dark_Matter_Density\": data[:] = 0", "return rv if size is None: size = sum(g.count(selector) for", "ds = f[\"/Grid%08i/%s\" % (grid.id, field)][:] f.close() return ds.transpose()[:, None,", "f for field in fields: ftype, fname = field ds", "installations of h5py this works, but # on others, nope.", "% ax)[()], dtype=\"=f8\") for ax in \"xyz\" ) if selector", "grid.ds.particle_types for name, v in self.grids_in_memory[grid.id].items(): # NOTE: This won't", "name, v in group.items(): # NOTE: This won't work with", "for g in chunk.objs: if g.id not in self.grids_in_memory: continue", "fields.append((\"enzo\", str(name))) return fields def _read_fluid_selection(self, chunks, selector, fields, size):", "in self.grids_in_memory[grid.id].items(): # NOTE: This won't work with 1D datasets", "yield (ptype, field), data[mask] class IOHandlerPacked2D(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_2d\" _particle_reader", "the same dtype, we can go ahead and # set", "fields.append((\"DarkMatter\", str(name))) else: fields.append((\"enzo\", str(name))) dtypes.add(v.dtype) if len(dtypes) == 1:", "io_iter(self, chunks, fields): h5_dtype = self._field_dtype for chunk in chunks:", "filename: # Note one really important thing here: even if", "= set() add_io = \"io\" in grid.ds.particle_types add_dm = \"DarkMatter\"", "are of the same size. So, let's grab one. if", "to be a version thing. # dg.close() if close: fid.close()", "let's grab one. if not hasattr(v, \"shape\") or v.dtype ==", "-ghost_zones), slice(ghost_zones, -ghost_zones), ) BaseIOHandler.__init__(self, ds) def _read_field_names(self, grid): fields", "all floats # are of the same size. So, let's", "pds = ds elif ptype == \"DarkMatter\": if g.NumberOfActiveParticles[ptype] ==", "h5py.h5f.open( obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY ) filename = obj.filename for field in", "self.grids_in_memory: continue for field in fields: ftype, fname = field", "for g in chunk.objs: if f is None: # print(\"Opening", "if grid.filename is None: return [] f = h5py.File(grid.filename, mode=\"r\")", "\"shape\") or v.dtype == \"O\": continue elif v.ndim == 1:", "field fsize = size rv[field] = np.empty(fsize, dtype=\"float64\") ng =", "okay for now. self._field_dtype = list(dtypes)[0] f.close() return fields @property", "== 1: # Now, if everything we saw was the", "for field in field_list: data = np.asarray(pds.get(field)[()], \"=f8\") if field", "f.close() return fields @property def _read_exception(self): return (KeyError,) def _read_particle_coords(self,", "ghost_zones=3): self.ds = ds import enzo self.enzo = enzo self.grids_in_memory", "be doing file opening and whatnot. This is a #", "= sum(g.count(selector) for chunk in chunks for g in chunk.objs)", "slice(ghost_zones, -ghost_zones), slice(ghost_zones, -ghost_zones), slice(ghost_zones, -ghost_zones), ) BaseIOHandler.__init__(self, ds) def", "want a *hard error* here. # if g.id not in", "if g.filename is None: continue if f is None: #", "slice(NGZ, -NGZ)) def _read_obj_field(self, *args, **kwargs): return super()._read_obj_field(*args, **kwargs)[self._base] class", "= ds elif ptype == \"DarkMatter\": if g.NumberOfActiveParticles[ptype] == 0:", "floats # are of the same size. So, let's grab", "continue for field in fields: ftype, fname = field data_view", "ytLogger as mylog from yt.utilities.on_demand_imports import _h5py as h5py _convert_mass", "some installations of h5py this works, but # on others,", "data[mask] if f: f.close() def io_iter(self, chunks, fields): h5_dtype =", "y, z, 0.0) if mask is None: continue for field", "fixed later -- it just needs to be # okay", "= np.asarray(pds.get(field)[()], \"=f8\") if field in _convert_mass: data *= g.dds.prod(dtype=\"f8\")", "= (None, None) fid, data = fid_data if fid is", "return rv def _read_particle_coords(self, chunks, ptf): chunks = list(chunks) for", "f[\"/Grid%08i/%s\" % (grid.id, field)][:] f.close() return ds.transpose()[:, :, None] def", "= data * g.dds.prod(dtype=\"f8\") yield (ptype, field), data[mask] class IOHandlerPacked2D(IOHandlerPackedHDF5):", "None: gds = f for field in fields: ftype, fname", "mask = selector.select_points(x, y, z, 0.0) if mask is None:", "one we can return to. if fid is not None:", "correct -- it will get fixed later -- it just", "continue for ptype, field_list in sorted(ptf.items()): x, y, z =", "particle group in data.\" ) pn = _particle_position_names.get(ptype, r\"particle_position_%s\") x,", "ng = sum(len(c.objs) for c in chunks) mylog.debug( \"Reading %s", "f.get(\"/Grid%08i\" % g.id) for ftype, fname in fields: rv[(ftype, fname)]", "in grid.ds.particle_types for name, v in self.grids_in_memory[grid.id].items(): # NOTE: This", "in \"xyz\" ) if selector is None: # This only", "len(v.dims) == 1: if grid.ds.dimensionality == 1: fields.append((\"enzo\", str(name))) elif", "np.asarray(pds.get(field)[()], \"=f8\") if field in _convert_mass: data *= g.dds.prod(dtype=\"f8\") yield", "be correct -- it will get fixed later -- it", "_dataset_type = \"enzo_packed_2d\" _particle_reader = False def _read_data_set(self, grid, field):", "gds = f.get(\"/Grid%08i\" % g.id) for ftype, fname in fields:", "continue if f is None: # print(\"Opening (read) %s\" %", "= f.get(\"/Grid%08i\" % g.id) for ftype, fname in fields: rv[(ftype,", "thing here: even if we do # implement LRU caching", "return rv class IOHandlerPacked1D(IOHandlerPackedHDF5): _dataset_type = \"enzo_packed_1d\" _particle_reader = False", "x, y, z = ( self.grids_in_memory[g.id][\"particle_position_x\"], self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"], ) mask", "but one we can return to. if fid is not", "self.old_grids_in_memory = enzo.old_grid_data self.my_slice = ( slice(ghost_zones, -ghost_zones), slice(ghost_zones, -ghost_zones),", "== 1: if grid.ds.dimensionality == 1: fields.append((\"enzo\", str(name))) elif add_io:", "mylog.debug( \"Reading %s cells of %s fields in %s grids\",", "= field fsize = size rv[field] = np.empty(fsize, dtype=\"float64\") ng", "None: data = np.empty(obj.ActiveDimensions[::-1], dtype=self._field_dtype) ftype, fname = field try:", "field in _convert_mass: data *= g.dds.prod(dtype=\"f8\") yield (ptype, field), data[mask]", "h5_dtype = self._field_dtype for chunk in chunks: fid = None", "from yt.utilities.logger import ytLogger as mylog from yt.utilities.on_demand_imports import _h5py", "is None: fid_data = (None, None) fid, data = fid_data", "is None: size = sum(g.count(selector) for chunk in chunks for", "grid.ds.particle_types add_dm = \"DarkMatter\" in grid.ds.particle_types for name, v in", "chunk.objs: # We want a *hard error* here. # if", "This does *not* need # to be correct -- it", "fields: nodal_flag = self.ds.field_info[field].nodal_flag dims = obj.ActiveDimensions[::-1] + nodal_flag[::-1] data", "g.id not in self.grids_in_memory: continue for field in fields: ftype,", "if we do # implement LRU caching in the _read_obj_field", "self.grids_in_memory: continue nap = sum(g.NumberOfActiveParticles.values()) if g.NumberOfParticles == 0 and", "self.grids_in_memory[g.id][\"particle_position_y\"], self.grids_in_memory[g.id][\"particle_position_z\"], ) yield ptype, (x, y, z) def _read_particle_fields(self,", "in group.items(): # NOTE: This won't work with 1D datasets", "continue pds = ds elif ptype == \"DarkMatter\": if g.NumberOfActiveParticles[ptype]", "if data is None: data = np.empty(obj.ActiveDimensions[::-1], dtype=self._field_dtype) ftype, fname", "enzo.grid_data self.old_grids_in_memory = enzo.old_grid_data self.my_slice = ( slice(ghost_zones, -ghost_zones), slice(ghost_zones,", "try: node = \"/Grid%08i/%s\" % (obj.id, fname) dg = h5py.h5d.open(fid,", "nap == 0: continue for ptype in sorted(ptf): x, y,", "and nap == 0: continue ds = f.get(\"/Grid%08i\" % g.id)", "in fields], ng, ) ind = 0 for chunk in", "None: # print(\"Opening (read) %s\" % g.filename) f = h5py.File(g.filename,", "filename f = None for g in chunk.objs: if g.filename", "# okay for now. self._field_dtype = list(dtypes)[0] f.close() return fields", "= True fid = h5py.h5f.open(obj.filename.encode(\"latin-1\"), h5py.h5f.ACC_RDONLY) else: close = False", "for name, v in self.grids_in_memory[grid.id].items(): # NOTE: This won't work", "g.filename) f = h5py.File(g.filename, mode=\"r\") gds = f.get(\"/Grid%08i\" % g.id)", "= \"float64\" def _read_field_names(self, grid): if grid.filename is None: return", "of Enzo I know about, we can assume all floats", "if g.NumberOfParticles == 0: continue pds = ds elif ptype", "ind += nd assert ind == fsize return rv def" ]
[ "= argparse.ArgumentParser(description='Enumarate CIDR ranges') parser.add_argument('ranges', metavar='range', type=str, nargs='*', help='List of", "help='Sort CIDR ranges') args = parser.parse_args() if args.files: files =", "files: with open(f, \"r\") as fd: for l in fd.readlines():", "nargs='*', help='List of CIDR ranges to enumerate') parser.add_argument('-f', '--files', metavar='file',", "if(do_sort): cidrs = sorted(cidrs) #print(cidrs) for cidr in cidrs: for", "\"r\") as fd: for l in fd.readlines(): ranges.append(l.strip()) enum_ranges(ranges, do_sort=args.sort)", "tools \"\"\" import argparse import netaddr def enum_ranges(ranges, do_sort): cidrs=[]", "give a list or ranges or input files\") parser.print_help() return", "parser.print_help() return for f in files: with open(f, \"r\") as", "very simple tool to help enumerate IP ranges when being", "ranges when being used with other tools \"\"\" import argparse", "help='List of CIDR ranges to enumerate') parser.add_argument('-f', '--files', metavar='file', type=str,", "ranges): print (\"Please give a list or ranges or input", "for r in ranges: try: cidrs.append(netaddr.IPNetwork(r)) except Exception as e:", "ip in cidr: print(ip) def main(): parser = argparse.ArgumentParser(description='Enumarate CIDR", "tool to help enumerate IP ranges when being used with", "netaddr def enum_ranges(ranges, do_sort): cidrs=[] for r in ranges: try:", "metavar='range', type=str, nargs='*', help='List of CIDR ranges to enumerate') parser.add_argument('-f',", "f in files: with open(f, \"r\") as fd: for l", "return if(do_sort): cidrs = sorted(cidrs) #print(cidrs) for cidr in cidrs:", "help='List of files to retrieve CIDR ranges to enumerate') parser.add_argument('-s',", "cidr in cidrs: for ip in cidr: print(ip) def main():", "with open(f, \"r\") as fd: for l in fd.readlines(): ranges.append(l.strip())", "cidrs.append(netaddr.IPNetwork(r)) except Exception as e: print(\"Error:\", e) return if(do_sort): cidrs", "IP ranges when being used with other tools \"\"\" import", "open(f, \"r\") as fd: for l in fd.readlines(): ranges.append(l.strip()) enum_ranges(ranges,", "(files or ranges): print (\"Please give a list or ranges", "\"\"\" cidr_enum.py is a very simple tool to help enumerate", "#!/usr/bin/env python3 \"\"\" cidr_enum.py is a very simple tool to", "a list or ranges or input files\") parser.print_help() return for", "argparse.ArgumentParser(description='Enumarate CIDR ranges') parser.add_argument('ranges', metavar='range', type=str, nargs='*', help='List of CIDR", "ranges or input files\") parser.print_help() return for f in files:", "l in fd.readlines(): ranges.append(l.strip()) enum_ranges(ranges, do_sort=args.sort) if __name__ == '__main__':", "help enumerate IP ranges when being used with other tools", "fd: for l in fd.readlines(): ranges.append(l.strip()) enum_ranges(ranges, do_sort=args.sort) if __name__", "or input files\") parser.print_help() return for f in files: with", "for cidr in cidrs: for ip in cidr: print(ip) def", "python3 \"\"\" cidr_enum.py is a very simple tool to help", "other tools \"\"\" import argparse import netaddr def enum_ranges(ranges, do_sort):", "CIDR ranges') parser.add_argument('ranges', metavar='range', type=str, nargs='*', help='List of CIDR ranges", "action='store_true', help='Sort CIDR ranges') args = parser.parse_args() if args.files: files", "retrieve CIDR ranges to enumerate') parser.add_argument('-s', '--sort', action='store_true', help='Sort CIDR", "in files: with open(f, \"r\") as fd: for l in", "do_sort): cidrs=[] for r in ranges: try: cidrs.append(netaddr.IPNetwork(r)) except Exception", "CIDR ranges') args = parser.parse_args() if args.files: files = list(args.files)", "= parser.parse_args() if args.files: files = list(args.files) else: files =", "if args.files: files = list(args.files) else: files = [] ranges", "in fd.readlines(): ranges.append(l.strip()) enum_ranges(ranges, do_sort=args.sort) if __name__ == '__main__': main()", "import netaddr def enum_ranges(ranges, do_sort): cidrs=[] for r in ranges:", "parser = argparse.ArgumentParser(description='Enumarate CIDR ranges') parser.add_argument('ranges', metavar='range', type=str, nargs='*', help='List", "type=str, nargs='*', help='List of CIDR ranges to enumerate') parser.add_argument('-f', '--files',", "else: files = [] ranges = list(args.ranges) if not (files", "files = list(args.files) else: files = [] ranges = list(args.ranges)", "def main(): parser = argparse.ArgumentParser(description='Enumarate CIDR ranges') parser.add_argument('ranges', metavar='range', type=str,", "simple tool to help enumerate IP ranges when being used", "cidr_enum.py is a very simple tool to help enumerate IP", "to enumerate') parser.add_argument('-s', '--sort', action='store_true', help='Sort CIDR ranges') args =", "in cidr: print(ip) def main(): parser = argparse.ArgumentParser(description='Enumarate CIDR ranges')", "parser.add_argument('-f', '--files', metavar='file', type=str, nargs='*', help='List of files to retrieve", "ranges to enumerate') parser.add_argument('-s', '--sort', action='store_true', help='Sort CIDR ranges') args", "files = [] ranges = list(args.ranges) if not (files or", "for f in files: with open(f, \"r\") as fd: for", "for l in fd.readlines(): ranges.append(l.strip()) enum_ranges(ranges, do_sort=args.sort) if __name__ ==", "input files\") parser.print_help() return for f in files: with open(f,", "= list(args.files) else: files = [] ranges = list(args.ranges) if", "enum_ranges(ranges, do_sort): cidrs=[] for r in ranges: try: cidrs.append(netaddr.IPNetwork(r)) except", "or ranges): print (\"Please give a list or ranges or", "cidr: print(ip) def main(): parser = argparse.ArgumentParser(description='Enumarate CIDR ranges') parser.add_argument('ranges',", "list or ranges or input files\") parser.print_help() return for f", "of CIDR ranges to enumerate') parser.add_argument('-f', '--files', metavar='file', type=str, nargs='*',", "print(ip) def main(): parser = argparse.ArgumentParser(description='Enumarate CIDR ranges') parser.add_argument('ranges', metavar='range',", "= list(args.ranges) if not (files or ranges): print (\"Please give", "when being used with other tools \"\"\" import argparse import", "a very simple tool to help enumerate IP ranges when", "Exception as e: print(\"Error:\", e) return if(do_sort): cidrs = sorted(cidrs)", "or ranges or input files\") parser.print_help() return for f in", "parser.add_argument('-s', '--sort', action='store_true', help='Sort CIDR ranges') args = parser.parse_args() if", "print (\"Please give a list or ranges or input files\")", "being used with other tools \"\"\" import argparse import netaddr", "\"\"\" import argparse import netaddr def enum_ranges(ranges, do_sort): cidrs=[] for", "return for f in files: with open(f, \"r\") as fd:", "ranges to enumerate') parser.add_argument('-f', '--files', metavar='file', type=str, nargs='*', help='List of", "in ranges: try: cidrs.append(netaddr.IPNetwork(r)) except Exception as e: print(\"Error:\", e)", "def enum_ranges(ranges, do_sort): cidrs=[] for r in ranges: try: cidrs.append(netaddr.IPNetwork(r))", "if not (files or ranges): print (\"Please give a list", "of files to retrieve CIDR ranges to enumerate') parser.add_argument('-s', '--sort',", "files\") parser.print_help() return for f in files: with open(f, \"r\")", "parser.add_argument('ranges', metavar='range', type=str, nargs='*', help='List of CIDR ranges to enumerate')", "sorted(cidrs) #print(cidrs) for cidr in cidrs: for ip in cidr:", "#print(cidrs) for cidr in cidrs: for ip in cidr: print(ip)", "used with other tools \"\"\" import argparse import netaddr def", "print(\"Error:\", e) return if(do_sort): cidrs = sorted(cidrs) #print(cidrs) for cidr", "cidrs=[] for r in ranges: try: cidrs.append(netaddr.IPNetwork(r)) except Exception as", "cidrs: for ip in cidr: print(ip) def main(): parser =", "cidrs = sorted(cidrs) #print(cidrs) for cidr in cidrs: for ip", "for ip in cidr: print(ip) def main(): parser = argparse.ArgumentParser(description='Enumarate", "ranges = list(args.ranges) if not (files or ranges): print (\"Please", "CIDR ranges to enumerate') parser.add_argument('-f', '--files', metavar='file', type=str, nargs='*', help='List", "'--files', metavar='file', type=str, nargs='*', help='List of files to retrieve CIDR", "main(): parser = argparse.ArgumentParser(description='Enumarate CIDR ranges') parser.add_argument('ranges', metavar='range', type=str, nargs='*',", "as fd: for l in fd.readlines(): ranges.append(l.strip()) enum_ranges(ranges, do_sort=args.sort) if", "argparse import netaddr def enum_ranges(ranges, do_sort): cidrs=[] for r in", "try: cidrs.append(netaddr.IPNetwork(r)) except Exception as e: print(\"Error:\", e) return if(do_sort):", "to enumerate') parser.add_argument('-f', '--files', metavar='file', type=str, nargs='*', help='List of files", "CIDR ranges to enumerate') parser.add_argument('-s', '--sort', action='store_true', help='Sort CIDR ranges')", "import argparse import netaddr def enum_ranges(ranges, do_sort): cidrs=[] for r", "enumerate IP ranges when being used with other tools \"\"\"", "type=str, nargs='*', help='List of files to retrieve CIDR ranges to", "nargs='*', help='List of files to retrieve CIDR ranges to enumerate')", "ranges') args = parser.parse_args() if args.files: files = list(args.files) else:", "as e: print(\"Error:\", e) return if(do_sort): cidrs = sorted(cidrs) #print(cidrs)", "e) return if(do_sort): cidrs = sorted(cidrs) #print(cidrs) for cidr in", "[] ranges = list(args.ranges) if not (files or ranges): print", "list(args.files) else: files = [] ranges = list(args.ranges) if not", "parser.parse_args() if args.files: files = list(args.files) else: files = []", "to retrieve CIDR ranges to enumerate') parser.add_argument('-s', '--sort', action='store_true', help='Sort", "list(args.ranges) if not (files or ranges): print (\"Please give a", "in cidrs: for ip in cidr: print(ip) def main(): parser", "not (files or ranges): print (\"Please give a list or", "is a very simple tool to help enumerate IP ranges", "with other tools \"\"\" import argparse import netaddr def enum_ranges(ranges,", "metavar='file', type=str, nargs='*', help='List of files to retrieve CIDR ranges", "<gh_stars>0 #!/usr/bin/env python3 \"\"\" cidr_enum.py is a very simple tool", "except Exception as e: print(\"Error:\", e) return if(do_sort): cidrs =", "files to retrieve CIDR ranges to enumerate') parser.add_argument('-s', '--sort', action='store_true',", "enumerate') parser.add_argument('-s', '--sort', action='store_true', help='Sort CIDR ranges') args = parser.parse_args()", "enumerate') parser.add_argument('-f', '--files', metavar='file', type=str, nargs='*', help='List of files to", "args.files: files = list(args.files) else: files = [] ranges =", "'--sort', action='store_true', help='Sort CIDR ranges') args = parser.parse_args() if args.files:", "ranges') parser.add_argument('ranges', metavar='range', type=str, nargs='*', help='List of CIDR ranges to", "args = parser.parse_args() if args.files: files = list(args.files) else: files", "ranges: try: cidrs.append(netaddr.IPNetwork(r)) except Exception as e: print(\"Error:\", e) return", "= [] ranges = list(args.ranges) if not (files or ranges):", "to help enumerate IP ranges when being used with other", "= sorted(cidrs) #print(cidrs) for cidr in cidrs: for ip in", "e: print(\"Error:\", e) return if(do_sort): cidrs = sorted(cidrs) #print(cidrs) for", "(\"Please give a list or ranges or input files\") parser.print_help()", "r in ranges: try: cidrs.append(netaddr.IPNetwork(r)) except Exception as e: print(\"Error:\"," ]
[ "depth=18, pretrained=None, pretrained2d=False, norm_eval=False, conv_cfg=dict(type='Conv3d'), norm_cfg=dict(type='SyncBN', requires_grad=True, eps=1e-3), act_cfg=dict(type='ReLU'), conv1_kernel=(3,", "type=dataset_type_unlabeled, ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline_weak=train_pipeline_weak, pipeline_strong=train_pipeline_strong, pipeline_format=train_pipeline_format, contrast_clip_num=1 ), val=dict( type=dataset_type,", "scale=(-1, 256)), dict(type='ThreeCrop', crop_size=256), dict(type='Flip', flip_ratio=0), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'),", ") # optimizer optimizer = dict( type='SGD', lr=0.2, momentum=0.9, weight_decay=0.0001)", "5 workers_per_gpu=4, # Default: 4 train_dataloader=dict(drop_last=True, pin_memory=True), train_labeled=dict( type=dataset_type_labeled, ann_file=ann_file_train_labeled,", "warmup_epoch=10, fixmatch_threshold=0.3, temp_align_indices=(0, 1, 2, 3), align_loss_func='Cosine', pseudo_label_metric='avg', crossclip_contrast_loss=[], crossclip_contrast_range=[],", "] test_pipeline = [ dict(type='DecordInit'), dict( type='SampleFrames', clip_len=8, frame_interval=8, num_clips=10,", "] data = dict( videos_per_gpu=8, # NOTE: Need to reduce", "redist_to_rgb=False), dict(type='FormatShape', input_format='NCTHW'), dict(type='FormatShape_Diff', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label', 'imgs_diff'], meta_keys=[]),", "act_cfg=dict(type='ReLU'), conv1_kernel=(3, 7, 7), conv1_stride_t=1, pool1_stride_t=1, inflate=(1, 1, 1, 1),", "= 'VideoDataset_Contrastive' dataset_type_unlabeled = 'UnlabeledVideoDataset_MultiView_Contrastive' # dataset_type_appearance = 'RawframeDataset_withAPP' data_root", "type='SampleFrames', clip_len=8, frame_interval=8, num_clips=10, test_mode=True), dict(type='DecordDecode'), dict(type='Resize', scale=(-1, 256)), dict(type='ThreeCrop',", "reduce batch size. 16 -> 5 workers_per_gpu=4, # Default: 4", "dict(type='Flip', flip_ratio=0), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),", "= 'data/kinetics400/kinetics400_val_list_videos.txt' ann_file_test = 'data/kinetics400/kinetics400_val_list_videos.txt' img_norm_cfg = dict( mean=[123.675, 116.28,", "] val_pipeline = [ dict(type='DecordInit'), dict( type='SampleFrames', clip_len=8, frame_interval=8, num_clips=1,", "dict( interval=20, # Default: 20 hooks=[ dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook'), ]) precise_bn", "shared by both weak and strong train_pipeline_format = [ dict(type='Normalize',", "work_dir = None load_from = None resume_from = None workflow", "total_frames_offset=-1), dict(type='DecordDecode_Custom', extra_modalities=['tempgrad']), dict(type='Resize', scale=(-1, 256), lazy=True), dict(type='RandomResizedCrop', lazy=True), dict(type='Resize',", "None load_from = None resume_from = None workflow = [('train',", "keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] data = dict( videos_per_gpu=8,", "# model settings model = dict( type='Semi_AppSup_TempSup_SimCLR_Crossclip_PTV_Recognizer3D', backbone=dict( type='ResNet3d', depth=18,", "16 -> 5 workers_per_gpu=4, # Default: 4 train_dataloader=dict(drop_last=True, pin_memory=True), train_labeled=dict(", "gpus optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2)) # learning policy lr_config =", "2, 2, 2), zero_init_residual=False), cls_head=dict( type='I3DHead', num_classes=400, in_channels=512, spatial_type='avg', dropout_ratio=0.5,", "meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label', 'imgs_diff']) ] val_pipeline = [ dict(type='DecordInit'),", "[ dict(type='DecordInit'), dict(type='SampleFrames_Custom', clip_len=8, frame_interval=8, num_clips=1, total_frames_offset=-1), dict(type='DecordDecode_Custom', extra_modalities=['tempgrad']), dict(type='Resize',", "'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] data = dict( videos_per_gpu=8, #", "both weak and strong train_pipeline_format = [ dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff',", "dict(type='Resize', scale=(224, 224), keep_ratio=False, lazy=True), dict(type='Flip', flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'), dict(type='Normalize',", "3), align_loss_func='Cosine', pseudo_label_metric='avg', crossclip_contrast_loss=[], crossclip_contrast_range=[], ), test_cfg=dict(average_clips='score')) # dataset settings", "videos_per_gpu=8, # NOTE: Need to reduce batch size. 16 ->", "4 train_dataloader=dict(drop_last=True, pin_memory=True), train_labeled=dict( type=dataset_type_labeled, ann_file=ann_file_train_labeled, data_prefix=data_root, pipeline=train_pipeline, contrast_clip_num=1 ),", "), train_unlabeled=dict( type=dataset_type_unlabeled, ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline_weak=train_pipeline_weak, pipeline_strong=train_pipeline_strong, pipeline_format=train_pipeline_format, contrast_clip_num=1 ),", "dict(type='Resize', scale=(224, 224), keep_ratio=False, lazy=True), dict(type='Flip', flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'), ]", "test_mode=True), dict(type='DecordDecode'), dict(type='Resize', scale=(-1, 256), lazy=True), dict(type='CenterCrop', crop_size=224, lazy=True), dict(type='Flip',", "model = dict( type='Semi_AppSup_TempSup_SimCLR_Crossclip_PTV_Recognizer3D', backbone=dict( type='ResNet3d', depth=18, pretrained=None, pretrained2d=False, norm_eval=False,", "input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] data =", "type='I3DHead', num_classes=400, in_channels=512, spatial_type='avg', dropout_ratio=0.5, init_std=0.01), cls_head_temp=None, temp_backbone='same', temp_sup_head='same', train_cfg=dict(", "data = dict( videos_per_gpu=8, # NOTE: Need to reduce batch", "topk=(1, 5)) # Default: 5 log_config = dict( interval=20, #", "2, 2), zero_init_residual=False), cls_head=dict( type='I3DHead', num_classes=400, in_channels=512, spatial_type='avg', dropout_ratio=0.5, init_std=0.01),", "dict(type='TensorboardLoggerHook'), ]) precise_bn = dict(num_iters=200, interval=5, bn_range=['backbone', 'cls_head']) dist_params =", "data_root_val = 'data/kinetics400/videos_val' labeled_percentage = 1 ann_file_train_labeled = f'data/kinetics400/videossl_splits/kinetics400_train_{labeled_percentage}_percent_labeled_videos.txt' ann_file_train_unlabeled", "to increase this number for different splits. Default: 180 checkpoint_config", "dict(type='ToTensor', keys=['imgs']) ] test_pipeline = [ dict(type='DecordInit'), dict( type='SampleFrames', clip_len=8,", "dict( type='SampleFrames', clip_len=8, frame_interval=8, num_clips=1, test_mode=True), dict(type='DecordDecode'), dict(type='Resize', scale=(-1, 256),", "for 8 gpus optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2)) # learning policy", "scale=(-1, 256), lazy=True), dict(type='CenterCrop', crop_size=224, lazy=True), dict(type='Flip', flip_ratio=0, lazy=True), dict(type='Fuse'),", "dict( type='SampleFrames', clip_len=8, frame_interval=8, num_clips=10, test_mode=True), dict(type='DecordDecode'), dict(type='Resize', scale=(-1, 256)),", "pipeline=train_pipeline, contrast_clip_num=1 ), train_unlabeled=dict( type=dataset_type_unlabeled, ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline_weak=train_pipeline_weak, pipeline_strong=train_pipeline_strong, pipeline_format=train_pipeline_format,", "'data/kinetics400/videos_train' data_root_val = 'data/kinetics400/videos_val' labeled_percentage = 1 ann_file_train_labeled = f'data/kinetics400/videossl_splits/kinetics400_train_{labeled_percentage}_percent_labeled_videos.txt'", "optimizer optimizer = dict( type='SGD', lr=0.2, momentum=0.9, weight_decay=0.0001) # this", "modality='imgs_diff') ] # Formating the input tensors, shared by both", "number for different splits. Default: 180 checkpoint_config = dict(interval=5, max_keep_ckpts=3)", "input tensors, shared by both weak and strong train_pipeline_format =", "log_level = 'INFO' work_dir = None load_from = None resume_from", "this lr 0.2 is used for 8 gpus optimizer_config =", "keep_ratio=False, lazy=True), dict(type='Flip', flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'), ] # Only used", "pipeline_strong=train_pipeline_strong, pipeline_format=train_pipeline_format, contrast_clip_num=1 ), val=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=val_pipeline, test_mode=True),", "dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] test_pipeline", "clip_len=8, frame_interval=8, num_clips=1, test_mode=True), dict(type='DecordDecode'), dict(type='Resize', scale=(-1, 256), lazy=True), dict(type='CenterCrop',", "= dict(grad_clip=dict(max_norm=40, norm_type=2)) # learning policy lr_config = dict(policy='CosineAnnealing', min_lr=0,", "**img_norm_cfg), dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False, redist_to_rgb=False), dict(type='FormatShape', input_format='NCTHW'), dict(type='FormatShape_Diff', input_format='NCTHW'), dict(type='Collect',", "-> 5 workers_per_gpu=4, # Default: 4 train_dataloader=dict(drop_last=True, pin_memory=True), train_labeled=dict( type=dataset_type_labeled,", "0.2 is used for 8 gpus optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2))", "temp_backbone='same', temp_sup_head='same', train_cfg=dict( warmup_epoch=10, fixmatch_threshold=0.3, temp_align_indices=(0, 1, 2, 3), align_loss_func='Cosine',", "dataset settings dataset_type = 'VideoDataset' dataset_type_labeled = 'VideoDataset_Contrastive' dataset_type_unlabeled =", "ann_file=ann_file_val, data_prefix=data_root_val, pipeline=val_pipeline, test_mode=True), test=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=test_pipeline, test_mode=True),", "pretrained2d=False, norm_eval=False, conv_cfg=dict(type='Conv3d'), norm_cfg=dict(type='SyncBN', requires_grad=True, eps=1e-3), act_cfg=dict(type='ReLU'), conv1_kernel=(3, 7, 7),", "interval=5, metrics=['top_k_accuracy', 'mean_class_accuracy'], topk=(1, 5)) # Default: 5 log_config =", "20 hooks=[ dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook'), ]) precise_bn = dict(num_iters=200, interval=5, bn_range=['backbone',", "dict(grad_clip=dict(max_norm=40, norm_type=2)) # learning policy lr_config = dict(policy='CosineAnnealing', min_lr=0, warmup='linear',", "224), keep_ratio=False, lazy=True), dict(type='Flip', flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'), ] # Only", "both weak and strong train_pipeline_weak = [ dict(type='DecordInit'), dict(type='SampleFrames_Custom', clip_len=8,", "settings model = dict( type='Semi_AppSup_TempSup_SimCLR_Crossclip_PTV_Recognizer3D', backbone=dict( type='ResNet3d', depth=18, pretrained=None, pretrained2d=False,", "Default: 5 log_config = dict( interval=20, # Default: 20 hooks=[", "need to increase this number for different splits. Default: 180", "spatial_strides=(1, 2, 2, 2), temporal_strides=(1, 2, 2, 2), zero_init_residual=False), cls_head=dict(", "dict(type='Fuse_WithDiff'), dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False, redist_to_rgb=False), dict(type='FormatShape', input_format='NCTHW'), dict(type='FormatShape_Diff',", "lazy=True), dict(type='Flip', flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'), dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False,", "input_format='NCTHW'), dict(type='FormatShape_Diff', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label', 'imgs_diff'], meta_keys=[]), dict(type='ToTensor', keys=['imgs',", "dict(num_iters=200, interval=5, bn_range=['backbone', 'cls_head']) dist_params = dict(backend='nccl') log_level = 'INFO'", "cls_head=dict( type='I3DHead', num_classes=400, in_channels=512, spatial_type='avg', dropout_ratio=0.5, init_std=0.01), cls_head_temp=None, temp_backbone='same', temp_sup_head='same',", "align_loss_func='Cosine', pseudo_label_metric='avg', crossclip_contrast_loss=[], crossclip_contrast_range=[], ), test_cfg=dict(average_clips='score')) # dataset settings dataset_type", "# optimizer optimizer = dict( type='SGD', lr=0.2, momentum=0.9, weight_decay=0.0001) #", "45 # Might need to increase this number for different", "[ dict(type='Imgaug', transforms='default'), dict(type='Imgaug_Custom', transforms='default', modality='imgs_diff') ] # Formating the", "train_pipeline_weak = [ dict(type='DecordInit'), dict(type='SampleFrames_Custom', clip_len=8, frame_interval=8, num_clips=1, total_frames_offset=-1), dict(type='DecordDecode_Custom',", "the frame and resize, shared by both weak and strong", "pipeline_format=train_pipeline_format, contrast_clip_num=1 ), val=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=val_pipeline, test_mode=True), test=dict(", "dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook'), ]) precise_bn = dict(num_iters=200, interval=5, bn_range=['backbone', 'cls_head']) dist_params", "used for strong augmentation train_pipeline_strong = [ dict(type='Imgaug', transforms='default'), dict(type='Imgaug_Custom',", "Default: 20 hooks=[ dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook'), ]) precise_bn = dict(num_iters=200, interval=5,", "224), keep_ratio=False, lazy=True), dict(type='Flip', flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'), dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff',", "7), conv1_stride_t=1, pool1_stride_t=1, inflate=(1, 1, 1, 1), spatial_strides=(1, 2, 2,", "ann_file_train_unlabeled = 'data/kinetics400/kinetics400_train_list_videos.txt' ann_file_val = 'data/kinetics400/kinetics400_val_list_videos.txt' ann_file_test = 'data/kinetics400/kinetics400_val_list_videos.txt' img_norm_cfg", "= 'data/kinetics400/kinetics400_train_list_videos.txt' ann_file_val = 'data/kinetics400/kinetics400_val_list_videos.txt' ann_file_test = 'data/kinetics400/kinetics400_val_list_videos.txt' img_norm_cfg =", "size. 16 -> 5 workers_per_gpu=4, # Default: 4 train_dataloader=dict(drop_last=True, pin_memory=True),", "norm_type=2)) # learning policy lr_config = dict(policy='CosineAnnealing', min_lr=0, warmup='linear', warmup_ratio=0.1,", "dropout_ratio=0.5, init_std=0.01), cls_head_temp=None, temp_backbone='same', temp_sup_head='same', train_cfg=dict( warmup_epoch=10, fixmatch_threshold=0.3, temp_align_indices=(0, 1,", "and strong train_pipeline_format = [ dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False,", "dataset_type_labeled = 'VideoDataset_Contrastive' dataset_type_unlabeled = 'UnlabeledVideoDataset_MultiView_Contrastive' # dataset_type_appearance = 'RawframeDataset_withAPP'", "= 'INFO' work_dir = None load_from = None resume_from =", "meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label', 'imgs_diff']) ] # Get the frame", "cls_head_temp=None, temp_backbone='same', temp_sup_head='same', train_cfg=dict( warmup_epoch=10, fixmatch_threshold=0.3, temp_align_indices=(0, 1, 2, 3),", "dict( interval=5, metrics=['top_k_accuracy', 'mean_class_accuracy'], topk=(1, 5)) # Default: 5 log_config", "'data/kinetics400/videos_val' labeled_percentage = 1 ann_file_train_labeled = f'data/kinetics400/videossl_splits/kinetics400_train_{labeled_percentage}_percent_labeled_videos.txt' ann_file_train_unlabeled = 'data/kinetics400/kinetics400_train_list_videos.txt'", "pipeline=val_pipeline), videos_per_gpu_precise_bn=5 ) # optimizer optimizer = dict( type='SGD', lr=0.2,", "'VideoDataset_Contrastive' dataset_type_unlabeled = 'UnlabeledVideoDataset_MultiView_Contrastive' # dataset_type_appearance = 'RawframeDataset_withAPP' data_root =", "dict(type='Flip', flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'), dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False, redist_to_rgb=False),", "splits. Default: 180 checkpoint_config = dict(interval=5, max_keep_ckpts=3) evaluation = dict(", "lr_config = dict(policy='CosineAnnealing', min_lr=0, warmup='linear', warmup_ratio=0.1, warmup_by_epoch=True, warmup_iters=10) total_epochs =", "flip_ratio=0), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor',", "Get the frame and resize, shared by both weak and", "crop_size=256), dict(type='Flip', flip_ratio=0), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'],", "= [ dict(type='DecordInit'), dict(type='SampleFrames_Custom', clip_len=8, frame_interval=8, num_clips=1, total_frames_offset=-1), dict(type='DecordDecode_Custom', extra_modalities=['tempgrad']),", "in_channels=512, spatial_type='avg', dropout_ratio=0.5, init_std=0.01), cls_head_temp=None, temp_backbone='same', temp_sup_head='same', train_cfg=dict( warmup_epoch=10, fixmatch_threshold=0.3,", "# Default: 20 hooks=[ dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook'), ]) precise_bn = dict(num_iters=200,", "lr=0.2, momentum=0.9, weight_decay=0.0001) # this lr 0.2 is used for", "pin_memory=True), train_labeled=dict( type=dataset_type_labeled, ann_file=ann_file_train_labeled, data_prefix=data_root, pipeline=train_pipeline, contrast_clip_num=1 ), train_unlabeled=dict( type=dataset_type_unlabeled,", "**img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ]", "dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs'])", "keys=['imgs', 'label', 'imgs_diff'], meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label', 'imgs_diff']) ] val_pipeline", "transforms='default', modality='imgs_diff') ] # Formating the input tensors, shared by", "type='SampleFrames', clip_len=8, frame_interval=8, num_clips=1, test_mode=True), dict(type='DecordDecode'), dict(type='Resize', scale=(-1, 256), lazy=True),", "strong train_pipeline_format = [ dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False, redist_to_rgb=False),", "= 'data/kinetics400/videos_val' labeled_percentage = 1 ann_file_train_labeled = f'data/kinetics400/videossl_splits/kinetics400_train_{labeled_percentage}_percent_labeled_videos.txt' ann_file_train_unlabeled =", "116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=False) train_pipeline = [ dict(type='DecordInit'),", "= 'data/kinetics400/kinetics400_val_list_videos.txt' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12,", "test_mode=True), precise_bn=dict( type=dataset_type, ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline=val_pipeline), videos_per_gpu_precise_bn=5 ) # optimizer", "max_keep_ckpts=3) evaluation = dict( interval=5, metrics=['top_k_accuracy', 'mean_class_accuracy'], topk=(1, 5)) #", "type='Semi_AppSup_TempSup_SimCLR_Crossclip_PTV_Recognizer3D', backbone=dict( type='ResNet3d', depth=18, pretrained=None, pretrained2d=False, norm_eval=False, conv_cfg=dict(type='Conv3d'), norm_cfg=dict(type='SyncBN', requires_grad=True,", "checkpoint_config = dict(interval=5, max_keep_ckpts=3) evaluation = dict( interval=5, metrics=['top_k_accuracy', 'mean_class_accuracy'],", "180 checkpoint_config = dict(interval=5, max_keep_ckpts=3) evaluation = dict( interval=5, metrics=['top_k_accuracy',", "flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'), ] # Only used for strong augmentation", "5)) # Default: 5 log_config = dict( interval=20, # Default:", "dict(policy='CosineAnnealing', min_lr=0, warmup='linear', warmup_ratio=0.1, warmup_by_epoch=True, warmup_iters=10) total_epochs = 45 #", "Default: 180 checkpoint_config = dict(interval=5, max_keep_ckpts=3) evaluation = dict( interval=5,", "dict(backend='nccl') log_level = 'INFO' work_dir = None load_from = None", "dict(type='Imgaug', transforms='default'), dict(type='Imgaug_Custom', transforms='default', modality='imgs_diff') ] # Formating the input", "'imgs_diff']) ] # Get the frame and resize, shared by", "strong train_pipeline_weak = [ dict(type='DecordInit'), dict(type='SampleFrames_Custom', clip_len=8, frame_interval=8, num_clips=1, total_frames_offset=-1),", "weight_decay=0.0001) # this lr 0.2 is used for 8 gpus", "Only used for strong augmentation train_pipeline_strong = [ dict(type='Imgaug', transforms='default'),", "tensors, shared by both weak and strong train_pipeline_format = [", "# dataset settings dataset_type = 'VideoDataset' dataset_type_labeled = 'VideoDataset_Contrastive' dataset_type_unlabeled", "'mean_class_accuracy'], topk=(1, 5)) # Default: 5 log_config = dict( interval=20,", "videos_per_gpu_precise_bn=5 ) # optimizer optimizer = dict( type='SGD', lr=0.2, momentum=0.9,", "= 45 # Might need to increase this number for", "type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=val_pipeline, test_mode=True), test=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=test_pipeline,", "'imgs_diff'], meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label', 'imgs_diff']) ] # Get the", "= dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=False) train_pipeline", "'label', 'imgs_diff'], meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label', 'imgs_diff']) ] # Get", "pretrained=None, pretrained2d=False, norm_eval=False, conv_cfg=dict(type='Conv3d'), norm_cfg=dict(type='SyncBN', requires_grad=True, eps=1e-3), act_cfg=dict(type='ReLU'), conv1_kernel=(3, 7,", "dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] data", "backbone=dict( type='ResNet3d', depth=18, pretrained=None, pretrained2d=False, norm_eval=False, conv_cfg=dict(type='Conv3d'), norm_cfg=dict(type='SyncBN', requires_grad=True, eps=1e-3),", "= None load_from = None resume_from = None workflow =", "lazy=True), dict(type='Flip', flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'), ] # Only used for", "1, 1, 1), spatial_strides=(1, 2, 2, 2), temporal_strides=(1, 2, 2,", "dict(type='ToTensor', keys=['imgs', 'label', 'imgs_diff']) ] # Get the frame and", "inflate=(1, 1, 1, 1), spatial_strides=(1, 2, 2, 2), temporal_strides=(1, 2,", "1), spatial_strides=(1, 2, 2, 2), temporal_strides=(1, 2, 2, 2), zero_init_residual=False),", "# Formating the input tensors, shared by both weak and", "dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=False) train_pipeline =", "by both weak and strong train_pipeline_weak = [ dict(type='DecordInit'), dict(type='SampleFrames_Custom',", "test_mode=True), dict(type='DecordDecode'), dict(type='Resize', scale=(-1, 256)), dict(type='ThreeCrop', crop_size=256), dict(type='Flip', flip_ratio=0), dict(type='Normalize',", "'imgs_diff'], meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label', 'imgs_diff']) ] val_pipeline = [", "lazy=True), dict(type='RandomResizedCrop', lazy=True), dict(type='Resize', scale=(224, 224), keep_ratio=False, lazy=True), dict(type='Flip', flip_ratio=0.5,", "ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline_weak=train_pipeline_weak, pipeline_strong=train_pipeline_strong, pipeline_format=train_pipeline_format, contrast_clip_num=1 ), val=dict( type=dataset_type, ann_file=ann_file_val,", "dict(type='Fuse_WithDiff'), ] # Only used for strong augmentation train_pipeline_strong =", "keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] test_pipeline = [ dict(type='DecordInit'),", "frame and resize, shared by both weak and strong train_pipeline_weak", "dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] data = dict(", "pool1_stride_t=1, inflate=(1, 1, 1, 1), spatial_strides=(1, 2, 2, 2), temporal_strides=(1,", "= 'data/kinetics400/videos_train' data_root_val = 'data/kinetics400/videos_val' labeled_percentage = 1 ann_file_train_labeled =", "'RawframeDataset_withAPP' data_root = 'data/kinetics400/videos_train' data_root_val = 'data/kinetics400/videos_val' labeled_percentage = 1", "log_config = dict( interval=20, # Default: 20 hooks=[ dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook'),", "dict(type='DecordInit'), dict( type='SampleFrames', clip_len=8, frame_interval=8, num_clips=1, test_mode=True), dict(type='DecordDecode'), dict(type='Resize', scale=(-1,", "val_pipeline = [ dict(type='DecordInit'), dict( type='SampleFrames', clip_len=8, frame_interval=8, num_clips=1, test_mode=True),", "256), lazy=True), dict(type='RandomResizedCrop', lazy=True), dict(type='Resize', scale=(224, 224), keep_ratio=False, lazy=True), dict(type='Flip',", "the input tensors, shared by both weak and strong train_pipeline_format", "bn_range=['backbone', 'cls_head']) dist_params = dict(backend='nccl') log_level = 'INFO' work_dir =", "'data/kinetics400/kinetics400_val_list_videos.txt' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375],", "weak and strong train_pipeline_weak = [ dict(type='DecordInit'), dict(type='SampleFrames_Custom', clip_len=8, frame_interval=8,", "dict(type='ThreeCrop', crop_size=256), dict(type='Flip', flip_ratio=0), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs',", "learning policy lr_config = dict(policy='CosineAnnealing', min_lr=0, warmup='linear', warmup_ratio=0.1, warmup_by_epoch=True, warmup_iters=10)", "train_pipeline_strong = [ dict(type='Imgaug', transforms='default'), dict(type='Imgaug_Custom', transforms='default', modality='imgs_diff') ] #", "meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] data = dict( videos_per_gpu=8, # NOTE:", "data_prefix=data_root_val, pipeline=test_pipeline, test_mode=True), precise_bn=dict( type=dataset_type, ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline=val_pipeline), videos_per_gpu_precise_bn=5 )", "optimizer = dict( type='SGD', lr=0.2, momentum=0.9, weight_decay=0.0001) # this lr", "warmup='linear', warmup_ratio=0.1, warmup_by_epoch=True, warmup_iters=10) total_epochs = 45 # Might need", "eps=1e-3), act_cfg=dict(type='ReLU'), conv1_kernel=(3, 7, 7), conv1_stride_t=1, pool1_stride_t=1, inflate=(1, 1, 1,", "# Get the frame and resize, shared by both weak", "scale=(-1, 256), lazy=True), dict(type='RandomResizedCrop', lazy=True), dict(type='Resize', scale=(224, 224), keep_ratio=False, lazy=True),", "= dict( type='SGD', lr=0.2, momentum=0.9, weight_decay=0.0001) # this lr 0.2", "precise_bn = dict(num_iters=200, interval=5, bn_range=['backbone', 'cls_head']) dist_params = dict(backend='nccl') log_level", "temporal_strides=(1, 2, 2, 2), zero_init_residual=False), cls_head=dict( type='I3DHead', num_classes=400, in_channels=512, spatial_type='avg',", "dict(type='Resize', scale=(-1, 256), lazy=True), dict(type='RandomResizedCrop', lazy=True), dict(type='Resize', scale=(224, 224), keep_ratio=False,", "dataset_type_unlabeled = 'UnlabeledVideoDataset_MultiView_Contrastive' # dataset_type_appearance = 'RawframeDataset_withAPP' data_root = 'data/kinetics400/videos_train'", "norm_eval=False, conv_cfg=dict(type='Conv3d'), norm_cfg=dict(type='SyncBN', requires_grad=True, eps=1e-3), act_cfg=dict(type='ReLU'), conv1_kernel=(3, 7, 7), conv1_stride_t=1,", "2), zero_init_residual=False), cls_head=dict( type='I3DHead', num_classes=400, in_channels=512, spatial_type='avg', dropout_ratio=0.5, init_std=0.01), cls_head_temp=None,", "crossclip_contrast_loss=[], crossclip_contrast_range=[], ), test_cfg=dict(average_clips='score')) # dataset settings dataset_type = 'VideoDataset'", "data_prefix=data_root_val, pipeline=val_pipeline, test_mode=True), test=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=test_pipeline, test_mode=True), precise_bn=dict(", "and resize, shared by both weak and strong train_pipeline_weak =", "keys=['imgs', 'label', 'imgs_diff']) ] val_pipeline = [ dict(type='DecordInit'), dict( type='SampleFrames',", "# Might need to increase this number for different splits.", "7, 7), conv1_stride_t=1, pool1_stride_t=1, inflate=(1, 1, 1, 1), spatial_strides=(1, 2,", "57.375], to_bgr=False) train_pipeline = [ dict(type='DecordInit'), dict(type='SampleFrames_Custom', clip_len=8, frame_interval=8, num_clips=1,", "total_epochs = 45 # Might need to increase this number", "'VideoDataset' dataset_type_labeled = 'VideoDataset_Contrastive' dataset_type_unlabeled = 'UnlabeledVideoDataset_MultiView_Contrastive' # dataset_type_appearance =", "num_classes=400, in_channels=512, spatial_type='avg', dropout_ratio=0.5, init_std=0.01), cls_head_temp=None, temp_backbone='same', temp_sup_head='same', train_cfg=dict( warmup_epoch=10,", "raw_to_diff=False, redist_to_rgb=False), dict(type='FormatShape', input_format='NCTHW'), dict(type='FormatShape_Diff', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label', 'imgs_diff'],", "= dict( interval=20, # Default: 20 hooks=[ dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook'), ])", "dict( type='Semi_AppSup_TempSup_SimCLR_Crossclip_PTV_Recognizer3D', backbone=dict( type='ResNet3d', depth=18, pretrained=None, pretrained2d=False, norm_eval=False, conv_cfg=dict(type='Conv3d'), norm_cfg=dict(type='SyncBN',", "1, 2, 3), align_loss_func='Cosine', pseudo_label_metric='avg', crossclip_contrast_loss=[], crossclip_contrast_range=[], ), test_cfg=dict(average_clips='score')) #", "warmup_by_epoch=True, warmup_iters=10) total_epochs = 45 # Might need to increase", "train_dataloader=dict(drop_last=True, pin_memory=True), train_labeled=dict( type=dataset_type_labeled, ann_file=ann_file_train_labeled, data_prefix=data_root, pipeline=train_pipeline, contrast_clip_num=1 ), train_unlabeled=dict(", "**img_norm_cfg, raw_to_diff=False, redist_to_rgb=False), dict(type='FormatShape', input_format='NCTHW'), dict(type='FormatShape_Diff', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label',", "= 'RawframeDataset_withAPP' data_root = 'data/kinetics400/videos_train' data_root_val = 'data/kinetics400/videos_val' labeled_percentage =", "dict(type='DecordDecode_Custom', extra_modalities=['tempgrad']), dict(type='Resize', scale=(-1, 256), lazy=True), dict(type='RandomResizedCrop', lazy=True), dict(type='Resize', scale=(224,", "5 log_config = dict( interval=20, # Default: 20 hooks=[ dict(type='TextLoggerHook'),", "load_from = None resume_from = None workflow = [('train', 1)]", "] # Only used for strong augmentation train_pipeline_strong = [", "keys=['imgs', 'label', 'imgs_diff'], meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label', 'imgs_diff']) ] #", "model settings model = dict( type='Semi_AppSup_TempSup_SimCLR_Crossclip_PTV_Recognizer3D', backbone=dict( type='ResNet3d', depth=18, pretrained=None,", "dict(type='DecordInit'), dict( type='SampleFrames', clip_len=8, frame_interval=8, num_clips=10, test_mode=True), dict(type='DecordDecode'), dict(type='Resize', scale=(-1,", "'label', 'imgs_diff'], meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label', 'imgs_diff']) ] val_pipeline =", "'INFO' work_dir = None load_from = None resume_from = None", "= [ dict(type='Imgaug', transforms='default'), dict(type='Imgaug_Custom', transforms='default', modality='imgs_diff') ] # Formating", "'imgs_diff']) ] val_pipeline = [ dict(type='DecordInit'), dict( type='SampleFrames', clip_len=8, frame_interval=8,", "NOTE: Need to reduce batch size. 16 -> 5 workers_per_gpu=4,", "num_clips=1, test_mode=True), dict(type='DecordDecode'), dict(type='Resize', scale=(-1, 256), lazy=True), dict(type='CenterCrop', crop_size=224, lazy=True),", "dict(type='ToTensor', keys=['imgs']) ] data = dict( videos_per_gpu=8, # NOTE: Need", "train_cfg=dict( warmup_epoch=10, fixmatch_threshold=0.3, temp_align_indices=(0, 1, 2, 3), align_loss_func='Cosine', pseudo_label_metric='avg', crossclip_contrast_loss=[],", "hooks=[ dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook'), ]) precise_bn = dict(num_iters=200, interval=5, bn_range=['backbone', 'cls_head'])", "= [ dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False, redist_to_rgb=False), dict(type='FormatShape', input_format='NCTHW'),", "= 'UnlabeledVideoDataset_MultiView_Contrastive' # dataset_type_appearance = 'RawframeDataset_withAPP' data_root = 'data/kinetics400/videos_train' data_root_val", "img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=False)", "mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=False) train_pipeline = [", "train_labeled=dict( type=dataset_type_labeled, ann_file=ann_file_train_labeled, data_prefix=data_root, pipeline=train_pipeline, contrast_clip_num=1 ), train_unlabeled=dict( type=dataset_type_unlabeled, ann_file=ann_file_train_unlabeled,", "policy lr_config = dict(policy='CosineAnnealing', min_lr=0, warmup='linear', warmup_ratio=0.1, warmup_by_epoch=True, warmup_iters=10) total_epochs", "ann_file=ann_file_val, data_prefix=data_root_val, pipeline=test_pipeline, test_mode=True), precise_bn=dict( type=dataset_type, ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline=val_pipeline), videos_per_gpu_precise_bn=5", "metrics=['top_k_accuracy', 'mean_class_accuracy'], topk=(1, 5)) # Default: 5 log_config = dict(", "data_prefix=data_root, pipeline=train_pipeline, contrast_clip_num=1 ), train_unlabeled=dict( type=dataset_type_unlabeled, ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline_weak=train_pipeline_weak, pipeline_strong=train_pipeline_strong,", "ann_file_val = 'data/kinetics400/kinetics400_val_list_videos.txt' ann_file_test = 'data/kinetics400/kinetics400_val_list_videos.txt' img_norm_cfg = dict( mean=[123.675,", "'label', 'imgs_diff']) ] val_pipeline = [ dict(type='DecordInit'), dict( type='SampleFrames', clip_len=8,", "input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] test_pipeline =", "data_prefix=data_root, pipeline_weak=train_pipeline_weak, pipeline_strong=train_pipeline_strong, pipeline_format=train_pipeline_format, contrast_clip_num=1 ), val=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val,", "val=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=val_pipeline, test_mode=True), test=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val,", "ann_file=ann_file_train_labeled, data_prefix=data_root, pipeline=train_pipeline, contrast_clip_num=1 ), train_unlabeled=dict( type=dataset_type_unlabeled, ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline_weak=train_pipeline_weak,", "dict(type='FormatShape', input_format='NCTHW'), dict(type='FormatShape_Diff', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label', 'imgs_diff'], meta_keys=[]), dict(type='ToTensor',", "type=dataset_type_labeled, ann_file=ann_file_train_labeled, data_prefix=data_root, pipeline=train_pipeline, contrast_clip_num=1 ), train_unlabeled=dict( type=dataset_type_unlabeled, ann_file=ann_file_train_unlabeled, data_prefix=data_root,", "= f'data/kinetics400/videossl_splits/kinetics400_train_{labeled_percentage}_percent_labeled_videos.txt' ann_file_train_unlabeled = 'data/kinetics400/kinetics400_train_list_videos.txt' ann_file_val = 'data/kinetics400/kinetics400_val_list_videos.txt' ann_file_test =", "dict(type='ToTensor', keys=['imgs', 'label', 'imgs_diff']) ] val_pipeline = [ dict(type='DecordInit'), dict(", "keys=['imgs']) ] test_pipeline = [ dict(type='DecordInit'), dict( type='SampleFrames', clip_len=8, frame_interval=8,", "meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] test_pipeline = [ dict(type='DecordInit'), dict( type='SampleFrames',", "= dict(backend='nccl') log_level = 'INFO' work_dir = None load_from =", "ann_file_test = 'data/kinetics400/kinetics400_val_list_videos.txt' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395,", "settings dataset_type = 'VideoDataset' dataset_type_labeled = 'VideoDataset_Contrastive' dataset_type_unlabeled = 'UnlabeledVideoDataset_MultiView_Contrastive'", "frame_interval=8, num_clips=1, test_mode=True), dict(type='DecordDecode'), dict(type='Resize', scale=(-1, 256), lazy=True), dict(type='CenterCrop', crop_size=224,", "ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline=val_pipeline), videos_per_gpu_precise_bn=5 ) # optimizer optimizer = dict(", "flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'), dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False, redist_to_rgb=False), dict(type='FormatShape',", "None resume_from = None workflow = [('train', 1)] find_unused_parameters =", "train_pipeline = [ dict(type='DecordInit'), dict(type='SampleFrames_Custom', clip_len=8, frame_interval=8, num_clips=1, total_frames_offset=-1), dict(type='DecordDecode_Custom',", "scale=(224, 224), keep_ratio=False, lazy=True), dict(type='Flip', flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'), dict(type='Normalize', **img_norm_cfg),", "dict(type='Flip', flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'), ] # Only used for strong", "Default: 4 train_dataloader=dict(drop_last=True, pin_memory=True), train_labeled=dict( type=dataset_type_labeled, ann_file=ann_file_train_labeled, data_prefix=data_root, pipeline=train_pipeline, contrast_clip_num=1", "), test_cfg=dict(average_clips='score')) # dataset settings dataset_type = 'VideoDataset' dataset_type_labeled =", "dataset_type = 'VideoDataset' dataset_type_labeled = 'VideoDataset_Contrastive' dataset_type_unlabeled = 'UnlabeledVideoDataset_MultiView_Contrastive' #", "[ dict(type='DecordInit'), dict( type='SampleFrames', clip_len=8, frame_interval=8, num_clips=10, test_mode=True), dict(type='DecordDecode'), dict(type='Resize',", "warmup_iters=10) total_epochs = 45 # Might need to increase this", "103.53], std=[58.395, 57.12, 57.375], to_bgr=False) train_pipeline = [ dict(type='DecordInit'), dict(type='SampleFrames_Custom',", "strong augmentation train_pipeline_strong = [ dict(type='Imgaug', transforms='default'), dict(type='Imgaug_Custom', transforms='default', modality='imgs_diff')", "dict(type='RandomResizedCrop', lazy=True), dict(type='Resize', scale=(224, 224), keep_ratio=False, lazy=True), dict(type='Flip', flip_ratio=0.5, lazy=True),", "# NOTE: Need to reduce batch size. 16 -> 5", "# Default: 5 log_config = dict( interval=20, # Default: 20", "dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False, redist_to_rgb=False), dict(type='FormatShape', input_format='NCTHW'), dict(type='FormatShape_Diff', input_format='NCTHW'),", "flip_ratio=0, lazy=True), dict(type='Fuse'), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'],", "keys=['imgs']) ] data = dict( videos_per_gpu=8, # NOTE: Need to", "conv1_stride_t=1, pool1_stride_t=1, inflate=(1, 1, 1, 1), spatial_strides=(1, 2, 2, 2),", "lazy=True), dict(type='Fuse_WithDiff'), dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False, redist_to_rgb=False), dict(type='FormatShape', input_format='NCTHW'),", "dict(type='Resize', scale=(-1, 256), lazy=True), dict(type='CenterCrop', crop_size=224, lazy=True), dict(type='Flip', flip_ratio=0, lazy=True),", "conv_cfg=dict(type='Conv3d'), norm_cfg=dict(type='SyncBN', requires_grad=True, eps=1e-3), act_cfg=dict(type='ReLU'), conv1_kernel=(3, 7, 7), conv1_stride_t=1, pool1_stride_t=1,", "dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False, redist_to_rgb=False), dict(type='FormatShape', input_format='NCTHW'), dict(type='FormatShape_Diff', input_format='NCTHW'), dict(type='Collect', keys=['imgs',", "type=dataset_type, ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline=val_pipeline), videos_per_gpu_precise_bn=5 ) # optimizer optimizer =", "clip_len=8, frame_interval=8, num_clips=1, total_frames_offset=-1), dict(type='DecordDecode_Custom', extra_modalities=['tempgrad']), dict(type='Resize', scale=(-1, 256), lazy=True),", "'cls_head']) dist_params = dict(backend='nccl') log_level = 'INFO' work_dir = None", "test_pipeline = [ dict(type='DecordInit'), dict( type='SampleFrames', clip_len=8, frame_interval=8, num_clips=10, test_mode=True),", "dict(interval=5, max_keep_ckpts=3) evaluation = dict( interval=5, metrics=['top_k_accuracy', 'mean_class_accuracy'], topk=(1, 5))", "dict(type='SampleFrames_Custom', clip_len=8, frame_interval=8, num_clips=1, total_frames_offset=-1), dict(type='DecordDecode_Custom', extra_modalities=['tempgrad']), dict(type='Resize', scale=(-1, 256),", "workers_per_gpu=4, # Default: 4 train_dataloader=dict(drop_last=True, pin_memory=True), train_labeled=dict( type=dataset_type_labeled, ann_file=ann_file_train_labeled, data_prefix=data_root,", "interval=5, bn_range=['backbone', 'cls_head']) dist_params = dict(backend='nccl') log_level = 'INFO' work_dir", "dict(type='Resize', scale=(-1, 256)), dict(type='ThreeCrop', crop_size=256), dict(type='Flip', flip_ratio=0), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape',", "std=[58.395, 57.12, 57.375], to_bgr=False) train_pipeline = [ dict(type='DecordInit'), dict(type='SampleFrames_Custom', clip_len=8,", "data_root = 'data/kinetics400/videos_train' data_root_val = 'data/kinetics400/videos_val' labeled_percentage = 1 ann_file_train_labeled", "'UnlabeledVideoDataset_MultiView_Contrastive' # dataset_type_appearance = 'RawframeDataset_withAPP' data_root = 'data/kinetics400/videos_train' data_root_val =", "# Only used for strong augmentation train_pipeline_strong = [ dict(type='Imgaug',", "lazy=True), dict(type='Resize', scale=(224, 224), keep_ratio=False, lazy=True), dict(type='Flip', flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'),", "f'data/kinetics400/videossl_splits/kinetics400_train_{labeled_percentage}_percent_labeled_videos.txt' ann_file_train_unlabeled = 'data/kinetics400/kinetics400_train_list_videos.txt' ann_file_val = 'data/kinetics400/kinetics400_val_list_videos.txt' ann_file_test = 'data/kinetics400/kinetics400_val_list_videos.txt'", "= 'VideoDataset' dataset_type_labeled = 'VideoDataset_Contrastive' dataset_type_unlabeled = 'UnlabeledVideoDataset_MultiView_Contrastive' # dataset_type_appearance", "temp_align_indices=(0, 1, 2, 3), align_loss_func='Cosine', pseudo_label_metric='avg', crossclip_contrast_loss=[], crossclip_contrast_range=[], ), test_cfg=dict(average_clips='score'))", "pseudo_label_metric='avg', crossclip_contrast_loss=[], crossclip_contrast_range=[], ), test_cfg=dict(average_clips='score')) # dataset settings dataset_type =", "57.12, 57.375], to_bgr=False) train_pipeline = [ dict(type='DecordInit'), dict(type='SampleFrames_Custom', clip_len=8, frame_interval=8,", "pipeline_weak=train_pipeline_weak, pipeline_strong=train_pipeline_strong, pipeline_format=train_pipeline_format, contrast_clip_num=1 ), val=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=val_pipeline,", "] # Formating the input tensors, shared by both weak", "= dict(policy='CosineAnnealing', min_lr=0, warmup='linear', warmup_ratio=0.1, warmup_by_epoch=True, warmup_iters=10) total_epochs = 45", "# this lr 0.2 is used for 8 gpus optimizer_config", "256), lazy=True), dict(type='CenterCrop', crop_size=224, lazy=True), dict(type='Flip', flip_ratio=0, lazy=True), dict(type='Fuse'), dict(type='Normalize',", "increase this number for different splits. Default: 180 checkpoint_config =", "evaluation = dict( interval=5, metrics=['top_k_accuracy', 'mean_class_accuracy'], topk=(1, 5)) # Default:", "weak and strong train_pipeline_format = [ dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff', **img_norm_cfg,", "dist_params = dict(backend='nccl') log_level = 'INFO' work_dir = None load_from", "fixmatch_threshold=0.3, temp_align_indices=(0, 1, 2, 3), align_loss_func='Cosine', pseudo_label_metric='avg', crossclip_contrast_loss=[], crossclip_contrast_range=[], ),", "keys=['imgs', 'label', 'imgs_diff']) ] # Get the frame and resize,", "dict(type='CenterCrop', crop_size=224, lazy=True), dict(type='Flip', flip_ratio=0, lazy=True), dict(type='Fuse'), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape',", "8 gpus optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2)) # learning policy lr_config", "ann_file_train_labeled = f'data/kinetics400/videossl_splits/kinetics400_train_{labeled_percentage}_percent_labeled_videos.txt' ann_file_train_unlabeled = 'data/kinetics400/kinetics400_train_list_videos.txt' ann_file_val = 'data/kinetics400/kinetics400_val_list_videos.txt' ann_file_test", "= [ dict(type='DecordInit'), dict( type='SampleFrames', clip_len=8, frame_interval=8, num_clips=10, test_mode=True), dict(type='DecordDecode'),", "= None resume_from = None workflow = [('train', 1)] find_unused_parameters", "transforms='default'), dict(type='Imgaug_Custom', transforms='default', modality='imgs_diff') ] # Formating the input tensors,", "lazy=True), dict(type='Fuse'), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),", "dict(type='DecordDecode'), dict(type='Resize', scale=(-1, 256), lazy=True), dict(type='CenterCrop', crop_size=224, lazy=True), dict(type='Flip', flip_ratio=0,", "to_bgr=False) train_pipeline = [ dict(type='DecordInit'), dict(type='SampleFrames_Custom', clip_len=8, frame_interval=8, num_clips=1, total_frames_offset=-1),", "init_std=0.01), cls_head_temp=None, temp_backbone='same', temp_sup_head='same', train_cfg=dict( warmup_epoch=10, fixmatch_threshold=0.3, temp_align_indices=(0, 1, 2,", "'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] test_pipeline = [ dict(type='DecordInit'), dict(", "interval=20, # Default: 20 hooks=[ dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook'), ]) precise_bn =", "crossclip_contrast_range=[], ), test_cfg=dict(average_clips='score')) # dataset settings dataset_type = 'VideoDataset' dataset_type_labeled", "type='SGD', lr=0.2, momentum=0.9, weight_decay=0.0001) # this lr 0.2 is used", "lr 0.2 is used for 8 gpus optimizer_config = dict(grad_clip=dict(max_norm=40,", "resize, shared by both weak and strong train_pipeline_weak = [", "] # Get the frame and resize, shared by both", "precise_bn=dict( type=dataset_type, ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline=val_pipeline), videos_per_gpu_precise_bn=5 ) # optimizer optimizer", "dict(type='Imgaug_Custom', transforms='default', modality='imgs_diff') ] # Formating the input tensors, shared", "min_lr=0, warmup='linear', warmup_ratio=0.1, warmup_by_epoch=True, warmup_iters=10) total_epochs = 45 # Might", "contrast_clip_num=1 ), train_unlabeled=dict( type=dataset_type_unlabeled, ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline_weak=train_pipeline_weak, pipeline_strong=train_pipeline_strong, pipeline_format=train_pipeline_format, contrast_clip_num=1", "test=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=test_pipeline, test_mode=True), precise_bn=dict( type=dataset_type, ann_file=ann_file_train_unlabeled, data_prefix=data_root,", "[ dict(type='DecordInit'), dict( type='SampleFrames', clip_len=8, frame_interval=8, num_clips=1, test_mode=True), dict(type='DecordDecode'), dict(type='Resize',", "clip_len=8, frame_interval=8, num_clips=10, test_mode=True), dict(type='DecordDecode'), dict(type='Resize', scale=(-1, 256)), dict(type='ThreeCrop', crop_size=256),", "dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] test_pipeline = [", "Need to reduce batch size. 16 -> 5 workers_per_gpu=4, #", "momentum=0.9, weight_decay=0.0001) # this lr 0.2 is used for 8", "= dict( type='Semi_AppSup_TempSup_SimCLR_Crossclip_PTV_Recognizer3D', backbone=dict( type='ResNet3d', depth=18, pretrained=None, pretrained2d=False, norm_eval=False, conv_cfg=dict(type='Conv3d'),", "[ dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False, redist_to_rgb=False), dict(type='FormatShape', input_format='NCTHW'), dict(type='FormatShape_Diff',", "used for 8 gpus optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2)) # learning", "resume_from = None workflow = [('train', 1)] find_unused_parameters = False", "dict(type='Fuse'), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor',", "different splits. Default: 180 checkpoint_config = dict(interval=5, max_keep_ckpts=3) evaluation =", "), val=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=val_pipeline, test_mode=True), test=dict( type=dataset_type, ann_file=ann_file_val,", "1, 1), spatial_strides=(1, 2, 2, 2), temporal_strides=(1, 2, 2, 2),", "dict(type='Collect', keys=['imgs', 'label', 'imgs_diff'], meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label', 'imgs_diff']) ]", "and strong train_pipeline_weak = [ dict(type='DecordInit'), dict(type='SampleFrames_Custom', clip_len=8, frame_interval=8, num_clips=1,", "num_clips=1, total_frames_offset=-1), dict(type='DecordDecode_Custom', extra_modalities=['tempgrad']), dict(type='Resize', scale=(-1, 256), lazy=True), dict(type='RandomResizedCrop', lazy=True),", "for strong augmentation train_pipeline_strong = [ dict(type='Imgaug', transforms='default'), dict(type='Imgaug_Custom', transforms='default',", "dict(type='DecordInit'), dict(type='SampleFrames_Custom', clip_len=8, frame_interval=8, num_clips=1, total_frames_offset=-1), dict(type='DecordDecode_Custom', extra_modalities=['tempgrad']), dict(type='Resize', scale=(-1,", "norm_cfg=dict(type='SyncBN', requires_grad=True, eps=1e-3), act_cfg=dict(type='ReLU'), conv1_kernel=(3, 7, 7), conv1_stride_t=1, pool1_stride_t=1, inflate=(1,", "'label', 'imgs_diff']) ] # Get the frame and resize, shared", "requires_grad=True, eps=1e-3), act_cfg=dict(type='ReLU'), conv1_kernel=(3, 7, 7), conv1_stride_t=1, pool1_stride_t=1, inflate=(1, 1,", "frame_interval=8, num_clips=1, total_frames_offset=-1), dict(type='DecordDecode_Custom', extra_modalities=['tempgrad']), dict(type='Resize', scale=(-1, 256), lazy=True), dict(type='RandomResizedCrop',", "conv1_kernel=(3, 7, 7), conv1_stride_t=1, pool1_stride_t=1, inflate=(1, 1, 1, 1), spatial_strides=(1,", "dict( videos_per_gpu=8, # NOTE: Need to reduce batch size. 16", "spatial_type='avg', dropout_ratio=0.5, init_std=0.01), cls_head_temp=None, temp_backbone='same', temp_sup_head='same', train_cfg=dict( warmup_epoch=10, fixmatch_threshold=0.3, temp_align_indices=(0,", "num_clips=10, test_mode=True), dict(type='DecordDecode'), dict(type='Resize', scale=(-1, 256)), dict(type='ThreeCrop', crop_size=256), dict(type='Flip', flip_ratio=0),", "temp_sup_head='same', train_cfg=dict( warmup_epoch=10, fixmatch_threshold=0.3, temp_align_indices=(0, 1, 2, 3), align_loss_func='Cosine', pseudo_label_metric='avg',", "zero_init_residual=False), cls_head=dict( type='I3DHead', num_classes=400, in_channels=512, spatial_type='avg', dropout_ratio=0.5, init_std=0.01), cls_head_temp=None, temp_backbone='same',", "# Default: 4 train_dataloader=dict(drop_last=True, pin_memory=True), train_labeled=dict( type=dataset_type_labeled, ann_file=ann_file_train_labeled, data_prefix=data_root, pipeline=train_pipeline,", "= dict(interval=5, max_keep_ckpts=3) evaluation = dict( interval=5, metrics=['top_k_accuracy', 'mean_class_accuracy'], topk=(1,", "= 1 ann_file_train_labeled = f'data/kinetics400/videossl_splits/kinetics400_train_{labeled_percentage}_percent_labeled_videos.txt' ann_file_train_unlabeled = 'data/kinetics400/kinetics400_train_list_videos.txt' ann_file_val =", "test_mode=True), test=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=test_pipeline, test_mode=True), precise_bn=dict( type=dataset_type, ann_file=ann_file_train_unlabeled,", "to reduce batch size. 16 -> 5 workers_per_gpu=4, # Default:", "2, 3), align_loss_func='Cosine', pseudo_label_metric='avg', crossclip_contrast_loss=[], crossclip_contrast_range=[], ), test_cfg=dict(average_clips='score')) # dataset", "= [ dict(type='DecordInit'), dict( type='SampleFrames', clip_len=8, frame_interval=8, num_clips=1, test_mode=True), dict(type='DecordDecode'),", "= dict( interval=5, metrics=['top_k_accuracy', 'mean_class_accuracy'], topk=(1, 5)) # Default: 5", "lazy=True), dict(type='CenterCrop', crop_size=224, lazy=True), dict(type='Flip', flip_ratio=0, lazy=True), dict(type='Fuse'), dict(type='Normalize', **img_norm_cfg),", "type='ResNet3d', depth=18, pretrained=None, pretrained2d=False, norm_eval=False, conv_cfg=dict(type='Conv3d'), norm_cfg=dict(type='SyncBN', requires_grad=True, eps=1e-3), act_cfg=dict(type='ReLU'),", "dict(type='FormatShape_Diff', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label', 'imgs_diff'], meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label',", "'data/kinetics400/kinetics400_train_list_videos.txt' ann_file_val = 'data/kinetics400/kinetics400_val_list_videos.txt' ann_file_test = 'data/kinetics400/kinetics400_val_list_videos.txt' img_norm_cfg = dict(", "# learning policy lr_config = dict(policy='CosineAnnealing', min_lr=0, warmup='linear', warmup_ratio=0.1, warmup_by_epoch=True,", "# dataset_type_appearance = 'RawframeDataset_withAPP' data_root = 'data/kinetics400/videos_train' data_root_val = 'data/kinetics400/videos_val'", "shared by both weak and strong train_pipeline_weak = [ dict(type='DecordInit'),", "batch size. 16 -> 5 workers_per_gpu=4, # Default: 4 train_dataloader=dict(drop_last=True,", "this number for different splits. Default: 180 checkpoint_config = dict(interval=5,", "warmup_ratio=0.1, warmup_by_epoch=True, warmup_iters=10) total_epochs = 45 # Might need to", "2, 2, 2), temporal_strides=(1, 2, 2, 2), zero_init_residual=False), cls_head=dict( type='I3DHead',", "by both weak and strong train_pipeline_format = [ dict(type='Normalize', **img_norm_cfg),", "= dict(num_iters=200, interval=5, bn_range=['backbone', 'cls_head']) dist_params = dict(backend='nccl') log_level =", "input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label', 'imgs_diff'], meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label', 'imgs_diff'])", "256)), dict(type='ThreeCrop', crop_size=256), dict(type='Flip', flip_ratio=0), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect',", "lazy=True), dict(type='Flip', flip_ratio=0, lazy=True), dict(type='Fuse'), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect',", "type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=test_pipeline, test_mode=True), precise_bn=dict( type=dataset_type, ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline=val_pipeline),", "lazy=True), dict(type='Fuse_WithDiff'), ] # Only used for strong augmentation train_pipeline_strong", "labeled_percentage = 1 ann_file_train_labeled = f'data/kinetics400/videossl_splits/kinetics400_train_{labeled_percentage}_percent_labeled_videos.txt' ann_file_train_unlabeled = 'data/kinetics400/kinetics400_train_list_videos.txt' ann_file_val", "Might need to increase this number for different splits. Default:", "for different splits. Default: 180 checkpoint_config = dict(interval=5, max_keep_ckpts=3) evaluation", "train_pipeline_format = [ dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff', **img_norm_cfg, raw_to_diff=False, redist_to_rgb=False), dict(type='FormatShape',", "crop_size=224, lazy=True), dict(type='Flip', flip_ratio=0, lazy=True), dict(type='Fuse'), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'),", "test_cfg=dict(average_clips='score')) # dataset settings dataset_type = 'VideoDataset' dataset_type_labeled = 'VideoDataset_Contrastive'", "scale=(224, 224), keep_ratio=False, lazy=True), dict(type='Flip', flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'), ] #", "dict(type='Flip', flip_ratio=0, lazy=True), dict(type='Fuse'), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs',", "2, 2), temporal_strides=(1, 2, 2, 2), zero_init_residual=False), cls_head=dict( type='I3DHead', num_classes=400,", "1 ann_file_train_labeled = f'data/kinetics400/videossl_splits/kinetics400_train_{labeled_percentage}_percent_labeled_videos.txt' ann_file_train_unlabeled = 'data/kinetics400/kinetics400_train_list_videos.txt' ann_file_val = 'data/kinetics400/kinetics400_val_list_videos.txt'", "= dict( videos_per_gpu=8, # NOTE: Need to reduce batch size.", "contrast_clip_num=1 ), val=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=val_pipeline, test_mode=True), test=dict( type=dataset_type,", "extra_modalities=['tempgrad']), dict(type='Resize', scale=(-1, 256), lazy=True), dict(type='RandomResizedCrop', lazy=True), dict(type='Resize', scale=(224, 224),", "is used for 8 gpus optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2)) #", "dict(type='DecordDecode'), dict(type='Resize', scale=(-1, 256)), dict(type='ThreeCrop', crop_size=256), dict(type='Flip', flip_ratio=0), dict(type='Normalize', **img_norm_cfg),", "dataset_type_appearance = 'RawframeDataset_withAPP' data_root = 'data/kinetics400/videos_train' data_root_val = 'data/kinetics400/videos_val' labeled_percentage", "dict( type='SGD', lr=0.2, momentum=0.9, weight_decay=0.0001) # this lr 0.2 is", "pipeline=test_pipeline, test_mode=True), precise_bn=dict( type=dataset_type, ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline=val_pipeline), videos_per_gpu_precise_bn=5 ) #", "frame_interval=8, num_clips=10, test_mode=True), dict(type='DecordDecode'), dict(type='Resize', scale=(-1, 256)), dict(type='ThreeCrop', crop_size=256), dict(type='Flip',", "keep_ratio=False, lazy=True), dict(type='Flip', flip_ratio=0.5, lazy=True), dict(type='Fuse_WithDiff'), dict(type='Normalize', **img_norm_cfg), dict(type='Normalize_Diff', **img_norm_cfg,", "train_unlabeled=dict( type=dataset_type_unlabeled, ann_file=ann_file_train_unlabeled, data_prefix=data_root, pipeline_weak=train_pipeline_weak, pipeline_strong=train_pipeline_strong, pipeline_format=train_pipeline_format, contrast_clip_num=1 ), val=dict(", "]) precise_bn = dict(num_iters=200, interval=5, bn_range=['backbone', 'cls_head']) dist_params = dict(backend='nccl')", "pipeline=val_pipeline, test_mode=True), test=dict( type=dataset_type, ann_file=ann_file_val, data_prefix=data_root_val, pipeline=test_pipeline, test_mode=True), precise_bn=dict( type=dataset_type,", "data_prefix=data_root, pipeline=val_pipeline), videos_per_gpu_precise_bn=5 ) # optimizer optimizer = dict( type='SGD',", "Formating the input tensors, shared by both weak and strong", "optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2)) # learning policy lr_config = dict(policy='CosineAnnealing',", "augmentation train_pipeline_strong = [ dict(type='Imgaug', transforms='default'), dict(type='Imgaug_Custom', transforms='default', modality='imgs_diff') ]", "2), temporal_strides=(1, 2, 2, 2), zero_init_residual=False), cls_head=dict( type='I3DHead', num_classes=400, in_channels=512,", "'data/kinetics400/kinetics400_val_list_videos.txt' ann_file_test = 'data/kinetics400/kinetics400_val_list_videos.txt' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53]," ]
[ "= [0,0,0,160,240] # 2nd byte common to both channels voltages", "voltages for display while not (channel == 1 or channel", "%.2fV\" % voltages[i] raw_input(\"When ready hit enter.\\n\") r = spi.xfer2([16,0])", "== \"m\": print \"jumper connecting GPIO 7 to CSB\" print", "py-spidev as in the README.txt file # spi must also", "until answer 0 or 1 given if channel == 1:", "# Check valid user input channel = raw_input(\"Try again -", "DAC is on SPI channel 1 (CE1 - aka GPIO7)", "analogue test:\" if board_type == \"m\": print \"jumper connecting GPIO", "test:\" if board_type == \"m\": print \"jumper connecting GPIO 7", "to prevent spi failures import subprocess unload_spi = subprocess.Popen('sudo rmmod", "12 = shutdown, bits 11-4 data, bits 3-0 ignored #", "spi = spidev.SpiDev() spi.open(0,1) # The Gertboard DAC is on", "proper answer given, carry on num_list = [176,180,184,186,191] # set", "to the Gertboard dtoa test by <NAME> & <NAME> #", "selection common = [0,0,0,160,240] # 2nd byte common to both", "it yourself. # This will not work unless you have", "channel = raw_input(\"Which channel do you want to test? Type", "should read about %.2fV\" % voltages[i] raw_input(\"When ready hit enter.\\n\")", "word to DAC # bit 15 = channel, bit 14", "so we need two arguments, which together make 16 bits.", "# channel is set by user input channel = int(which_channel())", "test? Type 0 or 1.\\n\") # User inputs channel number", "2nd byte common to both channels voltages = [0.0,0.5,1.02,1.36,2.04] #", "10010000 00000000 [144,0] # The DAC is controlled by writing", "is a byte (8 bits), so we need two arguments,", "to MOSI\" print \"jumper connecting GP9 to MISO\" print \"jumper", "start_spi = subprocess.Popen('sudo modprobe spi_bcm2708', shell=True, stdout=subprocess.PIPE) sleep(3) def which_channel():", "meter should read about %.2fV\" % voltages[i] raw_input(\"When ready hit", "16 bit word to DAC # bit 15 = channel,", "on your system import spidev import sys from time import", "rmmod spi_bcm2708', shell=True, stdout=subprocess.PIPE) start_spi = subprocess.Popen('sudo modprobe spi_bcm2708', shell=True,", "to test? Type 0 or 1.\\n\") # User inputs channel", "connections (set your meter to read V DC):\" print \"", "# voltages for display while not (channel == 1 or", "yourself. # This will not work unless you have installed", "board_type == \"m\": print \"jumper connecting GPIO 7 to CSB\"", "by <NAME> & <NAME> # Use at your own risk", "system import spidev import sys from time import sleep board_type", "in the README.txt file # spi must also be enabled", "common to both channels voltages = [0.0,0.5,1.02,1.36,2.04] # voltages for", "are the connections for the digital to analogue test:\" if", "drivers to prevent spi failures import subprocess unload_spi = subprocess.Popen('sudo", "== 0): # channel is set by user input channel", "off channel A = 00010000 00000000 [16,0] r = spi.xfer2([144,0])", "for display while not (channel == 1 or channel ==", "it converts it to 8 bit binary # each argument", "do you want to test? Type 0 or 1.\\n\") #", "please!\\n\") # Make them do it again if wrong return", "both channels voltages = [0.0,0.5,1.02,1.36,2.04] # voltages for display while", "if board_type == \"m\": print \"jumper connecting GPIO 7 to", "spidev sends to the DAC. If you need to delve", "not channel.isdigit(): # Check valid user input channel = raw_input(\"Try", "B = 10010000 00000000 [144,0] # The DAC is controlled", "probe to DA%d on J29\" % channel raw_input(\"When ready hit", "given, carry on num_list = [176,180,184,186,191] # set correct channel-dependent", "check it yourself. # This will not work unless you", "sleep board_type = sys.argv[-1] # reload spi drivers to prevent", "spi failures import subprocess unload_spi = subprocess.Popen('sudo rmmod spi_bcm2708', shell=True,", "decimal number and it converts it to 8 bit binary", "= int(which_channel()) # continue asking until answer 0 or 1", "# The DAC is controlled by writing 2 bytes (16", "to CSnB\" print \"Multimeter connections (set your meter to read", "#write the two bytes to the DAC print \"Your meter", "00000000 [16,0] r = spi.xfer2([144,0]) # switch off channel B", "You feed spidev a decimal number and it converts it", "two bytes to the DAC print \"Your meter should read", "channel spi = spidev.SpiDev() spi.open(0,1) # The Gertboard DAC is", "for i in range(5): r = spi.xfer2([num_list[i],common[i]]) #write the two", "If you need to delve further, have a look at", "SPI channel 1 (CE1 - aka GPIO7) channel = 3", "D/A header\" % channel else: print \"jumper connecting GP11 to", "writing 2 bytes (16 bits) to it. # So we", "spidev import sys from time import sleep board_type = sys.argv[-1]", "[16,0] r = spi.xfer2([144,0]) # switch off channel B =", "sure the code is harmless, but check it yourself. #", "def which_channel(): channel = raw_input(\"Which channel do you want to", "\" connect red probe to DA%d on D/A header\" %", "or 1.\\n\") # User inputs channel number while not channel.isdigit():", "0): # channel is set by user input channel =", "sleep(3) def which_channel(): channel = raw_input(\"Which channel do you want", "have installed py-spidev as in the README.txt file # spi", "not (channel == 1 or channel == 0): # channel", "byte 1 else: num_list = [48,52,56,58,63] print \"These are the", "# set correct channel-dependent list for byte 1 else: num_list", "to analogue test:\" if board_type == \"m\": print \"jumper connecting", "channel A = 00010000 00000000 [16,0] r = spi.xfer2([144,0]) #", "\"jumper connecting GP9 to MISO\" print \"jumper connecting GP7 to", "spi drivers to prevent spi failures import subprocess unload_spi =", "= spi.xfer2([144,0]) # switch off channel B = 10010000 00000000", "2.7 version by <NAME> of http://RasPi.TV # functionally equivalent to", "bits), so we need two arguments, which together make 16", "if wrong return channel spi = spidev.SpiDev() spi.open(0,1) # The", "feed spidev a decimal number and it converts it to", "sys from time import sleep board_type = sys.argv[-1] # reload", "asking until answer 0 or 1 given if channel ==", "answer 0 or 1 given if channel == 1: #", "spi_bcm2708', shell=True, stdout=subprocess.PIPE) start_spi = subprocess.Popen('sudo modprobe spi_bcm2708', shell=True, stdout=subprocess.PIPE)", "you want to test? Type 0 or 1.\\n\") # User", "J29\" % channel raw_input(\"When ready hit enter.\\n\") for i in", "own risk - I'm pretty sure the code is harmless,", "(16 bits) to it. # So we need to write", "if channel == 1: # once proper answer given, carry", "\" connect black probe to GND\" print \" connect red", "CSnB\" print \"Multimeter connections (set your meter to read V", "print \"jumper connecting GP9 to MISO\" print \"jumper connecting GP7", "channel = 3 # set initial value to force user", "make 16 bits. # that's what spidev sends to the", "probe to DA%d on D/A header\" % channel else: print", "11-4 data, bits 3-0 ignored # You feed spidev a", "(8 bits), so we need two arguments, which together make", "must also be enabled on your system import spidev import", "force user selection common = [0,0,0,160,240] # 2nd byte common", "1 else: num_list = [48,52,56,58,63] print \"These are the connections", "on J29\" % channel raw_input(\"When ready hit enter.\\n\") for i", "README.txt file # spi must also be enabled on your", "bytes to the DAC print \"Your meter should read about", "functionally equivalent to the Gertboard dtoa test by <NAME> &", "stdout=subprocess.PIPE) start_spi = subprocess.Popen('sudo modprobe spi_bcm2708', shell=True, stdout=subprocess.PIPE) sleep(3) def", "write a 16 bit word to DAC # bit 15", "\"These are the connections for the digital to analogue test:\"", "= sys.argv[-1] # reload spi drivers to prevent spi failures", "\"Your meter should read about %.2fV\" % voltages[i] raw_input(\"When ready", "data, bits 3-0 ignored # You feed spidev a decimal", "spidev a decimal number and it converts it to 8", "hit enter.\\n\") for i in range(5): r = spi.xfer2([num_list[i],common[i]]) #write", "and it converts it to 8 bit binary # each", "ready hit enter.\\n\") r = spi.xfer2([16,0]) # switch off channel", "num_list = [48,52,56,58,63] print \"These are the connections for the", "raw_input(\"When ready hit enter.\\n\") r = spi.xfer2([16,0]) # switch off", "to MISO\" print \"jumper connecting GP7 to CSnB\" print \"Multimeter", "This will not work unless you have installed py-spidev as", "or channel == 0): # channel is set by user", "channel else: print \"jumper connecting GP11 to SCLK\" print \"jumper", "inputs channel number while not channel.isdigit(): # Check valid user", "bits. # that's what spidev sends to the DAC. If", "GPIO 7 to CSB\" print \"Multimeter connections (set your meter", "1 (CE1 - aka GPIO7) channel = 3 # set", "in range(5): r = spi.xfer2([num_list[i],common[i]]) #write the two bytes to", "subprocess.Popen('sudo modprobe spi_bcm2708', shell=True, stdout=subprocess.PIPE) sleep(3) def which_channel(): channel =", "Gertboard DAC is on SPI channel 1 (CE1 - aka", "# This will not work unless you have installed py-spidev", "to the DAC. If you need to delve further, have", "to both channels voltages = [0.0,0.5,1.02,1.36,2.04] # voltages for display", "GP7 to CSnB\" print \"Multimeter connections (set your meter to", "unless you have installed py-spidev as in the README.txt file", "= [176,180,184,186,191] # set correct channel-dependent list for byte 1", "bit 14 = ignored, bit 13 =gain, bit 12 =", "print \" connect black probe to GND\" print \" connect", "# switch off channel A = 00010000 00000000 [16,0] r", "= spidev.SpiDev() spi.open(0,1) # The Gertboard DAC is on SPI", "connecting GP7 to CSnB\" print \"Multimeter connections (set your meter", "= spi.xfer2([num_list[i],common[i]]) #write the two bytes to the DAC print", "i in range(5): r = spi.xfer2([num_list[i],common[i]]) #write the two bytes", "a decimal number and it converts it to 8 bit", "00010000 00000000 [16,0] r = spi.xfer2([144,0]) # switch off channel", "we need two arguments, which together make 16 bits. #", "== 1 or channel == 0): # channel is set", "stdout=subprocess.PIPE) sleep(3) def which_channel(): channel = raw_input(\"Which channel do you", "which together make 16 bits. # that's what spidev sends", "# The Gertboard DAC is on SPI channel 1 (CE1", "% voltages[i] raw_input(\"When ready hit enter.\\n\") r = spi.xfer2([16,0]) #", "# Use at your own risk - I'm pretty sure", "input channel = int(which_channel()) # continue asking until answer 0", "from time import sleep board_type = sys.argv[-1] # reload spi", "# spi must also be enabled on your system import", "0 or 1 please!\\n\") # Make them do it again", "MISO\" print \"jumper connecting GP7 to CSnB\" print \"Multimeter connections", "number while not channel.isdigit(): # Check valid user input channel", "need two arguments, which together make 16 bits. # that's", "failures import subprocess unload_spi = subprocess.Popen('sudo rmmod spi_bcm2708', shell=True, stdout=subprocess.PIPE)", "to DA%d on D/A header\" % channel else: print \"jumper", "channel-dependent list for byte 1 else: num_list = [48,52,56,58,63] print", "spidev.SpiDev() spi.open(0,1) # The Gertboard DAC is on SPI channel", "user input channel = raw_input(\"Try again - just numbers 0", "# functionally equivalent to the Gertboard dtoa test by <NAME>", "GP11 to SCLK\" print \"jumper connecting GP10 to MOSI\" print", "prevent spi failures import subprocess unload_spi = subprocess.Popen('sudo rmmod spi_bcm2708',", "what spidev sends to the DAC. If you need to", "sends to the DAC. If you need to delve further,", "display while not (channel == 1 or channel == 0):", "answer given, carry on num_list = [176,180,184,186,191] # set correct", "by <NAME> of http://RasPi.TV # functionally equivalent to the Gertboard", "numbers 0 or 1 please!\\n\") # Make them do it", "channel is set by user input channel = int(which_channel()) #", "= 3 # set initial value to force user selection", "on num_list = [176,180,184,186,191] # set correct channel-dependent list for", "#!/usr/bin/python2.7 # Python 2.7 version by <NAME> of http://RasPi.TV #", "read about %.2fV\" % voltages[i] raw_input(\"When ready hit enter.\\n\") r", "DAC. If you need to delve further, have a look", "to CSB\" print \"Multimeter connections (set your meter to read", "which_channel(): channel = raw_input(\"Which channel do you want to test?", "again if wrong return channel spi = spidev.SpiDev() spi.open(0,1) #", "given if channel == 1: # once proper answer given,", "will not work unless you have installed py-spidev as in", "enter.\\n\") for i in range(5): r = spi.xfer2([num_list[i],common[i]]) #write the", "# continue asking until answer 0 or 1 given if", "to it. # So we need to write a 16", "your own risk - I'm pretty sure the code is", "set correct channel-dependent list for byte 1 else: num_list =", "DAC # bit 15 = channel, bit 14 = ignored,", "by writing 2 bytes (16 bits) to it. # So", "to DAC # bit 15 = channel, bit 14 =", "= 00010000 00000000 [16,0] r = spi.xfer2([144,0]) # switch off", "spi.xfer2([144,0]) # switch off channel B = 10010000 00000000 [144,0]", "code is harmless, but check it yourself. # This will", "to DA%d on J29\" % channel raw_input(\"When ready hit enter.\\n\")", "return channel spi = spidev.SpiDev() spi.open(0,1) # The Gertboard DAC", "MOSI\" print \"jumper connecting GP9 to MISO\" print \"jumper connecting", "Check valid user input channel = raw_input(\"Try again - just", "= 10010000 00000000 [144,0] # The DAC is controlled by", "\"jumper connecting GP10 to MOSI\" print \"jumper connecting GP9 to", "connect red probe to DA%d on J29\" % channel raw_input(\"When", "it to 8 bit binary # each argument is a", "on D/A header\" % channel else: print \"jumper connecting GP11", "(set your meter to read V DC):\" print \" connect", "red probe to DA%d on D/A header\" % channel else:", "enter.\\n\") r = spi.xfer2([16,0]) # switch off channel A =", "sys.argv[-1] # reload spi drivers to prevent spi failures import", "version by <NAME> of http://RasPi.TV # functionally equivalent to the", "1: # once proper answer given, carry on num_list =", "# once proper answer given, carry on num_list = [176,180,184,186,191]", "DAC is controlled by writing 2 bytes (16 bits) to", "your meter to read V DC):\" print \" connect black", "two arguments, which together make 16 bits. # that's what", "<gh_stars>0 #!/usr/bin/python2.7 # Python 2.7 version by <NAME> of http://RasPi.TV", "DAC print \"Your meter should read about %.2fV\" % voltages[i]", "8 bit binary # each argument is a byte (8", "byte (8 bits), so we need two arguments, which together", "again - just numbers 0 or 1 please!\\n\") # Make", "the Gertboard dtoa test by <NAME> & <NAME> # Use", "connecting GP11 to SCLK\" print \"jumper connecting GP10 to MOSI\"", "channels voltages = [0.0,0.5,1.02,1.36,2.04] # voltages for display while not", "time import sleep board_type = sys.argv[-1] # reload spi drivers", "(channel == 1 or channel == 0): # channel is", "do it again if wrong return channel spi = spidev.SpiDev()", "valid user input channel = raw_input(\"Try again - just numbers", "[144,0] # The DAC is controlled by writing 2 bytes", "aka GPIO7) channel = 3 # set initial value to", "reload spi drivers to prevent spi failures import subprocess unload_spi", "print \" connect red probe to DA%d on D/A header\"", "voltages = [0.0,0.5,1.02,1.36,2.04] # voltages for display while not (channel", "int(which_channel()) # continue asking until answer 0 or 1 given", "# switch off channel B = 10010000 00000000 [144,0] #", "to SCLK\" print \"jumper connecting GP10 to MOSI\" print \"jumper", "connect red probe to DA%d on D/A header\" % channel", "# Python 2.7 version by <NAME> of http://RasPi.TV # functionally", "r = spi.xfer2([16,0]) # switch off channel A = 00010000", "Type 0 or 1.\\n\") # User inputs channel number while", "red probe to DA%d on J29\" % channel raw_input(\"When ready", "3-0 ignored # You feed spidev a decimal number and", "meter to read V DC):\" print \" connect black probe", "as in the README.txt file # spi must also be", "channel = int(which_channel()) # continue asking until answer 0 or", "The DAC is controlled by writing 2 bytes (16 bits)", "V DC):\" print \" connect black probe to GND\" print", "your system import spidev import sys from time import sleep", "spi.open(0,1) # The Gertboard DAC is on SPI channel 1", "pretty sure the code is harmless, but check it yourself.", "or 1 please!\\n\") # Make them do it again if", "% channel raw_input(\"When ready hit enter.\\n\") for i in range(5):", "hit enter.\\n\") r = spi.xfer2([16,0]) # switch off channel A", "import subprocess unload_spi = subprocess.Popen('sudo rmmod spi_bcm2708', shell=True, stdout=subprocess.PIPE) start_spi", "# set initial value to force user selection common =", "for byte 1 else: num_list = [48,52,56,58,63] print \"These are", "# bit 15 = channel, bit 14 = ignored, bit", "the code is harmless, but check it yourself. # This", "work unless you have installed py-spidev as in the README.txt", "to write a 16 bit word to DAC # bit", "binary # each argument is a byte (8 bits), so", "user selection common = [0,0,0,160,240] # 2nd byte common to", "by user input channel = int(which_channel()) # continue asking until", "channel B = 10010000 00000000 [144,0] # The DAC is", "read V DC):\" print \" connect black probe to GND\"", "<NAME> # Use at your own risk - I'm pretty", "them do it again if wrong return channel spi =", "User inputs channel number while not channel.isdigit(): # Check valid", "it. # So we need to write a 16 bit", "you need to delve further, have a look at the", "<NAME> & <NAME> # Use at your own risk -", "1 please!\\n\") # Make them do it again if wrong", "is on SPI channel 1 (CE1 - aka GPIO7) channel", "GP9 to MISO\" print \"jumper connecting GP7 to CSnB\" print", "http://RasPi.TV # functionally equivalent to the Gertboard dtoa test by", "argument is a byte (8 bits), so we need two", "the README.txt file # spi must also be enabled on", "common = [0,0,0,160,240] # 2nd byte common to both channels", "channel == 1: # once proper answer given, carry on", "wrong return channel spi = spidev.SpiDev() spi.open(0,1) # The Gertboard", "modprobe spi_bcm2708', shell=True, stdout=subprocess.PIPE) sleep(3) def which_channel(): channel = raw_input(\"Which", "installed py-spidev as in the README.txt file # spi must", "black probe to GND\" print \" connect red probe to", "# that's what spidev sends to the DAC. If you", "= [0.0,0.5,1.02,1.36,2.04] # voltages for display while not (channel ==", "risk - I'm pretty sure the code is harmless, but", "correct channel-dependent list for byte 1 else: num_list = [48,52,56,58,63]", "is harmless, but check it yourself. # This will not", "\"m\": print \"jumper connecting GPIO 7 to CSB\" print \"Multimeter", "converts it to 8 bit binary # each argument is", "import sys from time import sleep board_type = sys.argv[-1] #", "spi_bcm2708', shell=True, stdout=subprocess.PIPE) sleep(3) def which_channel(): channel = raw_input(\"Which channel", "[176,180,184,186,191] # set correct channel-dependent list for byte 1 else:", "to force user selection common = [0,0,0,160,240] # 2nd byte", "print \"jumper connecting GP11 to SCLK\" print \"jumper connecting GP10", "need to write a 16 bit word to DAC #", "else: print \"jumper connecting GP11 to SCLK\" print \"jumper connecting", "0 or 1.\\n\") # User inputs channel number while not", "r = spi.xfer2([num_list[i],common[i]]) #write the two bytes to the DAC", "- aka GPIO7) channel = 3 # set initial value", "DA%d on J29\" % channel raw_input(\"When ready hit enter.\\n\") for", "the digital to analogue test:\" if board_type == \"m\": print", "not work unless you have installed py-spidev as in the", "channel, bit 14 = ignored, bit 13 =gain, bit 12", "bit 12 = shutdown, bits 11-4 data, bits 3-0 ignored", "1 or channel == 0): # channel is set by", "channel == 0): # channel is set by user input", "ignored # You feed spidev a decimal number and it", "print \"Your meter should read about %.2fV\" % voltages[i] raw_input(\"When", "at your own risk - I'm pretty sure the code", "import spidev import sys from time import sleep board_type =", "while not (channel == 1 or channel == 0): #", "7 to CSB\" print \"Multimeter connections (set your meter to", "together make 16 bits. # that's what spidev sends to", "raw_input(\"Which channel do you want to test? Type 0 or", "Python 2.7 version by <NAME> of http://RasPi.TV # functionally equivalent", "the DAC print \"Your meter should read about %.2fV\" %", "= channel, bit 14 = ignored, bit 13 =gain, bit", "connections for the digital to analogue test:\" if board_type ==", "So we need to write a 16 bit word to", "Use at your own risk - I'm pretty sure the", "GND\" print \" connect red probe to DA%d on D/A", "is set by user input channel = int(which_channel()) # continue", "\" connect red probe to DA%d on J29\" % channel", "[0.0,0.5,1.02,1.36,2.04] # voltages for display while not (channel == 1", "about %.2fV\" % voltages[i] raw_input(\"When ready hit enter.\\n\") r =", "bit 13 =gain, bit 12 = shutdown, bits 11-4 data,", "print \"jumper connecting GP7 to CSnB\" print \"Multimeter connections (set", "I'm pretty sure the code is harmless, but check it", "# Make them do it again if wrong return channel", "you have installed py-spidev as in the README.txt file #", "GND\" print \" connect red probe to DA%d on J29\"", "bits 11-4 data, bits 3-0 ignored # You feed spidev", "of http://RasPi.TV # functionally equivalent to the Gertboard dtoa test", "switch off channel B = 10010000 00000000 [144,0] # The", "[0,0,0,160,240] # 2nd byte common to both channels voltages =", "A = 00010000 00000000 [16,0] r = spi.xfer2([144,0]) # switch", "channel 1 (CE1 - aka GPIO7) channel = 3 #", "to delve further, have a look at the datasheet. :)", "we need to write a 16 bit word to DAC", "just numbers 0 or 1 please!\\n\") # Make them do", "ready hit enter.\\n\") for i in range(5): r = spi.xfer2([num_list[i],common[i]])", "need to delve further, have a look at the datasheet.", "r = spi.xfer2([144,0]) # switch off channel B = 10010000", "list for byte 1 else: num_list = [48,52,56,58,63] print \"These", "ignored, bit 13 =gain, bit 12 = shutdown, bits 11-4", "bit 15 = channel, bit 14 = ignored, bit 13", "test by <NAME> & <NAME> # Use at your own", "continue asking until answer 0 or 1 given if channel", "bit binary # each argument is a byte (8 bits),", "connecting GP9 to MISO\" print \"jumper connecting GP7 to CSnB\"", "initial value to force user selection common = [0,0,0,160,240] #", "= raw_input(\"Try again - just numbers 0 or 1 please!\\n\")", "channel raw_input(\"When ready hit enter.\\n\") for i in range(5): r", "shell=True, stdout=subprocess.PIPE) start_spi = subprocess.Popen('sudo modprobe spi_bcm2708', shell=True, stdout=subprocess.PIPE) sleep(3)", "0 or 1 given if channel == 1: # once", "header\" % channel else: print \"jumper connecting GP11 to SCLK\"", "set by user input channel = int(which_channel()) # continue asking", "1 given if channel == 1: # once proper answer", "controlled by writing 2 bytes (16 bits) to it. #", "shutdown, bits 11-4 data, bits 3-0 ignored # You feed", "- just numbers 0 or 1 please!\\n\") # Make them", "[48,52,56,58,63] print \"These are the connections for the digital to", "bits) to it. # So we need to write a", "& <NAME> # Use at your own risk - I'm", "# You feed spidev a decimal number and it converts", "# reload spi drivers to prevent spi failures import subprocess", "spi.xfer2([num_list[i],common[i]]) #write the two bytes to the DAC print \"Your", "DC):\" print \" connect black probe to GND\" print \"", "board_type = sys.argv[-1] # reload spi drivers to prevent spi", "channel do you want to test? Type 0 or 1.\\n\")", "% channel else: print \"jumper connecting GP11 to SCLK\" print", "or 1 given if channel == 1: # once proper", "is controlled by writing 2 bytes (16 bits) to it.", "00000000 [144,0] # The DAC is controlled by writing 2", "# each argument is a byte (8 bits), so we", "Gertboard dtoa test by <NAME> & <NAME> # Use at", "probe to GND\" print \" connect red probe to DA%d", "for the digital to analogue test:\" if board_type == \"m\":", "\"jumper connecting GP7 to CSnB\" print \"Multimeter connections (set your", "to the DAC print \"Your meter should read about %.2fV\"", "to read V DC):\" print \" connect black probe to", "value to force user selection common = [0,0,0,160,240] # 2nd", "dtoa test by <NAME> & <NAME> # Use at your", "else: num_list = [48,52,56,58,63] print \"These are the connections for", "subprocess.Popen('sudo rmmod spi_bcm2708', shell=True, stdout=subprocess.PIPE) start_spi = subprocess.Popen('sudo modprobe spi_bcm2708',", "print \" connect red probe to DA%d on J29\" %", "15 = channel, bit 14 = ignored, bit 13 =gain,", "num_list = [176,180,184,186,191] # set correct channel-dependent list for byte", "- I'm pretty sure the code is harmless, but check", "shell=True, stdout=subprocess.PIPE) sleep(3) def which_channel(): channel = raw_input(\"Which channel do", "the two bytes to the DAC print \"Your meter should", "harmless, but check it yourself. # This will not work", "digital to analogue test:\" if board_type == \"m\": print \"jumper", "channel.isdigit(): # Check valid user input channel = raw_input(\"Try again", "import sleep board_type = sys.argv[-1] # reload spi drivers to", "The Gertboard DAC is on SPI channel 1 (CE1 -", "user input channel = int(which_channel()) # continue asking until answer", "16 bits. # that's what spidev sends to the DAC.", "on SPI channel 1 (CE1 - aka GPIO7) channel =", "off channel B = 10010000 00000000 [144,0] # The DAC", "bytes (16 bits) to it. # So we need to", "2 bytes (16 bits) to it. # So we need", "file # spi must also be enabled on your system", "equivalent to the Gertboard dtoa test by <NAME> & <NAME>", "1.\\n\") # User inputs channel number while not channel.isdigit(): #", "it again if wrong return channel spi = spidev.SpiDev() spi.open(0,1)", "= spi.xfer2([16,0]) # switch off channel A = 00010000 00000000", "# 2nd byte common to both channels voltages = [0.0,0.5,1.02,1.36,2.04]", "channel = raw_input(\"Try again - just numbers 0 or 1", "a 16 bit word to DAC # bit 15 =", "bits 3-0 ignored # You feed spidev a decimal number", "to GND\" print \" connect red probe to DA%d on", "the connections for the digital to analogue test:\" if board_type", "arguments, which together make 16 bits. # that's what spidev", "== 1: # once proper answer given, carry on num_list", "to 8 bit binary # each argument is a byte", "enabled on your system import spidev import sys from time", "subprocess unload_spi = subprocess.Popen('sudo rmmod spi_bcm2708', shell=True, stdout=subprocess.PIPE) start_spi =", "connecting GPIO 7 to CSB\" print \"Multimeter connections (set your", "also be enabled on your system import spidev import sys", "byte common to both channels voltages = [0.0,0.5,1.02,1.36,2.04] # voltages", "<NAME> of http://RasPi.TV # functionally equivalent to the Gertboard dtoa", "spi must also be enabled on your system import spidev", "the DAC. If you need to delve further, have a", "= shutdown, bits 11-4 data, bits 3-0 ignored # You", "CSB\" print \"Multimeter connections (set your meter to read V", "GP10 to MOSI\" print \"jumper connecting GP9 to MISO\" print", "print \"These are the connections for the digital to analogue", "raw_input(\"When ready hit enter.\\n\") for i in range(5): r =", "a byte (8 bits), so we need two arguments, which", "set initial value to force user selection common = [0,0,0,160,240]", "number and it converts it to 8 bit binary #", "raw_input(\"Try again - just numbers 0 or 1 please!\\n\") #", "=gain, bit 12 = shutdown, bits 11-4 data, bits 3-0", "bit word to DAC # bit 15 = channel, bit", "want to test? Type 0 or 1.\\n\") # User inputs", "voltages[i] raw_input(\"When ready hit enter.\\n\") r = spi.xfer2([16,0]) # switch", "= subprocess.Popen('sudo modprobe spi_bcm2708', shell=True, stdout=subprocess.PIPE) sleep(3) def which_channel(): channel", "= ignored, bit 13 =gain, bit 12 = shutdown, bits", "channel number while not channel.isdigit(): # Check valid user input", "range(5): r = spi.xfer2([num_list[i],common[i]]) #write the two bytes to the", "switch off channel A = 00010000 00000000 [16,0] r =", "spi.xfer2([16,0]) # switch off channel A = 00010000 00000000 [16,0]", "that's what spidev sends to the DAC. If you need", "connect black probe to GND\" print \" connect red probe", "print \"Multimeter connections (set your meter to read V DC):\"", "= [48,52,56,58,63] print \"These are the connections for the digital", "while not channel.isdigit(): # Check valid user input channel =", "carry on num_list = [176,180,184,186,191] # set correct channel-dependent list", "once proper answer given, carry on num_list = [176,180,184,186,191] #", "# User inputs channel number while not channel.isdigit(): # Check", "unload_spi = subprocess.Popen('sudo rmmod spi_bcm2708', shell=True, stdout=subprocess.PIPE) start_spi = subprocess.Popen('sudo", "\"jumper connecting GPIO 7 to CSB\" print \"Multimeter connections (set", "print \"jumper connecting GP10 to MOSI\" print \"jumper connecting GP9", "GPIO7) channel = 3 # set initial value to force", "SCLK\" print \"jumper connecting GP10 to MOSI\" print \"jumper connecting", "= raw_input(\"Which channel do you want to test? Type 0", "= subprocess.Popen('sudo rmmod spi_bcm2708', shell=True, stdout=subprocess.PIPE) start_spi = subprocess.Popen('sudo modprobe", "Make them do it again if wrong return channel spi", "but check it yourself. # This will not work unless", "\"Multimeter connections (set your meter to read V DC):\" print", "DA%d on D/A header\" % channel else: print \"jumper connecting", "input channel = raw_input(\"Try again - just numbers 0 or", "be enabled on your system import spidev import sys from", "(CE1 - aka GPIO7) channel = 3 # set initial", "print \"jumper connecting GPIO 7 to CSB\" print \"Multimeter connections", "# So we need to write a 16 bit word", "13 =gain, bit 12 = shutdown, bits 11-4 data, bits", "each argument is a byte (8 bits), so we need", "\"jumper connecting GP11 to SCLK\" print \"jumper connecting GP10 to", "14 = ignored, bit 13 =gain, bit 12 = shutdown,", "connecting GP10 to MOSI\" print \"jumper connecting GP9 to MISO\"", "3 # set initial value to force user selection common" ]
[ "a set of variables and redraw the status bar text.", "all information, which might get displayed in the status bar", "False def erase(self): \"\"\"Erase status bar text.\"\"\" self.view.erase_status('00_git_gutter') def update(self,", "__init__(self, view, settings): \"\"\"Initialize object.\"\"\" # the sublime.View the status", "variables (iter): An iterateable object with all the variables to", "the active template. Returns: bool: True - if at least", ". import blame from . import templates class SimpleStatusBarTemplate(object): \"\"\"A", "# a list of variables used by this template variables", "defined template. Arguments: variables (iter): An iterateable object with all", "inserted: parts.append('{inserted}+') if deleted: parts.append('{deleted}-') if modified: parts.append(u'{modified}≠') # blame", "= view # the settings.ViewSettings object which stores GitGutter' settings", "by the template. False - if no variable is used", "the active branch name 'branch': None, # the branch we", "text rendering. It stores all information, which might get displayed", "# initialize the jinja2 template self.template = None # the", "message to display in the status bar. \"\"\" if not", "the branch we compare against 'compare': None, # the upstream", "functions to partially update them. \"\"\" def __init__(self, view, settings):", "line's change Returns: string: The formatted message to display in", "= self.settings.get('show_status_bar_text', False) if self.template and not enabled: self.template =", "user defined template. Arguments: variables (iter): An iterateable object with", "0, # the commits the local is behind of upstream", "modified=0, line_author=None, line_author_age=None, **kwargs): \"\"\"Format the status bar text using", "to display in the status bar. \"\"\" if not repo", "GitGutterStatusBar(object): \"\"\"The class manages status bar text rendering. It stores", "if at least one variable is used by the template.", "Arguments: variables (iter): An iterateable object with all the variables", "repo or not branch: return '' parts = ['{repo}/{branch}'] #", "if no variable is used by the template. \"\"\" try:", "return ', '.join(parts).format(**locals()) class GitGutterStatusBar(object): \"\"\"The class manages status bar", "redraw the status bar text. Arguments: kwargs (dict): The dictionary", "None, # the upstream branch name 'remote': None, # the", "blame from . import templates class SimpleStatusBarTemplate(object): \"\"\"A simple template", "one.\"\"\" # a list of variables used by this template", "age of the active line's change Returns: string: The formatted", "!= value: self.vars[key] = value want_update = True if want_update:", "manages status bar text rendering. It stores all information, which", "'behind': 0, # repository statistics 'added_files': 0, 'deleted_files': 0, 'modified_files':", "active branch name 'branch': None, # the branch we compare", "return '' parts = ['{repo}/{branch}'] # Compare against if compare", "might get displayed in the status bar and provides functions", "upstream 'behind': 0, # repository statistics 'added_files': 0, 'deleted_files': 0,", "# repository statistics 'added_files': 0, 'deleted_files': 0, 'modified_files': 0, 'staged_files':", "against 'compare': None, # the upstream branch name 'remote': None,", "self.vars[key] != value: self.vars[key] = value want_update = True if", "the active line line_author_age (string): The age of the active", "deleted lines modified (int): The amount of modified lines line_author", "object which stores GitGutter' settings self.settings = settings # initialize", "variables to check for existence within the active template. Returns:", "deleted: parts.append('{deleted}-') if modified: parts.append(u'{modified}≠') # blame message if line_author", "not in ('HEAD', branch, None): parts.append('Comparing against {compare}') # File", "class manages status bar text rendering. It stores all information,", "= None self.erase() return enabled def has(self, variables): \"\"\"Check if", "The amount of modified lines line_author (string): The author of", "rules. Arguments: repo (string): The repository name branch (string): The", "not enabled: self.template = None self.vars['repo'] = None self.erase() return", "**kwargs): \"\"\"Update a set of variables and redraw the status", "Compare against if compare not in ('HEAD', branch, None): parts.append('Comparing", "0, 'deleted_files': 0, 'modified_files': 0, 'staged_files': 0, # file statistics", "self.template.variables for var in variables) except: return False def erase(self):", "active line's change Returns: string: The formatted message to display", "'inserted', 'deleted', 'modified', 'line_author', 'line_author_age' ]) @staticmethod def render(repo=None, branch=None,", "'line_author_age' ]) @staticmethod def render(repo=None, branch=None, compare=None, inserted=0, deleted=0, modified=0,", "variables and redraw the status bar text. Arguments: kwargs (dict):", "bar text using a static set of rules. Arguments: repo", "at least one variable is used by the template. False", "if line_author and line_author_age: parts.append(u'⟢ {line_author} ({line_author_age})') # join template", "in kwargs.items(): if self.vars[key] != value: self.vars[key] = value want_update", "deleted=0, modified=0, line_author=None, line_author_age=None, **kwargs): \"\"\"Format the status bar text", "and provides functions to partially update them. \"\"\" def __init__(self,", "kwargs.items(): if self.vars[key] != value: self.vars[key] = value want_update =", "self.vars[var] = None def is_enabled(self): \"\"\"Return whether status bar text", "used by this template variables = frozenset([ 'repo', 'branch', 'compare',", "# the settings.ViewSettings object which stores GitGutter' settings self.settings =", "(string): The age of the active line's change Returns: string:", "status bar text using a static set of rules. Arguments:", "status bar and provides functions to partially update them. \"\"\"", "return any(var in self.template.variables for var in variables) except: return", "with the same interface as jinja2's one.\"\"\" # a list", "template class with the same interface as jinja2's one.\"\"\" #", "# sublime text git integration enabled 'st_git_status': view.settings().get('show_git_status', False), #", "'.join(parts).format(**locals()) class GitGutterStatusBar(object): \"\"\"The class manages status bar text rendering.", "= { # sublime text git integration enabled 'st_git_status': view.settings().get('show_git_status',", "iterateable object with all the variables to check for existence", "variables for var in blame.BLAME_VARIABLES: self.vars[var] = None def is_enabled(self):", "want_update: if not self.template: self.template = templates.create( self.settings, 'status_bar_text', SimpleStatusBarTemplate)", "view.settings().get('show_git_status', False), # the repository name 'repo': None, # the", "update them. \"\"\" def __init__(self, view, settings): \"\"\"Initialize object.\"\"\" #", "lines modified (int): The amount of modified lines line_author (string):", "bar. \"\"\" if not repo or not branch: return ''", "used by the user defined template. Arguments: variables (iter): An", "by the template. \"\"\" try: return any(var in self.template.variables for", "'ahead': 0, # the commits the local is behind of", "a list of variables used by this template variables =", "# the commits the local is ahead of upstream 'ahead':", "object.\"\"\" # the sublime.View the status bar is attached to", "return False def erase(self): \"\"\"Erase status bar text.\"\"\" self.view.erase_status('00_git_gutter') def", "modified lines line_author (string): The author of the active line", ". import templates class SimpleStatusBarTemplate(object): \"\"\"A simple template class with", "False - if no variable is used by the template.", "stores all information, which might get displayed in the status", "in ('HEAD', branch, None): parts.append('Comparing against {compare}') # File statistics", "value: self.vars[key] = value want_update = True if want_update: if", "bar text is enabled in settings or not.\"\"\" enabled =", "value want_update = True if want_update: if not self.template: self.template", "key, value in kwargs.items(): if self.vars[key] != value: self.vars[key] =", "{line_author} ({line_author_age})') # join template and fill with locals return", "repository name 'repo': None, # the active branch name 'branch':", "bar is attached to self.view = view # the settings.ViewSettings", "erase(self): \"\"\"Erase status bar text.\"\"\" self.view.erase_status('00_git_gutter') def update(self, **kwargs): \"\"\"Update", "for key, value in kwargs.items(): if self.vars[key] != value: self.vars[key]", "'branch': None, # the branch we compare against 'compare': None,", "branch name 'branch': None, # the branch we compare against", "to check for existence within the active template. Returns: bool:", "any(var in self.template.variables for var in variables) except: return False", "if modified: parts.append(u'{modified}≠') # blame message if line_author and line_author_age:", "'' parts = ['{repo}/{branch}'] # Compare against if compare not", "'state': None, 'deleted': 0, 'inserted': 0, 'modified': 0, } #", "= None def is_enabled(self): \"\"\"Return whether status bar text is", "variables. \"\"\" want_update = False for key, value in kwargs.items():", "them. \"\"\" def __init__(self, view, settings): \"\"\"Initialize object.\"\"\" # the", "by this template variables = frozenset([ 'repo', 'branch', 'compare', 'inserted',", "displayed in the status bar and provides functions to partially", "behind of upstream 'behind': 0, # repository statistics 'added_files': 0,", "-*- import sublime from . import blame from . import", "of upstream 'behind': 0, # repository statistics 'added_files': 0, 'deleted_files':", "- if no variable is used by the template. \"\"\"", "the repository name 'repo': None, # the active branch name", "changed variables to update the status bar text with. Raises:", "in the status bar. \"\"\" if not repo or not", "the jinja2 template self.template = None # the variables to", "git integration enabled 'st_git_status': view.settings().get('show_git_status', False), # the repository name", "variable is used by the template. False - if no", "@staticmethod def render(repo=None, branch=None, compare=None, inserted=0, deleted=0, modified=0, line_author=None, line_author_age=None,", "of variables is used by the user defined template. Arguments:", "information, which might get displayed in the status bar and", "in the status bar and provides functions to partially update", "'st_git_status': view.settings().get('show_git_status', False), # the repository name 'repo': None, #", "the active line's change Returns: string: The formatted message to", "upstream branch name 'remote': None, # the commits the local", "if a set of variables is used by the user", "The compared branch/tag/commit inserted (int): The amount of inserted lines", "\"\"\" want_update = False for key, value in kwargs.items(): if", "status bar text. Arguments: kwargs (dict): The dictionary of possibly", "\"\"\" try: return any(var in self.template.variables for var in variables)", "in variables) except: return False def erase(self): \"\"\"Erase status bar", "with. Raises: KeyError, if `kwargs` contains unknown variables. \"\"\" want_update", "# declare all blame variables for var in blame.BLAME_VARIABLES: self.vars[var]", "self.template = None # the variables to use to render", "if deleted: parts.append('{deleted}-') if modified: parts.append(u'{modified}≠') # blame message if", "statistics 'state': None, 'deleted': 0, 'inserted': 0, 'modified': 0, }", "if self.vars[key] != value: self.vars[key] = value want_update = True", "not branch: return '' parts = ['{repo}/{branch}'] # Compare against", "if self.template and not enabled: self.template = None self.vars['repo'] =", "line_author_age=None, **kwargs): \"\"\"Format the status bar text using a static", "Returns: bool: True - if at least one variable is", "self.settings = settings # initialize the jinja2 template self.template =", "this template variables = frozenset([ 'repo', 'branch', 'compare', 'inserted', 'deleted',", "author of the active line line_author_age (string): The age of", "of deleted lines modified (int): The amount of modified lines", "branch/tag/commit inserted (int): The amount of inserted lines deleted (int):", "deleted (int): The amount of deleted lines modified (int): The", "status bar text rendering. It stores all information, which might", "bar self.vars = { # sublime text git integration enabled", "\"\"\"Update a set of variables and redraw the status bar", "line line_author_age (string): The age of the active line's change", "parts.append('{inserted}+') if deleted: parts.append('{deleted}-') if modified: parts.append(u'{modified}≠') # blame message", "enabled = self.settings.get('show_status_bar_text', False) if self.template and not enabled: self.template", "is enabled in settings or not.\"\"\" enabled = self.settings.get('show_status_bar_text', False)", "(int): The amount of deleted lines modified (int): The amount", "class GitGutterStatusBar(object): \"\"\"The class manages status bar text rendering. It", "# the repository name 'repo': None, # the active branch", "the commits the local is behind of upstream 'behind': 0,", "template self.template = None # the variables to use to", "the settings.ViewSettings object which stores GitGutter' settings self.settings = settings", "status bar self.vars = { # sublime text git integration", "def render(repo=None, branch=None, compare=None, inserted=0, deleted=0, modified=0, line_author=None, line_author_age=None, **kwargs):", "branch name. compare (string): The compared branch/tag/commit inserted (int): The", "sublime from . import blame from . import templates class", "# File statistics if inserted: parts.append('{inserted}+') if deleted: parts.append('{deleted}-') if", "object with all the variables to check for existence within", "the upstream branch name 'remote': None, # the commits the", "variables to use to render the status bar self.vars =", "used by the template. \"\"\" try: return any(var in self.template.variables", "KeyError, if `kwargs` contains unknown variables. \"\"\" want_update = False", "repo (string): The repository name branch (string): The branch name.", "False), # the repository name 'repo': None, # the active", "(iter): An iterateable object with all the variables to check", "The amount of inserted lines deleted (int): The amount of", "of rules. Arguments: repo (string): The repository name branch (string):", "def update(self, **kwargs): \"\"\"Update a set of variables and redraw", "\"\"\" def __init__(self, view, settings): \"\"\"Initialize object.\"\"\" # the sublime.View", "not.\"\"\" enabled = self.settings.get('show_status_bar_text', False) if self.template and not enabled:", "has(self, variables): \"\"\"Check if a set of variables is used", "change Returns: string: The formatted message to display in the", "list of variables used by this template variables = frozenset([", "value in kwargs.items(): if self.vars[key] != value: self.vars[key] = value", "self.template and not enabled: self.template = None self.vars['repo'] = None", "and fill with locals return ', '.join(parts).format(**locals()) class GitGutterStatusBar(object): \"\"\"The", "blame variables for var in blame.BLAME_VARIABLES: self.vars[var] = None def", "parts = ['{repo}/{branch}'] # Compare against if compare not in", "The dictionary of possibly changed variables to update the status", "jinja2's one.\"\"\" # a list of variables used by this", "\"\"\"The class manages status bar text rendering. It stores all", "'deleted', 'modified', 'line_author', 'line_author_age' ]) @staticmethod def render(repo=None, branch=None, compare=None,", "variables is used by the user defined template. Arguments: variables", "and line_author_age: parts.append(u'⟢ {line_author} ({line_author_age})') # join template and fill", "None # the variables to use to render the status", "inserted lines deleted (int): The amount of deleted lines modified", "file statistics 'state': None, 'deleted': 0, 'inserted': 0, 'modified': 0,", "line_author_age: parts.append(u'⟢ {line_author} ({line_author_age})') # join template and fill with", "False for key, value in kwargs.items(): if self.vars[key] != value:", "File statistics if inserted: parts.append('{inserted}+') if deleted: parts.append('{deleted}-') if modified:", "the commits the local is ahead of upstream 'ahead': 0,", "all the variables to check for existence within the active", "'deleted_files': 0, 'modified_files': 0, 'staged_files': 0, # file statistics 'state':", "parts.append('{deleted}-') if modified: parts.append(u'{modified}≠') # blame message if line_author and", "0, 'modified_files': 0, 'staged_files': 0, # file statistics 'state': None,", "and not enabled: self.template = None self.vars['repo'] = None self.erase()", "if `kwargs` contains unknown variables. \"\"\" want_update = False for", "statistics if inserted: parts.append('{inserted}+') if deleted: parts.append('{deleted}-') if modified: parts.append(u'{modified}≠')", "status bar text with. Raises: KeyError, if `kwargs` contains unknown", "'modified', 'line_author', 'line_author_age' ]) @staticmethod def render(repo=None, branch=None, compare=None, inserted=0,", "set of rules. Arguments: repo (string): The repository name branch", "# join template and fill with locals return ', '.join(parts).format(**locals())", "coding: utf-8 -*- import sublime from . import blame from", "join template and fill with locals return ', '.join(parts).format(**locals()) class", "bar text. Arguments: kwargs (dict): The dictionary of possibly changed", "in blame.BLAME_VARIABLES: self.vars[var] = None def is_enabled(self): \"\"\"Return whether status", "unknown variables. \"\"\" want_update = False for key, value in", "text using a static set of rules. Arguments: repo (string):", "the status bar is attached to self.view = view #", "None, # the commits the local is ahead of upstream", "repository name branch (string): The branch name. compare (string): The", "= None self.vars['repo'] = None self.erase() return enabled def has(self,", "in self.template.variables for var in variables) except: return False def", "# the variables to use to render the status bar", "inserted=0, deleted=0, modified=0, line_author=None, line_author_age=None, **kwargs): \"\"\"Format the status bar", "view # the settings.ViewSettings object which stores GitGutter' settings self.settings", "enabled 'st_git_status': view.settings().get('show_git_status', False), # the repository name 'repo': None,", "is used by the template. False - if no variable", "text.\"\"\" self.view.erase_status('00_git_gutter') def update(self, **kwargs): \"\"\"Update a set of variables", "branch, None): parts.append('Comparing against {compare}') # File statistics if inserted:", "the sublime.View the status bar is attached to self.view =", "(string): The repository name branch (string): The branch name. compare", "if inserted: parts.append('{inserted}+') if deleted: parts.append('{deleted}-') if modified: parts.append(u'{modified}≠') #", "name. compare (string): The compared branch/tag/commit inserted (int): The amount", "= value want_update = True if want_update: if not self.template:", "is attached to self.view = view # the settings.ViewSettings object", "and redraw the status bar text. Arguments: kwargs (dict): The", "\"\"\"Check if a set of variables is used by the", "of modified lines line_author (string): The author of the active", "want_update = True if want_update: if not self.template: self.template =", "repository statistics 'added_files': 0, 'deleted_files': 0, 'modified_files': 0, 'staged_files': 0,", "settings or not.\"\"\" enabled = self.settings.get('show_status_bar_text', False) if self.template and", "status bar is attached to self.view = view # the", "the status bar text. Arguments: kwargs (dict): The dictionary of", "self.template: self.template = templates.create( self.settings, 'status_bar_text', SimpleStatusBarTemplate) self.view.set_status( '00_git_gutter', self.template.render(**self.vars))", "of the active line's change Returns: string: The formatted message", "'compare': None, # the upstream branch name 'remote': None, #", "enabled in settings or not.\"\"\" enabled = self.settings.get('show_status_bar_text', False) if", "settings.ViewSettings object which stores GitGutter' settings self.settings = settings #", "contains unknown variables. \"\"\" want_update = False for key, value", "settings # initialize the jinja2 template self.template = None #", "# the active branch name 'branch': None, # the branch", "attached to self.view = view # the settings.ViewSettings object which", "0, # file statistics 'state': None, 'deleted': 0, 'inserted': 0,", "possibly changed variables to update the status bar text with.", "render(repo=None, branch=None, compare=None, inserted=0, deleted=0, modified=0, line_author=None, line_author_age=None, **kwargs): \"\"\"Format", "None, # the branch we compare against 'compare': None, #", "return enabled def has(self, variables): \"\"\"Check if a set of", "to self.view = view # the settings.ViewSettings object which stores", "of the active line line_author_age (string): The age of the", "(string): The compared branch/tag/commit inserted (int): The amount of inserted", "'modified': 0, } # declare all blame variables for var", "('HEAD', branch, None): parts.append('Comparing against {compare}') # File statistics if", "blame message if line_author and line_author_age: parts.append(u'⟢ {line_author} ({line_author_age})') #", "= ['{repo}/{branch}'] # Compare against if compare not in ('HEAD',", "The repository name branch (string): The branch name. compare (string):", "} # declare all blame variables for var in blame.BLAME_VARIABLES:", "The formatted message to display in the status bar. \"\"\"", "is_enabled(self): \"\"\"Return whether status bar text is enabled in settings", "Arguments: repo (string): The repository name branch (string): The branch", "', '.join(parts).format(**locals()) class GitGutterStatusBar(object): \"\"\"The class manages status bar text", "for var in variables) except: return False def erase(self): \"\"\"Erase", "compare (string): The compared branch/tag/commit inserted (int): The amount of", "class SimpleStatusBarTemplate(object): \"\"\"A simple template class with the same interface", "if not repo or not branch: return '' parts =", "**kwargs): \"\"\"Format the status bar text using a static set", "from . import blame from . import templates class SimpleStatusBarTemplate(object):", "status bar text.\"\"\" self.view.erase_status('00_git_gutter') def update(self, **kwargs): \"\"\"Update a set", "to use to render the status bar self.vars = {", "(dict): The dictionary of possibly changed variables to update the", "bar text with. Raises: KeyError, if `kwargs` contains unknown variables.", "-*- coding: utf-8 -*- import sublime from . import blame", "The author of the active line line_author_age (string): The age", "the same interface as jinja2's one.\"\"\" # a list of", "check for existence within the active template. Returns: bool: True", "declare all blame variables for var in blame.BLAME_VARIABLES: self.vars[var] =", "of inserted lines deleted (int): The amount of deleted lines", "of variables used by this template variables = frozenset([ 'repo',", "sublime text git integration enabled 'st_git_status': view.settings().get('show_git_status', False), # the", "name 'remote': None, # the commits the local is ahead", "var in variables) except: return False def erase(self): \"\"\"Erase status", "to update the status bar text with. Raises: KeyError, if", "use to render the status bar self.vars = { #", "SimpleStatusBarTemplate(object): \"\"\"A simple template class with the same interface as", "set of variables and redraw the status bar text. Arguments:", "self.vars[key] = value want_update = True if want_update: if not", "- if at least one variable is used by the", "or not.\"\"\" enabled = self.settings.get('show_status_bar_text', False) if self.template and not", "'staged_files': 0, # file statistics 'state': None, 'deleted': 0, 'inserted':", "whether status bar text is enabled in settings or not.\"\"\"", "name 'branch': None, # the branch we compare against 'compare':", "the status bar and provides functions to partially update them.", "template. Returns: bool: True - if at least one variable", "def has(self, variables): \"\"\"Check if a set of variables is", "of variables and redraw the status bar text. Arguments: kwargs", "if compare not in ('HEAD', branch, None): parts.append('Comparing against {compare}')", "a static set of rules. Arguments: repo (string): The repository", "all blame variables for var in blame.BLAME_VARIABLES: self.vars[var] = None", "template. Arguments: variables (iter): An iterateable object with all the", "= False for key, value in kwargs.items(): if self.vars[key] !=", "least one variable is used by the template. False -", "branch we compare against 'compare': None, # the upstream branch", "{compare}') # File statistics if inserted: parts.append('{inserted}+') if deleted: parts.append('{deleted}-')", "'remote': None, # the commits the local is ahead of", "0, } # declare all blame variables for var in", "against {compare}') # File statistics if inserted: parts.append('{inserted}+') if deleted:", "# the sublime.View the status bar is attached to self.view", "import sublime from . import blame from . import templates", "branch name 'remote': None, # the commits the local is", "the template. \"\"\" try: return any(var in self.template.variables for var", "\"\"\"Erase status bar text.\"\"\" self.view.erase_status('00_git_gutter') def update(self, **kwargs): \"\"\"Update a", "# Compare against if compare not in ('HEAD', branch, None):", "amount of inserted lines deleted (int): The amount of deleted", "set of variables is used by the user defined template.", "one variable is used by the template. False - if", "0, 'inserted': 0, 'modified': 0, } # declare all blame", "utf-8 -*- import sublime from . import blame from .", "bar text rendering. It stores all information, which might get", "None self.vars['repo'] = None self.erase() return enabled def has(self, variables):", "is used by the template. \"\"\" try: return any(var in", "the local is behind of upstream 'behind': 0, # repository", "static set of rules. Arguments: repo (string): The repository name", "= True if want_update: if not self.template: self.template = templates.create(", "self.vars = { # sublime text git integration enabled 'st_git_status':", "Returns: string: The formatted message to display in the status", "integration enabled 'st_git_status': view.settings().get('show_git_status', False), # the repository name 'repo':", "({line_author_age})') # join template and fill with locals return ',", "# the branch we compare against 'compare': None, # the", "{ # sublime text git integration enabled 'st_git_status': view.settings().get('show_git_status', False),", "text is enabled in settings or not.\"\"\" enabled = self.settings.get('show_status_bar_text',", "of possibly changed variables to update the status bar text", "not self.template: self.template = templates.create( self.settings, 'status_bar_text', SimpleStatusBarTemplate) self.view.set_status( '00_git_gutter',", "modified: parts.append(u'{modified}≠') # blame message if line_author and line_author_age: parts.append(u'⟢", "if not self.template: self.template = templates.create( self.settings, 'status_bar_text', SimpleStatusBarTemplate) self.view.set_status(", "= frozenset([ 'repo', 'branch', 'compare', 'inserted', 'deleted', 'modified', 'line_author', 'line_author_age'", "active line line_author_age (string): The age of the active line's", "against if compare not in ('HEAD', branch, None): parts.append('Comparing against", "we compare against 'compare': None, # the upstream branch name", "if want_update: if not self.template: self.template = templates.create( self.settings, 'status_bar_text',", "Raises: KeyError, if `kwargs` contains unknown variables. \"\"\" want_update =", "var in blame.BLAME_VARIABLES: self.vars[var] = None def is_enabled(self): \"\"\"Return whether", "used by the template. False - if no variable is", "to partially update them. \"\"\" def __init__(self, view, settings): \"\"\"Initialize", "The amount of deleted lines modified (int): The amount of", "local is ahead of upstream 'ahead': 0, # the commits", "provides functions to partially update them. \"\"\" def __init__(self, view,", "'inserted': 0, 'modified': 0, } # declare all blame variables", "# the commits the local is behind of upstream 'behind':", "bool: True - if at least one variable is used", "self.erase() return enabled def has(self, variables): \"\"\"Check if a set", "import templates class SimpleStatusBarTemplate(object): \"\"\"A simple template class with the", "\"\"\"Format the status bar text using a static set of", "None def is_enabled(self): \"\"\"Return whether status bar text is enabled", "True if want_update: if not self.template: self.template = templates.create( self.settings,", "try: return any(var in self.template.variables for var in variables) except:", "lines deleted (int): The amount of deleted lines modified (int):", "want_update = False for key, value in kwargs.items(): if self.vars[key]", "True - if at least one variable is used by", "(string): The author of the active line line_author_age (string): The", "settings): \"\"\"Initialize object.\"\"\" # the sublime.View the status bar is", "variables) except: return False def erase(self): \"\"\"Erase status bar text.\"\"\"", "def is_enabled(self): \"\"\"Return whether status bar text is enabled in", "= settings # initialize the jinja2 template self.template = None", "template and fill with locals return ', '.join(parts).format(**locals()) class GitGutterStatusBar(object):", "'repo': None, # the active branch name 'branch': None, #", "# -*- coding: utf-8 -*- import sublime from . import", "(string): The branch name. compare (string): The compared branch/tag/commit inserted", "# file statistics 'state': None, 'deleted': 0, 'inserted': 0, 'modified':", "\"\"\"Return whether status bar text is enabled in settings or", "is used by the user defined template. Arguments: variables (iter):", "interface as jinja2's one.\"\"\" # a list of variables used", "<gh_stars>0 # -*- coding: utf-8 -*- import sublime from .", "templates class SimpleStatusBarTemplate(object): \"\"\"A simple template class with the same", "the status bar text using a static set of rules.", "template. \"\"\" try: return any(var in self.template.variables for var in", "fill with locals return ', '.join(parts).format(**locals()) class GitGutterStatusBar(object): \"\"\"The class", "self.view = view # the settings.ViewSettings object which stores GitGutter'", "line_author_age (string): The age of the active line's change Returns:", "dictionary of possibly changed variables to update the status bar", "jinja2 template self.template = None # the variables to use", "local is behind of upstream 'behind': 0, # repository statistics", "active template. Returns: bool: True - if at least one", "variables used by this template variables = frozenset([ 'repo', 'branch',", "0, 'modified': 0, } # declare all blame variables for", "'repo', 'branch', 'compare', 'inserted', 'deleted', 'modified', 'line_author', 'line_author_age' ]) @staticmethod", "line_author=None, line_author_age=None, **kwargs): \"\"\"Format the status bar text using a", "self.settings.get('show_status_bar_text', False) if self.template and not enabled: self.template = None", "from . import templates class SimpleStatusBarTemplate(object): \"\"\"A simple template class", "variables = frozenset([ 'repo', 'branch', 'compare', 'inserted', 'deleted', 'modified', 'line_author',", "parts.append(u'{modified}≠') # blame message if line_author and line_author_age: parts.append(u'⟢ {line_author}", "is behind of upstream 'behind': 0, # repository statistics 'added_files':", "upstream 'ahead': 0, # the commits the local is behind", "inserted (int): The amount of inserted lines deleted (int): The", "rendering. It stores all information, which might get displayed in", "render the status bar self.vars = { # sublime text", "(int): The amount of modified lines line_author (string): The author", "for var in blame.BLAME_VARIABLES: self.vars[var] = None def is_enabled(self): \"\"\"Return", "= None # the variables to use to render the", "def __init__(self, view, settings): \"\"\"Initialize object.\"\"\" # the sublime.View the", "`kwargs` contains unknown variables. \"\"\" want_update = False for key,", "locals return ', '.join(parts).format(**locals()) class GitGutterStatusBar(object): \"\"\"The class manages status", "class with the same interface as jinja2's one.\"\"\" # a", "partially update them. \"\"\" def __init__(self, view, settings): \"\"\"Initialize object.\"\"\"", "bar text.\"\"\" self.view.erase_status('00_git_gutter') def update(self, **kwargs): \"\"\"Update a set of", "with all the variables to check for existence within the", "modified (int): The amount of modified lines line_author (string): The", "branch=None, compare=None, inserted=0, deleted=0, modified=0, line_author=None, line_author_age=None, **kwargs): \"\"\"Format the", "a set of variables is used by the user defined", "for existence within the active template. Returns: bool: True -", "bar and provides functions to partially update them. \"\"\" def", "text git integration enabled 'st_git_status': view.settings().get('show_git_status', False), # the repository", "compare against 'compare': None, # the upstream branch name 'remote':", "\"\"\"Initialize object.\"\"\" # the sublime.View the status bar is attached", "0, 'staged_files': 0, # file statistics 'state': None, 'deleted': 0,", "update(self, **kwargs): \"\"\"Update a set of variables and redraw the", "simple template class with the same interface as jinja2's one.\"\"\"", "# blame message if line_author and line_author_age: parts.append(u'⟢ {line_author} ({line_author_age})')", "ahead of upstream 'ahead': 0, # the commits the local", "the user defined template. Arguments: variables (iter): An iterateable object", "parts.append('Comparing against {compare}') # File statistics if inserted: parts.append('{inserted}+') if", "to render the status bar self.vars = { # sublime", "self.vars['repo'] = None self.erase() return enabled def has(self, variables): \"\"\"Check", "line_author (string): The author of the active line line_author_age (string):", "template variables = frozenset([ 'repo', 'branch', 'compare', 'inserted', 'deleted', 'modified',", "the status bar self.vars = { # sublime text git", "sublime.View the status bar is attached to self.view = view", "enabled def has(self, variables): \"\"\"Check if a set of variables", "blame.BLAME_VARIABLES: self.vars[var] = None def is_enabled(self): \"\"\"Return whether status bar", "None, # the active branch name 'branch': None, # the", "lines line_author (string): The author of the active line line_author_age", "'modified_files': 0, 'staged_files': 0, # file statistics 'state': None, 'deleted':", "name branch (string): The branch name. compare (string): The compared", "compared branch/tag/commit inserted (int): The amount of inserted lines deleted", "of upstream 'ahead': 0, # the commits the local is", "'deleted': 0, 'inserted': 0, 'modified': 0, } # declare all", "view, settings): \"\"\"Initialize object.\"\"\" # the sublime.View the status bar", "stores GitGutter' settings self.settings = settings # initialize the jinja2", "frozenset([ 'repo', 'branch', 'compare', 'inserted', 'deleted', 'modified', 'line_author', 'line_author_age' ])", "import blame from . import templates class SimpleStatusBarTemplate(object): \"\"\"A simple", "name 'repo': None, # the active branch name 'branch': None,", "self.template = None self.vars['repo'] = None self.erase() return enabled def", "parts.append(u'⟢ {line_author} ({line_author_age})') # join template and fill with locals", "def erase(self): \"\"\"Erase status bar text.\"\"\" self.view.erase_status('00_git_gutter') def update(self, **kwargs):", "variables): \"\"\"Check if a set of variables is used by", "settings self.settings = settings # initialize the jinja2 template self.template", "'added_files': 0, 'deleted_files': 0, 'modified_files': 0, 'staged_files': 0, # file", "None self.erase() return enabled def has(self, variables): \"\"\"Check if a", "['{repo}/{branch}'] # Compare against if compare not in ('HEAD', branch,", "statistics 'added_files': 0, 'deleted_files': 0, 'modified_files': 0, 'staged_files': 0, #", "within the active template. Returns: bool: True - if at", "the local is ahead of upstream 'ahead': 0, # the", "status bar text is enabled in settings or not.\"\"\" enabled", "branch (string): The branch name. compare (string): The compared branch/tag/commit", "\"\"\"A simple template class with the same interface as jinja2's", "compare not in ('HEAD', branch, None): parts.append('Comparing against {compare}') #", "by the user defined template. Arguments: variables (iter): An iterateable", "the variables to check for existence within the active template.", "'compare', 'inserted', 'deleted', 'modified', 'line_author', 'line_author_age' ]) @staticmethod def render(repo=None,", "(int): The amount of inserted lines deleted (int): The amount", "text with. Raises: KeyError, if `kwargs` contains unknown variables. \"\"\"", "the variables to use to render the status bar self.vars", "the status bar text with. Raises: KeyError, if `kwargs` contains", "kwargs (dict): The dictionary of possibly changed variables to update", "the template. False - if no variable is used by", "enabled: self.template = None self.vars['repo'] = None self.erase() return enabled", "string: The formatted message to display in the status bar.", "existence within the active template. Returns: bool: True - if", "as jinja2's one.\"\"\" # a list of variables used by", "0, # repository statistics 'added_files': 0, 'deleted_files': 0, 'modified_files': 0,", "which stores GitGutter' settings self.settings = settings # initialize the", "line_author and line_author_age: parts.append(u'⟢ {line_author} ({line_author_age})') # join template and", "no variable is used by the template. \"\"\" try: return", "formatted message to display in the status bar. \"\"\" if", "not repo or not branch: return '' parts = ['{repo}/{branch}']", "\"\"\" if not repo or not branch: return '' parts", "commits the local is ahead of upstream 'ahead': 0, #", "display in the status bar. \"\"\" if not repo or", "which might get displayed in the status bar and provides", "amount of modified lines line_author (string): The author of the", "except: return False def erase(self): \"\"\"Erase status bar text.\"\"\" self.view.erase_status('00_git_gutter')", "self.view.erase_status('00_git_gutter') def update(self, **kwargs): \"\"\"Update a set of variables and", "compare=None, inserted=0, deleted=0, modified=0, line_author=None, line_author_age=None, **kwargs): \"\"\"Format the status", "'branch', 'compare', 'inserted', 'deleted', 'modified', 'line_author', 'line_author_age' ]) @staticmethod def", "with locals return ', '.join(parts).format(**locals()) class GitGutterStatusBar(object): \"\"\"The class manages", "status bar. \"\"\" if not repo or not branch: return", "template. False - if no variable is used by the", "The age of the active line's change Returns: string: The", "get displayed in the status bar and provides functions to", "None, 'deleted': 0, 'inserted': 0, 'modified': 0, } # declare", "branch: return '' parts = ['{repo}/{branch}'] # Compare against if", "It stores all information, which might get displayed in the", "or not branch: return '' parts = ['{repo}/{branch}'] # Compare", "same interface as jinja2's one.\"\"\" # a list of variables", "initialize the jinja2 template self.template = None # the variables", "the status bar. \"\"\" if not repo or not branch:", "message if line_author and line_author_age: parts.append(u'⟢ {line_author} ({line_author_age})') # join", "variables to update the status bar text with. Raises: KeyError,", "False) if self.template and not enabled: self.template = None self.vars['repo']", "commits the local is behind of upstream 'behind': 0, #", "update the status bar text with. Raises: KeyError, if `kwargs`", "using a static set of rules. Arguments: repo (string): The", "GitGutter' settings self.settings = settings # initialize the jinja2 template", "None): parts.append('Comparing against {compare}') # File statistics if inserted: parts.append('{inserted}+')", "]) @staticmethod def render(repo=None, branch=None, compare=None, inserted=0, deleted=0, modified=0, line_author=None,", "in settings or not.\"\"\" enabled = self.settings.get('show_status_bar_text', False) if self.template", "Arguments: kwargs (dict): The dictionary of possibly changed variables to", "is ahead of upstream 'ahead': 0, # the commits the", "The branch name. compare (string): The compared branch/tag/commit inserted (int):", "'line_author', 'line_author_age' ]) @staticmethod def render(repo=None, branch=None, compare=None, inserted=0, deleted=0,", "# the upstream branch name 'remote': None, # the commits", "text. Arguments: kwargs (dict): The dictionary of possibly changed variables", "amount of deleted lines modified (int): The amount of modified", "variable is used by the template. \"\"\" try: return any(var", "An iterateable object with all the variables to check for" ]
[ "-*- coding: utf-8 -*- from __future__ import unicode_literals from django.test", "import unicode_literals from django.test import TestCase class RandomTestCase(TestCase): def test_one_plus_one1(self):", "__future__ import unicode_literals from django.test import TestCase class RandomTestCase(TestCase): def", "<reponame>bunya017/Django-Polls-App<gh_stars>0 # -*- coding: utf-8 -*- from __future__ import unicode_literals", "unicode_literals from django.test import TestCase class RandomTestCase(TestCase): def test_one_plus_one1(self): self.assertEqual(1+1,", "coding: utf-8 -*- from __future__ import unicode_literals from django.test import", "utf-8 -*- from __future__ import unicode_literals from django.test import TestCase", "-*- from __future__ import unicode_literals from django.test import TestCase class", "from django.test import TestCase class RandomTestCase(TestCase): def test_one_plus_one1(self): self.assertEqual(1+1, 2)", "from __future__ import unicode_literals from django.test import TestCase class RandomTestCase(TestCase):", "# -*- coding: utf-8 -*- from __future__ import unicode_literals from" ]
[ "passowrd = sso.get_login_credentials(\"WATCHER\") # Open a sample video available in", "= cv2.VideoCapture('https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_2mb.mp4') #if not vcap.isOpened(): # print \"File Cannot be", "video windows before it ends if you want if cv2.waitKey(22)", "# log = l.setup_logging(__name__) def main(args=None): # username, passowrd =", "sso as sso import opencv2 as cv2 import urllib import", "the resulting frame cv2.imshow('frame',frame) # Press q to close the", "# import logging # import hercules.lib.util.hercules_logging as l # from", "ret, frame = vcap.read() #print cap.isOpened(), ret if frame is", "Cannot be Opened\" while(True): # Capture frame-by-frame ret, frame =", "hercules.lib.util.hercules_logging as l # from hercules.lib.util import sso as sso", "urllib import numpy as np # log = l.setup_logging(__name__) def", "np # log = l.setup_logging(__name__) def main(args=None): # username, passowrd", "if you want if cv2.waitKey(22) & 0xFF == ord('q'): break", "log = l.setup_logging(__name__) def main(args=None): # username, passowrd = sso.get_login_credentials(\"WATCHER\")", "cv2.imshow('frame',frame) # Press q to close the video windows before", "main(args=None): # username, passowrd = sso.get_login_credentials(\"WATCHER\") # Open a sample", "sample-videos vcap = cv2.VideoCapture('https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_2mb.mp4') #if not vcap.isOpened(): # print \"File", "# Press q to close the video windows before it", "before it ends if you want if cv2.waitKey(22) & 0xFF", "release the capture vcap.release() cv2.destroyAllWindows() print(\"Video stop\") if __name__ ==", "# Open a sample video available in sample-videos vcap =", "ends if you want if cv2.waitKey(22) & 0xFF == ord('q'):", "print(\"Frame is None\") break # When everything done, release the", "sso.get_login_credentials(\"WATCHER\") # Open a sample video available in sample-videos vcap", "the video windows before it ends if you want if", "#if not vcap.isOpened(): # print \"File Cannot be Opened\" while(True):", "sso import opencv2 as cv2 import urllib import numpy as", "vcap = cv2.VideoCapture('https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_2mb.mp4') #if not vcap.isOpened(): # print \"File Cannot", "the capture vcap.release() cv2.destroyAllWindows() print(\"Video stop\") if __name__ == \"__main__\":", "want if cv2.waitKey(22) & 0xFF == ord('q'): break else: print(\"Frame", "None\") break # When everything done, release the capture vcap.release()", "import sso as sso import opencv2 as cv2 import urllib", "# from hercules.lib.util import sso as sso import opencv2 as", "numpy as np # log = l.setup_logging(__name__) def main(args=None): #", "ret if frame is not None: # Display the resulting", "to close the video windows before it ends if you", "Display the resulting frame cv2.imshow('frame',frame) # Press q to close", "Open a sample video available in sample-videos vcap = cv2.VideoCapture('https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_2mb.mp4')", "a sample video available in sample-videos vcap = cv2.VideoCapture('https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_2mb.mp4') #if", "# import hercules.lib.util.hercules_logging as l # from hercules.lib.util import sso", "def main(args=None): # username, passowrd = sso.get_login_credentials(\"WATCHER\") # Open a", "vcap.read() #print cap.isOpened(), ret if frame is not None: #", "logging # import hercules.lib.util.hercules_logging as l # from hercules.lib.util import", "cap.isOpened(), ret if frame is not None: # Display the", "else: print(\"Frame is None\") break # When everything done, release", "as np # log = l.setup_logging(__name__) def main(args=None): # username,", "l.setup_logging(__name__) def main(args=None): # username, passowrd = sso.get_login_credentials(\"WATCHER\") # Open", "frame is not None: # Display the resulting frame cv2.imshow('frame',frame)", "windows before it ends if you want if cv2.waitKey(22) &", "be Opened\" while(True): # Capture frame-by-frame ret, frame = vcap.read()", "as sso import opencv2 as cv2 import urllib import numpy", "None: # Display the resulting frame cv2.imshow('frame',frame) # Press q", "#print cap.isOpened(), ret if frame is not None: # Display", "= l.setup_logging(__name__) def main(args=None): # username, passowrd = sso.get_login_credentials(\"WATCHER\") #", "<gh_stars>0 # import logging # import hercules.lib.util.hercules_logging as l #", "l # from hercules.lib.util import sso as sso import opencv2", "break else: print(\"Frame is None\") break # When everything done,", "resulting frame cv2.imshow('frame',frame) # Press q to close the video", "print \"File Cannot be Opened\" while(True): # Capture frame-by-frame ret,", "# When everything done, release the capture vcap.release() cv2.destroyAllWindows() print(\"Video", "is None\") break # When everything done, release the capture", "cv2.VideoCapture('https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_2mb.mp4') #if not vcap.isOpened(): # print \"File Cannot be Opened\"", "# username, passowrd = sso.get_login_credentials(\"WATCHER\") # Open a sample video", "== ord('q'): break else: print(\"Frame is None\") break # When", "break # When everything done, release the capture vcap.release() cv2.destroyAllWindows()", "frame-by-frame ret, frame = vcap.read() #print cap.isOpened(), ret if frame", "done, release the capture vcap.release() cv2.destroyAllWindows() print(\"Video stop\") if __name__", "# Display the resulting frame cv2.imshow('frame',frame) # Press q to", "capture vcap.release() cv2.destroyAllWindows() print(\"Video stop\") if __name__ == \"__main__\": main()", "import logging # import hercules.lib.util.hercules_logging as l # from hercules.lib.util", "everything done, release the capture vcap.release() cv2.destroyAllWindows() print(\"Video stop\") if", "When everything done, release the capture vcap.release() cv2.destroyAllWindows() print(\"Video stop\")", "frame = vcap.read() #print cap.isOpened(), ret if frame is not", "it ends if you want if cv2.waitKey(22) & 0xFF ==", "import hercules.lib.util.hercules_logging as l # from hercules.lib.util import sso as", "not None: # Display the resulting frame cv2.imshow('frame',frame) # Press", "cv2.waitKey(22) & 0xFF == ord('q'): break else: print(\"Frame is None\")", "Opened\" while(True): # Capture frame-by-frame ret, frame = vcap.read() #print", "as cv2 import urllib import numpy as np # log", "vcap.isOpened(): # print \"File Cannot be Opened\" while(True): # Capture", "0xFF == ord('q'): break else: print(\"Frame is None\") break #", "video available in sample-videos vcap = cv2.VideoCapture('https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_2mb.mp4') #if not vcap.isOpened():", "ord('q'): break else: print(\"Frame is None\") break # When everything", "import opencv2 as cv2 import urllib import numpy as np", "not vcap.isOpened(): # print \"File Cannot be Opened\" while(True): #", "# print \"File Cannot be Opened\" while(True): # Capture frame-by-frame", "q to close the video windows before it ends if", "import urllib import numpy as np # log = l.setup_logging(__name__)", "sample video available in sample-videos vcap = cv2.VideoCapture('https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_2mb.mp4') #if not", "& 0xFF == ord('q'): break else: print(\"Frame is None\") break", "in sample-videos vcap = cv2.VideoCapture('https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_2mb.mp4') #if not vcap.isOpened(): # print", "cv2 import urllib import numpy as np # log =", "username, passowrd = sso.get_login_credentials(\"WATCHER\") # Open a sample video available", "= vcap.read() #print cap.isOpened(), ret if frame is not None:", "Press q to close the video windows before it ends", "hercules.lib.util import sso as sso import opencv2 as cv2 import", "frame cv2.imshow('frame',frame) # Press q to close the video windows", "import numpy as np # log = l.setup_logging(__name__) def main(args=None):", "you want if cv2.waitKey(22) & 0xFF == ord('q'): break else:", "if frame is not None: # Display the resulting frame", "while(True): # Capture frame-by-frame ret, frame = vcap.read() #print cap.isOpened(),", "is not None: # Display the resulting frame cv2.imshow('frame',frame) #", "Capture frame-by-frame ret, frame = vcap.read() #print cap.isOpened(), ret if", "= sso.get_login_credentials(\"WATCHER\") # Open a sample video available in sample-videos", "\"File Cannot be Opened\" while(True): # Capture frame-by-frame ret, frame", "# Capture frame-by-frame ret, frame = vcap.read() #print cap.isOpened(), ret", "as l # from hercules.lib.util import sso as sso import", "if cv2.waitKey(22) & 0xFF == ord('q'): break else: print(\"Frame is", "close the video windows before it ends if you want", "opencv2 as cv2 import urllib import numpy as np #", "from hercules.lib.util import sso as sso import opencv2 as cv2", "available in sample-videos vcap = cv2.VideoCapture('https://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_2mb.mp4') #if not vcap.isOpened(): #" ]
[ "= node_type super(NodeTypeNotFoundError, self).__init__(\"Node type '{}' does not exist.\".format(node_type)) class", "MalformedUpdateDictionaryError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class InvalidPropertyError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class", "GraphAPIError(APIException): \"\"\"Base class for exceptions in this module.\"\"\" pass class", "= status.HTTP_400_BAD_REQUEST class InvalidPropertyError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class InvalidValueError(GraphAPIError): status_code", "def __init__(self, id): self.id = id super(NodeNotFoundError, self).__init__(\"Node with id", "\"\"\" status_code = status.HTTP_400_BAD_REQUEST class MalformedUpdateDictionaryError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class", "<filename>ribbon/exceptions.py from rest_framework.exceptions import APIException from rest_framework import status class", "\"\"\" Creating a node requires a type. \"\"\" status_code =", "status_code = status.HTTP_403_FORBIDDEN default_detail = 'Insufficient permissions for the request.'", "NodeNotFoundError(GraphAPIError): status_code = status.HTTP_404_NOT_FOUND def __init__(self, id): self.id = id", "node_type super(NodeTypeNotFoundError, self).__init__(\"Node type '{}' does not exist.\".format(node_type)) class MissingNodeTypeError(GraphAPIError):", "PermissionDenied(GraphAPIError): status_code = status.HTTP_403_FORBIDDEN default_detail = 'Insufficient permissions for the", "status_code = status.HTTP_404_NOT_FOUND def __init__(self, node_type): self.node_type = node_type super(NodeTypeNotFoundError,", "class NodeTypeNotFoundError(GraphAPIError): status_code = status.HTTP_404_NOT_FOUND def __init__(self, node_type): self.node_type =", "= status.HTTP_404_NOT_FOUND def __init__(self, id): self.id = id super(NodeNotFoundError, self).__init__(\"Node", "status.HTTP_400_BAD_REQUEST class MalformedUpdateDictionaryError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class InvalidPropertyError(GraphAPIError): status_code =", "InvalidPropertyError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class InvalidValueError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class", "self.node_type = node_type super(NodeTypeNotFoundError, self).__init__(\"Node type '{}' does not exist.\".format(node_type))", "node requires a type. \"\"\" status_code = status.HTTP_400_BAD_REQUEST class MalformedUpdateDictionaryError(GraphAPIError):", "exceptions in this module.\"\"\" pass class NodeNotFoundError(GraphAPIError): status_code = status.HTTP_404_NOT_FOUND", "status class GraphAPIError(APIException): \"\"\"Base class for exceptions in this module.\"\"\"", "not exist.\".format(node_type)) class MissingNodeTypeError(GraphAPIError): \"\"\" Creating a node requires a", "type. \"\"\" status_code = status.HTTP_400_BAD_REQUEST class MalformedUpdateDictionaryError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST", "rest_framework.exceptions import APIException from rest_framework import status class GraphAPIError(APIException): \"\"\"Base", "does not exist.\".format(node_type)) class MissingNodeTypeError(GraphAPIError): \"\"\" Creating a node requires", "status_code = status.HTTP_400_BAD_REQUEST class InvalidPropertyError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class InvalidValueError(GraphAPIError):", "self.id = id super(NodeNotFoundError, self).__init__(\"Node with id '{}' does not", "module.\"\"\" pass class NodeNotFoundError(GraphAPIError): status_code = status.HTTP_404_NOT_FOUND def __init__(self, id):", "'{}' does not exist.\".format(id)) class NodeTypeNotFoundError(GraphAPIError): status_code = status.HTTP_404_NOT_FOUND def", "requires a type. \"\"\" status_code = status.HTTP_400_BAD_REQUEST class MalformedUpdateDictionaryError(GraphAPIError): status_code", "= status.HTTP_400_BAD_REQUEST class PermissionDenied(GraphAPIError): status_code = status.HTTP_403_FORBIDDEN default_detail = 'Insufficient", "in this module.\"\"\" pass class NodeNotFoundError(GraphAPIError): status_code = status.HTTP_404_NOT_FOUND def", "exist.\".format(id)) class NodeTypeNotFoundError(GraphAPIError): status_code = status.HTTP_404_NOT_FOUND def __init__(self, node_type): self.node_type", "super(NodeNotFoundError, self).__init__(\"Node with id '{}' does not exist.\".format(id)) class NodeTypeNotFoundError(GraphAPIError):", "status_code = status.HTTP_400_BAD_REQUEST class MalformedUpdateDictionaryError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class InvalidPropertyError(GraphAPIError):", "a type. \"\"\" status_code = status.HTTP_400_BAD_REQUEST class MalformedUpdateDictionaryError(GraphAPIError): status_code =", "this module.\"\"\" pass class NodeNotFoundError(GraphAPIError): status_code = status.HTTP_404_NOT_FOUND def __init__(self,", "class PermissionDenied(GraphAPIError): status_code = status.HTTP_403_FORBIDDEN default_detail = 'Insufficient permissions for", "status.HTTP_404_NOT_FOUND def __init__(self, id): self.id = id super(NodeNotFoundError, self).__init__(\"Node with", "= id super(NodeNotFoundError, self).__init__(\"Node with id '{}' does not exist.\".format(id))", "Creating a node requires a type. \"\"\" status_code = status.HTTP_400_BAD_REQUEST", "MissingNodeTypeError(GraphAPIError): \"\"\" Creating a node requires a type. \"\"\" status_code", "from rest_framework import status class GraphAPIError(APIException): \"\"\"Base class for exceptions", "status.HTTP_400_BAD_REQUEST class InvalidValueError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class PermissionDenied(GraphAPIError): status_code =", "status_code = status.HTTP_400_BAD_REQUEST class PermissionDenied(GraphAPIError): status_code = status.HTTP_403_FORBIDDEN default_detail =", "__init__(self, id): self.id = id super(NodeNotFoundError, self).__init__(\"Node with id '{}'", "= status.HTTP_404_NOT_FOUND def __init__(self, node_type): self.node_type = node_type super(NodeTypeNotFoundError, self).__init__(\"Node", "exist.\".format(node_type)) class MissingNodeTypeError(GraphAPIError): \"\"\" Creating a node requires a type.", "class for exceptions in this module.\"\"\" pass class NodeNotFoundError(GraphAPIError): status_code", "pass class NodeNotFoundError(GraphAPIError): status_code = status.HTTP_404_NOT_FOUND def __init__(self, id): self.id", "class InvalidValueError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class PermissionDenied(GraphAPIError): status_code = status.HTTP_403_FORBIDDEN", "self).__init__(\"Node type '{}' does not exist.\".format(node_type)) class MissingNodeTypeError(GraphAPIError): \"\"\" Creating", "import status class GraphAPIError(APIException): \"\"\"Base class for exceptions in this", "id super(NodeNotFoundError, self).__init__(\"Node with id '{}' does not exist.\".format(id)) class", "type '{}' does not exist.\".format(node_type)) class MissingNodeTypeError(GraphAPIError): \"\"\" Creating a", "from rest_framework.exceptions import APIException from rest_framework import status class GraphAPIError(APIException):", "class MissingNodeTypeError(GraphAPIError): \"\"\" Creating a node requires a type. \"\"\"", "class MalformedUpdateDictionaryError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class InvalidPropertyError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST", "def __init__(self, node_type): self.node_type = node_type super(NodeTypeNotFoundError, self).__init__(\"Node type '{}'", "id '{}' does not exist.\".format(id)) class NodeTypeNotFoundError(GraphAPIError): status_code = status.HTTP_404_NOT_FOUND", "a node requires a type. \"\"\" status_code = status.HTTP_400_BAD_REQUEST class", "'{}' does not exist.\".format(node_type)) class MissingNodeTypeError(GraphAPIError): \"\"\" Creating a node", "not exist.\".format(id)) class NodeTypeNotFoundError(GraphAPIError): status_code = status.HTTP_404_NOT_FOUND def __init__(self, node_type):", "class NodeNotFoundError(GraphAPIError): status_code = status.HTTP_404_NOT_FOUND def __init__(self, id): self.id =", "status.HTTP_404_NOT_FOUND def __init__(self, node_type): self.node_type = node_type super(NodeTypeNotFoundError, self).__init__(\"Node type", "APIException from rest_framework import status class GraphAPIError(APIException): \"\"\"Base class for", "status_code = status.HTTP_404_NOT_FOUND def __init__(self, id): self.id = id super(NodeNotFoundError,", "__init__(self, node_type): self.node_type = node_type super(NodeTypeNotFoundError, self).__init__(\"Node type '{}' does", "status_code = status.HTTP_400_BAD_REQUEST class InvalidValueError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class PermissionDenied(GraphAPIError):", "for exceptions in this module.\"\"\" pass class NodeNotFoundError(GraphAPIError): status_code =", "self).__init__(\"Node with id '{}' does not exist.\".format(id)) class NodeTypeNotFoundError(GraphAPIError): status_code", "NodeTypeNotFoundError(GraphAPIError): status_code = status.HTTP_404_NOT_FOUND def __init__(self, node_type): self.node_type = node_type", "status.HTTP_400_BAD_REQUEST class PermissionDenied(GraphAPIError): status_code = status.HTTP_403_FORBIDDEN default_detail = 'Insufficient permissions", "import APIException from rest_framework import status class GraphAPIError(APIException): \"\"\"Base class", "status.HTTP_400_BAD_REQUEST class InvalidPropertyError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class InvalidValueError(GraphAPIError): status_code =", "\"\"\"Base class for exceptions in this module.\"\"\" pass class NodeNotFoundError(GraphAPIError):", "class GraphAPIError(APIException): \"\"\"Base class for exceptions in this module.\"\"\" pass", "id): self.id = id super(NodeNotFoundError, self).__init__(\"Node with id '{}' does", "InvalidValueError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class PermissionDenied(GraphAPIError): status_code = status.HTTP_403_FORBIDDEN default_detail", "super(NodeTypeNotFoundError, self).__init__(\"Node type '{}' does not exist.\".format(node_type)) class MissingNodeTypeError(GraphAPIError): \"\"\"", "= status.HTTP_400_BAD_REQUEST class InvalidValueError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class PermissionDenied(GraphAPIError): status_code", "= status.HTTP_400_BAD_REQUEST class MalformedUpdateDictionaryError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class InvalidPropertyError(GraphAPIError): status_code", "class InvalidPropertyError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST class InvalidValueError(GraphAPIError): status_code = status.HTTP_400_BAD_REQUEST", "with id '{}' does not exist.\".format(id)) class NodeTypeNotFoundError(GraphAPIError): status_code =", "rest_framework import status class GraphAPIError(APIException): \"\"\"Base class for exceptions in", "does not exist.\".format(id)) class NodeTypeNotFoundError(GraphAPIError): status_code = status.HTTP_404_NOT_FOUND def __init__(self,", "node_type): self.node_type = node_type super(NodeTypeNotFoundError, self).__init__(\"Node type '{}' does not" ]
[ "# Author: LeonardoM011<<EMAIL>> # Created on 2021-02-05 21:56 # Set", "connect to binance with api keys.') def main(): output.print_ok('Starting kobe", "# time.sleep(5.0) # client.futures_create_order(symbol=\"BTCUSDT\", side=\"SELL\", type=\"STOP\", quantity=0.001, price=57975.0, stopPrice=57976.0, workingType=\"MARK_PRICE\")", "while True: api_key = get_api_key(\"BINANCE_API_KEY\") api_secret = get_api_key(\"BINANCE_API_SECRET_KEY\") output.print_info('Connecting to", "hour t.sleep(300) except KeyboardInterrupt: print('Program canceled...') def connect(): while True:", "client.futures_get_open_orders() if minute < 10: if not open_trade and hour_repeated", "can # Globals: client = None # Main program loop", "and got price\") #while(True): # btcusdt_price = requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") # print(\"BTC/USDT:", "quantity=0.001, price=57975.0, stopPrice=57976.0, workingType=\"MARK_PRICE\") hour_repeated = hour t.sleep(300) except KeyboardInterrupt:", "bot using binance api # Author: LeonardoM011<<EMAIL>> # Created on", "# time.sleep(1.0) #btcusdtindex = find_index_of('symbol', 'BTCUSDT', client.get_all_tickers()) #while (True): #", "print('Program canceled...') def connect(): while True: api_key = get_api_key(\"BINANCE_API_KEY\") api_secret", "Client from fun import * import candles as can #", "find_index_of('symbol', 'BTCUSDT', client.get_all_tickers()) #while (True): # print(client.get_all_tickers()[btcusdtindex]) # time.sleep(5.0) #", "to binance with api keys.') def main(): output.print_ok('Starting kobe trading", "new trade (in seconds) # ---------------------- # Imports: import os", "None # Main program loop def start(): hour_repeated = -1", "{}\".format(btcusdt_price.json()['price'])) # time.sleep(1.0) #btcusdtindex = find_index_of('symbol', 'BTCUSDT', client.get_all_tickers()) #while (True):", "api keys.') return output.print_failed('Cannot connect to binance with api keys.')", "# datetime.datetime.now().year #btcusdt_price = requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") #if (btcusdt_price.status_code != 200): #", "canceled...') def connect(): while True: api_key = get_api_key(\"BINANCE_API_KEY\") api_secret =", "# print(\"Error connecting to api server to get price\") #", "for setting up new trade (in seconds) # ---------------------- #", "fun import * import candles as can # Globals: client", "= get_api_key(\"BINANCE_API_SECRET_KEY\") output.print_info('Connecting to binance...') global client client = Client(api_key,", "can we check for setting up new trade (in seconds)", "api # Author: LeonardoM011<<EMAIL>> # Created on 2021-02-05 21:56 #", "connected using api keys.') return output.print_failed('Cannot connect to binance with", "get price\") # return #print(\"Successfully connected and got price\") #while(True):", "sys import time as t import datetime # Adding python-binance", "return #print(\"Successfully connected and got price\") #while(True): # btcusdt_price =", "(True): # print(client.get_all_tickers()[btcusdtindex]) # time.sleep(5.0) # client.futures_create_order(symbol=\"BTCUSDT\", side=\"SELL\", type=\"STOP\", quantity=0.001,", "price\") # return #print(\"Successfully connected and got price\") #while(True): #", "Author: LeonardoM011<<EMAIL>> # Created on 2021-02-05 21:56 # Set constants", "hour_repeated != hour: candles = client.futures_klines(symbol=\"BTCUSDT\", interval=Client.KLINE_INTERVAL_1HOUR, contractType=\"PERPETUAL\") info =", "stopPrice=57976.0, workingType=\"MARK_PRICE\") # client.futures_create_order(symbol=\"BTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.001) if __name__ ==", "open_trade and hour_repeated != hour: candles = client.futures_klines(symbol=\"BTCUSDT\", interval=Client.KLINE_INTERVAL_1HOUR, contractType=\"PERPETUAL\")", "and hour_repeated != hour: candles = client.futures_klines(symbol=\"BTCUSDT\", interval=Client.KLINE_INTERVAL_1HOUR, contractType=\"PERPETUAL\") info", "candles client.futures_create_order(symbol=\"BTCUSDT\", side=candle_side, type=Client.ORDER_TYPE_MARKET, quantity=0.001) client.futures_create_order(symbol=\"BTCUSDT\", side=can.flip_side(candle_side), type=Client.ORDER_TYPE_STOP_LOSS_LIMIT, quantity=0.001, price=57975.0,", "time.sleep(5.0) # client.futures_create_order(symbol=\"BTCUSDT\", side=\"SELL\", type=\"STOP\", quantity=0.001, price=57975.0, stopPrice=57976.0, workingType=\"MARK_PRICE\") #", "import os import sys import time as t import datetime", "# Imports: import os import sys import time as t", "#try: # client.get_all_orders() #except BinanceAPIException as e: # print e.status_code", "#while(True): # btcusdt_price = requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") # print(\"BTC/USDT: {}\".format(btcusdt_price.json()['price'])) # time.sleep(1.0)", "workingType=\"MARK_PRICE\") # client.futures_create_order(symbol=\"BTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.001) if __name__ == \"__main__\":", "# client.futures_create_order(symbol=\"BTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.001) if __name__ == \"__main__\": main()", "workingType=\"MARK_PRICE\") hour_repeated = hour t.sleep(300) except KeyboardInterrupt: print('Program canceled...') def", "loop def start(): hour_repeated = -1 try: while True: time", "can.get_candle_info(candles[:-1]) candle_side = can.get_side(info) if candle_side: output.print_info('Initiating trade...') #current_price =", "time.hour minute = time.minute open_trade = client.futures_get_open_orders() if minute <", "connected to binance.') if check_account_status(client): output.print_ok('Successfully connected using api keys.')", "hour = time.hour minute = time.minute open_trade = client.futures_get_open_orders() if", "# print e.status_code # print e.message # datetime.datetime.now().year #btcusdt_price =", "api_secret) if check_connectivity(client): output.print_ok('Successfully connected to binance.') if check_account_status(client): output.print_ok('Successfully", "= candles client.futures_create_order(symbol=\"BTCUSDT\", side=candle_side, type=Client.ORDER_TYPE_MARKET, quantity=0.001) client.futures_create_order(symbol=\"BTCUSDT\", side=can.flip_side(candle_side), type=Client.ORDER_TYPE_STOP_LOSS_LIMIT, quantity=0.001,", "side=\"SELL\", type=\"STOP\", quantity=0.001, price=57975.0, stopPrice=57976.0, workingType=\"MARK_PRICE\") # client.futures_create_order(symbol=\"BTCUSDT\", side=\"BUY\", type=\"MARKET\",", "connect() start() #try: # client.get_all_orders() #except BinanceAPIException as e: #", "= client.futures_klines(symbol=\"BTCUSDT\", interval=Client.KLINE_INTERVAL_1HOUR, contractType=\"PERPETUAL\") info = can.get_candle_info(candles[:-1]) candle_side = can.get_side(info)", "start() #try: # client.get_all_orders() #except BinanceAPIException as e: # print", "e.status_code # print e.message # datetime.datetime.now().year #btcusdt_price = requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") #if", "with api keys.') def main(): output.print_ok('Starting kobe trading bot...') connect()", "21:56 # Set constants here: DELTA_TIME = 300 # How", "10: if not open_trade and hour_repeated != hour: candles =", "!= 200): # print(\"Error connecting to api server to get", "requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") # print(\"BTC/USDT: {}\".format(btcusdt_price.json()['price'])) # time.sleep(1.0) #btcusdtindex = find_index_of('symbol', 'BTCUSDT',", "and importing python-binance sys.path.insert(1, \"../deps/binance\") from binance.client import Client from", "side=candle_side, type=Client.ORDER_TYPE_MARKET, quantity=0.001) client.futures_create_order(symbol=\"BTCUSDT\", side=can.flip_side(candle_side), type=Client.ORDER_TYPE_STOP_LOSS_LIMIT, quantity=0.001, price=57975.0, stopPrice=57976.0, workingType=\"MARK_PRICE\")", "< 10: if not open_trade and hour_repeated != hour: candles", "trading bot using binance api # Author: LeonardoM011<<EMAIL>> # Created", "# ---------------------- # Imports: import os import sys import time", "print e.status_code # print e.message # datetime.datetime.now().year #btcusdt_price = requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\")", "trade (in seconds) # ---------------------- # Imports: import os import", "to path and importing python-binance sys.path.insert(1, \"../deps/binance\") from binance.client import", "Set constants here: DELTA_TIME = 300 # How long can", "client = Client(api_key, api_secret) if check_connectivity(client): output.print_ok('Successfully connected to binance.')", "as can # Globals: client = None # Main program", "type=Client.ORDER_TYPE_MARKET, quantity=0.001) client.futures_create_order(symbol=\"BTCUSDT\", side=can.flip_side(candle_side), type=Client.ORDER_TYPE_STOP_LOSS_LIMIT, quantity=0.001, price=57975.0, stopPrice=57976.0, workingType=\"MARK_PRICE\") hour_repeated", "price=57975.0, stopPrice=57976.0, workingType=\"MARK_PRICE\") hour_repeated = hour t.sleep(300) except KeyboardInterrupt: print('Program", "as t import datetime # Adding python-binance to path and", "trading bot...') connect() start() #try: # client.get_all_orders() #except BinanceAPIException as", "# print(client.get_all_tickers()[btcusdtindex]) # time.sleep(5.0) # client.futures_create_order(symbol=\"BTCUSDT\", side=\"SELL\", type=\"STOP\", quantity=0.001, price=57975.0,", "= None # Main program loop def start(): hour_repeated =", "to binance.') if check_account_status(client): output.print_ok('Successfully connected using api keys.') return", "output.print_ok('Successfully connected using api keys.') return output.print_failed('Cannot connect to binance", "open_trade = client.futures_get_open_orders() if minute < 10: if not open_trade", "to binance...') global client client = Client(api_key, api_secret) if check_connectivity(client):", "import Client from fun import * import candles as can", "How long can we check for setting up new trade", "if not open_trade and hour_repeated != hour: candles = client.futures_klines(symbol=\"BTCUSDT\",", "keys.') def main(): output.print_ok('Starting kobe trading bot...') connect() start() #try:", "connect(): while True: api_key = get_api_key(\"BINANCE_API_KEY\") api_secret = get_api_key(\"BINANCE_API_SECRET_KEY\") output.print_info('Connecting", "= hour t.sleep(300) except KeyboardInterrupt: print('Program canceled...') def connect(): while", "def main(): output.print_ok('Starting kobe trading bot...') connect() start() #try: #", "output.print_info('Initiating trade...') #current_price = client.futures_mark_price(symbol=\"BTCUSDT\", contractType=\"PERPETUAL\")['markPrice'] close_price = candles client.futures_create_order(symbol=\"BTCUSDT\",", "Created on 2021-02-05 21:56 # Set constants here: DELTA_TIME =", "not open_trade and hour_repeated != hour: candles = client.futures_klines(symbol=\"BTCUSDT\", interval=Client.KLINE_INTERVAL_1HOUR,", "candles as can # Globals: client = None # Main", "#print(\"Successfully connected and got price\") #while(True): # btcusdt_price = requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\")", "= datetime.datetime.now() hour = time.hour minute = time.minute open_trade =", "candle_side: output.print_info('Initiating trade...') #current_price = client.futures_mark_price(symbol=\"BTCUSDT\", contractType=\"PERPETUAL\")['markPrice'] close_price = candles", "= client.futures_mark_price(symbol=\"BTCUSDT\", contractType=\"PERPETUAL\")['markPrice'] close_price = candles client.futures_create_order(symbol=\"BTCUSDT\", side=candle_side, type=Client.ORDER_TYPE_MARKET, quantity=0.001)", "Client(api_key, api_secret) if check_connectivity(client): output.print_ok('Successfully connected to binance.') if check_account_status(client):", "stopPrice=57976.0, workingType=\"MARK_PRICE\") hour_repeated = hour t.sleep(300) except KeyboardInterrupt: print('Program canceled...')", "if minute < 10: if not open_trade and hour_repeated !=", "True: api_key = get_api_key(\"BINANCE_API_KEY\") api_secret = get_api_key(\"BINANCE_API_SECRET_KEY\") output.print_info('Connecting to binance...')", "= requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") #if (btcusdt_price.status_code != 200): # print(\"Error connecting to", "api server to get price\") # return #print(\"Successfully connected and", "client.futures_create_order(symbol=\"BTCUSDT\", side=can.flip_side(candle_side), type=Client.ORDER_TYPE_STOP_LOSS_LIMIT, quantity=0.001, price=57975.0, stopPrice=57976.0, workingType=\"MARK_PRICE\") hour_repeated = hour", "import * import candles as can # Globals: client =", "# client.get_all_orders() #except BinanceAPIException as e: # print e.status_code #", "#!/usr/bin/env python3 # Crypto trading bot using binance api #", "#btcusdt_price = requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") #if (btcusdt_price.status_code != 200): # print(\"Error connecting", "to api server to get price\") # return #print(\"Successfully connected", "contractType=\"PERPETUAL\")['markPrice'] close_price = candles client.futures_create_order(symbol=\"BTCUSDT\", side=candle_side, type=Client.ORDER_TYPE_MARKET, quantity=0.001) client.futures_create_order(symbol=\"BTCUSDT\", side=can.flip_side(candle_side),", "= requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") # print(\"BTC/USDT: {}\".format(btcusdt_price.json()['price'])) # time.sleep(1.0) #btcusdtindex = find_index_of('symbol',", "e: # print e.status_code # print e.message # datetime.datetime.now().year #btcusdt_price", "check_account_status(client): output.print_ok('Successfully connected using api keys.') return output.print_failed('Cannot connect to", "300 # How long can we check for setting up", "import time as t import datetime # Adding python-binance to", "---------------------- # Imports: import os import sys import time as", "# Main program loop def start(): hour_repeated = -1 try:", "print e.message # datetime.datetime.now().year #btcusdt_price = requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") #if (btcusdt_price.status_code !=", "output.print_ok('Successfully connected to binance.') if check_account_status(client): output.print_ok('Successfully connected using api", "api_key = get_api_key(\"BINANCE_API_KEY\") api_secret = get_api_key(\"BINANCE_API_SECRET_KEY\") output.print_info('Connecting to binance...') global", "interval=Client.KLINE_INTERVAL_1HOUR, contractType=\"PERPETUAL\") info = can.get_candle_info(candles[:-1]) candle_side = can.get_side(info) if candle_side:", "client.get_all_tickers()) #while (True): # print(client.get_all_tickers()[btcusdtindex]) # time.sleep(5.0) # client.futures_create_order(symbol=\"BTCUSDT\", side=\"SELL\",", "print(client.get_all_tickers()[btcusdtindex]) # time.sleep(5.0) # client.futures_create_order(symbol=\"BTCUSDT\", side=\"SELL\", type=\"STOP\", quantity=0.001, price=57975.0, stopPrice=57976.0,", "info = can.get_candle_info(candles[:-1]) candle_side = can.get_side(info) if candle_side: output.print_info('Initiating trade...')", "setting up new trade (in seconds) # ---------------------- # Imports:", "btcusdt_price = requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") # print(\"BTC/USDT: {}\".format(btcusdt_price.json()['price'])) # time.sleep(1.0) #btcusdtindex =", "# Globals: client = None # Main program loop def", "from fun import * import candles as can # Globals:", "python-binance to path and importing python-binance sys.path.insert(1, \"../deps/binance\") from binance.client", "200): # print(\"Error connecting to api server to get price\")", "up new trade (in seconds) # ---------------------- # Imports: import", "#while (True): # print(client.get_all_tickers()[btcusdtindex]) # time.sleep(5.0) # client.futures_create_order(symbol=\"BTCUSDT\", side=\"SELL\", type=\"STOP\",", "KeyboardInterrupt: print('Program canceled...') def connect(): while True: api_key = get_api_key(\"BINANCE_API_KEY\")", "= find_index_of('symbol', 'BTCUSDT', client.get_all_tickers()) #while (True): # print(client.get_all_tickers()[btcusdtindex]) # time.sleep(5.0)", "hour_repeated = -1 try: while True: time = datetime.datetime.now() hour", "2021-02-05 21:56 # Set constants here: DELTA_TIME = 300 #", "-1 try: while True: time = datetime.datetime.now() hour = time.hour", "type=\"STOP\", quantity=0.001, price=57975.0, stopPrice=57976.0, workingType=\"MARK_PRICE\") # client.futures_create_order(symbol=\"BTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.001)", "quantity=0.001) client.futures_create_order(symbol=\"BTCUSDT\", side=can.flip_side(candle_side), type=Client.ORDER_TYPE_STOP_LOSS_LIMIT, quantity=0.001, price=57975.0, stopPrice=57976.0, workingType=\"MARK_PRICE\") hour_repeated =", "!= hour: candles = client.futures_klines(symbol=\"BTCUSDT\", interval=Client.KLINE_INTERVAL_1HOUR, contractType=\"PERPETUAL\") info = can.get_candle_info(candles[:-1])", "# Crypto trading bot using binance api # Author: LeonardoM011<<EMAIL>>", "e.message # datetime.datetime.now().year #btcusdt_price = requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") #if (btcusdt_price.status_code != 200):", "'BTCUSDT', client.get_all_tickers()) #while (True): # print(client.get_all_tickers()[btcusdtindex]) # time.sleep(5.0) # client.futures_create_order(symbol=\"BTCUSDT\",", "\"../deps/binance\") from binance.client import Client from fun import * import", "output.print_failed('Cannot connect to binance with api keys.') def main(): output.print_ok('Starting", "time = datetime.datetime.now() hour = time.hour minute = time.minute open_trade", "= get_api_key(\"BINANCE_API_KEY\") api_secret = get_api_key(\"BINANCE_API_SECRET_KEY\") output.print_info('Connecting to binance...') global client", "time.minute open_trade = client.futures_get_open_orders() if minute < 10: if not", "long can we check for setting up new trade (in", "on 2021-02-05 21:56 # Set constants here: DELTA_TIME = 300", "t import datetime # Adding python-binance to path and importing", "def connect(): while True: api_key = get_api_key(\"BINANCE_API_KEY\") api_secret = get_api_key(\"BINANCE_API_SECRET_KEY\")", "binance...') global client client = Client(api_key, api_secret) if check_connectivity(client): output.print_ok('Successfully", "Imports: import os import sys import time as t import", "print(\"Error connecting to api server to get price\") # return", "type=Client.ORDER_TYPE_STOP_LOSS_LIMIT, quantity=0.001, price=57975.0, stopPrice=57976.0, workingType=\"MARK_PRICE\") hour_repeated = hour t.sleep(300) except", "minute = time.minute open_trade = client.futures_get_open_orders() if minute < 10:", "close_price = candles client.futures_create_order(symbol=\"BTCUSDT\", side=candle_side, type=Client.ORDER_TYPE_MARKET, quantity=0.001) client.futures_create_order(symbol=\"BTCUSDT\", side=can.flip_side(candle_side), type=Client.ORDER_TYPE_STOP_LOSS_LIMIT,", "if check_account_status(client): output.print_ok('Successfully connected using api keys.') return output.print_failed('Cannot connect", "# btcusdt_price = requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") # print(\"BTC/USDT: {}\".format(btcusdt_price.json()['price'])) # time.sleep(1.0) #btcusdtindex", "= client.futures_get_open_orders() if minute < 10: if not open_trade and", "sys.path.insert(1, \"../deps/binance\") from binance.client import Client from fun import *", "using api keys.') return output.print_failed('Cannot connect to binance with api", "client.get_all_orders() #except BinanceAPIException as e: # print e.status_code # print", "quantity=0.001, price=57975.0, stopPrice=57976.0, workingType=\"MARK_PRICE\") # client.futures_create_order(symbol=\"BTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.001) if", "client.futures_create_order(symbol=\"BTCUSDT\", side=candle_side, type=Client.ORDER_TYPE_MARKET, quantity=0.001) client.futures_create_order(symbol=\"BTCUSDT\", side=can.flip_side(candle_side), type=Client.ORDER_TYPE_STOP_LOSS_LIMIT, quantity=0.001, price=57975.0, stopPrice=57976.0,", "check_connectivity(client): output.print_ok('Successfully connected to binance.') if check_account_status(client): output.print_ok('Successfully connected using", "main(): output.print_ok('Starting kobe trading bot...') connect() start() #try: # client.get_all_orders()", "datetime.datetime.now().year #btcusdt_price = requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") #if (btcusdt_price.status_code != 200): # print(\"Error", "contractType=\"PERPETUAL\") info = can.get_candle_info(candles[:-1]) candle_side = can.get_side(info) if candle_side: output.print_info('Initiating", "price\") #while(True): # btcusdt_price = requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") # print(\"BTC/USDT: {}\".format(btcusdt_price.json()['price'])) #", "time.sleep(1.0) #btcusdtindex = find_index_of('symbol', 'BTCUSDT', client.get_all_tickers()) #while (True): # print(client.get_all_tickers()[btcusdtindex])", "import datetime # Adding python-binance to path and importing python-binance", "# client.futures_create_order(symbol=\"BTCUSDT\", side=\"SELL\", type=\"STOP\", quantity=0.001, price=57975.0, stopPrice=57976.0, workingType=\"MARK_PRICE\") # client.futures_create_order(symbol=\"BTCUSDT\",", "BinanceAPIException as e: # print e.status_code # print e.message #", "True: time = datetime.datetime.now() hour = time.hour minute = time.minute", "side=can.flip_side(candle_side), type=Client.ORDER_TYPE_STOP_LOSS_LIMIT, quantity=0.001, price=57975.0, stopPrice=57976.0, workingType=\"MARK_PRICE\") hour_repeated = hour t.sleep(300)", "get_api_key(\"BINANCE_API_KEY\") api_secret = get_api_key(\"BINANCE_API_SECRET_KEY\") output.print_info('Connecting to binance...') global client client", "while True: time = datetime.datetime.now() hour = time.hour minute =", "candles = client.futures_klines(symbol=\"BTCUSDT\", interval=Client.KLINE_INTERVAL_1HOUR, contractType=\"PERPETUAL\") info = can.get_candle_info(candles[:-1]) candle_side =", "os import sys import time as t import datetime #", "output.print_info('Connecting to binance...') global client client = Client(api_key, api_secret) if", "kobe trading bot...') connect() start() #try: # client.get_all_orders() #except BinanceAPIException", "check for setting up new trade (in seconds) # ----------------------", "Globals: client = None # Main program loop def start():", "here: DELTA_TIME = 300 # How long can we check", "api keys.') def main(): output.print_ok('Starting kobe trading bot...') connect() start()", "api_secret = get_api_key(\"BINANCE_API_SECRET_KEY\") output.print_info('Connecting to binance...') global client client =", "client.futures_mark_price(symbol=\"BTCUSDT\", contractType=\"PERPETUAL\")['markPrice'] close_price = candles client.futures_create_order(symbol=\"BTCUSDT\", side=candle_side, type=Client.ORDER_TYPE_MARKET, quantity=0.001) client.futures_create_order(symbol=\"BTCUSDT\",", "#except BinanceAPIException as e: # print e.status_code # print e.message", "binance with api keys.') def main(): output.print_ok('Starting kobe trading bot...')", "# Created on 2021-02-05 21:56 # Set constants here: DELTA_TIME", "constants here: DELTA_TIME = 300 # How long can we", "client.futures_klines(symbol=\"BTCUSDT\", interval=Client.KLINE_INTERVAL_1HOUR, contractType=\"PERPETUAL\") info = can.get_candle_info(candles[:-1]) candle_side = can.get_side(info) if", "# Adding python-binance to path and importing python-binance sys.path.insert(1, \"../deps/binance\")", "python3 # Crypto trading bot using binance api # Author:", "output.print_ok('Starting kobe trading bot...') connect() start() #try: # client.get_all_orders() #except", "# print e.message # datetime.datetime.now().year #btcusdt_price = requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") #if (btcusdt_price.status_code", "connected and got price\") #while(True): # btcusdt_price = requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") #", "* import candles as can # Globals: client = None", "client = None # Main program loop def start(): hour_repeated", "= -1 try: while True: time = datetime.datetime.now() hour =", "client client = Client(api_key, api_secret) if check_connectivity(client): output.print_ok('Successfully connected to", "time as t import datetime # Adding python-binance to path", "import sys import time as t import datetime # Adding", "= can.get_side(info) if candle_side: output.print_info('Initiating trade...') #current_price = client.futures_mark_price(symbol=\"BTCUSDT\", contractType=\"PERPETUAL\")['markPrice']", "bot...') connect() start() #try: # client.get_all_orders() #except BinanceAPIException as e:", "datetime # Adding python-binance to path and importing python-binance sys.path.insert(1,", "get_api_key(\"BINANCE_API_SECRET_KEY\") output.print_info('Connecting to binance...') global client client = Client(api_key, api_secret)", "start(): hour_repeated = -1 try: while True: time = datetime.datetime.now()", "def start(): hour_repeated = -1 try: while True: time =", "using binance api # Author: LeonardoM011<<EMAIL>> # Created on 2021-02-05", "print(\"BTC/USDT: {}\".format(btcusdt_price.json()['price'])) # time.sleep(1.0) #btcusdtindex = find_index_of('symbol', 'BTCUSDT', client.get_all_tickers()) #while", "binance api # Author: LeonardoM011<<EMAIL>> # Created on 2021-02-05 21:56", "Crypto trading bot using binance api # Author: LeonardoM011<<EMAIL>> #", "(in seconds) # ---------------------- # Imports: import os import sys", "binance.client import Client from fun import * import candles as", "# Set constants here: DELTA_TIME = 300 # How long", "python-binance sys.path.insert(1, \"../deps/binance\") from binance.client import Client from fun import", "binance.') if check_account_status(client): output.print_ok('Successfully connected using api keys.') return output.print_failed('Cannot", "except KeyboardInterrupt: print('Program canceled...') def connect(): while True: api_key =", "#btcusdtindex = find_index_of('symbol', 'BTCUSDT', client.get_all_tickers()) #while (True): # print(client.get_all_tickers()[btcusdtindex]) #", "= time.hour minute = time.minute open_trade = client.futures_get_open_orders() if minute", "minute < 10: if not open_trade and hour_repeated != hour:", "trade...') #current_price = client.futures_mark_price(symbol=\"BTCUSDT\", contractType=\"PERPETUAL\")['markPrice'] close_price = candles client.futures_create_order(symbol=\"BTCUSDT\", side=candle_side,", "#if (btcusdt_price.status_code != 200): # print(\"Error connecting to api server", "server to get price\") # return #print(\"Successfully connected and got", "if candle_side: output.print_info('Initiating trade...') #current_price = client.futures_mark_price(symbol=\"BTCUSDT\", contractType=\"PERPETUAL\")['markPrice'] close_price =", "keys.') return output.print_failed('Cannot connect to binance with api keys.') def", "we check for setting up new trade (in seconds) #", "path and importing python-binance sys.path.insert(1, \"../deps/binance\") from binance.client import Client", "got price\") #while(True): # btcusdt_price = requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") # print(\"BTC/USDT: {}\".format(btcusdt_price.json()['price']))", "= 300 # How long can we check for setting", "can.get_side(info) if candle_side: output.print_info('Initiating trade...') #current_price = client.futures_mark_price(symbol=\"BTCUSDT\", contractType=\"PERPETUAL\")['markPrice'] close_price", "requests.get(\"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\") #if (btcusdt_price.status_code != 200): # print(\"Error connecting to api", "= can.get_candle_info(candles[:-1]) candle_side = can.get_side(info) if candle_side: output.print_info('Initiating trade...') #current_price", "(btcusdt_price.status_code != 200): # print(\"Error connecting to api server to", "connecting to api server to get price\") # return #print(\"Successfully", "as e: # print e.status_code # print e.message # datetime.datetime.now().year", "# How long can we check for setting up new", "= time.minute open_trade = client.futures_get_open_orders() if minute < 10: if", "LeonardoM011<<EMAIL>> # Created on 2021-02-05 21:56 # Set constants here:", "to get price\") # return #print(\"Successfully connected and got price\")", "importing python-binance sys.path.insert(1, \"../deps/binance\") from binance.client import Client from fun", "datetime.datetime.now() hour = time.hour minute = time.minute open_trade = client.futures_get_open_orders()", "= Client(api_key, api_secret) if check_connectivity(client): output.print_ok('Successfully connected to binance.') if", "# return #print(\"Successfully connected and got price\") #while(True): # btcusdt_price", "client.futures_create_order(symbol=\"BTCUSDT\", side=\"SELL\", type=\"STOP\", quantity=0.001, price=57975.0, stopPrice=57976.0, workingType=\"MARK_PRICE\") # client.futures_create_order(symbol=\"BTCUSDT\", side=\"BUY\",", "seconds) # ---------------------- # Imports: import os import sys import", "if check_connectivity(client): output.print_ok('Successfully connected to binance.') if check_account_status(client): output.print_ok('Successfully connected", "Main program loop def start(): hour_repeated = -1 try: while", "DELTA_TIME = 300 # How long can we check for", "#current_price = client.futures_mark_price(symbol=\"BTCUSDT\", contractType=\"PERPETUAL\")['markPrice'] close_price = candles client.futures_create_order(symbol=\"BTCUSDT\", side=candle_side, type=Client.ORDER_TYPE_MARKET,", "try: while True: time = datetime.datetime.now() hour = time.hour minute", "price=57975.0, stopPrice=57976.0, workingType=\"MARK_PRICE\") # client.futures_create_order(symbol=\"BTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.001) if __name__", "global client client = Client(api_key, api_secret) if check_connectivity(client): output.print_ok('Successfully connected", "program loop def start(): hour_repeated = -1 try: while True:", "candle_side = can.get_side(info) if candle_side: output.print_info('Initiating trade...') #current_price = client.futures_mark_price(symbol=\"BTCUSDT\",", "hour_repeated = hour t.sleep(300) except KeyboardInterrupt: print('Program canceled...') def connect():", "return output.print_failed('Cannot connect to binance with api keys.') def main():", "from binance.client import Client from fun import * import candles", "t.sleep(300) except KeyboardInterrupt: print('Program canceled...') def connect(): while True: api_key", "Adding python-binance to path and importing python-binance sys.path.insert(1, \"../deps/binance\") from", "hour: candles = client.futures_klines(symbol=\"BTCUSDT\", interval=Client.KLINE_INTERVAL_1HOUR, contractType=\"PERPETUAL\") info = can.get_candle_info(candles[:-1]) candle_side", "import candles as can # Globals: client = None #", "# print(\"BTC/USDT: {}\".format(btcusdt_price.json()['price'])) # time.sleep(1.0) #btcusdtindex = find_index_of('symbol', 'BTCUSDT', client.get_all_tickers())" ]
[ "AGNs agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='#fff717', markersize=6.5, label=r'AGN', markeredgecolor='w',", "plotTimeSinceMergerDist(scale_merger_AGN, scale_merger_gal, z_AGN, z_gal, cosmo, bin_size, redshift_limit): \"\"\" Plot the", "markeredgewidth=mew[i]) # DM halos j = i + 2 ax.plot(s_m_gal,", "defines the cuts in the merger times @l :: array", "fontsize=14) ax.set_yscale(\"log\") ax.set_xscale(\"log\") return ax, fig, t_merger_agn, t_merger_gal def mergerRedshiftPlot(cen_sat_AGN,", "fig, ax = plt.subplots(1,1,figsize=(7,6)) distance_Mpc = cosmo.comoving_distance(np.arange(0,redshift_limit, resolution)) redshifts =", "merger_bins_agn, c_t_agn = np.unique(t_merger_agn, return_counts=True) merger_bins_gal, c_t_gal = np.unique(t_merger_gal, return_counts=True)", "ax.axvline(x=t_m_cut, color='r', linestyle= l[i], label='%.1f Gyr'%t_m_cut) ax.legend(fontsize=14, loc='lower left') return", "1]: ax.plot(dt_m[i], z_R[i], plot_params[2][i], color=plot_params[1][i], ms=plot_params[3][i], label=plot_params[0][i], markeredgecolor=plot_params[4][i], markeredgewidth=plot_params[5][i]) #", "= np.unique(cen_sat_halo[i]['HALO_scale_of_last_MM'], return_counts=True) # agns ax.plot(s_m_agn, c_agn, color=c[i], marker=m[i], ls='',", "on the clusters found \"\"\" fig, ax = plt.subplots(1,2,figsize=(19,7)) #", "plot the time since merger distribution for galaxies and agns", "the selected 'clusters' @pos_z_AGN :: postion and redshifts of all", "'b^', label='AGNs', ms=4) # set labels/legends setLabel(ax, r'$\\Delta t_{merger} =", "functions used for plotting graphs and maps in the 1st", "'default', legend=False) print('Redshift-Comoving distance relationship') return def plotMergerDistribution(merger_val_gal, counts_gal, merger_val_agn,", "ax2.invert_xaxis() ax2.set_xlabel('Redshift (z)') ax2.xaxis.set_major_formatter(FormatStrFormatter('%.1f')) print(\"Objects with merger redshifts z <", "for c, c_gal in enumerate(counts_gal): if c_gal != 0: f_agn.append(((counts_agn[c]*100)/c_gal))", "fraction as a function of redshift f_agn, idx = [],", "'clusters' @pos_z_AGN :: postion and redshifts of all the selected", "# plot the merger distribution for galaxies and agns ax1.plot(merger_val_gal,", "\"\"\"Function to plot the relation between redshift and the comoving", "defining plot properties @param ax :: axes to be held", "= [np.min(redshift_bins_agn[1:])-0.02, np.max(redshift_bins_agn[1:])] setLabel(ax[1], r'Redshift$_R$', r'$f_{AGN}$ (%s)'%\"%\", '', xlim, 'default',", "import Table, Column from astropy.coordinates import SkyCoord from astropy.cosmology import", "l = ax.legend(loc='best', fontsize=14) for legend_handle in l.legendHandles: legend_handle._legmarker.set_markersize(12) ax.grid(False)", ":: x-y limits for the axis \"\"\" ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if", "legend=False) ax.legend(loc='lower left', fontsize=14) ax.set_yscale(\"log\") ax.set_xscale(\"log\") return ax, fig, t_merger_agn,", "satellite AGNs(galaxies) @dt_m :: time difference after merger for cen/sat", "for a in scale_factor_arr]) ax2.invert_xaxis() ax2.set_xlabel('Redshift (z)') ax2.xaxis.set_major_formatter(FormatStrFormatter('%.1f')) print(\"Objects with", "= ax.plot(pos_z_halo[0], pos_z_halo[1], '.', color='#fcd16d', markersize=0.2, label=r'All DM Halos', alpha=0.2)", "ax.legend(loc='best', fontsize=14) for legend_handle in l.legendHandles: legend_handle._legmarker.set_markersize(12) ax.grid(False) ax.set_title(title, fontsize=18)", "s_m_gal, c_gal = np.unique(cen_sat_halo[i]['HALO_scale_of_last_MM'], return_counts=True) # agns ax.plot(s_m_agn, c_agn, color=c[i],", "the x-label on top (converting a to redshift) a_min, a_max", "\"\"\" Function to plot the central and sattelite scale factors", "enumerate(t_merger_cut_arr): ax.axvline(x=t_m_cut, color='r', linestyle= l[i], label='%.1f Gyr'%t_m_cut) ax.legend(fontsize=14, loc='lower left')", "based of simulation resolution) @Returns :: plot showing the dependence", "python file contains all the functions used for plotting graphs", "Function to plot the host and satellite halo distribution @hd_halo", "defining limits xlim = [np.min(pos_z_halo[0]), np.max(pos_z_halo[0])] ylim = [np.min(pos_z_halo[1]), np.max(pos_z_halo[1])]", "difference after merger for cen/sat AGNs(galaxies) @plot_params :: to keep", "Function to plot the central and sattelite scale factors for", "# set label setLabel(ax, r'Scale, $a(t)$, of last Major Merger',", "the dependence of redshift on comoving distance \"\"\" fig, ax", "properties - 1 xlim = [np.min(redshift_bins_agn[1:])-0.02, np.max(redshift_bins_agn[1:])] setLabel(ax[1], r'Redshift$_R$', r'$f_{AGN}$", "on halos, clusters, and galaxies within them --> divided into", "'#38cee8', 'k', 'grey'], ['^', '*', '^', '*'], [9, 15, 5,", "the central and sattelite scale factors for mergers \"\"\" fig,", "plot the distribution (counts) of the merger scale factor/redshift \"\"\"", "# axis properties - 1 xlim = [np.min(redshift_bins_agn[1:])-0.02, np.max(redshift_bins_agn[1:])] setLabel(ax[1],", "ms=4) # axis properties - 1 xlim = [np.min(redshift_bins_agn[1:])-0.02, np.max(redshift_bins_agn[1:])]", "function of redshift f_agn, idx = [], [] for c,", "c_t_gal, merger_bins_gal = np.histogram(np.array(t_merger_gal), bins = bin_size[1]) merger_bins_agn = merger_bins_agn[:-1]", "i + 2 ax.plot(s_m_gal, c_gal, color=c[j], marker=m[j], ls='', ms=ms[j], label=labels[j],", "'default', 'default', legend=False) ax.legend(loc='lower left', fontsize=14) ax.set_yscale(\"log\") ax.set_xscale(\"log\") return ax,", "plotting clusters cluster = ax.plot(pos_z_clu[0], pos_z_clu[1], 'o', color= '#03a351', markersize=3,", "visual preference for i in [2, 3, 0, 1]: ax.plot(dt_m[i],", "xlim = [np.min(redshift_bins_agn[1:]), np.max(redshift_bins_agn[1:])] setLabel(ax[0], r'Redshift$_R$', 'Counts','', xlim, 'default', legend=True)", "1st notebook (.ipynb) of the repository: 01. Exploring parameters in", "Table, Column from astropy.coordinates import SkyCoord from astropy.cosmology import FlatLambdaCDM,", "# plotting clusters cluster = ax.plot(pos_z_clu[0], pos_z_clu[1], 'o', color= '#03a351',", "PatchCollection from matplotlib.patches import Rectangle import Exploring_DM_Haloes as edh def", "setLabel(ax, 'R.A. (deg)', 'Dec (deg)', '', xlim, ylim, legend=True) print('Redshift", "labels/legends setLabel(ax, r'$\\Delta t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]', 'Cumulative counts', '',", "return def plotHostSubHalos(pos_z_cen_halo, pos_z_sat_halo, pos_z_AGN): \"\"\" Function to plot the", "concerned plot @t_merger_cut_arr :: array that defines the cuts in", "limit in redshift --> end point for interpolation @resolution ::", "'ks', ms=4, label=r'DM Halos') ax[0].plot(redshift_bins_agn[1:], counts_agn, 'bs', ms=4, label=r'AGNs') #", "and agns ax.plot(merger_bins_gal, np.cumsum(c_t_gal), 'k^', label='DM Halos', ms=4) ax.plot(merger_bins_agn, np.cumsum(c_t_agn),", "ax2.set_xticks([(1/a) -1 for a in scale_factor_arr]) ax2.invert_xaxis() ax2.set_xlabel('Redshift (z)') ax2.xaxis.set_major_formatter(FormatStrFormatter('%.1f'))", "distance (Mpc)', '', 'default', 'default', legend=False) print('Redshift-Comoving distance relationship') return", "bin_size[1]) merger_bins_agn = merger_bins_agn[:-1] merger_bins_gal = merger_bins_gal[:-1] else: merger_bins_agn, c_t_agn", "the useful histogram properties counts_agn, redshift_bins_agn = np.histogram(pos_z_AGN[2], bins =", "all the functions used for plotting graphs and maps in", "\\neq -1$', alpha=0.7) # plotting AGNs agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1],", "last Major Merger', 'Counts', '', 'default', 'default', legend=True) ax.set_yscale(\"log\") #", "xlim, ylim, legend=True): \"\"\" Function defining plot properties @param ax", "'', 'default', 'default', legend=False) print('Redshift-Comoving distance relationship') return def plotMergerDistribution(merger_val_gal,", ":: axes to be held @param xlabel, ylabel :: labels", "xlim, ylim, legend=True) print('Redshift z<%.2f'%(np.max(pos_z_clu[2]))) return def plotHostSubHalos(pos_z_cen_halo, pos_z_sat_halo, pos_z_AGN):", "ax.plot(s_m_gal, c_gal, color=c[j], marker=m[j], ls='', ms=ms[j], label=labels[j], markeredgecolor=mec[j], markeredgewidth=mew[j]) #", "else: merger_bins_agn, c_t_agn = np.unique(t_merger_agn, return_counts=True) merger_bins_gal, c_t_gal = np.unique(t_merger_gal,", "fig, ax = plt.subplots(1,1,figsize=(7,6)) # plot the time since merger", "distribution as a function of redshift ax[0].plot(redshift_bins_gal[1:], counts_gal, 'ks', ms=4,", "based on the clusters found \"\"\" fig, ax = plt.subplots(1,2,figsize=(19,7))", "!= 'default': ax.set_ylim(ylim) if legend: l = ax.legend(loc='best', fontsize=14) for", "AGNs', 'central DM halos', 'satellite DM halos'] c, m, ms", "plt.savefig('figures/agn_frac.pdf', facecolor='w', edgecolor='w') print( 'Reddhift z<%.2f'%redshift_limit_agn ) return redshift_bins_gal[1:] def", "'grey'], ['^', '*', '^', '*'], [9, 15, 5, 9] mec,", "host halos host_halos = ax.plot(ra_cen, dec_cen, '.', color= 'k', markersize=0.06,", "times within the concerned plot @t_merger_cut_arr :: array that defines", "import matplotlib from mpl_toolkits import axes_grid1 import matplotlib.pyplot as plt", "-1 for a in scale_factor_arr]) ax2.invert_xaxis() ax2.set_xlabel('Redshift (z)') ax2.xaxis.set_major_formatter(FormatStrFormatter('%.1f')) print(\"Objects", "counts_agn, redshift_bins_agn = np.histogram(pos_z_AGN[2], bins = bin_size) counts_gal, redshift_bins_gal =", "written by: <NAME> Project supervised by <NAME> Date created: 23rd", "@pos_z_clu :: postion and redshifts of all the selected 'clusters'", "= [np.min(pos_z_halo[0]), np.max(pos_z_halo[0])] ylim = [np.min(pos_z_halo[1]), np.max(pos_z_halo[1])] setLabel(ax, 'R.A. (deg)',", "Function to plot the time since merger as a function", "@pos_z_AGN :: postion and redshifts of all the selected AGNs", "upper limit in redshift --> end point for interpolation @resolution", "'Comoving distance (Mpc)', '', 'default', 'default', legend=False) print('Redshift-Comoving distance relationship')", "M_\\odot$ '%(np.log10(halo_m_500c))) # plotting AGNs agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*',", "import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D from matplotlib.ticker", "dec_cen, '.', color= 'k', markersize=0.06, label=r'Host-halos $P_{id}=-1$', alpha=0.4) # plotting", "= [], [] for c, c_gal in enumerate(counts_gal): if c_gal", "mew] def plotTimeSinceMergerDist(scale_merger_AGN, scale_merger_gal, z_AGN, z_gal, cosmo, bin_size, redshift_limit): \"\"\"", "defines the linestyles used to denote these cuts (refer to", "np.histogram(np.array(t_merger_agn), bins = bin_size[1]) c_t_gal, merger_bins_gal = np.histogram(np.array(t_merger_gal), bins =", "ax.legend(loc='lower left', fontsize=14) ax.set_yscale(\"log\") ax.set_xscale(\"log\") return ax, fig, t_merger_agn, t_merger_gal", "z: ', redshift_limit) return [labels, c, m, ms, mec, mew]", "legend=True) ax.set_xscale(\"log\") plt.savefig('figures/t_since_merger_z_plot_%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') return ax def plotMergerTimeCuts(ax, t_merger_cut_arr,", "the selected AGNs \"\"\" ra_cen, dec_cen = pos_z_cen_halo[0], pos_z_cen_halo[1] ra_sat,", "color=c[j], marker=m[j], ls='', ms=ms[j], label=labels[j], markeredgecolor=mec[j], markeredgewidth=mew[j]) # set label", "plotMergerTimeCuts(ax, t_merger_cut_arr, l): \"\"\" Function to plot the defined cuts", "the x-y axis @param title :: title of the plot", "of the x-y axis @param title :: title of the", "axis properties - 1 xlim = [np.min(redshift_bins_agn[1:])-0.02, np.max(redshift_bins_agn[1:])] setLabel(ax[1], r'Redshift$_R$',", "def plotCentralSatelliteScaleMergers(cen_sat_AGN, cen_sat_halo, redshift_limit): \"\"\" Function to plot the central", "events in the halos t_merger_agn = edh.getMergerTimeDifference(scale_merger_AGN, z_AGN, cosmo) t_merger_gal", "clusters, and galaxies within them --> divided into 3 because", "pos_z_cen_halo[0], pos_z_cen_halo[1] ra_sat, dec_sat = pos_z_sat_halo[0], pos_z_sat_halo[1] fig, ax =", "fig, ax = plt.subplots(1,2,figsize=(19,7)) # getting the useful histogram properties", "matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D from matplotlib.ticker import", "histogram properties counts_agn, redshift_bins_agn = np.histogram(pos_z_AGN[2], bins = bin_size) counts_gal,", "[cen_sat_AGN[0]['redshift_R'], cen_sat_AGN[1]['redshift_R'], cen_sat_halo[0]['redshift_R'], cen_sat_halo[1]['redshift_R']] # plot central, satellite merger distributions", "import astropy.io.fits as fits from astropy.table import Table, Column from", "def plotHostSubHalos(pos_z_cen_halo, pos_z_sat_halo, pos_z_AGN): \"\"\" Function to plot the host", "label='DM Halos') ax1.plot(merger_val_agn, counts_agn, 'bx', label='AGNs') setLabel(ax1, r'Scale, $a(t)$, of", "plotting host halos host_halos = ax.plot(ra_cen, dec_cen, '.', color= 'k',", "pos_z_AGN): \"\"\" Function to plot the host and satellite halo", "plotting AGNs agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='#fff717', markersize=6.5, label=r'AGN',", "i, t_m_cut in enumerate(t_merger_cut_arr): ax.axvline(x=t_m_cut, color='r', linestyle= l[i], label='%.1f Gyr'%t_m_cut)", ":: upper limit on redshift based on the clusters found", "xlim, 'default', legend=True) ax[0].set_yscale(\"log\") # agn fraction as a function", "defining limits xlim = [np.min(pos_z_AGN[0]), np.max(pos_z_AGN[0])] ylim = [np.min(pos_z_AGN[1]), np.max(pos_z_AGN[1])]", "2021 Last updated on 30th March 2021 \"\"\" # astropy", "idx.append(c) z_bin_modified = redshift_bins_gal[1:][np.array(idx)] # plot agn fraction ax[1].plot(z_bin_modified, f_agn,", "denote these cuts (refer to the initial codeblock in the", "'', 'default', 'default', legend=True) ax.set_xscale(\"log\") plt.savefig('figures/t_since_merger_z_plot_%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') return ax", "ax1.plot(merger_val_agn, counts_agn, 'bx', label='AGNs') setLabel(ax1, r'Scale, $a(t)$, of last Major", "# plot the time since merger distribution for galaxies and", "halos plot_params[3][1] = 9 z_R = [cen_sat_AGN[0]['redshift_R'], cen_sat_AGN[1]['redshift_R'], cen_sat_halo[0]['redshift_R'], cen_sat_halo[1]['redshift_R']]", "= [np.min(pos_z_AGN[1]), np.max(pos_z_AGN[1])] setLabel(ax, 'R.A. (deg)', 'Dec (deg)', '', xlim,", "time steps (set to e-4 based of simulation resolution) @Returns", "color= '#03a351', markersize=3, label=r'Clusters $M_{500c}> 10^{%.1f} M_\\odot$ '%(np.log10(halo_m_500c))) # plotting", "merger redshifts z < %.2f\"%z_at_value(cosmo.scale_factor, a_min)) plt.savefig('figures/merger_distribution_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') return", "= 9 z_R = [cen_sat_AGN[0]['redshift_R'], cen_sat_AGN[1]['redshift_R'], cen_sat_halo[0]['redshift_R'], cen_sat_halo[1]['redshift_R']] # plot", "mpl_toolkits import axes_grid1 import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d import", "all the selected AGNs \"\"\" ra_cen, dec_cen = pos_z_cen_halo[0], pos_z_cen_halo[1]", "bin_size[0]: c_t_agn, merger_bins_agn = np.histogram(np.array(t_merger_agn), bins = bin_size[1]) c_t_gal, merger_bins_gal", "and satellite AGNs(galaxies) @dt_m :: time difference after merger for", "cen_sat_AGN[1]['redshift_R'], cen_sat_halo[0]['redshift_R'], cen_sat_halo[1]['redshift_R']] # plot central, satellite merger distributions as", "- 1 xlim = [np.min(redshift_bins_agn[1:])-0.02, np.max(redshift_bins_agn[1:])] setLabel(ax[1], r'Redshift$_R$', r'$f_{AGN}$ (%s)'%\"%\",", "np.max(pos_z_AGN[1])] setLabel(ax, 'R.A. (deg)', 'Dec (deg)', '', xlim, ylim, legend=True)", "0: f_agn.append(((counts_agn[c]*100)/c_gal)) idx.append(c) z_bin_modified = redshift_bins_gal[1:][np.array(idx)] # plot agn fraction", "@redshift_limit :: upper limit in redshift --> end point for", "the galaxy and agn distribution as a function of redshift", "= [np.min(redshift_bins_agn[1:]), np.max(redshift_bins_agn[1:])] setLabel(ax[0], r'Redshift$_R$', 'Counts','', xlim, 'default', legend=True) ax[0].set_yscale(\"log\")", "central DM halos plot_params[3][1] = 9 z_R = [cen_sat_AGN[0]['redshift_R'], cen_sat_AGN[1]['redshift_R'],", "fontsize=18) return def plotAgnClusterDistribution(pos_z_clu, pos_z_AGN, pos_z_halo, cluster_params): \"\"\" Function to", "plot the merger distribution for galaxies and agns ax1.plot(merger_val_gal, counts_gal,", "per visual preference for i in [2, 3, 0, 1]:", "because each hd_halo holds info on 1000 halos alone @pos_z_AGN", "relevant info on halos, clusters, and galaxies within them -->", "markeredgecolor=plot_params[4][i], markeredgewidth=plot_params[5][i]) # set labels/legends setLabel(ax, r'$\\Delta t_{merger} = t(z_{merger})-t(z_{current})$", "the initial codeblock in the notebook) \"\"\" for i, t_m_cut", "used to denote these cuts (refer to the initial codeblock", "bins = bin_size[1]) c_t_gal, merger_bins_gal = np.histogram(np.array(t_merger_gal), bins = bin_size[1])", "since merger bins and counts if bin_size[0]: c_t_agn, merger_bins_agn =", "halo_m_500c = cluster_params[0] fig, ax = plt.subplots(1,1,figsize=(9,8)) # plotting halos", "alpha=0.7) # plotting AGNs agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='#fff717',", "'k', 'grey'], ['^', '*', '^', '*'], [9, 15, 5, 9]", "[np.min(redshift_bins_agn[1:])-0.02, np.max(redshift_bins_agn[1:])] setLabel(ax[1], r'Redshift$_R$', r'$f_{AGN}$ (%s)'%\"%\", '', xlim, 'default', legend=False)", "= plt.subplots(1,1,figsize=(7,6)) # plot the time since merger distribution for", "'default', legend=False) ax[1].set_yscale(\"log\") plt.savefig('figures/agn_frac.pdf', facecolor='w', edgecolor='w') print( 'Reddhift z<%.2f'%redshift_limit_agn )", "c_t_agn, merger_bins_agn = np.histogram(np.array(t_merger_agn), bins = bin_size[1]) c_t_gal, merger_bins_gal =", "01. Exploring parameters in DM halos and sub-halos Script written", "t_m_cut in enumerate(t_merger_cut_arr): ax.axvline(x=t_m_cut, color='r', linestyle= l[i], label='%.1f Gyr'%t_m_cut) ax.legend(fontsize=14,", "'R.A. (deg)', 'Dec (deg)', '', xlim, ylim, legend=True) print('Redshift z<%.2f'%(np.max(pos_z_clu[2])))", "to plot the distribution (counts) of the merger scale factor/redshift", "'o', color='#07d9f5', markersize=0.07, label=r'Satellite halos $P_{id} \\neq -1$', alpha=0.7) #", "axes and defining limits xlim = [np.min(pos_z_halo[0]), np.max(pos_z_halo[0])] ylim =", "bin_size) counts_gal, redshift_bins_gal = np.histogram(pos_z_gal[2], bins = bin_size) # plotting", "(.ipynb) of the repository: 01. Exploring parameters in DM halos", "galaxies and agns ax1.plot(merger_val_gal, counts_gal, 'kx', label='DM Halos') ax1.plot(merger_val_agn, counts_agn,", "from matplotlib.patches import Rectangle import Exploring_DM_Haloes as edh def setLabel(ax,", "-*- \"\"\"Plotting.py for notebook 01_Exploring_DM_Halos This python file contains all", "AGNs @pos_z_gal :: postion and redshifts of all the selected", "= ax.legend(loc='best', fontsize=14) for legend_handle in l.legendHandles: legend_handle._legmarker.set_markersize(12) ax.grid(False) ax.set_title(title,", "Function to plot the defined cuts in merger times within", "label='AGNs', ms=4) # set labels/legends setLabel(ax, r'$\\Delta t_{merger} = t(z_{merger})-t(z_{current})$", "the functions used for plotting graphs and maps in the", "[] for c, c_gal in enumerate(counts_gal): if c_gal != 0:", "limits for the axis \"\"\" ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if xlim !=", "importlib # plotting imports import matplotlib from mpl_toolkits import axes_grid1", "= t(z_{merger})-t(z_{current})$ [Gyr]', r'Redshift$_R$', '', 'default', 'default', legend=True) ax.set_xscale(\"log\") plt.savefig('figures/t_since_merger_z_plot_%.2f.pdf'%redshift_limit,", "pos_z_sat_halo[1] fig, ax = plt.subplots(1,1,figsize=(9,8)) # plotting host halos host_halos", "astropy.coordinates import SkyCoord from astropy.cosmology import FlatLambdaCDM, z_at_value import numpy", "= np.unique(cen_sat_AGN[i]['HALO_scale_of_last_MM'], return_counts=True) s_m_gal, c_gal = np.unique(cen_sat_halo[i]['HALO_scale_of_last_MM'], return_counts=True) # agns", "axes and defining limits xlim = [np.min(pos_z_AGN[0]), np.max(pos_z_AGN[0])] ylim =", "ax.set_title(title, fontsize=18) return def plotAgnClusterDistribution(pos_z_clu, pos_z_AGN, pos_z_halo, cluster_params): \"\"\" Function", "setLabel(ax, r'$\\Delta t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]', r'Redshift$_R$', '', 'default', 'default',", "from matplotlib.collections import PatchCollection from matplotlib.patches import Rectangle import Exploring_DM_Haloes", "(refer to the initial codeblock in the notebook) \"\"\" for", "return def plotMergerDistribution(merger_val_gal, counts_gal, merger_val_agn, counts_agn, cosmo, redshift_limit): \"\"\" Function", "# plotting AGNs agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='k', markersize=3.5,", "def plotTimeSinceMergerDist(scale_merger_AGN, scale_merger_gal, z_AGN, z_gal, cosmo, bin_size, redshift_limit): \"\"\" Plot", "and agns ax1.plot(merger_val_gal, counts_gal, 'kx', label='DM Halos') ax1.plot(merger_val_agn, counts_agn, 'bx',", "the selected galaxies @redshift_limit_agn :: upper limit on redshift based", "print('AGNs: %d, Host (central) halos: %.2e, Sattelite halos: %.2e'%(len(pos_z_AGN[0]), len(ra_cen),", "Merger', 'Counts', '', 'default', 'default', legend=True) ax.set_yscale(\"log\") # setting the", "i in [0, 1]: s_m_agn, c_agn = np.unique(cen_sat_AGN[i]['HALO_scale_of_last_MM'], return_counts=True) s_m_gal,", "agn fraction in the given pixel @pos_z_AGN :: postion and", "plotting halos halos = ax.plot(pos_z_halo[0], pos_z_halo[1], '.', color='#fcd16d', markersize=0.2, label=r'All", "matplotlib.collections import PatchCollection from matplotlib.patches import Rectangle import Exploring_DM_Haloes as", "of the redshift @cen_sat_AGN(gal) :: handels to access the central", "on comoving distance \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) distance_Mpc =", "merger scale factor/redshift \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) ax1 =", "= [cen_sat_AGN[0]['redshift_R'], cen_sat_AGN[1]['redshift_R'], cen_sat_halo[0]['redshift_R'], cen_sat_halo[1]['redshift_R']] # plot central, satellite merger", "cm from matplotlib.collections import PatchCollection from matplotlib.patches import Rectangle import", "by <NAME> Date created: 23rd February 2021 Last updated on", "np.max(pos_z_halo[1])] setLabel(ax, 'R.A. (deg)', 'Dec (deg)', '', xlim, ylim, legend=True)", "= ax1.twiny() # plot the merger distribution for galaxies and", "Merger', 'Counts', '', 'default', 'default', legend=True) ax.set_yscale(\"log\") plt.savefig('figures/merger_dist_cenAndsat_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w')", "l): \"\"\" Function to plot the defined cuts in merger", "satellite halo distribution @hd_halo :: table with all relevant info", "@cosmo :: cosmology package loaded @redshift_limit :: upper limit in", "of halos with respective galaxies & agns given the time", "coding: utf-8 -*- \"\"\"Plotting.py for notebook 01_Exploring_DM_Halos This python file", "distribution of halos with respective galaxies & agns given the", "import KDTree from scipy.interpolate import interp1d import os import importlib", "merger_bins_agn = np.histogram(np.array(t_merger_agn), bins = bin_size[1]) c_t_gal, merger_bins_gal = np.histogram(np.array(t_merger_gal),", "created: 23rd February 2021 Last updated on 30th March 2021", "since merger events in the halos t_merger_agn = edh.getMergerTimeDifference(scale_merger_AGN, z_AGN,", "scale factors for mergers \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) labels", "t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]', r'Redshift$_R$', '', 'default', 'default', legend=True) ax.set_xscale(\"log\")", "ax[0].plot(redshift_bins_gal[1:], counts_gal, 'ks', ms=4, label=r'DM Halos') ax[0].plot(redshift_bins_agn[1:], counts_agn, 'bs', ms=4,", "np.min(merger_val_gal), np.max(merger_val_gal) scale_factor_arr = [a_max, a_min*4, a_min*2, a_min] ax2.set_xticks([(1/a) -1", "ax = plt.subplots(1,1,figsize=(7,6)) # change marker size for central DM", "pixel @pos_z_AGN :: postion and redshifts of all the selected", "distribution for galaxies and agns ax.plot(merger_bins_gal, np.cumsum(c_t_gal), 'k^', label='DM Halos',", "package loaded @redshift_limit :: upper limit in redshift --> end", "Date created: 23rd February 2021 Last updated on 30th March", "from mpl_toolkits import axes_grid1 import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d", "1 xlim = [np.min(redshift_bins_agn[1:])-0.02, np.max(redshift_bins_agn[1:])] setLabel(ax[1], r'Redshift$_R$', r'$f_{AGN}$ (%s)'%\"%\", '',", "labels/legends setLabel(ax, r'$\\Delta t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]', r'Redshift$_R$', '', 'default',", "array that defines the linestyles used to denote these cuts", "that defines the cuts in the merger times @l ::", "plt.subplots(1,1,figsize=(7,6)) ax1 = plt.gca() ax2 = ax1.twiny() # plot the", "label=plot_params[0][i], markeredgecolor=plot_params[4][i], markeredgewidth=plot_params[5][i]) # set labels/legends setLabel(ax, r'$\\Delta t_{merger} =", "Axes3D from matplotlib.ticker import LinearLocator, FormatStrFormatter from matplotlib import cm", "markersize=0.06, label=r'Host-halos $P_{id}=-1$', alpha=0.4) # plotting sat halos sat_halos =", "to access the central and satellite AGNs(galaxies) @dt_m :: time", "labels of the x-y axis @param title :: title of", "scale_factor_arr]) ax2.invert_xaxis() ax2.set_xlabel('Redshift (z)') ax2.xaxis.set_major_formatter(FormatStrFormatter('%.1f')) print(\"Objects with merger redshifts z", "for galaxies and agns ax1.plot(merger_val_gal, counts_gal, 'kx', label='DM Halos') ax1.plot(merger_val_agn,", "get the t since merger bins and counts if bin_size[0]:", "updated on 30th March 2021 \"\"\" # astropy modules import", "properties @param ax :: axes to be held @param xlabel,", "upper limit on redshift based on the clusters found \"\"\"", "# get the time difference since merger events in the", "of the plot @param xlim, ylim :: x-y limits for", "all the selected 'clusters' @pos_z_AGN :: postion and redshifts of", "by: <NAME> Project supervised by <NAME> Date created: 23rd February", "plot agn fraction ax[1].plot(z_bin_modified, f_agn, 's', color='#6b0385', ms=4) # axis", "'Reddhift z<%.2f'%redshift_limit_agn ) return redshift_bins_gal[1:] def plotRedshiftComovingDistance(cosmo, redshift_limit, resolution =", "counts_gal, 'ks', ms=4, label=r'DM Halos') ax[0].plot(redshift_bins_agn[1:], counts_agn, 'bs', ms=4, label=r'AGNs')", "of all the selected galaxies @redshift_limit_agn :: upper limit on", "legend_handle._legmarker.set_markersize(12) ax.grid(False) ax.set_title(title, fontsize=18) return def plotAgnClusterDistribution(pos_z_clu, pos_z_AGN, pos_z_halo, cluster_params):", "0.4, 1, 0.7] for i in [0, 1]: s_m_agn, c_agn", "edgecolor='w') print( 'Reddhift z<%.2f'%redshift_limit_agn ) return redshift_bins_gal[1:] def plotRedshiftComovingDistance(cosmo, redshift_limit,", "from matplotlib.ticker import LinearLocator, FormatStrFormatter from matplotlib import cm from", "within them --> divided into 3 because each hd_halo holds", "between plots, array containing [labels, c, m, ms] \"\"\" fig,", "plotting graphs and maps in the 1st notebook (.ipynb) of", "(%s)'%\"%\", '', xlim, 'default', legend=False) ax[1].set_yscale(\"log\") plt.savefig('figures/agn_frac.pdf', facecolor='w', edgecolor='w') print(", "Project supervised by <NAME> Date created: 23rd February 2021 Last", "ax.plot(merger_bins_agn, np.cumsum(c_t_agn), 'b^', label='AGNs', ms=4) # set labels/legends setLabel(ax, r'$\\Delta", "redshift and the comoving distance @cosmo :: cosmology package loaded", "the merger scale factor/redshift \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) ax1", "factor/redshift \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) ax1 = plt.gca() ax2", "last Major Merger', 'Counts', '', 'default', 'default', legend=True) ax.set_yscale(\"log\") plt.savefig('figures/merger_dist_cenAndsat_z%.2f.pdf'%redshift_limit,", "ax.set_yscale(\"log\") plt.savefig('figures/merger_dist_cenAndsat_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') print('Objects below z: ', redshift_limit) return", "np.max(pos_z_halo[0])] ylim = [np.min(pos_z_halo[1]), np.max(pos_z_halo[1])] setLabel(ax, 'R.A. (deg)', 'Dec (deg)',", "all the selected galaxies @redshift_limit_agn :: upper limit on redshift", "and counts if bin_size[0]: c_t_agn, merger_bins_agn = np.histogram(np.array(t_merger_agn), bins =", "the selected galaxies \"\"\" halo_m_500c = cluster_params[0] fig, ax =", "a_min, a_max = np.min(merger_val_gal), np.max(merger_val_gal) scale_factor_arr = [a_max, a_min*4, a_min*2,", "redshift_bins_gal[1:][np.array(idx)] # plot agn fraction ax[1].plot(z_bin_modified, f_agn, 's', color='#6b0385', ms=4)", "2021 \"\"\" # astropy modules import astropy.units as u import", "[np.min(redshift_bins_agn[1:]), np.max(redshift_bins_agn[1:])] setLabel(ax[0], r'Redshift$_R$', 'Counts','', xlim, 'default', legend=True) ax[0].set_yscale(\"log\") #", "top (converting a to redshift) a_min, a_max = np.min(merger_val_gal), np.max(merger_val_gal)", "maps in the 1st notebook (.ipynb) of the repository: 01.", "$P_{id}=-1$', alpha=0.4) # plotting sat halos sat_halos = ax.plot(ra_sat, dec_sat,", "limits xlim = [np.min(pos_z_AGN[0]), np.max(pos_z_AGN[0])] ylim = [np.min(pos_z_AGN[1]), np.max(pos_z_AGN[1])] setLabel(ax,", "Function to plot the agn fraction in the given pixel", "return def plotAgnClusterDistribution(pos_z_clu, pos_z_AGN, pos_z_halo, cluster_params): \"\"\" Function to plot", "z_gal, cosmo, bin_size, redshift_limit): \"\"\" Plot the distribution of halos", "t_merger_gal def mergerRedshiftPlot(cen_sat_AGN, cen_sat_halo, dt_m, plot_params, redshift_limit): \"\"\" Function to", "used for plotting graphs and maps in the 1st notebook", "'Counts','', xlim, 'default', legend=True) ax[0].set_yscale(\"log\") # agn fraction as a", "@redshift_limit_agn :: upper limit on redshift based on the clusters", "cen/sat AGNs(galaxies) @plot_params :: to keep consistency between plots, array", "DM halos plot_params[3][1] = 9 z_R = [cen_sat_AGN[0]['redshift_R'], cen_sat_AGN[1]['redshift_R'], cen_sat_halo[0]['redshift_R'],", "legend=False) print('Redshift-Comoving distance relationship') return def plotMergerDistribution(merger_val_gal, counts_gal, merger_val_agn, counts_agn,", "'.', color= 'k', markersize=0.06, label=r'Host-halos $P_{id}=-1$', alpha=0.4) # plotting sat", "# -*- coding: utf-8 -*- \"\"\"Plotting.py for notebook 01_Exploring_DM_Halos This", "and defining limits xlim = [np.min(pos_z_AGN[0]), np.max(pos_z_AGN[0])] ylim = [np.min(pos_z_AGN[1]),", "np.unique(cen_sat_halo[i]['HALO_scale_of_last_MM'], return_counts=True) # agns ax.plot(s_m_agn, c_agn, color=c[i], marker=m[i], ls='', ms=ms[i],", "the comoving distance @cosmo :: cosmology package loaded @redshift_limit ::", "plt.subplots(1,1,figsize=(9,8)) # plotting halos halos = ax.plot(pos_z_halo[0], pos_z_halo[1], '.', color='#fcd16d',", "clusters found \"\"\" fig, ax = plt.subplots(1,2,figsize=(19,7)) # getting the", "z < %.2f\"%z_at_value(cosmo.scale_factor, a_min)) plt.savefig('figures/merger_distribution_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') return def plotCentralSatelliteScaleMergers(cen_sat_AGN,", "matplotlib from mpl_toolkits import axes_grid1 import matplotlib.pyplot as plt from", "'#03a351', markersize=3, label=r'Clusters $M_{500c}> 10^{%.1f} M_\\odot$ '%(np.log10(halo_m_500c))) # plotting AGNs", "--> end point for interpolation @resolution :: resolution of time", "halos t_merger_agn = edh.getMergerTimeDifference(scale_merger_AGN, z_AGN, cosmo) t_merger_gal = edh.getMergerTimeDifference(scale_merger_gal, z_gal,", "np.unique(cen_sat_AGN[i]['HALO_scale_of_last_MM'], return_counts=True) s_m_gal, c_gal = np.unique(cen_sat_halo[i]['HALO_scale_of_last_MM'], return_counts=True) # agns ax.plot(s_m_agn,", "= [np.min(pos_z_halo[1]), np.max(pos_z_halo[1])] setLabel(ax, 'R.A. (deg)', 'Dec (deg)', '', xlim,", "time since merger \"\"\" # get the time difference since", "import FlatLambdaCDM, z_at_value import numpy as np # scipy modules", "Exploring parameters in DM halos and sub-halos Script written by:", ":: to keep consistency between plots, array containing [labels, c,", "as u import astropy.io.fits as fits from astropy.table import Table,", "xlim, ylim :: x-y limits for the axis \"\"\" ax.set_xlabel(xlabel)", "ax = plt.subplots(1,1,figsize=(7,6)) ax1 = plt.gca() ax2 = ax1.twiny() #", "ra_cen, dec_cen = pos_z_cen_halo[0], pos_z_cen_halo[1] ra_sat, dec_sat = pos_z_sat_halo[0], pos_z_sat_halo[1]", "in the given pixel @pos_z_AGN :: postion and redshifts of", "the merger distribution for galaxies and agns ax1.plot(merger_val_gal, counts_gal, 'kx',", "c_t_agn = np.unique(t_merger_agn, return_counts=True) merger_bins_gal, c_t_gal = np.unique(t_merger_gal, return_counts=True) fig,", ":: postion and redshifts of all the selected 'clusters' @pos_z_AGN", "plt.subplots(1,2,figsize=(19,7)) # getting the useful histogram properties counts_agn, redshift_bins_agn =", "redshift_limit, resolution = 0.0001): \"\"\"Function to plot the relation between", "np.histogram(pos_z_gal[2], bins = bin_size) # plotting the galaxy and agn", "set label setLabel(ax, r'Scale, $a(t)$, of last Major Merger', 'Counts',", "holds info on 1000 halos alone @pos_z_AGN :: postion and", ":: handels to access the central and satellite AGNs(galaxies) @dt_m", "consistency between plots, array containing [labels, c, m, ms] \"\"\"", "<filename>imported_files/plotting_edh01.py # -*- coding: utf-8 -*- \"\"\"Plotting.py for notebook 01_Exploring_DM_Halos", "1]: s_m_agn, c_agn = np.unique(cen_sat_AGN[i]['HALO_scale_of_last_MM'], return_counts=True) s_m_gal, c_gal = np.unique(cen_sat_halo[i]['HALO_scale_of_last_MM'],", "set labels/legends setLabel(ax, r'$\\Delta t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]', 'Cumulative counts',", "plot the relation between redshift and the comoving distance @cosmo", "for interpolation @resolution :: resolution of time steps (set to", "s_m_agn, c_agn = np.unique(cen_sat_AGN[i]['HALO_scale_of_last_MM'], return_counts=True) s_m_gal, c_gal = np.unique(cen_sat_halo[i]['HALO_scale_of_last_MM'], return_counts=True)", "a function of the redshift @cen_sat_AGN(gal) :: handels to access", "for the axis \"\"\" ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if xlim != 'default':", "distribution (counts) of the merger scale factor/redshift \"\"\" fig, ax", "'default', legend=True) ax.set_xscale(\"log\") plt.savefig('figures/t_since_merger_z_plot_%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') return ax def plotMergerTimeCuts(ax,", "plt.subplots(1,1,figsize=(9,8)) # plotting host halos host_halos = ax.plot(ra_cen, dec_cen, '.',", "for mergers \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) labels = [r'central", "resolution) ax.plot(redshifts, distance_Mpc, 'k.', ms=1) setLabel(ax, 'Redshift (z)', 'Comoving distance", "Halos', ms=4) ax.plot(merger_bins_agn, np.cumsum(c_t_agn), 'b^', label='AGNs', ms=4) # set labels/legends", "'*', '^', '*'], [9, 15, 5, 9] mec, mew =", "markeredgewidth=0.4) # labeling axes and defining limits xlim = [np.min(pos_z_AGN[0]),", "['^', '*', '^', '*'], [9, 15, 5, 9] mec, mew", "0.7] for i in [0, 1]: s_m_agn, c_agn = np.unique(cen_sat_AGN[i]['HALO_scale_of_last_MM'],", "scipy modules from scipy.spatial import KDTree from scipy.interpolate import interp1d", "ax = plt.subplots(1,1,figsize=(7,6)) # plot the time since merger distribution", "to the initial codeblock in the notebook) \"\"\" for i,", "(deg)', 'Dec (deg)', '', xlim, ylim, legend=True) print('Redshift z<%.2f'%(np.max(pos_z_clu[2]))) return", "plt.subplots(1,1,figsize=(7,6)) labels = [r'central AGNs', r'satellite AGNs', 'central DM halos',", "selected AGNs \"\"\" ra_cen, dec_cen = pos_z_cen_halo[0], pos_z_cen_halo[1] ra_sat, dec_sat", "# labeling axes and defining limits xlim = [np.min(pos_z_AGN[0]), np.max(pos_z_AGN[0])]", "label=r'DM Halos') ax[0].plot(redshift_bins_agn[1:], counts_agn, 'bs', ms=4, label=r'AGNs') # axis properties", "plot the defined cuts in merger times within the concerned", "the concerned plot @t_merger_cut_arr :: array that defines the cuts", "dec_sat, 'o', color='#07d9f5', markersize=0.07, label=r'Satellite halos $P_{id} \\neq -1$', alpha=0.7)", "np.max(pos_z_AGN[0])] ylim = [np.min(pos_z_AGN[1]), np.max(pos_z_AGN[1])] setLabel(ax, 'R.A. (deg)', 'Dec (deg)',", "redshift_limit): \"\"\" Function to plot the central and sattelite scale", "from astropy.table import Table, Column from astropy.coordinates import SkyCoord from", "of the repository: 01. Exploring parameters in DM halos and", "redshifts z < %.2f\"%z_at_value(cosmo.scale_factor, a_min)) plt.savefig('figures/merger_distribution_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') return def", "of redshift on comoving distance \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6))", "- 0 xlim = [np.min(redshift_bins_agn[1:]), np.max(redshift_bins_agn[1:])] setLabel(ax[0], r'Redshift$_R$', 'Counts','', xlim,", "cuts in the merger times @l :: array that defines", "'', xlim, ylim, legend=True) print('Redshift z<%.2f'%(np.max(pos_z_clu[2]))) return def plotHostSubHalos(pos_z_cen_halo, pos_z_sat_halo,", "a_min*2, a_min] ax2.set_xticks([(1/a) -1 for a in scale_factor_arr]) ax2.invert_xaxis() ax2.set_xlabel('Redshift", "pos_z_cen_halo[1] ra_sat, dec_sat = pos_z_sat_halo[0], pos_z_sat_halo[1] fig, ax = plt.subplots(1,1,figsize=(9,8))", "of all the selected galaxies \"\"\" halo_m_500c = cluster_params[0] fig,", "redshift on comoving distance \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) distance_Mpc", "and galaxies within them --> divided into 3 because each", "r'$f_{AGN}$ (%s)'%\"%\", '', xlim, 'default', legend=False) ax[1].set_yscale(\"log\") plt.savefig('figures/agn_frac.pdf', facecolor='w', edgecolor='w')", "fig, t_merger_agn, t_merger_gal def mergerRedshiftPlot(cen_sat_AGN, cen_sat_halo, dt_m, plot_params, redshift_limit): \"\"\"", "Rectangle import Exploring_DM_Haloes as edh def setLabel(ax, xlabel, ylabel, title,", "1, 0.7] for i in [0, 1]: s_m_agn, c_agn =", "edh.getMergerTimeDifference(scale_merger_AGN, z_AGN, cosmo) t_merger_gal = edh.getMergerTimeDifference(scale_merger_gal, z_gal, cosmo) # get", "relationship') return def plotMergerDistribution(merger_val_gal, counts_gal, merger_val_agn, counts_agn, cosmo, redshift_limit): \"\"\"", "return ax def plotMergerTimeCuts(ax, t_merger_cut_arr, l): \"\"\" Function to plot", "j = i + 2 ax.plot(s_m_gal, c_gal, color=c[j], marker=m[j], ls='',", "c, m, ms = ['b', '#38cee8', 'k', 'grey'], ['^', '*',", "bins and counts if bin_size[0]: c_t_agn, merger_bins_agn = np.histogram(np.array(t_merger_agn), bins", ":: array that defines the linestyles used to denote these", "ax.set_ylim(ylim) if legend: l = ax.legend(loc='best', fontsize=14) for legend_handle in", "'', xlim, 'default', legend=False) ax[1].set_yscale(\"log\") plt.savefig('figures/agn_frac.pdf', facecolor='w', edgecolor='w') print( 'Reddhift", "label setLabel(ax, r'Scale, $a(t)$, of last Major Merger', 'Counts', '',", "as a function of redshift ax[0].plot(redshift_bins_gal[1:], counts_gal, 'ks', ms=4, label=r'DM", "postion and redshifts of all the selected 'clusters' @pos_z_AGN ::", "= ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='k', markersize=3.5, label=r'AGN', alpha=0.7) # labeling", "x-y axis @param title :: title of the plot @param", "markersize=6.5, label=r'AGN', markeredgecolor='w', markeredgewidth=0.4) # labeling axes and defining limits", "'Dec (deg)', '', xlim, ylim, legend=True) print('Redshift z<%.2f'%(np.max(pos_z_clu[2]))) return def", "with respective galaxies & agns given the time since merger", "plt from mpl_toolkits.mplot3d.axes3d import Axes3D from matplotlib.ticker import LinearLocator, FormatStrFormatter", "agns ax1.plot(merger_val_gal, counts_gal, 'kx', label='DM Halos') ax1.plot(merger_val_agn, counts_agn, 'bx', label='AGNs')", "pos_z_halo, cluster_params): \"\"\" Function to plot the AGN cluster distribution", "Halos') ax1.plot(merger_val_agn, counts_agn, 'bx', label='AGNs') setLabel(ax1, r'Scale, $a(t)$, of last", "of all the selected AGNs @pos_z_gal :: postion and redshifts", "%.2f\"%z_at_value(cosmo.scale_factor, a_min)) plt.savefig('figures/merger_distribution_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') return def plotCentralSatelliteScaleMergers(cen_sat_AGN, cen_sat_halo, redshift_limit):", "for central DM halos plot_params[3][1] = 9 z_R = [cen_sat_AGN[0]['redshift_R'],", "f_agn, 's', color='#6b0385', ms=4) # axis properties - 1 xlim", "'', 'default', 'default', legend=False) ax.legend(loc='lower left', fontsize=14) ax.set_yscale(\"log\") ax.set_xscale(\"log\") return", "= plt.subplots(1,2,figsize=(19,7)) # getting the useful histogram properties counts_agn, redshift_bins_agn", "redshift based on the clusters found \"\"\" fig, ax =", "to plot the central and sattelite scale factors for mergers", "\"\"\" ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if xlim != 'default': ax.set_xlim(xlim) if ylim", "fig, ax = plt.subplots(1,1,figsize=(7,6)) ax1 = plt.gca() ax2 = ax1.twiny()", "'default', legend=True) ax.set_yscale(\"log\") plt.savefig('figures/merger_dist_cenAndsat_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') print('Objects below z: ',", "keep consistency between plots, array containing [labels, c, m, ms]", "KDTree from scipy.interpolate import interp1d import os import importlib #", "legend=True) ax.set_yscale(\"log\") # setting the x-label on top (converting a", "\"\"\" Function defining plot properties @param ax :: axes to", ":: upper limit in redshift --> end point for interpolation", "def plotRedshiftComovingDistance(cosmo, redshift_limit, resolution = 0.0001): \"\"\"Function to plot the", "astropy.table import Table, Column from astropy.coordinates import SkyCoord from astropy.cosmology", "to be held @param xlabel, ylabel :: labels of the", "= ax.plot(ra_cen, dec_cen, '.', color= 'k', markersize=0.06, label=r'Host-halos $P_{id}=-1$', alpha=0.4)", "Host (central) halos: %.2e, Sattelite halos: %.2e'%(len(pos_z_AGN[0]), len(ra_cen), len(ra_sat))) return", "Last updated on 30th March 2021 \"\"\" # astropy modules", "Function to plot the AGN cluster distribution @pos_z_clu :: postion", "ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if xlim != 'default': ax.set_xlim(xlim) if ylim !=", "return [labels, c, m, ms, mec, mew] def plotTimeSinceMergerDist(scale_merger_AGN, scale_merger_gal,", "notebook (.ipynb) of the repository: 01. Exploring parameters in DM", "= ['b', '#38cee8', 'k', 'grey'], ['^', '*', '^', '*'], [9,", "central, satellite merger distributions as per visual preference for i", "ax = plt.subplots(1,2,figsize=(19,7)) # getting the useful histogram properties counts_agn,", "= bin_size[1]) merger_bins_agn = merger_bins_agn[:-1] merger_bins_gal = merger_bins_gal[:-1] else: merger_bins_agn,", "color= 'k', markersize=0.06, label=r'Host-halos $P_{id}=-1$', alpha=0.4) # plotting sat halos", "(deg)', 'Dec (deg)', '', xlim, ylim, legend=True) print('AGNs: %d, Host", "cluster distribution @pos_z_clu :: postion and redshifts of all the", "limits xlim = [np.min(pos_z_halo[0]), np.max(pos_z_halo[0])] ylim = [np.min(pos_z_halo[1]), np.max(pos_z_halo[1])] setLabel(ax,", "the linestyles used to denote these cuts (refer to the", "'default': ax.set_ylim(ylim) if legend: l = ax.legend(loc='best', fontsize=14) for legend_handle", "times @l :: array that defines the linestyles used to", "label=r'Host-halos $P_{id}=-1$', alpha=0.4) # plotting sat halos sat_halos = ax.plot(ra_sat,", "the agn fraction in the given pixel @pos_z_AGN :: postion", "plot_params, redshift_limit): \"\"\" Function to plot the time since merger", "def mergerRedshiftPlot(cen_sat_AGN, cen_sat_halo, dt_m, plot_params, redshift_limit): \"\"\" Function to plot", "to plot the AGN cluster distribution @pos_z_clu :: postion and", "plot showing the dependence of redshift on comoving distance \"\"\"", "for notebook 01_Exploring_DM_Halos This python file contains all the functions", "def setLabel(ax, xlabel, ylabel, title, xlim, ylim, legend=True): \"\"\" Function", "# astropy modules import astropy.units as u import astropy.io.fits as", "galaxies and agns ax.plot(merger_bins_gal, np.cumsum(c_t_gal), 'k^', label='DM Halos', ms=4) ax.plot(merger_bins_agn,", "'Dec (deg)', '', xlim, ylim, legend=True) print('AGNs: %d, Host (central)", "\"\"\" Function to plot the AGN cluster distribution @pos_z_clu ::", "'*'], [9, 15, 5, 9] mec, mew = ['w', 'k',", "r'$\\Delta t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]', 'Cumulative counts', '', 'default', 'default',", "cosmo, bin_size, redshift_limit): \"\"\" Plot the distribution of halos with", "This python file contains all the functions used for plotting", "AGNs(galaxies) @dt_m :: time difference after merger for cen/sat AGNs(galaxies)", "plot the agn fraction in the given pixel @pos_z_AGN ::", "merger events in the halos t_merger_agn = edh.getMergerTimeDifference(scale_merger_AGN, z_AGN, cosmo)", "\"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) # change marker size for", "[np.min(pos_z_AGN[1]), np.max(pos_z_AGN[1])] setLabel(ax, 'R.A. (deg)', 'Dec (deg)', '', xlim, ylim,", "satellite merger distributions as per visual preference for i in", "import interp1d import os import importlib # plotting imports import", "r'Redshift$_R$', r'$f_{AGN}$ (%s)'%\"%\", '', xlim, 'default', legend=False) ax[1].set_yscale(\"log\") plt.savefig('figures/agn_frac.pdf', facecolor='w',", "merger_bins_agn[:-1] merger_bins_gal = merger_bins_gal[:-1] else: merger_bins_agn, c_t_agn = np.unique(t_merger_agn, return_counts=True)", "cosmo) t_merger_gal = edh.getMergerTimeDifference(scale_merger_gal, z_gal, cosmo) # get the t", "halo distribution @hd_halo :: table with all relevant info on", "0, 1]: ax.plot(dt_m[i], z_R[i], plot_params[2][i], color=plot_params[1][i], ms=plot_params[3][i], label=plot_params[0][i], markeredgecolor=plot_params[4][i], markeredgewidth=plot_params[5][i])", "the time difference since merger events in the halos t_merger_agn", "[2, 3, 0, 1]: ax.plot(dt_m[i], z_R[i], plot_params[2][i], color=plot_params[1][i], ms=plot_params[3][i], label=plot_params[0][i],", "import os import importlib # plotting imports import matplotlib from", "redshift_bins_gal[1:] def plotRedshiftComovingDistance(cosmo, redshift_limit, resolution = 0.0001): \"\"\"Function to plot", "if bin_size[0]: c_t_agn, merger_bins_agn = np.histogram(np.array(t_merger_agn), bins = bin_size[1]) c_t_gal,", "np.cumsum(c_t_agn), 'b^', label='AGNs', ms=4) # set labels/legends setLabel(ax, r'$\\Delta t_{merger}", "@dt_m :: time difference after merger for cen/sat AGNs(galaxies) @plot_params", "axis properties - 0 xlim = [np.min(redshift_bins_agn[1:]), np.max(redshift_bins_agn[1:])] setLabel(ax[0], r'Redshift$_R$',", "ms=4) ax.plot(merger_bins_agn, np.cumsum(c_t_agn), 'b^', label='AGNs', ms=4) # set labels/legends setLabel(ax,", "fig, ax = plt.subplots(1,1,figsize=(9,8)) # plotting host halos host_halos =", "the time since merger distribution for galaxies and agns ax.plot(merger_bins_gal,", "a_max = np.min(merger_val_gal), np.max(merger_val_gal) scale_factor_arr = [a_max, a_min*4, a_min*2, a_min]", "c_agn = np.unique(cen_sat_AGN[i]['HALO_scale_of_last_MM'], return_counts=True) s_m_gal, c_gal = np.unique(cen_sat_halo[i]['HALO_scale_of_last_MM'], return_counts=True) #", "xlim = [np.min(redshift_bins_agn[1:])-0.02, np.max(redshift_bins_agn[1:])] setLabel(ax[1], r'Redshift$_R$', r'$f_{AGN}$ (%s)'%\"%\", '', xlim,", "to plot the agn fraction in the given pixel @pos_z_AGN", "graphs and maps in the 1st notebook (.ipynb) of the", "plt.savefig('figures/merger_distribution_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') return def plotCentralSatelliteScaleMergers(cen_sat_AGN, cen_sat_halo, redshift_limit): \"\"\" Function", ":: cosmology package loaded @redshift_limit :: upper limit in redshift", "+ 2 ax.plot(s_m_gal, c_gal, color=c[j], marker=m[j], ls='', ms=ms[j], label=labels[j], markeredgecolor=mec[j],", "dt_m, plot_params, redshift_limit): \"\"\" Function to plot the time since", "scipy.interpolate import interp1d import os import importlib # plotting imports", "distribution @pos_z_clu :: postion and redshifts of all the selected", "within the concerned plot @t_merger_cut_arr :: array that defines the", "', redshift_limit) return [labels, c, m, ms, mec, mew] def", "facecolor='w', edgecolor='w') return def plotCentralSatelliteScaleMergers(cen_sat_AGN, cen_sat_halo, redshift_limit): \"\"\" Function to", "limit on redshift based on the clusters found \"\"\" fig,", "ax.plot(pos_z_halo[0], pos_z_halo[1], '.', color='#fcd16d', markersize=0.2, label=r'All DM Halos', alpha=0.2) #", "\"\"\" for i, t_m_cut in enumerate(t_merger_cut_arr): ax.axvline(x=t_m_cut, color='r', linestyle= l[i],", "'Counts', '', 'default', 'default', legend=True) ax.set_yscale(\"log\") # setting the x-label", "loaded @redshift_limit :: upper limit in redshift --> end point", "as plt from mpl_toolkits.mplot3d.axes3d import Axes3D from matplotlib.ticker import LinearLocator,", "halos'] c, m, ms = ['b', '#38cee8', 'k', 'grey'], ['^',", "= plt.gca() ax2 = ax1.twiny() # plot the merger distribution", "as a function of the redshift @cen_sat_AGN(gal) :: handels to", "color='#fcd16d', markersize=0.2, label=r'All DM Halos', alpha=0.2) # plotting clusters cluster", "edh.getMergerTimeDifference(scale_merger_gal, z_gal, cosmo) # get the t since merger bins", "pos_z_clu[1], 'o', color= '#03a351', markersize=3, label=r'Clusters $M_{500c}> 10^{%.1f} M_\\odot$ '%(np.log10(halo_m_500c)))", "galaxies within them --> divided into 3 because each hd_halo", "galaxies \"\"\" halo_m_500c = cluster_params[0] fig, ax = plt.subplots(1,1,figsize=(9,8)) #", "2 ax.plot(s_m_gal, c_gal, color=c[j], marker=m[j], ls='', ms=ms[j], label=labels[j], markeredgecolor=mec[j], markeredgewidth=mew[j])", "# set labels/legends setLabel(ax, r'$\\Delta t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]', r'Redshift$_R$',", "useful histogram properties counts_agn, redshift_bins_agn = np.histogram(pos_z_AGN[2], bins = bin_size)", "ax, fig, t_merger_agn, t_merger_gal def mergerRedshiftPlot(cen_sat_AGN, cen_sat_halo, dt_m, plot_params, redshift_limit):", ":: table with all relevant info on halos, clusters, and", "dec_sat = pos_z_sat_halo[0], pos_z_sat_halo[1] fig, ax = plt.subplots(1,1,figsize=(9,8)) # plotting", "'^', '*'], [9, 15, 5, 9] mec, mew = ['w',", "'', 'default', 'default', legend=True) ax.set_yscale(\"log\") # setting the x-label on", "Function defining plot properties @param ax :: axes to be", ":: time difference after merger for cen/sat AGNs(galaxies) @plot_params ::", "hd_halo holds info on 1000 halos alone @pos_z_AGN :: postion", "redshifts = np.arange(0,redshift_limit, resolution) ax.plot(redshifts, distance_Mpc, 'k.', ms=1) setLabel(ax, 'Redshift", "'default': ax.set_xlim(xlim) if ylim != 'default': ax.set_ylim(ylim) if legend: l", "for plotting graphs and maps in the 1st notebook (.ipynb)", "getting the useful histogram properties counts_agn, redshift_bins_agn = np.histogram(pos_z_AGN[2], bins", "merger_bins_gal = np.histogram(np.array(t_merger_gal), bins = bin_size[1]) merger_bins_agn = merger_bins_agn[:-1] merger_bins_gal", "@pos_z_gal :: postion and redshifts of all the selected galaxies", "alpha=0.7) # labeling axes and defining limits xlim = [np.min(pos_z_halo[0]),", "a_min*4, a_min*2, a_min] ax2.set_xticks([(1/a) -1 for a in scale_factor_arr]) ax2.invert_xaxis()", "pos_z_halo[1], '.', color='#fcd16d', markersize=0.2, label=r'All DM Halos', alpha=0.2) # plotting", "color='#07d9f5', markersize=0.07, label=r'Satellite halos $P_{id} \\neq -1$', alpha=0.7) # plotting", "relation between redshift and the comoving distance @cosmo :: cosmology", "to plot the time since merger as a function of", "halos alone @pos_z_AGN :: postion and redshifts of all the", "the time since merger as a function of the redshift", "divided into 3 because each hd_halo holds info on 1000", "ax1 = plt.gca() ax2 = ax1.twiny() # plot the merger", "ax2 = ax1.twiny() # plot the merger distribution for galaxies", "setting the x-label on top (converting a to redshift) a_min,", "bin_size) # plotting the galaxy and agn distribution as a", "halos: %.2e, Sattelite halos: %.2e'%(len(pos_z_AGN[0]), len(ra_cen), len(ra_sat))) return def plotAGNfraction(pos_z_AGN,", "a_min] ax2.set_xticks([(1/a) -1 for a in scale_factor_arr]) ax2.invert_xaxis() ax2.set_xlabel('Redshift (z)')", "merger distributions as per visual preference for i in [2,", "ax[0].set_yscale(\"log\") # agn fraction as a function of redshift f_agn,", "= cluster_params[0] fig, ax = plt.subplots(1,1,figsize=(9,8)) # plotting halos halos", "the axis \"\"\" ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if xlim != 'default': ax.set_xlim(xlim)", "@param xlabel, ylabel :: labels of the x-y axis @param", "matplotlib.ticker import LinearLocator, FormatStrFormatter from matplotlib import cm from matplotlib.collections", "fraction ax[1].plot(z_bin_modified, f_agn, 's', color='#6b0385', ms=4) # axis properties -", "'central DM halos', 'satellite DM halos'] c, m, ms =", "time difference after merger for cen/sat AGNs(galaxies) @plot_params :: to", "galaxies @redshift_limit_agn :: upper limit on redshift based on the", "if c_gal != 0: f_agn.append(((counts_agn[c]*100)/c_gal)) idx.append(c) z_bin_modified = redshift_bins_gal[1:][np.array(idx)] #", "ax = plt.subplots(1,1,figsize=(9,8)) # plotting halos halos = ax.plot(pos_z_halo[0], pos_z_halo[1],", "function of redshift ax[0].plot(redshift_bins_gal[1:], counts_gal, 'ks', ms=4, label=r'DM Halos') ax[0].plot(redshift_bins_agn[1:],", "np.unique(t_merger_gal, return_counts=True) fig, ax = plt.subplots(1,1,figsize=(7,6)) # plot the time", ":: labels of the x-y axis @param title :: title", "plotAgnClusterDistribution(pos_z_clu, pos_z_AGN, pos_z_halo, cluster_params): \"\"\" Function to plot the AGN", "alpha=0.2) # plotting clusters cluster = ax.plot(pos_z_clu[0], pos_z_clu[1], 'o', color=", "(z)', 'Comoving distance (Mpc)', '', 'default', 'default', legend=False) print('Redshift-Comoving distance", "= ['w', 'k', 'k', '#abaeb3'], [0.7, 0.4, 1, 0.7] for", "in the notebook) \"\"\" for i, t_m_cut in enumerate(t_merger_cut_arr): ax.axvline(x=t_m_cut,", "@param title :: title of the plot @param xlim, ylim", "0 xlim = [np.min(redshift_bins_agn[1:]), np.max(redshift_bins_agn[1:])] setLabel(ax[0], r'Redshift$_R$', 'Counts','', xlim, 'default',", "ylabel :: labels of the x-y axis @param title ::", "redshift_limit): \"\"\" Function to plot the distribution (counts) of the", ":: resolution of time steps (set to e-4 based of", ":: title of the plot @param xlim, ylim :: x-y", "fig, ax = plt.subplots(1,1,figsize=(7,6)) # change marker size for central", "facecolor='w', edgecolor='w') print( 'Reddhift z<%.2f'%redshift_limit_agn ) return redshift_bins_gal[1:] def plotRedshiftComovingDistance(cosmo,", "bins = bin_size[1]) merger_bins_agn = merger_bins_agn[:-1] merger_bins_gal = merger_bins_gal[:-1] else:", "to denote these cuts (refer to the initial codeblock in", "with all relevant info on halos, clusters, and galaxies within", "time since merger distribution for galaxies and agns ax.plot(merger_bins_gal, np.cumsum(c_t_gal),", "0.0001): \"\"\"Function to plot the relation between redshift and the", "the central and satellite AGNs(galaxies) @dt_m :: time difference after", "info on 1000 halos alone @pos_z_AGN :: postion and redshifts", "return redshift_bins_gal[1:] def plotRedshiftComovingDistance(cosmo, redshift_limit, resolution = 0.0001): \"\"\"Function to", "= ax.plot(pos_z_clu[0], pos_z_clu[1], 'o', color= '#03a351', markersize=3, label=r'Clusters $M_{500c}> 10^{%.1f}", "[np.min(pos_z_halo[0]), np.max(pos_z_halo[0])] ylim = [np.min(pos_z_halo[1]), np.max(pos_z_halo[1])] setLabel(ax, 'R.A. (deg)', 'Dec", "pos_z_sat_halo[0], pos_z_sat_halo[1] fig, ax = plt.subplots(1,1,figsize=(9,8)) # plotting host halos", "on 1000 halos alone @pos_z_AGN :: postion and redshifts of", "'%(np.log10(halo_m_500c))) # plotting AGNs agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='k',", "AGNs \"\"\" ra_cen, dec_cen = pos_z_cen_halo[0], pos_z_cen_halo[1] ra_sat, dec_sat =", "the given pixel @pos_z_AGN :: postion and redshifts of all", "3, 0, 1]: ax.plot(dt_m[i], z_R[i], plot_params[2][i], color=plot_params[1][i], ms=plot_params[3][i], label=plot_params[0][i], markeredgecolor=plot_params[4][i],", "!= 'default': ax.set_xlim(xlim) if ylim != 'default': ax.set_ylim(ylim) if legend:", "cluster_params[0] fig, ax = plt.subplots(1,1,figsize=(9,8)) # plotting halos halos =", "= plt.subplots(1,1,figsize=(7,6)) labels = [r'central AGNs', r'satellite AGNs', 'central DM", "halos sat_halos = ax.plot(ra_sat, dec_sat, 'o', color='#07d9f5', markersize=0.07, label=r'Satellite halos", "resolution) @Returns :: plot showing the dependence of redshift on", "counts', '', 'default', 'default', legend=False) ax.legend(loc='lower left', fontsize=14) ax.set_yscale(\"log\") ax.set_xscale(\"log\")", "f_agn.append(((counts_agn[c]*100)/c_gal)) idx.append(c) z_bin_modified = redshift_bins_gal[1:][np.array(idx)] # plot agn fraction ax[1].plot(z_bin_modified,", "a in scale_factor_arr]) ax2.invert_xaxis() ax2.set_xlabel('Redshift (z)') ax2.xaxis.set_major_formatter(FormatStrFormatter('%.1f')) print(\"Objects with merger", "a function of redshift ax[0].plot(redshift_bins_gal[1:], counts_gal, 'ks', ms=4, label=r'DM Halos')", "redshifts of all the selected 'clusters' @pos_z_AGN :: postion and", "axes_grid1 import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D from", "= np.min(merger_val_gal), np.max(merger_val_gal) scale_factor_arr = [a_max, a_min*4, a_min*2, a_min] ax2.set_xticks([(1/a)", "ax :: axes to be held @param xlabel, ylabel ::", "markeredgecolor=mec[i], markeredgewidth=mew[i]) # DM halos j = i + 2", "label=r'AGN', alpha=0.7) # labeling axes and defining limits xlim =", "%d, Host (central) halos: %.2e, Sattelite halos: %.2e'%(len(pos_z_AGN[0]), len(ra_cen), len(ra_sat)))", "t_merger_gal = edh.getMergerTimeDifference(scale_merger_gal, z_gal, cosmo) # get the t since", "np.histogram(pos_z_AGN[2], bins = bin_size) counts_gal, redshift_bins_gal = np.histogram(pos_z_gal[2], bins =", "@cen_sat_AGN(gal) :: handels to access the central and satellite AGNs(galaxies)", "as a function of redshift f_agn, idx = [], []", "halos j = i + 2 ax.plot(s_m_gal, c_gal, color=c[j], marker=m[j],", "ax.set_yscale(\"log\") # setting the x-label on top (converting a to", "to e-4 based of simulation resolution) @Returns :: plot showing", "plotCentralSatelliteScaleMergers(cen_sat_AGN, cen_sat_halo, redshift_limit): \"\"\" Function to plot the central and", "'Redshift (z)', 'Comoving distance (Mpc)', '', 'default', 'default', legend=False) print('Redshift-Comoving", "= np.arange(0,redshift_limit, resolution) ax.plot(redshifts, distance_Mpc, 'k.', ms=1) setLabel(ax, 'Redshift (z)',", "'bs', ms=4, label=r'AGNs') # axis properties - 0 xlim =", "# plot agn fraction ax[1].plot(z_bin_modified, f_agn, 's', color='#6b0385', ms=4) #", "r'$\\Delta t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]', r'Redshift$_R$', '', 'default', 'default', legend=True)", "cosmo, redshift_limit): \"\"\" Function to plot the distribution (counts) of", "scale factor/redshift \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) ax1 = plt.gca()", "ylim, legend=True) print('Redshift z<%.2f'%(np.max(pos_z_clu[2]))) return def plotHostSubHalos(pos_z_cen_halo, pos_z_sat_halo, pos_z_AGN): \"\"\"", "9] mec, mew = ['w', 'k', 'k', '#abaeb3'], [0.7, 0.4,", "held @param xlabel, ylabel :: labels of the x-y axis", "cluster = ax.plot(pos_z_clu[0], pos_z_clu[1], 'o', color= '#03a351', markersize=3, label=r'Clusters $M_{500c}>", "@resolution :: resolution of time steps (set to e-4 based", "plt.subplots(1,1,figsize=(7,6)) # plot the time since merger distribution for galaxies", "setLabel(ax, r'$\\Delta t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]', 'Cumulative counts', '', 'default',", "notebook) \"\"\" for i, t_m_cut in enumerate(t_merger_cut_arr): ax.axvline(x=t_m_cut, color='r', linestyle=", "DM halos and sub-halos Script written by: <NAME> Project supervised", "defined cuts in merger times within the concerned plot @t_merger_cut_arr", "SkyCoord from astropy.cosmology import FlatLambdaCDM, z_at_value import numpy as np", "(Mpc)', '', 'default', 'default', legend=False) print('Redshift-Comoving distance relationship') return def", "of last Major Merger', 'Counts', '', 'default', 'default', legend=True) ax.set_yscale(\"log\")", "plotting imports import matplotlib from mpl_toolkits import axes_grid1 import matplotlib.pyplot", "m, ms] \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) # change marker", "'k^', label='DM Halos', ms=4) ax.plot(merger_bins_agn, np.cumsum(c_t_agn), 'b^', label='AGNs', ms=4) #", "# plotting sat halos sat_halos = ax.plot(ra_sat, dec_sat, 'o', color='#07d9f5',", "size for central DM halos plot_params[3][1] = 9 z_R =", "'default', legend=True) ax[0].set_yscale(\"log\") # agn fraction as a function of", "'default', legend=True) ax.set_yscale(\"log\") # setting the x-label on top (converting", "astropy.cosmology import FlatLambdaCDM, z_at_value import numpy as np # scipy", "= pos_z_sat_halo[0], pos_z_sat_halo[1] fig, ax = plt.subplots(1,1,figsize=(9,8)) # plotting host", "AGNs agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='k', markersize=3.5, label=r'AGN', alpha=0.7)", "import PatchCollection from matplotlib.patches import Rectangle import Exploring_DM_Haloes as edh", "repository: 01. Exploring parameters in DM halos and sub-halos Script", "ax[0].plot(redshift_bins_agn[1:], counts_agn, 'bs', ms=4, label=r'AGNs') # axis properties - 0", "plots, array containing [labels, c, m, ms] \"\"\" fig, ax", "1000 halos alone @pos_z_AGN :: postion and redshifts of all", "u import astropy.io.fits as fits from astropy.table import Table, Column", "'', 'default', 'default', legend=True) ax.set_yscale(\"log\") plt.savefig('figures/merger_dist_cenAndsat_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') print('Objects below", "on top (converting a to redshift) a_min, a_max = np.min(merger_val_gal),", "setLabel(ax, r'Scale, $a(t)$, of last Major Merger', 'Counts', '', 'default',", "the AGN cluster distribution @pos_z_clu :: postion and redshifts of", "# setting the x-label on top (converting a to redshift)", "= pos_z_cen_halo[0], pos_z_cen_halo[1] ra_sat, dec_sat = pos_z_sat_halo[0], pos_z_sat_halo[1] fig, ax", "'kx', label='DM Halos') ax1.plot(merger_val_agn, counts_agn, 'bx', label='AGNs') setLabel(ax1, r'Scale, $a(t)$,", "and redshifts of all the selected 'clusters' @pos_z_AGN :: postion", "'default', 'default', legend=False) print('Redshift-Comoving distance relationship') return def plotMergerDistribution(merger_val_gal, counts_gal,", "return ax, fig, t_merger_agn, t_merger_gal def mergerRedshiftPlot(cen_sat_AGN, cen_sat_halo, dt_m, plot_params,", "# plotting host halos host_halos = ax.plot(ra_cen, dec_cen, '.', color=", "contains all the functions used for plotting graphs and maps", "imports import matplotlib from mpl_toolkits import axes_grid1 import matplotlib.pyplot as", "set labels/legends setLabel(ax, r'$\\Delta t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]', r'Redshift$_R$', '',", "xlim = [np.min(pos_z_halo[0]), np.max(pos_z_halo[0])] ylim = [np.min(pos_z_halo[1]), np.max(pos_z_halo[1])] setLabel(ax, 'R.A.", "# plotting halos halos = ax.plot(pos_z_halo[0], pos_z_halo[1], '.', color='#fcd16d', markersize=0.2,", "z_R[i], plot_params[2][i], color=plot_params[1][i], ms=plot_params[3][i], label=plot_params[0][i], markeredgecolor=plot_params[4][i], markeredgewidth=plot_params[5][i]) # set labels/legends", "23rd February 2021 Last updated on 30th March 2021 \"\"\"", "agns ax.plot(merger_bins_gal, np.cumsum(c_t_gal), 'k^', label='DM Halos', ms=4) ax.plot(merger_bins_agn, np.cumsum(c_t_agn), 'b^',", "'', xlim, ylim, legend=True) print('AGNs: %d, Host (central) halos: %.2e,", "all the selected AGNs @pos_z_gal :: postion and redshifts of", "= edh.getMergerTimeDifference(scale_merger_AGN, z_AGN, cosmo) t_merger_gal = edh.getMergerTimeDifference(scale_merger_gal, z_gal, cosmo) #", "on 30th March 2021 \"\"\" # astropy modules import astropy.units", "pos_z_sat_halo, pos_z_AGN): \"\"\" Function to plot the host and satellite", "February 2021 Last updated on 30th March 2021 \"\"\" #", "[r'central AGNs', r'satellite AGNs', 'central DM halos', 'satellite DM halos']", "legend=True): \"\"\" Function defining plot properties @param ax :: axes", "= bin_size) # plotting the galaxy and agn distribution as", "redshift @cen_sat_AGN(gal) :: handels to access the central and satellite", "FlatLambdaCDM, z_at_value import numpy as np # scipy modules from", "= np.unique(t_merger_agn, return_counts=True) merger_bins_gal, c_t_gal = np.unique(t_merger_gal, return_counts=True) fig, ax", "pos_z_gal, redshift_limit_agn, bin_size): \"\"\" Function to plot the agn fraction", "@param xlim, ylim :: x-y limits for the axis \"\"\"", "in enumerate(counts_gal): if c_gal != 0: f_agn.append(((counts_agn[c]*100)/c_gal)) idx.append(c) z_bin_modified =", "facecolor='w', edgecolor='w') return ax def plotMergerTimeCuts(ax, t_merger_cut_arr, l): \"\"\" Function", "import astropy.units as u import astropy.io.fits as fits from astropy.table", "bin_size): \"\"\" Function to plot the agn fraction in the", "Major Merger', 'Counts', '', 'default', 'default', legend=True) ax.set_yscale(\"log\") # setting", "fraction in the given pixel @pos_z_AGN :: postion and redshifts", "ms=4, label=r'DM Halos') ax[0].plot(redshift_bins_agn[1:], counts_agn, 'bs', ms=4, label=r'AGNs') # axis", "ax.plot(pos_z_clu[0], pos_z_clu[1], 'o', color= '#03a351', markersize=3, label=r'Clusters $M_{500c}> 10^{%.1f} M_\\odot$", "legend_handle in l.legendHandles: legend_handle._legmarker.set_markersize(12) ax.grid(False) ax.set_title(title, fontsize=18) return def plotAgnClusterDistribution(pos_z_clu,", "after merger for cen/sat AGNs(galaxies) @plot_params :: to keep consistency", ":: array that defines the cuts in the merger times", "between redshift and the comoving distance @cosmo :: cosmology package", "a to redshift) a_min, a_max = np.min(merger_val_gal), np.max(merger_val_gal) scale_factor_arr =", "title, xlim, ylim, legend=True): \"\"\" Function defining plot properties @param", "[], [] for c, c_gal in enumerate(counts_gal): if c_gal !=", "mpl_toolkits.mplot3d.axes3d import Axes3D from matplotlib.ticker import LinearLocator, FormatStrFormatter from matplotlib", "halos and sub-halos Script written by: <NAME> Project supervised by", "ylim = [np.min(pos_z_halo[1]), np.max(pos_z_halo[1])] setLabel(ax, 'R.A. (deg)', 'Dec (deg)', '',", ":: postion and redshifts of all the selected AGNs \"\"\"", "label='DM Halos', ms=4) ax.plot(merger_bins_agn, np.cumsum(c_t_agn), 'b^', label='AGNs', ms=4) # set", "central and sattelite scale factors for mergers \"\"\" fig, ax", "(converting a to redshift) a_min, a_max = np.min(merger_val_gal), np.max(merger_val_gal) scale_factor_arr", "point for interpolation @resolution :: resolution of time steps (set", "redshifts of all the selected AGNs \"\"\" ra_cen, dec_cen =", "bin_size, redshift_limit): \"\"\" Plot the distribution of halos with respective", "edgecolor='w') return def plotCentralSatelliteScaleMergers(cen_sat_AGN, cen_sat_halo, redshift_limit): \"\"\" Function to plot", "'#abaeb3'], [0.7, 0.4, 1, 0.7] for i in [0, 1]:", "# agns ax.plot(s_m_agn, c_agn, color=c[i], marker=m[i], ls='', ms=ms[i], label=labels[i], markeredgecolor=mec[i],", "array containing [labels, c, m, ms] \"\"\" fig, ax =", "mec, mew = ['w', 'k', 'k', '#abaeb3'], [0.7, 0.4, 1,", "as np # scipy modules from scipy.spatial import KDTree from", "t(z_{merger})-t(z_{current})$ [Gyr]', 'Cumulative counts', '', 'default', 'default', legend=False) ax.legend(loc='lower left',", "ms=ms[j], label=labels[j], markeredgecolor=mec[j], markeredgewidth=mew[j]) # set label setLabel(ax, r'Scale, $a(t)$,", "'bx', label='AGNs') setLabel(ax1, r'Scale, $a(t)$, of last Major Merger', 'Counts',", "t_merger_agn, t_merger_gal def mergerRedshiftPlot(cen_sat_AGN, cen_sat_halo, dt_m, plot_params, redshift_limit): \"\"\" Function", "# set labels/legends setLabel(ax, r'$\\Delta t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]', 'Cumulative", "label=labels[j], markeredgecolor=mec[j], markeredgewidth=mew[j]) # set label setLabel(ax, r'Scale, $a(t)$, of", "xlim = [np.min(pos_z_AGN[0]), np.max(pos_z_AGN[0])] ylim = [np.min(pos_z_AGN[1]), np.max(pos_z_AGN[1])] setLabel(ax, 'R.A.", "legend=True) print('Redshift z<%.2f'%(np.max(pos_z_clu[2]))) return def plotHostSubHalos(pos_z_cen_halo, pos_z_sat_halo, pos_z_AGN): \"\"\" Function", "c_gal, color=c[j], marker=m[j], ls='', ms=ms[j], label=labels[j], markeredgecolor=mec[j], markeredgewidth=mew[j]) # set", "plot properties @param ax :: axes to be held @param", "and redshifts of all the selected AGNs @pos_z_gal :: postion", "setLabel(ax[1], r'Redshift$_R$', r'$f_{AGN}$ (%s)'%\"%\", '', xlim, 'default', legend=False) ax[1].set_yscale(\"log\") plt.savefig('figures/agn_frac.pdf',", "= plt.subplots(1,1,figsize=(7,6)) # change marker size for central DM halos", "'default', 'default', legend=True) ax.set_yscale(\"log\") plt.savefig('figures/merger_dist_cenAndsat_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') print('Objects below z:", "the host and satellite halo distribution @hd_halo :: table with", "fig, ax = plt.subplots(1,1,figsize=(7,6)) labels = [r'central AGNs', r'satellite AGNs',", "halos', 'satellite DM halos'] c, m, ms = ['b', '#38cee8',", "import cm from matplotlib.collections import PatchCollection from matplotlib.patches import Rectangle", "end point for interpolation @resolution :: resolution of time steps", "ax.plot(merger_bins_gal, np.cumsum(c_t_gal), 'k^', label='DM Halos', ms=4) ax.plot(merger_bins_agn, np.cumsum(c_t_agn), 'b^', label='AGNs',", "astropy.units as u import astropy.io.fits as fits from astropy.table import", "merger_bins_agn = merger_bins_agn[:-1] merger_bins_gal = merger_bins_gal[:-1] else: merger_bins_agn, c_t_agn =", "markeredgecolor=mec[j], markeredgewidth=mew[j]) # set label setLabel(ax, r'Scale, $a(t)$, of last", "as fits from astropy.table import Table, Column from astropy.coordinates import", "30th March 2021 \"\"\" # astropy modules import astropy.units as", "of the merger scale factor/redshift \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6))", "merger_bins_gal = merger_bins_gal[:-1] else: merger_bins_agn, c_t_agn = np.unique(t_merger_agn, return_counts=True) merger_bins_gal,", "ax.plot(dt_m[i], z_R[i], plot_params[2][i], color=plot_params[1][i], ms=plot_params[3][i], label=plot_params[0][i], markeredgecolor=plot_params[4][i], markeredgewidth=plot_params[5][i]) # set", "z_bin_modified = redshift_bins_gal[1:][np.array(idx)] # plot agn fraction ax[1].plot(z_bin_modified, f_agn, 's',", "initial codeblock in the notebook) \"\"\" for i, t_m_cut in", "each hd_halo holds info on 1000 halos alone @pos_z_AGN ::", "agn fraction ax[1].plot(z_bin_modified, f_agn, 's', color='#6b0385', ms=4) # axis properties", "facecolor='w', edgecolor='w') print('Objects below z: ', redshift_limit) return [labels, c,", "DM halos'] c, m, ms = ['b', '#38cee8', 'k', 'grey'],", "@param ax :: axes to be held @param xlabel, ylabel", "ax2.xaxis.set_major_formatter(FormatStrFormatter('%.1f')) print(\"Objects with merger redshifts z < %.2f\"%z_at_value(cosmo.scale_factor, a_min)) plt.savefig('figures/merger_distribution_z%.2f.pdf'%redshift_limit,", "the distribution (counts) of the merger scale factor/redshift \"\"\" fig,", "since merger \"\"\" # get the time difference since merger", "(set to e-4 based of simulation resolution) @Returns :: plot", "to plot the relation between redshift and the comoving distance", "= edh.getMergerTimeDifference(scale_merger_gal, z_gal, cosmo) # get the t since merger", "= 0.0001): \"\"\"Function to plot the relation between redshift and", "below z: ', redshift_limit) return [labels, c, m, ms, mec,", "for galaxies and agns ax.plot(merger_bins_gal, np.cumsum(c_t_gal), 'k^', label='DM Halos', ms=4)", "\"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) ax1 = plt.gca() ax2 =", "return def plotCentralSatelliteScaleMergers(cen_sat_AGN, cen_sat_halo, redshift_limit): \"\"\" Function to plot the", "print('Redshift-Comoving distance relationship') return def plotMergerDistribution(merger_val_gal, counts_gal, merger_val_agn, counts_agn, cosmo,", "= plt.subplots(1,1,figsize=(7,6)) distance_Mpc = cosmo.comoving_distance(np.arange(0,redshift_limit, resolution)) redshifts = np.arange(0,redshift_limit, resolution)", "# get the t since merger bins and counts if", "= ax.plot(ra_sat, dec_sat, 'o', color='#07d9f5', markersize=0.07, label=r'Satellite halos $P_{id} \\neq", "print(\"Objects with merger redshifts z < %.2f\"%z_at_value(cosmo.scale_factor, a_min)) plt.savefig('figures/merger_distribution_z%.2f.pdf'%redshift_limit, facecolor='w',", "t_merger_agn = edh.getMergerTimeDifference(scale_merger_AGN, z_AGN, cosmo) t_merger_gal = edh.getMergerTimeDifference(scale_merger_gal, z_gal, cosmo)", "def plotMergerDistribution(merger_val_gal, counts_gal, merger_val_agn, counts_agn, cosmo, redshift_limit): \"\"\" Function to", "these cuts (refer to the initial codeblock in the notebook)", "file contains all the functions used for plotting graphs and", "ms=ms[i], label=labels[i], markeredgecolor=mec[i], markeredgewidth=mew[i]) # DM halos j = i", "halos: %.2e'%(len(pos_z_AGN[0]), len(ra_cen), len(ra_sat))) return def plotAGNfraction(pos_z_AGN, pos_z_gal, redshift_limit_agn, bin_size):", "as per visual preference for i in [2, 3, 0,", "ylabel, title, xlim, ylim, legend=True): \"\"\" Function defining plot properties", "'default', 'default', legend=True) ax.set_xscale(\"log\") plt.savefig('figures/t_since_merger_z_plot_%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') return ax def", "comoving distance \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) distance_Mpc = cosmo.comoving_distance(np.arange(0,redshift_limit,", "ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='#fff717', markersize=6.5, label=r'AGN', markeredgecolor='w', markeredgewidth=0.4) # labeling", "np.unique(t_merger_agn, return_counts=True) merger_bins_gal, c_t_gal = np.unique(t_merger_gal, return_counts=True) fig, ax =", "in enumerate(t_merger_cut_arr): ax.axvline(x=t_m_cut, color='r', linestyle= l[i], label='%.1f Gyr'%t_m_cut) ax.legend(fontsize=14, loc='lower", "plot_params[2][i], color=plot_params[1][i], ms=plot_params[3][i], label=plot_params[0][i], markeredgecolor=plot_params[4][i], markeredgewidth=plot_params[5][i]) # set labels/legends setLabel(ax,", "selected AGNs @pos_z_gal :: postion and redshifts of all the", "# axis properties - 0 xlim = [np.min(redshift_bins_agn[1:]), np.max(redshift_bins_agn[1:])] setLabel(ax[0],", "$P_{id} \\neq -1$', alpha=0.7) # plotting AGNs agn = ax.plot(pos_z_AGN[0],", "agn fraction as a function of redshift f_agn, idx =", "ylim, legend=True): \"\"\" Function defining plot properties @param ax ::", "redshift_limit): \"\"\" Function to plot the time since merger as", "\"\"\" Function to plot the time since merger as a", "enumerate(counts_gal): if c_gal != 0: f_agn.append(((counts_agn[c]*100)/c_gal)) idx.append(c) z_bin_modified = redshift_bins_gal[1:][np.array(idx)]", "ms = ['b', '#38cee8', 'k', 'grey'], ['^', '*', '^', '*'],", "legend: l = ax.legend(loc='best', fontsize=14) for legend_handle in l.legendHandles: legend_handle._legmarker.set_markersize(12)", "\"\"\" halo_m_500c = cluster_params[0] fig, ax = plt.subplots(1,1,figsize=(9,8)) # plotting", "redshift_limit) return [labels, c, m, ms, mec, mew] def plotTimeSinceMergerDist(scale_merger_AGN,", "that defines the linestyles used to denote these cuts (refer", "# change marker size for central DM halos plot_params[3][1] =", "cluster_params): \"\"\" Function to plot the AGN cluster distribution @pos_z_clu", "\"\"\"Plotting.py for notebook 01_Exploring_DM_Halos This python file contains all the", "from astropy.cosmology import FlatLambdaCDM, z_at_value import numpy as np #", ":: plot showing the dependence of redshift on comoving distance", "l.legendHandles: legend_handle._legmarker.set_markersize(12) ax.grid(False) ax.set_title(title, fontsize=18) return def plotAgnClusterDistribution(pos_z_clu, pos_z_AGN, pos_z_halo,", "agns given the time since merger \"\"\" # get the", "ms] \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) # change marker size", "['w', 'k', 'k', '#abaeb3'], [0.7, 0.4, 1, 0.7] for i", "merger distribution for galaxies and agns ax1.plot(merger_val_gal, counts_gal, 'kx', label='DM", "if xlim != 'default': ax.set_xlim(xlim) if ylim != 'default': ax.set_ylim(ylim)", "labeling axes and defining limits xlim = [np.min(pos_z_AGN[0]), np.max(pos_z_AGN[0])] ylim", "ax def plotMergerTimeCuts(ax, t_merger_cut_arr, l): \"\"\" Function to plot the", "'default', legend=False) ax.legend(loc='lower left', fontsize=14) ax.set_yscale(\"log\") ax.set_xscale(\"log\") return ax, fig,", "setLabel(ax, 'R.A. (deg)', 'Dec (deg)', '', xlim, ylim, legend=True) print('AGNs:", "print('Objects below z: ', redshift_limit) return [labels, c, m, ms,", "['b', '#38cee8', 'k', 'grey'], ['^', '*', '^', '*'], [9, 15,", "merger_val_agn, counts_agn, cosmo, redshift_limit): \"\"\" Function to plot the distribution", "c_t_gal = np.unique(t_merger_gal, return_counts=True) fig, ax = plt.subplots(1,1,figsize=(7,6)) # plot", "= np.unique(t_merger_gal, return_counts=True) fig, ax = plt.subplots(1,1,figsize=(7,6)) # plot the", "5, 9] mec, mew = ['w', 'k', 'k', '#abaeb3'], [0.7,", "ax1.twiny() # plot the merger distribution for galaxies and agns", "legend=True) ax.set_yscale(\"log\") plt.savefig('figures/merger_dist_cenAndsat_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') print('Objects below z: ', redshift_limit)", "of redshift ax[0].plot(redshift_bins_gal[1:], counts_gal, 'ks', ms=4, label=r'DM Halos') ax[0].plot(redshift_bins_agn[1:], counts_agn,", "plt.subplots(1,1,figsize=(7,6)) # change marker size for central DM halos plot_params[3][1]", "ax[1].plot(z_bin_modified, f_agn, 's', color='#6b0385', ms=4) # axis properties - 1", "marker size for central DM halos plot_params[3][1] = 9 z_R", "cen_sat_halo[1]['redshift_R']] # plot central, satellite merger distributions as per visual", "= t(z_{merger})-t(z_{current})$ [Gyr]', 'Cumulative counts', '', 'default', 'default', legend=False) ax.legend(loc='lower", "legend=True) print('AGNs: %d, Host (central) halos: %.2e, Sattelite halos: %.2e'%(len(pos_z_AGN[0]),", "'Cumulative counts', '', 'default', 'default', legend=False) ax.legend(loc='lower left', fontsize=14) ax.set_yscale(\"log\")", "ax = plt.subplots(1,1,figsize=(7,6)) distance_Mpc = cosmo.comoving_distance(np.arange(0,redshift_limit, resolution)) redshifts = np.arange(0,redshift_limit,", "\"\"\" ra_cen, dec_cen = pos_z_cen_halo[0], pos_z_cen_halo[1] ra_sat, dec_sat = pos_z_sat_halo[0],", "in the halos t_merger_agn = edh.getMergerTimeDifference(scale_merger_AGN, z_AGN, cosmo) t_merger_gal =", "Script written by: <NAME> Project supervised by <NAME> Date created:", "ax1.plot(merger_val_gal, counts_gal, 'kx', label='DM Halos') ax1.plot(merger_val_agn, counts_agn, 'bx', label='AGNs') setLabel(ax1,", "halos halos = ax.plot(pos_z_halo[0], pos_z_halo[1], '.', color='#fcd16d', markersize=0.2, label=r'All DM", "[Gyr]', 'Cumulative counts', '', 'default', 'default', legend=False) ax.legend(loc='lower left', fontsize=14)", "t(z_{merger})-t(z_{current})$ [Gyr]', r'Redshift$_R$', '', 'default', 'default', legend=True) ax.set_xscale(\"log\") plt.savefig('figures/t_since_merger_z_plot_%.2f.pdf'%redshift_limit, facecolor='w',", "z_AGN, z_gal, cosmo, bin_size, redshift_limit): \"\"\" Plot the distribution of", "ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='k', markersize=3.5, label=r'AGN', alpha=0.7) # labeling axes", "and agn distribution as a function of redshift ax[0].plot(redshift_bins_gal[1:], counts_gal,", "[np.min(pos_z_AGN[0]), np.max(pos_z_AGN[0])] ylim = [np.min(pos_z_AGN[1]), np.max(pos_z_AGN[1])] setLabel(ax, 'R.A. (deg)', 'Dec", "ax.grid(False) ax.set_title(title, fontsize=18) return def plotAgnClusterDistribution(pos_z_clu, pos_z_AGN, pos_z_halo, cluster_params): \"\"\"", "redshift_bins_agn = np.histogram(pos_z_AGN[2], bins = bin_size) counts_gal, redshift_bins_gal = np.histogram(pos_z_gal[2],", "ms=1) setLabel(ax, 'Redshift (z)', 'Comoving distance (Mpc)', '', 'default', 'default',", "01_Exploring_DM_Halos This python file contains all the functions used for", "& agns given the time since merger \"\"\" # get", "a_min)) plt.savefig('figures/merger_distribution_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') return def plotCentralSatelliteScaleMergers(cen_sat_AGN, cen_sat_halo, redshift_limit): \"\"\"", "supervised by <NAME> Date created: 23rd February 2021 Last updated", "[np.min(pos_z_halo[1]), np.max(pos_z_halo[1])] setLabel(ax, 'R.A. (deg)', 'Dec (deg)', '', xlim, ylim,", "for i in [0, 1]: s_m_agn, c_agn = np.unique(cen_sat_AGN[i]['HALO_scale_of_last_MM'], return_counts=True)", "redshift ax[0].plot(redshift_bins_gal[1:], counts_gal, 'ks', ms=4, label=r'DM Halos') ax[0].plot(redshift_bins_agn[1:], counts_agn, 'bs',", "given pixel @pos_z_AGN :: postion and redshifts of all the", "ra_sat, dec_sat = pos_z_sat_halo[0], pos_z_sat_halo[1] fig, ax = plt.subplots(1,1,figsize=(9,8)) #", "z<%.2f'%(np.max(pos_z_clu[2]))) return def plotHostSubHalos(pos_z_cen_halo, pos_z_sat_halo, pos_z_AGN): \"\"\" Function to plot", "utf-8 -*- \"\"\"Plotting.py for notebook 01_Exploring_DM_Halos This python file contains", "all the selected galaxies \"\"\" halo_m_500c = cluster_params[0] fig, ax", "the plot @param xlim, ylim :: x-y limits for the", "\"\"\" Plot the distribution of halos with respective galaxies &", "astropy.io.fits as fits from astropy.table import Table, Column from astropy.coordinates", "label=labels[i], markeredgecolor=mec[i], markeredgewidth=mew[i]) # DM halos j = i +", "in the merger times @l :: array that defines the", "merger as a function of the redshift @cen_sat_AGN(gal) :: handels", "comoving distance @cosmo :: cosmology package loaded @redshift_limit :: upper", "color='k', markersize=3.5, label=r'AGN', alpha=0.7) # labeling axes and defining limits", "selected 'clusters' @pos_z_AGN :: postion and redshifts of all the", "color='#6b0385', ms=4) # axis properties - 1 xlim = [np.min(redshift_bins_agn[1:])-0.02,", "plotting sat halos sat_halos = ax.plot(ra_sat, dec_sat, 'o', color='#07d9f5', markersize=0.07,", "markersize=3, label=r'Clusters $M_{500c}> 10^{%.1f} M_\\odot$ '%(np.log10(halo_m_500c))) # plotting AGNs agn", "c_gal in enumerate(counts_gal): if c_gal != 0: f_agn.append(((counts_agn[c]*100)/c_gal)) idx.append(c) z_bin_modified", "agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='#fff717', markersize=6.5, label=r'AGN', markeredgecolor='w', markeredgewidth=0.4)", "edgecolor='w') print('Objects below z: ', redshift_limit) return [labels, c, m,", "sat_halos = ax.plot(ra_sat, dec_sat, 'o', color='#07d9f5', markersize=0.07, label=r'Satellite halos $P_{id}", "-*- coding: utf-8 -*- \"\"\"Plotting.py for notebook 01_Exploring_DM_Halos This python", "time difference since merger events in the halos t_merger_agn =", "merger_bins_gal, c_t_gal = np.unique(t_merger_gal, return_counts=True) fig, ax = plt.subplots(1,1,figsize=(7,6)) #", "'k.', ms=1) setLabel(ax, 'Redshift (z)', 'Comoving distance (Mpc)', '', 'default',", "cen_sat_halo[0]['redshift_R'], cen_sat_halo[1]['redshift_R']] # plot central, satellite merger distributions as per", "= np.histogram(np.array(t_merger_gal), bins = bin_size[1]) merger_bins_agn = merger_bins_agn[:-1] merger_bins_gal =", "halos, clusters, and galaxies within them --> divided into 3", "= np.histogram(pos_z_AGN[2], bins = bin_size) counts_gal, redshift_bins_gal = np.histogram(pos_z_gal[2], bins", "import numpy as np # scipy modules from scipy.spatial import", "label=r'All DM Halos', alpha=0.2) # plotting clusters cluster = ax.plot(pos_z_clu[0],", "halos host_halos = ax.plot(ra_cen, dec_cen, '.', color= 'k', markersize=0.06, label=r'Host-halos", "'o', color= '#03a351', markersize=3, label=r'Clusters $M_{500c}> 10^{%.1f} M_\\odot$ '%(np.log10(halo_m_500c))) #", "distance_Mpc, 'k.', ms=1) setLabel(ax, 'Redshift (z)', 'Comoving distance (Mpc)', '',", "postion and redshifts of all the selected AGNs \"\"\" ra_cen,", "factors for mergers \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) labels =", "ax[1].set_yscale(\"log\") plt.savefig('figures/agn_frac.pdf', facecolor='w', edgecolor='w') print( 'Reddhift z<%.2f'%redshift_limit_agn ) return redshift_bins_gal[1:]", "the redshift @cen_sat_AGN(gal) :: handels to access the central and", "and redshifts of all the selected galaxies @redshift_limit_agn :: upper", "numpy as np # scipy modules from scipy.spatial import KDTree", "and redshifts of all the selected AGNs \"\"\" ra_cen, dec_cen", "time since merger as a function of the redshift @cen_sat_AGN(gal)", "label=r'AGNs') # axis properties - 0 xlim = [np.min(redshift_bins_agn[1:]), np.max(redshift_bins_agn[1:])]", "\"\"\" Function to plot the agn fraction in the given", "\"\"\" # astropy modules import astropy.units as u import astropy.io.fits", "xlim, 'default', legend=False) ax[1].set_yscale(\"log\") plt.savefig('figures/agn_frac.pdf', facecolor='w', edgecolor='w') print( 'Reddhift z<%.2f'%redshift_limit_agn", "[labels, c, m, ms, mec, mew] def plotTimeSinceMergerDist(scale_merger_AGN, scale_merger_gal, z_AGN,", "xlabel, ylabel, title, xlim, ylim, legend=True): \"\"\" Function defining plot", "of all the selected 'clusters' @pos_z_AGN :: postion and redshifts", "galaxy and agn distribution as a function of redshift ax[0].plot(redshift_bins_gal[1:],", "interp1d import os import importlib # plotting imports import matplotlib", "z<%.2f'%redshift_limit_agn ) return redshift_bins_gal[1:] def plotRedshiftComovingDistance(cosmo, redshift_limit, resolution = 0.0001):", "\"\"\" Function to plot the distribution (counts) of the merger", "difference since merger events in the halos t_merger_agn = edh.getMergerTimeDifference(scale_merger_AGN,", "import axes_grid1 import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D", "idx = [], [] for c, c_gal in enumerate(counts_gal): if", "from matplotlib import cm from matplotlib.collections import PatchCollection from matplotlib.patches", "c, c_gal in enumerate(counts_gal): if c_gal != 0: f_agn.append(((counts_agn[c]*100)/c_gal)) idx.append(c)", "plt.gca() ax2 = ax1.twiny() # plot the merger distribution for", "'default', 'default', legend=True) ax.set_yscale(\"log\") # setting the x-label on top", "c_gal != 0: f_agn.append(((counts_agn[c]*100)/c_gal)) idx.append(c) z_bin_modified = redshift_bins_gal[1:][np.array(idx)] # plot", "respective galaxies & agns given the time since merger \"\"\"", "(central) halos: %.2e, Sattelite halos: %.2e'%(len(pos_z_AGN[0]), len(ra_cen), len(ra_sat))) return def", "distance \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) distance_Mpc = cosmo.comoving_distance(np.arange(0,redshift_limit, resolution))", "counts_gal, merger_val_agn, counts_agn, cosmo, redshift_limit): \"\"\" Function to plot the", "\"\"\" Function to plot the defined cuts in merger times", "3 because each hd_halo holds info on 1000 halos alone", "the 1st notebook (.ipynb) of the repository: 01. Exploring parameters", "scipy.spatial import KDTree from scipy.interpolate import interp1d import os import", "left', fontsize=14) ax.set_yscale(\"log\") ax.set_xscale(\"log\") return ax, fig, t_merger_agn, t_merger_gal def", "pos_z_AGN[1], '*', color='k', markersize=3.5, label=r'AGN', alpha=0.7) # labeling axes and", "modules import astropy.units as u import astropy.io.fits as fits from", "postion and redshifts of all the selected AGNs @pos_z_gal ::", "Sattelite halos: %.2e'%(len(pos_z_AGN[0]), len(ra_cen), len(ra_sat))) return def plotAGNfraction(pos_z_AGN, pos_z_gal, redshift_limit_agn,", "[labels, c, m, ms] \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) #", "'k', markersize=0.06, label=r'Host-halos $P_{id}=-1$', alpha=0.4) # plotting sat halos sat_halos", "sat halos sat_halos = ax.plot(ra_sat, dec_sat, 'o', color='#07d9f5', markersize=0.07, label=r'Satellite", "agn distribution as a function of redshift ax[0].plot(redshift_bins_gal[1:], counts_gal, 'ks',", "and satellite halo distribution @hd_halo :: table with all relevant", "r'Scale, $a(t)$, of last Major Merger', 'Counts', '', 'default', 'default',", "and sub-halos Script written by: <NAME> Project supervised by <NAME>", "if ylim != 'default': ax.set_ylim(ylim) if legend: l = ax.legend(loc='best',", "import importlib # plotting imports import matplotlib from mpl_toolkits import", "all relevant info on halos, clusters, and galaxies within them", "# DM halos j = i + 2 ax.plot(s_m_gal, c_gal,", "fontsize=14) for legend_handle in l.legendHandles: legend_handle._legmarker.set_markersize(12) ax.grid(False) ax.set_title(title, fontsize=18) return", "label='AGNs') setLabel(ax1, r'Scale, $a(t)$, of last Major Merger', 'Counts', '',", "containing [labels, c, m, ms] \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6))", "'*', color='k', markersize=3.5, label=r'AGN', alpha=0.7) # labeling axes and defining", "\"\"\" # get the time difference since merger events in", "modules from scipy.spatial import KDTree from scipy.interpolate import interp1d import", "halos with respective galaxies & agns given the time since", "= ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='#fff717', markersize=6.5, label=r'AGN', markeredgecolor='w', markeredgewidth=0.4) #", "in scale_factor_arr]) ax2.invert_xaxis() ax2.set_xlabel('Redshift (z)') ax2.xaxis.set_major_formatter(FormatStrFormatter('%.1f')) print(\"Objects with merger redshifts", "plot @param xlim, ylim :: x-y limits for the axis", ") return redshift_bins_gal[1:] def plotRedshiftComovingDistance(cosmo, redshift_limit, resolution = 0.0001): \"\"\"Function", "ms, mec, mew] def plotTimeSinceMergerDist(scale_merger_AGN, scale_merger_gal, z_AGN, z_gal, cosmo, bin_size,", "selected galaxies \"\"\" halo_m_500c = cluster_params[0] fig, ax = plt.subplots(1,1,figsize=(9,8))", "halos $P_{id} \\neq -1$', alpha=0.7) # plotting AGNs agn =", "and redshifts of all the selected galaxies \"\"\" halo_m_500c =", "simulation resolution) @Returns :: plot showing the dependence of redshift", "'*', color='#fff717', markersize=6.5, label=r'AGN', markeredgecolor='w', markeredgewidth=0.4) # labeling axes and", "np.max(redshift_bins_agn[1:])] setLabel(ax[0], r'Redshift$_R$', 'Counts','', xlim, 'default', legend=True) ax[0].set_yscale(\"log\") # agn", "distribution for galaxies and agns ax1.plot(merger_val_gal, counts_gal, 'kx', label='DM Halos')", "merger times within the concerned plot @t_merger_cut_arr :: array that", "in merger times within the concerned plot @t_merger_cut_arr :: array", "merger_bins_gal[:-1] else: merger_bins_agn, c_t_agn = np.unique(t_merger_agn, return_counts=True) merger_bins_gal, c_t_gal =", "# getting the useful histogram properties counts_agn, redshift_bins_agn = np.histogram(pos_z_AGN[2],", "into 3 because each hd_halo holds info on 1000 halos", "setLabel(ax[0], r'Redshift$_R$', 'Counts','', xlim, 'default', legend=True) ax[0].set_yscale(\"log\") # agn fraction", "ax.set_yscale(\"log\") ax.set_xscale(\"log\") return ax, fig, t_merger_agn, t_merger_gal def mergerRedshiftPlot(cen_sat_AGN, cen_sat_halo,", "the distribution of halos with respective galaxies & agns given", "= np.histogram(pos_z_gal[2], bins = bin_size) # plotting the galaxy and", "axis @param title :: title of the plot @param xlim,", "central and satellite AGNs(galaxies) @dt_m :: time difference after merger", "ax.plot(s_m_agn, c_agn, color=c[i], marker=m[i], ls='', ms=ms[i], label=labels[i], markeredgecolor=mec[i], markeredgewidth=mew[i]) #", "the notebook) \"\"\" for i, t_m_cut in enumerate(t_merger_cut_arr): ax.axvline(x=t_m_cut, color='r',", "sattelite scale factors for mergers \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6))", "[9, 15, 5, 9] mec, mew = ['w', 'k', 'k',", "t_merger_cut_arr, l): \"\"\" Function to plot the defined cuts in", "plotting AGNs agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='k', markersize=3.5, label=r'AGN',", "plt.savefig('figures/t_since_merger_z_plot_%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') return ax def plotMergerTimeCuts(ax, t_merger_cut_arr, l): \"\"\"", "'satellite DM halos'] c, m, ms = ['b', '#38cee8', 'k',", "mec, mew] def plotTimeSinceMergerDist(scale_merger_AGN, scale_merger_gal, z_AGN, z_gal, cosmo, bin_size, redshift_limit):", "= merger_bins_agn[:-1] merger_bins_gal = merger_bins_gal[:-1] else: merger_bins_agn, c_t_agn = np.unique(t_merger_agn,", "postion and redshifts of all the selected galaxies \"\"\" halo_m_500c", "of simulation resolution) @Returns :: plot showing the dependence of", "alpha=0.4) # plotting sat halos sat_halos = ax.plot(ra_sat, dec_sat, 'o',", "redshifts of all the selected galaxies \"\"\" halo_m_500c = cluster_params[0]", "'.', color='#fcd16d', markersize=0.2, label=r'All DM Halos', alpha=0.2) # plotting clusters", "fits from astropy.table import Table, Column from astropy.coordinates import SkyCoord", "Halos') ax[0].plot(redshift_bins_agn[1:], counts_agn, 'bs', ms=4, label=r'AGNs') # axis properties -", "\"\"\" fig, ax = plt.subplots(1,2,figsize=(19,7)) # getting the useful histogram", "\"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) labels = [r'central AGNs', r'satellite", "= bin_size[1]) c_t_gal, merger_bins_gal = np.histogram(np.array(t_merger_gal), bins = bin_size[1]) merger_bins_agn", "merger for cen/sat AGNs(galaxies) @plot_params :: to keep consistency between", "markeredgewidth=plot_params[5][i]) # set labels/legends setLabel(ax, r'$\\Delta t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]',", "ax.plot(ra_cen, dec_cen, '.', color= 'k', markersize=0.06, label=r'Host-halos $P_{id}=-1$', alpha=0.4) #", "in the 1st notebook (.ipynb) of the repository: 01. Exploring", "# plot central, satellite merger distributions as per visual preference", "# labeling axes and defining limits xlim = [np.min(pos_z_halo[0]), np.max(pos_z_halo[0])]", "def plotMergerTimeCuts(ax, t_merger_cut_arr, l): \"\"\" Function to plot the defined", "and maps in the 1st notebook (.ipynb) of the repository:", "for i in [2, 3, 0, 1]: ax.plot(dt_m[i], z_R[i], plot_params[2][i],", "np.cumsum(c_t_gal), 'k^', label='DM Halos', ms=4) ax.plot(merger_bins_agn, np.cumsum(c_t_agn), 'b^', label='AGNs', ms=4)", "the clusters found \"\"\" fig, ax = plt.subplots(1,2,figsize=(19,7)) # getting", "cosmo.comoving_distance(np.arange(0,redshift_limit, resolution)) redshifts = np.arange(0,redshift_limit, resolution) ax.plot(redshifts, distance_Mpc, 'k.', ms=1)", "print('Redshift z<%.2f'%(np.max(pos_z_clu[2]))) return def plotHostSubHalos(pos_z_cen_halo, pos_z_sat_halo, pos_z_AGN): \"\"\" Function to", "!= 0: f_agn.append(((counts_agn[c]*100)/c_gal)) idx.append(c) z_bin_modified = redshift_bins_gal[1:][np.array(idx)] # plot agn", "$M_{500c}> 10^{%.1f} M_\\odot$ '%(np.log10(halo_m_500c))) # plotting AGNs agn = ax.plot(pos_z_AGN[0],", "to keep consistency between plots, array containing [labels, c, m,", "plot the central and sattelite scale factors for mergers \"\"\"", "(counts) of the merger scale factor/redshift \"\"\" fig, ax =", "'Counts', '', 'default', 'default', legend=True) ax.set_yscale(\"log\") plt.savefig('figures/merger_dist_cenAndsat_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') print('Objects", "cuts (refer to the initial codeblock in the notebook) \"\"\"", "ax.set_xlim(xlim) if ylim != 'default': ax.set_ylim(ylim) if legend: l =", "@plot_params :: to keep consistency between plots, array containing [labels,", "Plot the distribution of halos with respective galaxies & agns", "cosmology package loaded @redshift_limit :: upper limit in redshift -->", "redshift f_agn, idx = [], [] for c, c_gal in", "edgecolor='w') return ax def plotMergerTimeCuts(ax, t_merger_cut_arr, l): \"\"\" Function to", "plotting the galaxy and agn distribution as a function of", "labels = [r'central AGNs', r'satellite AGNs', 'central DM halos', 'satellite", "plot the AGN cluster distribution @pos_z_clu :: postion and redshifts", "March 2021 \"\"\" # astropy modules import astropy.units as u", "return_counts=True) # agns ax.plot(s_m_agn, c_agn, color=c[i], marker=m[i], ls='', ms=ms[i], label=labels[i],", "the defined cuts in merger times within the concerned plot", "# agn fraction as a function of redshift f_agn, idx", "agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='k', markersize=3.5, label=r'AGN', alpha=0.7) #", "ylim != 'default': ax.set_ylim(ylim) if legend: l = ax.legend(loc='best', fontsize=14)", "preference for i in [2, 3, 0, 1]: ax.plot(dt_m[i], z_R[i],", "from astropy.coordinates import SkyCoord from astropy.cosmology import FlatLambdaCDM, z_at_value import", "properties - 0 xlim = [np.min(redshift_bins_agn[1:]), np.max(redshift_bins_agn[1:])] setLabel(ax[0], r'Redshift$_R$', 'Counts','',", "mergerRedshiftPlot(cen_sat_AGN, cen_sat_halo, dt_m, plot_params, redshift_limit): \"\"\" Function to plot the", "color=c[i], marker=m[i], ls='', ms=ms[i], label=labels[i], markeredgecolor=mec[i], markeredgewidth=mew[i]) # DM halos", "len(ra_cen), len(ra_sat))) return def plotAGNfraction(pos_z_AGN, pos_z_gal, redshift_limit_agn, bin_size): \"\"\" Function", "redshift_bins_gal = np.histogram(pos_z_gal[2], bins = bin_size) # plotting the galaxy", "ms=4) # set labels/legends setLabel(ax, r'$\\Delta t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]',", "import SkyCoord from astropy.cosmology import FlatLambdaCDM, z_at_value import numpy as", "dec_cen = pos_z_cen_halo[0], pos_z_cen_halo[1] ra_sat, dec_sat = pos_z_sat_halo[0], pos_z_sat_halo[1] fig,", "return_counts=True) merger_bins_gal, c_t_gal = np.unique(t_merger_gal, return_counts=True) fig, ax = plt.subplots(1,1,figsize=(7,6))", "redshift_limit_agn, bin_size): \"\"\" Function to plot the agn fraction in", "= redshift_bins_gal[1:][np.array(idx)] # plot agn fraction ax[1].plot(z_bin_modified, f_agn, 's', color='#6b0385',", "the cuts in the merger times @l :: array that", "def plotAGNfraction(pos_z_AGN, pos_z_gal, redshift_limit_agn, bin_size): \"\"\" Function to plot the", "i in [2, 3, 0, 1]: ax.plot(dt_m[i], z_R[i], plot_params[2][i], color=plot_params[1][i],", "ax.plot(redshifts, distance_Mpc, 'k.', ms=1) setLabel(ax, 'Redshift (z)', 'Comoving distance (Mpc)',", "r'Redshift$_R$', 'Counts','', xlim, 'default', legend=True) ax[0].set_yscale(\"log\") # agn fraction as", "plot_params[3][1] = 9 z_R = [cen_sat_AGN[0]['redshift_R'], cen_sat_AGN[1]['redshift_R'], cen_sat_halo[0]['redshift_R'], cen_sat_halo[1]['redshift_R']] #", "marker=m[i], ls='', ms=ms[i], label=labels[i], markeredgecolor=mec[i], markeredgewidth=mew[i]) # DM halos j", "of redshift f_agn, idx = [], [] for c, c_gal", "markeredgewidth=mew[j]) # set label setLabel(ax, r'Scale, $a(t)$, of last Major", "markersize=3.5, label=r'AGN', alpha=0.7) # labeling axes and defining limits xlim", "in [2, 3, 0, 1]: ax.plot(dt_m[i], z_R[i], plot_params[2][i], color=plot_params[1][i], ms=plot_params[3][i],", "e-4 based of simulation resolution) @Returns :: plot showing the", "plotAGNfraction(pos_z_AGN, pos_z_gal, redshift_limit_agn, bin_size): \"\"\" Function to plot the agn", "info on halos, clusters, and galaxies within them --> divided", "scale_merger_gal, z_AGN, z_gal, cosmo, bin_size, redshift_limit): \"\"\" Plot the distribution", "= plt.subplots(1,1,figsize=(9,8)) # plotting host halos host_halos = ax.plot(ra_cen, dec_cen,", "marker=m[j], ls='', ms=ms[j], label=labels[j], markeredgecolor=mec[j], markeredgewidth=mew[j]) # set label setLabel(ax,", "distance_Mpc = cosmo.comoving_distance(np.arange(0,redshift_limit, resolution)) redshifts = np.arange(0,redshift_limit, resolution) ax.plot(redshifts, distance_Mpc,", "host and satellite halo distribution @hd_halo :: table with all", "the halos t_merger_agn = edh.getMergerTimeDifference(scale_merger_AGN, z_AGN, cosmo) t_merger_gal = edh.getMergerTimeDifference(scale_merger_gal,", "counts_agn, cosmo, redshift_limit): \"\"\" Function to plot the distribution (counts)", "astropy modules import astropy.units as u import astropy.io.fits as fits", "array that defines the cuts in the merger times @l", "'s', color='#6b0385', ms=4) # axis properties - 1 xlim =", "them --> divided into 3 because each hd_halo holds info", "axis \"\"\" ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if xlim != 'default': ax.set_xlim(xlim) if", "= cosmo.comoving_distance(np.arange(0,redshift_limit, resolution)) redshifts = np.arange(0,redshift_limit, resolution) ax.plot(redshifts, distance_Mpc, 'k.',", "with merger redshifts z < %.2f\"%z_at_value(cosmo.scale_factor, a_min)) plt.savefig('figures/merger_distribution_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w')", "@t_merger_cut_arr :: array that defines the cuts in the merger", "r'Redshift$_R$', '', 'default', 'default', legend=True) ax.set_xscale(\"log\") plt.savefig('figures/t_since_merger_z_plot_%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') return", "agns ax.plot(s_m_agn, c_agn, color=c[i], marker=m[i], ls='', ms=ms[i], label=labels[i], markeredgecolor=mec[i], markeredgewidth=mew[i])", "# plotting imports import matplotlib from mpl_toolkits import axes_grid1 import", "'k', '#abaeb3'], [0.7, 0.4, 1, 0.7] for i in [0,", "AGNs(galaxies) @plot_params :: to keep consistency between plots, array containing", "DM halos', 'satellite DM halos'] c, m, ms = ['b',", "the relation between redshift and the comoving distance @cosmo ::", "legend=True) ax[0].set_yscale(\"log\") # agn fraction as a function of redshift", "[0.7, 0.4, 1, 0.7] for i in [0, 1]: s_m_agn,", "ls='', ms=ms[j], label=labels[j], markeredgecolor=mec[j], markeredgewidth=mew[j]) # set label setLabel(ax, r'Scale,", "merger distribution for galaxies and agns ax.plot(merger_bins_gal, np.cumsum(c_t_gal), 'k^', label='DM", "xlim != 'default': ax.set_xlim(xlim) if ylim != 'default': ax.set_ylim(ylim) if", "$a(t)$, of last Major Merger', 'Counts', '', 'default', 'default', legend=True)", "redshift_limit): \"\"\" Plot the distribution of halos with respective galaxies", "= np.histogram(np.array(t_merger_agn), bins = bin_size[1]) c_t_gal, merger_bins_gal = np.histogram(np.array(t_merger_gal), bins", "change marker size for central DM halos plot_params[3][1] = 9", "ls='', ms=ms[i], label=labels[i], markeredgecolor=mec[i], markeredgewidth=mew[i]) # DM halos j =", "[0, 1]: s_m_agn, c_agn = np.unique(cen_sat_AGN[i]['HALO_scale_of_last_MM'], return_counts=True) s_m_gal, c_gal =", "a function of redshift f_agn, idx = [], [] for", "notebook 01_Exploring_DM_Halos This python file contains all the functions used", "cosmo) # get the t since merger bins and counts", "interpolation @resolution :: resolution of time steps (set to e-4", "setLabel(ax, xlabel, ylabel, title, xlim, ylim, legend=True): \"\"\" Function defining", "ax2.set_xlabel('Redshift (z)') ax2.xaxis.set_major_formatter(FormatStrFormatter('%.1f')) print(\"Objects with merger redshifts z < %.2f\"%z_at_value(cosmo.scale_factor,", "showing the dependence of redshift on comoving distance \"\"\" fig,", "DM Halos', alpha=0.2) # plotting clusters cluster = ax.plot(pos_z_clu[0], pos_z_clu[1],", "in [0, 1]: s_m_agn, c_agn = np.unique(cen_sat_AGN[i]['HALO_scale_of_last_MM'], return_counts=True) s_m_gal, c_gal", "of time steps (set to e-4 based of simulation resolution)", "codeblock in the notebook) \"\"\" for i, t_m_cut in enumerate(t_merger_cut_arr):", "table with all relevant info on halos, clusters, and galaxies", "[a_max, a_min*4, a_min*2, a_min] ax2.set_xticks([(1/a) -1 for a in scale_factor_arr])", ":: postion and redshifts of all the selected galaxies @redshift_limit_agn", ":: postion and redshifts of all the selected galaxies \"\"\"", "ms=4, label=r'AGNs') # axis properties - 0 xlim = [np.min(redshift_bins_agn[1:]),", "title of the plot @param xlim, ylim :: x-y limits", "ax.set_xscale(\"log\") plt.savefig('figures/t_since_merger_z_plot_%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') return ax def plotMergerTimeCuts(ax, t_merger_cut_arr, l):", "np.max(merger_val_gal) scale_factor_arr = [a_max, a_min*4, a_min*2, a_min] ax2.set_xticks([(1/a) -1 for", "mergers \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) labels = [r'central AGNs',", "plot @t_merger_cut_arr :: array that defines the cuts in the", "xlabel, ylabel :: labels of the x-y axis @param title", "c_agn, color=c[i], marker=m[i], ls='', ms=ms[i], label=labels[i], markeredgecolor=mec[i], markeredgewidth=mew[i]) # DM", "legend=False) ax[1].set_yscale(\"log\") plt.savefig('figures/agn_frac.pdf', facecolor='w', edgecolor='w') print( 'Reddhift z<%.2f'%redshift_limit_agn ) return", "np.arange(0,redshift_limit, resolution) ax.plot(redshifts, distance_Mpc, 'k.', ms=1) setLabel(ax, 'Redshift (z)', 'Comoving", "return def plotAGNfraction(pos_z_AGN, pos_z_gal, redshift_limit_agn, bin_size): \"\"\" Function to plot", "the t since merger bins and counts if bin_size[0]: c_t_agn,", "from scipy.interpolate import interp1d import os import importlib # plotting", "return_counts=True) fig, ax = plt.subplots(1,1,figsize=(7,6)) # plot the time since", "plotHostSubHalos(pos_z_cen_halo, pos_z_sat_halo, pos_z_AGN): \"\"\" Function to plot the host and", "to plot the defined cuts in merger times within the", "plt.subplots(1,1,figsize=(7,6)) distance_Mpc = cosmo.comoving_distance(np.arange(0,redshift_limit, resolution)) redshifts = np.arange(0,redshift_limit, resolution) ax.plot(redshifts,", "t_{merger} = t(z_{merger})-t(z_{current})$ [Gyr]', 'Cumulative counts', '', 'default', 'default', legend=False)", "-1$', alpha=0.7) # plotting AGNs agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*',", "%.2e'%(len(pos_z_AGN[0]), len(ra_cen), len(ra_sat))) return def plotAGNfraction(pos_z_AGN, pos_z_gal, redshift_limit_agn, bin_size): \"\"\"", "= [r'central AGNs', r'satellite AGNs', 'central DM halos', 'satellite DM", "labeling axes and defining limits xlim = [np.min(pos_z_halo[0]), np.max(pos_z_halo[0])] ylim", "cuts in merger times within the concerned plot @t_merger_cut_arr ::", "'k', 'k', '#abaeb3'], [0.7, 0.4, 1, 0.7] for i in", "steps (set to e-4 based of simulation resolution) @Returns ::", "plotMergerDistribution(merger_val_gal, counts_gal, merger_val_agn, counts_agn, cosmo, redshift_limit): \"\"\" Function to plot", "distance @cosmo :: cosmology package loaded @redshift_limit :: upper limit", "merger bins and counts if bin_size[0]: c_t_agn, merger_bins_agn = np.histogram(np.array(t_merger_agn),", "for i, t_m_cut in enumerate(t_merger_cut_arr): ax.axvline(x=t_m_cut, color='r', linestyle= l[i], label='%.1f", "(z)') ax2.xaxis.set_major_formatter(FormatStrFormatter('%.1f')) print(\"Objects with merger redshifts z < %.2f\"%z_at_value(cosmo.scale_factor, a_min))", "= bin_size) counts_gal, redshift_bins_gal = np.histogram(pos_z_gal[2], bins = bin_size) #", "since merger distribution for galaxies and agns ax.plot(merger_bins_gal, np.cumsum(c_t_gal), 'k^',", "redshift) a_min, a_max = np.min(merger_val_gal), np.max(merger_val_gal) scale_factor_arr = [a_max, a_min*4,", "from scipy.spatial import KDTree from scipy.interpolate import interp1d import os", "in redshift --> end point for interpolation @resolution :: resolution", "alone @pos_z_AGN :: postion and redshifts of all the selected", "x-y limits for the axis \"\"\" ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) if xlim", "handels to access the central and satellite AGNs(galaxies) @dt_m ::", "DM halos j = i + 2 ax.plot(s_m_gal, c_gal, color=c[j],", "parameters in DM halos and sub-halos Script written by: <NAME>", "given the time since merger \"\"\" # get the time", "FormatStrFormatter from matplotlib import cm from matplotlib.collections import PatchCollection from", "halos = ax.plot(pos_z_halo[0], pos_z_halo[1], '.', color='#fcd16d', markersize=0.2, label=r'All DM Halos',", "merger \"\"\" # get the time difference since merger events", "f_agn, idx = [], [] for c, c_gal in enumerate(counts_gal):", "postion and redshifts of all the selected galaxies @redshift_limit_agn ::", "bin_size[1]) c_t_gal, merger_bins_gal = np.histogram(np.array(t_merger_gal), bins = bin_size[1]) merger_bins_agn =", "linestyles used to denote these cuts (refer to the initial", "<NAME> Date created: 23rd February 2021 Last updated on 30th", "title :: title of the plot @param xlim, ylim ::", "@hd_halo :: table with all relevant info on halos, clusters,", "label=r'AGN', markeredgecolor='w', markeredgewidth=0.4) # labeling axes and defining limits xlim", "< %.2f\"%z_at_value(cosmo.scale_factor, a_min)) plt.savefig('figures/merger_distribution_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') return def plotCentralSatelliteScaleMergers(cen_sat_AGN, cen_sat_halo,", "cen_sat_halo, redshift_limit): \"\"\" Function to plot the central and sattelite", "get the time difference since merger events in the halos", "Column from astropy.coordinates import SkyCoord from astropy.cosmology import FlatLambdaCDM, z_at_value", "redshifts of all the selected AGNs @pos_z_gal :: postion and", "for legend_handle in l.legendHandles: legend_handle._legmarker.set_markersize(12) ax.grid(False) ax.set_title(title, fontsize=18) return def", "label=r'Satellite halos $P_{id} \\neq -1$', alpha=0.7) # plotting AGNs agn", "import LinearLocator, FormatStrFormatter from matplotlib import cm from matplotlib.collections import", "counts_gal, redshift_bins_gal = np.histogram(pos_z_gal[2], bins = bin_size) # plotting the", "\"\"\" Function to plot the host and satellite halo distribution", "np.max(redshift_bins_agn[1:])] setLabel(ax[1], r'Redshift$_R$', r'$f_{AGN}$ (%s)'%\"%\", '', xlim, 'default', legend=False) ax[1].set_yscale(\"log\")", "xlim, ylim, legend=True) print('AGNs: %d, Host (central) halos: %.2e, Sattelite", "m, ms = ['b', '#38cee8', 'k', 'grey'], ['^', '*', '^',", "Function to plot the distribution (counts) of the merger scale", "plot central, satellite merger distributions as per visual preference for", "@Returns :: plot showing the dependence of redshift on comoving", "Major Merger', 'Counts', '', 'default', 'default', legend=True) ax.set_yscale(\"log\") plt.savefig('figures/merger_dist_cenAndsat_z%.2f.pdf'%redshift_limit, facecolor='w',", "t since merger bins and counts if bin_size[0]: c_t_agn, merger_bins_agn", "%.2e, Sattelite halos: %.2e'%(len(pos_z_AGN[0]), len(ra_cen), len(ra_sat))) return def plotAGNfraction(pos_z_AGN, pos_z_gal,", "dependence of redshift on comoving distance \"\"\" fig, ax =", "resolution = 0.0001): \"\"\"Function to plot the relation between redshift", "pos_z_AGN, pos_z_halo, cluster_params): \"\"\" Function to plot the AGN cluster", "= merger_bins_gal[:-1] else: merger_bins_agn, c_t_agn = np.unique(t_merger_agn, return_counts=True) merger_bins_gal, c_t_gal", "setLabel(ax1, r'Scale, $a(t)$, of last Major Merger', 'Counts', '', 'default',", "# plotting the galaxy and agn distribution as a function", "from mpl_toolkits.mplot3d.axes3d import Axes3D from matplotlib.ticker import LinearLocator, FormatStrFormatter from", "10^{%.1f} M_\\odot$ '%(np.log10(halo_m_500c))) # plotting AGNs agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1],", "Halos', alpha=0.2) # plotting clusters cluster = ax.plot(pos_z_clu[0], pos_z_clu[1], 'o',", "if legend: l = ax.legend(loc='best', fontsize=14) for legend_handle in l.legendHandles:", "import Rectangle import Exploring_DM_Haloes as edh def setLabel(ax, xlabel, ylabel,", "ylim = [np.min(pos_z_AGN[1]), np.max(pos_z_AGN[1])] setLabel(ax, 'R.A. (deg)', 'Dec (deg)', '',", "import Exploring_DM_Haloes as edh def setLabel(ax, xlabel, ylabel, title, xlim,", "AGN cluster distribution @pos_z_clu :: postion and redshifts of all", "counts if bin_size[0]: c_t_agn, merger_bins_agn = np.histogram(np.array(t_merger_agn), bins = bin_size[1])", "# plotting AGNs agn = ax.plot(pos_z_AGN[0], pos_z_AGN[1], '*', color='#fff717', markersize=6.5,", "ms=plot_params[3][i], label=plot_params[0][i], markeredgecolor=plot_params[4][i], markeredgewidth=plot_params[5][i]) # set labels/legends setLabel(ax, r'$\\Delta t_{merger}", "the selected AGNs @pos_z_gal :: postion and redshifts of all", "(deg)', '', xlim, ylim, legend=True) print('AGNs: %d, Host (central) halos:", "in l.legendHandles: legend_handle._legmarker.set_markersize(12) ax.grid(False) ax.set_title(title, fontsize=18) return def plotAgnClusterDistribution(pos_z_clu, pos_z_AGN,", "distribution @hd_halo :: table with all relevant info on halos,", "= [a_max, a_min*4, a_min*2, a_min] ax2.set_xticks([(1/a) -1 for a in", "edh def setLabel(ax, xlabel, ylabel, title, xlim, ylim, legend=True): \"\"\"", "len(ra_sat))) return def plotAGNfraction(pos_z_AGN, pos_z_gal, redshift_limit_agn, bin_size): \"\"\" Function to", "'R.A. (deg)', 'Dec (deg)', '', xlim, ylim, legend=True) print('AGNs: %d,", "c, m, ms, mec, mew] def plotTimeSinceMergerDist(scale_merger_AGN, scale_merger_gal, z_AGN, z_gal,", "bins = bin_size) counts_gal, redshift_bins_gal = np.histogram(pos_z_gal[2], bins = bin_size)", "ax = plt.subplots(1,1,figsize=(9,8)) # plotting host halos host_halos = ax.plot(ra_cen,", "found \"\"\" fig, ax = plt.subplots(1,2,figsize=(19,7)) # getting the useful", "np # scipy modules from scipy.spatial import KDTree from scipy.interpolate", "plotRedshiftComovingDistance(cosmo, redshift_limit, resolution = 0.0001): \"\"\"Function to plot the relation", "r'satellite AGNs', 'central DM halos', 'satellite DM halos'] c, m,", "function of the redshift @cen_sat_AGN(gal) :: handels to access the", "= plt.subplots(1,1,figsize=(9,8)) # plotting halos halos = ax.plot(pos_z_halo[0], pos_z_halo[1], '.',", "os import importlib # plotting imports import matplotlib from mpl_toolkits", "m, ms, mec, mew] def plotTimeSinceMergerDist(scale_merger_AGN, scale_merger_gal, z_AGN, z_gal, cosmo,", "np.histogram(np.array(t_merger_gal), bins = bin_size[1]) merger_bins_agn = merger_bins_agn[:-1] merger_bins_gal = merger_bins_gal[:-1]", "distance relationship') return def plotMergerDistribution(merger_val_gal, counts_gal, merger_val_agn, counts_agn, cosmo, redshift_limit):", "markersize=0.07, label=r'Satellite halos $P_{id} \\neq -1$', alpha=0.7) # plotting AGNs", "properties counts_agn, redshift_bins_agn = np.histogram(pos_z_AGN[2], bins = bin_size) counts_gal, redshift_bins_gal", "of all the selected AGNs \"\"\" ra_cen, dec_cen = pos_z_cen_halo[0],", "z_AGN, cosmo) t_merger_gal = edh.getMergerTimeDifference(scale_merger_gal, z_gal, cosmo) # get the", "<NAME> Project supervised by <NAME> Date created: 23rd February 2021", "sub-halos Script written by: <NAME> Project supervised by <NAME> Date", "plt.savefig('figures/merger_dist_cenAndsat_z%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w') print('Objects below z: ', redshift_limit) return [labels,", "on redshift based on the clusters found \"\"\" fig, ax", "as edh def setLabel(ax, xlabel, ylabel, title, xlim, ylim, legend=True):", "ax.set_xscale(\"log\") return ax, fig, t_merger_agn, t_merger_gal def mergerRedshiftPlot(cen_sat_AGN, cen_sat_halo, dt_m,", "selected galaxies @redshift_limit_agn :: upper limit on redshift based on", "the merger times @l :: array that defines the linestyles", "import Axes3D from matplotlib.ticker import LinearLocator, FormatStrFormatter from matplotlib import", "the repository: 01. Exploring parameters in DM halos and sub-halos", "to redshift) a_min, a_max = np.min(merger_val_gal), np.max(merger_val_gal) scale_factor_arr = [a_max,", "and defining limits xlim = [np.min(pos_z_halo[0]), np.max(pos_z_halo[0])] ylim = [np.min(pos_z_halo[1]),", "bins = bin_size) # plotting the galaxy and agn distribution", "plot the host and satellite halo distribution @hd_halo :: table", "for cen/sat AGNs(galaxies) @plot_params :: to keep consistency between plots,", "AGNs', r'satellite AGNs', 'central DM halos', 'satellite DM halos'] c,", "markersize=0.2, label=r'All DM Halos', alpha=0.2) # plotting clusters cluster =", "print( 'Reddhift z<%.2f'%redshift_limit_agn ) return redshift_bins_gal[1:] def plotRedshiftComovingDistance(cosmo, redshift_limit, resolution", "ax.plot(ra_sat, dec_sat, 'o', color='#07d9f5', markersize=0.07, label=r'Satellite halos $P_{id} \\neq -1$',", "redshift --> end point for interpolation @resolution :: resolution of", "= [np.min(pos_z_AGN[0]), np.max(pos_z_AGN[0])] ylim = [np.min(pos_z_AGN[1]), np.max(pos_z_AGN[1])] setLabel(ax, 'R.A. (deg)',", "to plot the host and satellite halo distribution @hd_halo ::", "scale_factor_arr = [a_max, a_min*4, a_min*2, a_min] ax2.set_xticks([(1/a) -1 for a", "mew = ['w', 'k', 'k', '#abaeb3'], [0.7, 0.4, 1, 0.7]", "c_gal = np.unique(cen_sat_halo[i]['HALO_scale_of_last_MM'], return_counts=True) # agns ax.plot(s_m_agn, c_agn, color=c[i], marker=m[i],", "counts_agn, 'bs', ms=4, label=r'AGNs') # axis properties - 0 xlim", "resolution of time steps (set to e-4 based of simulation", "counts_agn, 'bx', label='AGNs') setLabel(ax1, r'Scale, $a(t)$, of last Major Merger',", "host_halos = ax.plot(ra_cen, dec_cen, '.', color= 'k', markersize=0.06, label=r'Host-halos $P_{id}=-1$',", "ylim, legend=True) print('AGNs: %d, Host (central) halos: %.2e, Sattelite halos:", "galaxies & agns given the time since merger \"\"\" #", "(deg)', '', xlim, ylim, legend=True) print('Redshift z<%.2f'%(np.max(pos_z_clu[2]))) return def plotHostSubHalos(pos_z_cen_halo,", ":: postion and redshifts of all the selected AGNs @pos_z_gal", "Exploring_DM_Haloes as edh def setLabel(ax, xlabel, ylabel, title, xlim, ylim,", "redshifts of all the selected galaxies @redshift_limit_agn :: upper limit", "matplotlib import cm from matplotlib.collections import PatchCollection from matplotlib.patches import", "15, 5, 9] mec, mew = ['w', 'k', 'k', '#abaeb3'],", "fig, ax = plt.subplots(1,1,figsize=(9,8)) # plotting halos halos = ax.plot(pos_z_halo[0],", "access the central and satellite AGNs(galaxies) @dt_m :: time difference", "ax.set_ylabel(ylabel) if xlim != 'default': ax.set_xlim(xlim) if ylim != 'default':", "= i + 2 ax.plot(s_m_gal, c_gal, color=c[j], marker=m[j], ls='', ms=ms[j],", "ax = plt.subplots(1,1,figsize=(7,6)) labels = [r'central AGNs', r'satellite AGNs', 'central", "label=r'Clusters $M_{500c}> 10^{%.1f} M_\\odot$ '%(np.log10(halo_m_500c))) # plotting AGNs agn =", "since merger as a function of the redshift @cen_sat_AGN(gal) ::", "z_gal, cosmo) # get the t since merger bins and", "counts_gal, 'kx', label='DM Halos') ax1.plot(merger_val_agn, counts_agn, 'bx', label='AGNs') setLabel(ax1, r'Scale,", "# scipy modules from scipy.spatial import KDTree from scipy.interpolate import", "return_counts=True) s_m_gal, c_gal = np.unique(cen_sat_halo[i]['HALO_scale_of_last_MM'], return_counts=True) # agns ax.plot(s_m_agn, c_agn,", "distributions as per visual preference for i in [2, 3,", "pos_z_AGN[1], '*', color='#fff717', markersize=6.5, label=r'AGN', markeredgecolor='w', markeredgewidth=0.4) # labeling axes", "\"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) distance_Mpc = cosmo.comoving_distance(np.arange(0,redshift_limit, resolution)) redshifts", "clusters cluster = ax.plot(pos_z_clu[0], pos_z_clu[1], 'o', color= '#03a351', markersize=3, label=r'Clusters", "matplotlib.patches import Rectangle import Exploring_DM_Haloes as edh def setLabel(ax, xlabel,", "plot the time since merger as a function of the", "z_at_value import numpy as np # scipy modules from scipy.spatial", "color=plot_params[1][i], ms=plot_params[3][i], label=plot_params[0][i], markeredgecolor=plot_params[4][i], markeredgewidth=plot_params[5][i]) # set labels/legends setLabel(ax, r'$\\Delta", "def plotAgnClusterDistribution(pos_z_clu, pos_z_AGN, pos_z_halo, cluster_params): \"\"\" Function to plot the", "c, m, ms] \"\"\" fig, ax = plt.subplots(1,1,figsize=(7,6)) # change", "merger times @l :: array that defines the linestyles used", "LinearLocator, FormatStrFormatter from matplotlib import cm from matplotlib.collections import PatchCollection", "setLabel(ax, 'Redshift (z)', 'Comoving distance (Mpc)', '', 'default', 'default', legend=False)", "and sattelite scale factors for mergers \"\"\" fig, ax =", "ylim :: x-y limits for the axis \"\"\" ax.set_xlabel(xlabel) ax.set_ylabel(ylabel)", "in DM halos and sub-halos Script written by: <NAME> Project", "x-label on top (converting a to redshift) a_min, a_max =", "the time since merger \"\"\" # get the time difference", "[Gyr]', r'Redshift$_R$', '', 'default', 'default', legend=True) ax.set_xscale(\"log\") plt.savefig('figures/t_since_merger_z_plot_%.2f.pdf'%redshift_limit, facecolor='w', edgecolor='w')", "axes to be held @param xlabel, ylabel :: labels of", "--> divided into 3 because each hd_halo holds info on", "and the comoving distance @cosmo :: cosmology package loaded @redshift_limit", "resolution)) redshifts = np.arange(0,redshift_limit, resolution) ax.plot(redshifts, distance_Mpc, 'k.', ms=1) setLabel(ax,", "color='#fff717', markersize=6.5, label=r'AGN', markeredgecolor='w', markeredgewidth=0.4) # labeling axes and defining", "markeredgecolor='w', markeredgewidth=0.4) # labeling axes and defining limits xlim =", "= plt.subplots(1,1,figsize=(7,6)) ax1 = plt.gca() ax2 = ax1.twiny() # plot", "9 z_R = [cen_sat_AGN[0]['redshift_R'], cen_sat_AGN[1]['redshift_R'], cen_sat_halo[0]['redshift_R'], cen_sat_halo[1]['redshift_R']] # plot central,", "@l :: array that defines the linestyles used to denote", "cen_sat_halo, dt_m, plot_params, redshift_limit): \"\"\" Function to plot the time", "z_R = [cen_sat_AGN[0]['redshift_R'], cen_sat_AGN[1]['redshift_R'], cen_sat_halo[0]['redshift_R'], cen_sat_halo[1]['redshift_R']] # plot central, satellite", "be held @param xlabel, ylabel :: labels of the x-y" ]
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "import TimeReadCsvTrueFalseValues # noqa: F401 class TimeReadCsvNames: shapes = get_benchmark_shapes(\"omnisci.TimeReadCsvNames\")", "ownership. The Modin Development Team licenses this file to you", "for shape in self.shapes: df = generate_dataframe(\"pandas\", \"int\", *shape, RAND_LOW,", "\"modin\": pd.DataFrame([]) file_id = get_shape_id(shape) self.filename, self.names, self.dtype = cache[file_id]", "CONDITIONS OF # ANY KIND, either express or implied. See", "additional information regarding # copyright ownership. The Modin Development Team", "Unless required by applicable law or agreed to in writing,", "by applicable law or agreed to in writing, software distributed", "the specific language # governing permissions and limitations under the", "param_names = [\"shape\"] params = [shapes] def setup_cache(self, test_filename=\"io_test_file_csv_names\"): #", "more contributor license agreements. # See the NOTICE file distributed", "..utils import ( generate_dataframe, RAND_LOW, RAND_HIGH, ASV_USE_IMPL, IMPL, get_shape_id, trigger_import,", "def time_read_csv_names(self, cache, shape): df = IMPL[ASV_USE_IMPL].read_csv( self.filename, names=self.names, header=0,", "cache[file_id] def time_read_csv_names(self, cache, shape): df = IMPL[ASV_USE_IMPL].read_csv( self.filename, names=self.names,", "ASV_USE_IMPL, IMPL, get_shape_id, trigger_import, get_benchmark_shapes, ) from ..io.csv import TimeReadCsvTrueFalseValues", "# Licensed to Modin Development Team under one or more", "Version 2.0 (the \"License\"); you may not use this file", "..io.csv import TimeReadCsvTrueFalseValues # noqa: F401 class TimeReadCsvNames: shapes =", "return cache def setup(self, cache, shape): # ray init if", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "the License for the specific language # governing permissions and", "See the NOTICE file distributed with this work for additional", "Team under one or more contributor license agreements. # See", "OmniSci storage format benchmarks.\"\"\" import modin.pandas as pd from ..utils", "NOTICE file distributed with this work for additional information regarding", "Apache License, Version 2.0 (the \"License\"); you may not use", "2.0 (the \"License\"); you may not use this file except", "express or implied. See the License for the specific language", "get_benchmark_shapes(\"omnisci.TimeReadCsvNames\") param_names = [\"shape\"] params = [shapes] def setup_cache(self, test_filename=\"io_test_file_csv_names\"):", "{} for shape in self.shapes: df = generate_dataframe(\"pandas\", \"int\", *shape,", "get_shape_id(shape) self.filename, self.names, self.dtype = cache[file_id] def time_read_csv_names(self, cache, shape):", "with this work for additional information regarding # copyright ownership.", "this file except in # compliance with the License. You", "# ray init if ASV_USE_IMPL == \"modin\": pd.DataFrame([]) file_id =", "one or more contributor license agreements. # See the NOTICE", "regarding # copyright ownership. The Modin Development Team licenses this", "you under the # Apache License, Version 2.0 (the \"License\");", "self.names, self.dtype = cache[file_id] def time_read_csv_names(self, cache, shape): df =", "is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR", "the License. You may obtain a copy of the License", "import ( generate_dataframe, RAND_LOW, RAND_HIGH, ASV_USE_IMPL, IMPL, get_shape_id, trigger_import, get_benchmark_shapes,", "to Modin Development Team under one or more contributor license", "IMPL, get_shape_id, trigger_import, get_benchmark_shapes, ) from ..io.csv import TimeReadCsvTrueFalseValues #", "under the License. \"\"\"IO Modin on OmniSci storage format benchmarks.\"\"\"", "RAND_LOW, RAND_HIGH) file_id = get_shape_id(shape) cache[file_id] = ( f\"{test_filename}_{file_id}.csv\", df.columns.to_list(),", "distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS", "License for the specific language # governing permissions and limitations", "TimeReadCsvNames: shapes = get_benchmark_shapes(\"omnisci.TimeReadCsvNames\") param_names = [\"shape\"] params = [shapes]", "import modin.pandas as pd from ..utils import ( generate_dataframe, RAND_LOW,", "# governing permissions and limitations under the License. \"\"\"IO Modin", "file distributed with this work for additional information regarding #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "WARRANTIES OR CONDITIONS OF # ANY KIND, either express or", "test_filename=\"io_test_file_csv_names\"): # filenames with a metadata of saved dataframes cache", "ANY KIND, either express or implied. See the License for", "writing, software distributed under # the License is distributed on", "df.to_csv(cache[file_id][0], index=False) return cache def setup(self, cache, shape): # ray", "cache = {} for shape in self.shapes: df = generate_dataframe(\"pandas\",", "def setup(self, cache, shape): # ray init if ASV_USE_IMPL ==", "if ASV_USE_IMPL == \"modin\": pd.DataFrame([]) file_id = get_shape_id(shape) self.filename, self.names,", "class TimeReadCsvNames: shapes = get_benchmark_shapes(\"omnisci.TimeReadCsvNames\") param_names = [\"shape\"] params =", "this work for additional information regarding # copyright ownership. The", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "under the # Apache License, Version 2.0 (the \"License\"); you", "# filenames with a metadata of saved dataframes cache =", "Team licenses this file to you under the # Apache", "= [\"shape\"] params = [shapes] def setup_cache(self, test_filename=\"io_test_file_csv_names\"): # filenames", "under # the License is distributed on an \"AS IS\"", "in self.shapes: df = generate_dataframe(\"pandas\", \"int\", *shape, RAND_LOW, RAND_HIGH) file_id", "either express or implied. See the License for the specific", "RAND_LOW, RAND_HIGH, ASV_USE_IMPL, IMPL, get_shape_id, trigger_import, get_benchmark_shapes, ) from ..io.csv", "RAND_HIGH) file_id = get_shape_id(shape) cache[file_id] = ( f\"{test_filename}_{file_id}.csv\", df.columns.to_list(), df.dtypes.to_dict(),", "\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY", "init if ASV_USE_IMPL == \"modin\": pd.DataFrame([]) file_id = get_shape_id(shape) self.filename,", "( f\"{test_filename}_{file_id}.csv\", df.columns.to_list(), df.dtypes.to_dict(), ) df.to_csv(cache[file_id][0], index=False) return cache def", "pd from ..utils import ( generate_dataframe, RAND_LOW, RAND_HIGH, ASV_USE_IMPL, IMPL,", "with a metadata of saved dataframes cache = {} for", "and limitations under the License. \"\"\"IO Modin on OmniSci storage", "noqa: F401 class TimeReadCsvNames: shapes = get_benchmark_shapes(\"omnisci.TimeReadCsvNames\") param_names = [\"shape\"]", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES", "# See the NOTICE file distributed with this work for", "the # Apache License, Version 2.0 (the \"License\"); you may", "Licensed to Modin Development Team under one or more contributor", "with the License. You may obtain a copy of the", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "= {} for shape in self.shapes: df = generate_dataframe(\"pandas\", \"int\",", "df = generate_dataframe(\"pandas\", \"int\", *shape, RAND_LOW, RAND_HIGH) file_id = get_shape_id(shape)", "cache, shape): # ray init if ASV_USE_IMPL == \"modin\": pd.DataFrame([])", "you may not use this file except in # compliance", "Development Team licenses this file to you under the #", "= get_benchmark_shapes(\"omnisci.TimeReadCsvNames\") param_names = [\"shape\"] params = [shapes] def setup_cache(self,", "self.shapes: df = generate_dataframe(\"pandas\", \"int\", *shape, RAND_LOW, RAND_HIGH) file_id =", "copyright ownership. The Modin Development Team licenses this file to", "shape in self.shapes: df = generate_dataframe(\"pandas\", \"int\", *shape, RAND_LOW, RAND_HIGH)", "df.columns.to_list(), df.dtypes.to_dict(), ) df.to_csv(cache[file_id][0], index=False) return cache def setup(self, cache,", "<gh_stars>0 # Licensed to Modin Development Team under one or", "index=False) return cache def setup(self, cache, shape): # ray init", "# the License is distributed on an \"AS IS\" BASIS,", "governing permissions and limitations under the License. \"\"\"IO Modin on", "= [shapes] def setup_cache(self, test_filename=\"io_test_file_csv_names\"): # filenames with a metadata", "TimeReadCsvTrueFalseValues # noqa: F401 class TimeReadCsvNames: shapes = get_benchmark_shapes(\"omnisci.TimeReadCsvNames\") param_names", "[\"shape\"] params = [shapes] def setup_cache(self, test_filename=\"io_test_file_csv_names\"): # filenames with", "self.filename, self.names, self.dtype = cache[file_id] def time_read_csv_names(self, cache, shape): df", "software distributed under # the License is distributed on an", "this file to you under the # Apache License, Version", "distributed with this work for additional information regarding # copyright", "BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either", "\"\"\"IO Modin on OmniSci storage format benchmarks.\"\"\" import modin.pandas as", "for the specific language # governing permissions and limitations under", "dataframes cache = {} for shape in self.shapes: df =", "= generate_dataframe(\"pandas\", \"int\", *shape, RAND_LOW, RAND_HIGH) file_id = get_shape_id(shape) cache[file_id]", "*shape, RAND_LOW, RAND_HIGH) file_id = get_shape_id(shape) cache[file_id] = ( f\"{test_filename}_{file_id}.csv\",", "F401 class TimeReadCsvNames: shapes = get_benchmark_shapes(\"omnisci.TimeReadCsvNames\") param_names = [\"shape\"] params", "(the \"License\"); you may not use this file except in", "OF # ANY KIND, either express or implied. See the", "setup_cache(self, test_filename=\"io_test_file_csv_names\"): # filenames with a metadata of saved dataframes", "= get_shape_id(shape) self.filename, self.names, self.dtype = cache[file_id] def time_read_csv_names(self, cache,", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "a metadata of saved dataframes cache = {} for shape", "setup(self, cache, shape): # ray init if ASV_USE_IMPL == \"modin\":", "= get_shape_id(shape) cache[file_id] = ( f\"{test_filename}_{file_id}.csv\", df.columns.to_list(), df.dtypes.to_dict(), ) df.to_csv(cache[file_id][0],", "get_shape_id(shape) cache[file_id] = ( f\"{test_filename}_{file_id}.csv\", df.columns.to_list(), df.dtypes.to_dict(), ) df.to_csv(cache[file_id][0], index=False)", "= cache[file_id] def time_read_csv_names(self, cache, shape): df = IMPL[ASV_USE_IMPL].read_csv( self.filename,", "limitations under the License. \"\"\"IO Modin on OmniSci storage format", "Modin Development Team under one or more contributor license agreements.", "applicable law or agreed to in writing, software distributed under", "RAND_HIGH, ASV_USE_IMPL, IMPL, get_shape_id, trigger_import, get_benchmark_shapes, ) from ..io.csv import", "permissions and limitations under the License. \"\"\"IO Modin on OmniSci", "metadata of saved dataframes cache = {} for shape in", "# noqa: F401 class TimeReadCsvNames: shapes = get_benchmark_shapes(\"omnisci.TimeReadCsvNames\") param_names =", "modin.pandas as pd from ..utils import ( generate_dataframe, RAND_LOW, RAND_HIGH,", "shape): # ray init if ASV_USE_IMPL == \"modin\": pd.DataFrame([]) file_id", "== \"modin\": pd.DataFrame([]) file_id = get_shape_id(shape) self.filename, self.names, self.dtype =", "except in # compliance with the License. You may obtain", "the License is distributed on an \"AS IS\" BASIS, WITHOUT", "not use this file except in # compliance with the", "Development Team under one or more contributor license agreements. #", "trigger_import, get_benchmark_shapes, ) from ..io.csv import TimeReadCsvTrueFalseValues # noqa: F401", "licenses this file to you under the # Apache License,", "# # Unless required by applicable law or agreed to", "shape): df = IMPL[ASV_USE_IMPL].read_csv( self.filename, names=self.names, header=0, dtype=self.dtype, ) trigger_import(df)", "get_shape_id, trigger_import, get_benchmark_shapes, ) from ..io.csv import TimeReadCsvTrueFalseValues # noqa:", "as pd from ..utils import ( generate_dataframe, RAND_LOW, RAND_HIGH, ASV_USE_IMPL,", "cache def setup(self, cache, shape): # ray init if ASV_USE_IMPL", "an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF #", "\"License\"); you may not use this file except in #", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "def setup_cache(self, test_filename=\"io_test_file_csv_names\"): # filenames with a metadata of saved", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "KIND, either express or implied. See the License for the", "to in writing, software distributed under # the License is", "use this file except in # compliance with the License.", "law or agreed to in writing, software distributed under #", "implied. See the License for the specific language # governing", "contributor license agreements. # See the NOTICE file distributed with", "[shapes] def setup_cache(self, test_filename=\"io_test_file_csv_names\"): # filenames with a metadata of", "ray init if ASV_USE_IMPL == \"modin\": pd.DataFrame([]) file_id = get_shape_id(shape)", "of saved dataframes cache = {} for shape in self.shapes:", "compliance with the License. You may obtain a copy of", ") from ..io.csv import TimeReadCsvTrueFalseValues # noqa: F401 class TimeReadCsvNames:", "= ( f\"{test_filename}_{file_id}.csv\", df.columns.to_list(), df.dtypes.to_dict(), ) df.to_csv(cache[file_id][0], index=False) return cache", "to you under the # Apache License, Version 2.0 (the", "generate_dataframe, RAND_LOW, RAND_HIGH, ASV_USE_IMPL, IMPL, get_shape_id, trigger_import, get_benchmark_shapes, ) from", "from ..io.csv import TimeReadCsvTrueFalseValues # noqa: F401 class TimeReadCsvNames: shapes", "time_read_csv_names(self, cache, shape): df = IMPL[ASV_USE_IMPL].read_csv( self.filename, names=self.names, header=0, dtype=self.dtype,", "on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF", "get_benchmark_shapes, ) from ..io.csv import TimeReadCsvTrueFalseValues # noqa: F401 class", "cache, shape): df = IMPL[ASV_USE_IMPL].read_csv( self.filename, names=self.names, header=0, dtype=self.dtype, )", "or implied. See the License for the specific language #", "file to you under the # Apache License, Version 2.0", "License, Version 2.0 (the \"License\"); you may not use this", "storage format benchmarks.\"\"\" import modin.pandas as pd from ..utils import", "params = [shapes] def setup_cache(self, test_filename=\"io_test_file_csv_names\"): # filenames with a", "IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND,", "format benchmarks.\"\"\" import modin.pandas as pd from ..utils import (", "saved dataframes cache = {} for shape in self.shapes: df", "cache[file_id] = ( f\"{test_filename}_{file_id}.csv\", df.columns.to_list(), df.dtypes.to_dict(), ) df.to_csv(cache[file_id][0], index=False) return", "Modin on OmniSci storage format benchmarks.\"\"\" import modin.pandas as pd", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "agreements. # See the NOTICE file distributed with this work", "# ANY KIND, either express or implied. See the License", "pd.DataFrame([]) file_id = get_shape_id(shape) self.filename, self.names, self.dtype = cache[file_id] def", "generate_dataframe(\"pandas\", \"int\", *shape, RAND_LOW, RAND_HIGH) file_id = get_shape_id(shape) cache[file_id] =", "f\"{test_filename}_{file_id}.csv\", df.columns.to_list(), df.dtypes.to_dict(), ) df.to_csv(cache[file_id][0], index=False) return cache def setup(self,", "( generate_dataframe, RAND_LOW, RAND_HIGH, ASV_USE_IMPL, IMPL, get_shape_id, trigger_import, get_benchmark_shapes, )", "agreed to in writing, software distributed under # the License", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "df.dtypes.to_dict(), ) df.to_csv(cache[file_id][0], index=False) return cache def setup(self, cache, shape):", "# copyright ownership. The Modin Development Team licenses this file", "# compliance with the License. You may obtain a copy", "benchmarks.\"\"\" import modin.pandas as pd from ..utils import ( generate_dataframe,", "language # governing permissions and limitations under the License. \"\"\"IO", "license agreements. # See the NOTICE file distributed with this", "file except in # compliance with the License. You may", "shapes = get_benchmark_shapes(\"omnisci.TimeReadCsvNames\") param_names = [\"shape\"] params = [shapes] def", "filenames with a metadata of saved dataframes cache = {}", "License. You may obtain a copy of the License at", "License. \"\"\"IO Modin on OmniSci storage format benchmarks.\"\"\" import modin.pandas", "in writing, software distributed under # the License is distributed", "\"int\", *shape, RAND_LOW, RAND_HIGH) file_id = get_shape_id(shape) cache[file_id] = (", "information regarding # copyright ownership. The Modin Development Team licenses", "You may obtain a copy of the License at #", "in # compliance with the License. You may obtain a", "from ..utils import ( generate_dataframe, RAND_LOW, RAND_HIGH, ASV_USE_IMPL, IMPL, get_shape_id,", "The Modin Development Team licenses this file to you under", ") df.to_csv(cache[file_id][0], index=False) return cache def setup(self, cache, shape): #", "distributed under # the License is distributed on an \"AS", "required by applicable law or agreed to in writing, software", "work for additional information regarding # copyright ownership. The Modin", "on OmniSci storage format benchmarks.\"\"\" import modin.pandas as pd from", "specific language # governing permissions and limitations under the License.", "under one or more contributor license agreements. # See the", "file_id = get_shape_id(shape) cache[file_id] = ( f\"{test_filename}_{file_id}.csv\", df.columns.to_list(), df.dtypes.to_dict(), )", "the License. \"\"\"IO Modin on OmniSci storage format benchmarks.\"\"\" import", "Modin Development Team licenses this file to you under the", "the NOTICE file distributed with this work for additional information", "may not use this file except in # compliance with", "See the License for the specific language # governing permissions", "for additional information regarding # copyright ownership. The Modin Development", "# Apache License, Version 2.0 (the \"License\"); you may not", "file_id = get_shape_id(shape) self.filename, self.names, self.dtype = cache[file_id] def time_read_csv_names(self,", "or agreed to in writing, software distributed under # the", "ASV_USE_IMPL == \"modin\": pd.DataFrame([]) file_id = get_shape_id(shape) self.filename, self.names, self.dtype", "self.dtype = cache[file_id] def time_read_csv_names(self, cache, shape): df = IMPL[ASV_USE_IMPL].read_csv(", "WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express", "or more contributor license agreements. # See the NOTICE file", "OR CONDITIONS OF # ANY KIND, either express or implied." ]
[ "= image_aug(tmp_data[i],angle) tmp_data[i] = tmp_ if model == \"uf\": train_x1", "x[indx[500:600],:]), axis=0) test_y = np.concatenate((test_y, y[indx[500:600]]), axis=0) return train_x1, train_y1,", "im_sz = int(np.floor(pic.shape[0]*scale)) pic_ = np.uint8(np.zeros((im_sz,im_sz,3),dtype=int)) pic_[:,:,0] = ndimage.zoom(pic[:,:,0],scale) pic_[:,:,1]", "test_y)) errors[0] = errors[0]+(1 - np.mean(llf_single_task == test_y)) errors =", "p: p.map(perform_angle, angles) elif model == \"uf\": angles = np.arange(30,180,2)", "{\"network\" : network, \"euclidean_layer_idx\" : -2, \"num_classes\" : 10, \"optimizer\"", "print(\"Starting Rep {} of Angle {}\".format(rep, angle)) train_x1, train_y1, train_x2,", "= train_x1.reshape((train_x1.shape[0], train_x1.shape[1] * train_x1.shape[2] * train_x1.shape[3])) tmp_data = tmp_data.reshape((tmp_data.shape[0],", "activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=128, kernel_size=(3, 3), strides = 2, padding =", "import keras from keras import layers from joblib import Parallel,", "X = train_x1, y = train_y1, transformer_voter_decider_split = [0.67, 0.33,", "y[indx[250:500]]), axis=0) test_x = np.concatenate((test_x, x[indx[500:600],:]), axis=0) test_y = np.concatenate((test_y,", "def image_aug(pic, angle, centroid_x=23, centroid_y=23, win=16, scale=1.45): im_sz = int(np.floor(pic.shape[0]*scale))", "= x[indx[0:250],:] train_x2 = x[indx[250:500],:] train_y1 = y[indx[0:250]] train_y2 =", "\"num_classes\" : 10, \"optimizer\" : keras.optimizers.Adam(3e-4) } default_voter_class = KNNClassificationVoter", "if model == \"dnn\": for angle_adder in range(30, 180, granularity", "pic_ = np.uint8(np.zeros((im_sz,im_sz,3),dtype=int)) pic_[:,:,0] = ndimage.zoom(pic[:,:,0],scale) pic_[:,:,1] = ndimage.zoom(pic[:,:,1],scale) pic_[:,:,2]", "import rotate from scipy import ndimage from skimage.util import img_as_ubyte", "2 reps = 4 ######################## (X_train, y_train), (X_test, y_test) =", "Pool(4) as p: p.map(perform_angle, angles) elif model == \"uf\": angles", "= [0.67, 0.33, 0], decider_kwargs = {\"classes\" : np.unique(train_y1)} )", "in range(reps): print(\"Starting Rep {} of Angle {}\".format(rep, angle)) train_x1,", "= 4 ######################## (X_train, y_train), (X_test, y_test) = keras.datasets.cifar100.load_data() data_x", "train_y1 = np.concatenate((train_y1, y[indx[0:250]]), axis=0) train_y2 = np.concatenate((train_y2, y[indx[250:500]]), axis=0)", "np.zeros(2) for rep in range(reps): print(\"Starting Rep {} of Angle", "= 'softmax')) default_transformer_kwargs = {\"network\" : network, \"euclidean_layer_idx\" : -2,", "= NeuralClassificationTransformer network = keras.Sequential() network.add(layers.Conv2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=np.shape(train_x1)[1:]))", "import sys sys.path.append(\"../../proglearn/\") from progressive_learner import ProgressiveLearner from deciders import", "axis=0) train_x2 = np.concatenate((train_x2, x[indx[250:500],:]), axis=0) train_y1 = np.concatenate((train_y1, y[indx[0:250]]),", "pickle.dump(errors, f, protocol = 2) def image_aug(pic, angle, centroid_x=23, centroid_y=23,", "import Pool import tensorflow as tf from numba import cuda", "network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=128, kernel_size=(3, 3), strides = 2, padding = \"same\",", "progressive_learner.add_task( X = train_x1, y = train_y1, transformer_voter_decider_split = [0.67,", "default_decider_class) progressive_learner.add_task( X = train_x1, y = train_y1, transformer_voter_decider_split =", "import ProgressiveLearner from deciders import SimpleArgmaxAverage from transformers import TreeClassificationTransformer,", "acorn is not None: np.random.seed(acorn) errors = np.zeros(2) for rep", "= default_voter_class, default_voter_kwargs = default_voter_kwargs, default_decider_class = default_decider_class) progressive_learner.add_task( X", "= 2, padding = \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=64, kernel_size=(3, 3),", "kernel_size=(3, 3), activation='relu', input_shape=np.shape(train_x1)[1:])) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=32, kernel_size=(3, 3), strides =", "reps = 4 ######################## (X_train, y_train), (X_test, y_test) = keras.datasets.cifar100.load_data()", "test_y def LF_experiment(data_x, data_y, angle, model, granularity, reps=1, ntrees=29, acorn=None):", "in range(total_data): tmp_ = image_aug(tmp_data[i],angle) tmp_data[i] = tmp_ if model", "angles = np.arange(30,180,2) Parallel(n_jobs=-1)(delayed(LF_experiment)(data_x, data_y, angle, model, granularity, reps=20, ntrees=16,", "default_voter_class = KNNClassificationVoter default_voter_kwargs = {\"k\" : int(np.log2(len(train_x1)))} default_decider_class =", "p.map(perform_angle, angles) elif model == \"uf\": angles = np.arange(30,180,2) Parallel(n_jobs=-1)(delayed(LF_experiment)(data_x,", "default_voter_kwargs, default_decider_class = default_decider_class) progressive_learner.add_task( X = train_x1, y =", "test_x, test_y def LF_experiment(data_x, data_y, angle, model, granularity, reps=1, ntrees=29,", "= 1, backward_task_ids = [0] ) llf_task1=progressive_learner.predict(test_x, task_id=0) llf_single_task=progressive_learner.predict(test_x, task_id=0,", "activation='relu')) network.add(layers.Flatten()) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(units=10,", "axis=0) train_y2 = np.concatenate((train_y2, y[indx[250:500]]), axis=0) test_x = np.concatenate((test_x, x[indx[500:600],:]),", "network.add(layers.BatchNormalization()) network.add(layers.Dense(units=10, activation = 'softmax')) default_transformer_kwargs = {\"network\" : network,", "\"dnn\" granularity = 2 reps = 4 ######################## (X_train, y_train),", "multiprocessing import Pool import tensorflow as tf from numba import", "'softmax')) default_transformer_kwargs = {\"network\" : network, \"euclidean_layer_idx\" : -2, \"num_classes\"", "import cuda import sys sys.path.append(\"../../proglearn/\") from progressive_learner import ProgressiveLearner from", "import TreeClassificationTransformer, NeuralClassificationTransformer from voters import TreeClassificationVoter, KNNClassificationVoter def cross_val_data(data_x,", "= tmp_data, y = train_y2, transformer_data_proportion = 1, backward_task_ids =", "keras from keras import layers from joblib import Parallel, delayed", "DecisionTreeClassifier from itertools import product import keras from keras import", "2, padding = \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=64, kernel_size=(3, 3), strides", "model, granularity, reps=1, ntrees=29, acorn=None): if acorn is not None:", "3), activation='relu', input_shape=np.shape(train_x1)[1:])) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=32, kernel_size=(3, 3), strides = 2,", "joblib import Parallel, delayed from sklearn.ensemble.forest import _generate_unsampled_indices from sklearn.ensemble.forest", "test_y = y[indx[500:600]] else: train_x1 = np.concatenate((train_x1, x[indx[0:250],:]), axis=0) train_x2", "in range(total_cls): indx = idx[i]#np.roll(idx[i],(cv-1)*100) random.shuffle(indx) if i==0: train_x1 =", "from sklearn.ensemble.forest import _generate_sample_indices import numpy as np from sklearn.ensemble", "train_x1.shape[1] * train_x1.shape[2] * train_x1.shape[3])) tmp_data = tmp_data.reshape((tmp_data.shape[0], tmp_data.shape[1] *", "import ndimage from skimage.util import img_as_ubyte from joblib import Parallel,", "cross_val_data(data_x, data_y, total_cls=10) #change data angle for second task tmp_data", "tmp_data = train_x2.copy() _tmp_ = np.zeros((32,32,3), dtype=int) total_data = tmp_data.shape[0]", "= image_aug[centroid_x-win:centroid_x+win,centroid_y-win:centroid_y+win,:] return img_as_ubyte(image_aug_) ### MAIN HYPERPARAMS ### model =", "kernel_size=(3, 3), strides = 2, padding = \"same\", activation='relu')) network.add(layers.Flatten())", "test_x = x[indx[500:600],:] test_y = y[indx[500:600]] else: train_x1 = np.concatenate((train_x1,", "angle, centroid_x=23, centroid_y=23, win=16, scale=1.45): im_sz = int(np.floor(pic.shape[0]*scale)) pic_ =", "= 2, padding = \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=128, kernel_size=(3, 3),", "default_voter_class = default_voter_class, default_voter_kwargs = default_voter_kwargs, default_decider_class = default_decider_class) progressive_learner.add_task(", "np.concatenate([X_train, X_test]) data_y = np.concatenate([y_train, y_test]) data_y = data_y[:, 0]", "as p: p.map(perform_angle, angles) elif model == \"uf\": angles =", "== u)[0] for u in np.unique(data_y)] for i in range(total_cls):", "train_y1, train_x2, train_y2, test_x, test_y def LF_experiment(data_x, data_y, angle, model,", "tmp_data[i] = tmp_ if model == \"uf\": train_x1 = train_x1.reshape((train_x1.shape[0],", "train_x1.reshape((train_x1.shape[0], train_x1.shape[1] * train_x1.shape[2] * train_x1.shape[3])) tmp_data = tmp_data.reshape((tmp_data.shape[0], tmp_data.shape[1]", "import product import keras from keras import layers from joblib", "import numpy as np from sklearn.ensemble import BaggingClassifier from sklearn.tree", "tf from numba import cuda import sys sys.path.append(\"../../proglearn/\") from progressive_learner", "keras.datasets.cifar100.load_data() data_x = np.concatenate([X_train, X_test]) data_y = np.concatenate([y_train, y_test]) data_y", "from deciders import SimpleArgmaxAverage from transformers import TreeClassificationTransformer, NeuralClassificationTransformer from", "y_test) = keras.datasets.cifar100.load_data() data_x = np.concatenate([X_train, X_test]) data_y = np.concatenate([y_train,", "1, backward_task_ids = [0] ) llf_task1=progressive_learner.predict(test_x, task_id=0) llf_single_task=progressive_learner.predict(test_x, task_id=0, transformer_ids=[0])", "product import keras from keras import layers from joblib import", "TreeClassificationVoter, KNNClassificationVoter def cross_val_data(data_x, data_y, total_cls=10): x = data_x.copy() y", "np.random.seed(acorn) errors = np.zeros(2) for rep in range(reps): print(\"Starting Rep", "axis=0) test_y = np.concatenate((test_y, y[indx[500:600]]), axis=0) return train_x1, train_y1, train_x2,", "'wb') as f: pickle.dump(errors, f, protocol = 2) def image_aug(pic,", "{\"k\" : int(np.log2(len(train_x1)))} default_decider_class = SimpleArgmaxAverage progressive_learner = ProgressiveLearner(default_transformer_class =", "3), strides = 2, padding = \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=64,", "_tmp_ = np.zeros((32,32,3), dtype=int) total_data = tmp_data.shape[0] for i in", "in range(30, 180, granularity * 4): angles = angle_adder +", "import matplotlib.pyplot as plt import random import pickle from skimage.transform", "{}\".format(angle, errors)) with open('rotation_results/angle_'+str(angle)+'_'+model+'.pickle', 'wb') as f: pickle.dump(errors, f, protocol", "= errors[1]+(1 - np.mean(llf_task1 == test_y)) errors[0] = errors[0]+(1 -", "default_transformer_class = NeuralClassificationTransformer network = keras.Sequential() network.add(layers.Conv2D(filters=16, kernel_size=(3, 3), activation='relu',", "task_id=0) llf_single_task=progressive_learner.predict(test_x, task_id=0, transformer_ids=[0]) errors[1] = errors[1]+(1 - np.mean(llf_task1 ==", "network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(units=10, activation =", "transformer_data_proportion = 1, backward_task_ids = [0] ) llf_task1=progressive_learner.predict(test_x, task_id=0) llf_single_task=progressive_learner.predict(test_x,", "#print(image_aug.shape) image_aug_ = image_aug[centroid_x-win:centroid_x+win,centroid_y-win:centroid_y+win,:] return img_as_ubyte(image_aug_) ### MAIN HYPERPARAMS ###", "delayed from multiprocessing import Pool import tensorflow as tf from", ": int(np.log2(len(train_x1)))} default_decider_class = SimpleArgmaxAverage progressive_learner = ProgressiveLearner(default_transformer_class = default_transformer_class,", "keras import layers from joblib import Parallel, delayed from multiprocessing", "Angle {}\".format(rep, angle)) train_x1, train_y1, train_x2, train_y2, test_x, test_y =", "_generate_sample_indices import numpy as np from sklearn.ensemble import BaggingClassifier from", "ndimage.zoom(pic[:,:,0],scale) pic_[:,:,1] = ndimage.zoom(pic[:,:,1],scale) pic_[:,:,2] = ndimage.zoom(pic[:,:,2],scale) image_aug = rotate(pic_,", "[0.67, 0.33, 0], decider_kwargs = {\"classes\" : np.unique(train_y1)} ) progressive_learner.add_transformer(", "rotate from scipy import ndimage from skimage.util import img_as_ubyte from", "= tmp_ if model == \"uf\": train_x1 = train_x1.reshape((train_x1.shape[0], train_x1.shape[1]", "activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(units=10, activation = 'softmax')) default_transformer_kwargs", "network.add(layers.Conv2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=np.shape(train_x1)[1:])) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=32, kernel_size=(3, 3), strides", "= ndimage.zoom(pic[:,:,1],scale) pic_[:,:,2] = ndimage.zoom(pic[:,:,2],scale) image_aug = rotate(pic_, angle, resize=False)", ": keras.optimizers.Adam(3e-4) } default_voter_class = KNNClassificationVoter default_voter_kwargs = {\"k\" :", "granularity, reps=1, ntrees=29, acorn=None): if acorn is not None: np.random.seed(acorn)", "Pool import tensorflow as tf from numba import cuda import", "np.concatenate((train_y1, y[indx[0:250]]), axis=0) train_y2 = np.concatenate((train_y2, y[indx[250:500]]), axis=0) test_x =", "angle)) train_x1, train_y1, train_x2, train_y2, test_x, test_y = cross_val_data(data_x, data_y,", "= y[indx[250:500]] test_x = x[indx[500:600],:] test_y = y[indx[500:600]] else: train_x1", "default_decider_class = SimpleArgmaxAverage progressive_learner = ProgressiveLearner(default_transformer_class = default_transformer_class, default_transformer_kwargs =", "granularity, reps=reps, ntrees=16, acorn=1) if model == \"dnn\": for angle_adder", "test_x.shape[3])) with tf.device('/gpu:'+str(int(angle // granularity) % 4)): default_transformer_class = NeuralClassificationTransformer", "acorn=1) if model == \"dnn\": for angle_adder in range(30, 180,", "= x[indx[250:500],:] train_y1 = y[indx[0:250]] train_y2 = y[indx[250:500]] test_x =", "network.add(layers.Flatten()) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(units=10, activation", "test_y = cross_val_data(data_x, data_y, total_cls=10) #change data angle for second", "u)[0] for u in np.unique(data_y)] for i in range(total_cls): indx", "= np.concatenate((train_x2, x[indx[250:500],:]), axis=0) train_y1 = np.concatenate((train_y1, y[indx[0:250]]), axis=0) train_y2", "tmp_data.shape[2] * tmp_data.shape[3])) test_x = test_x.reshape((test_x.shape[0], test_x.shape[1] * test_x.shape[2] *", "= data_y.copy() idx = [np.where(data_y == u)[0] for u in", "* tmp_data.shape[3])) test_x = test_x.reshape((test_x.shape[0], test_x.shape[1] * test_x.shape[2] * test_x.shape[3]))", "test_x = test_x.reshape((test_x.shape[0], test_x.shape[1] * test_x.shape[2] * test_x.shape[3])) with tf.device('/gpu:'+str(int(angle", "padding = \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=128, kernel_size=(3, 3), strides =", "centroid_y=23, win=16, scale=1.45): im_sz = int(np.floor(pic.shape[0]*scale)) pic_ = np.uint8(np.zeros((im_sz,im_sz,3),dtype=int)) pic_[:,:,0]", "np.concatenate((test_x, x[indx[500:600],:]), axis=0) test_y = np.concatenate((test_y, y[indx[500:600]]), axis=0) return train_x1,", "progressive_learner.add_transformer( X = tmp_data, y = train_y2, transformer_data_proportion = 1,", "train_y1, transformer_voter_decider_split = [0.67, 0.33, 0], decider_kwargs = {\"classes\" :", "train_x2 = np.concatenate((train_x2, x[indx[250:500],:]), axis=0) train_y1 = np.concatenate((train_y1, y[indx[0:250]]), axis=0)", "train_x2 = x[indx[250:500],:] train_y1 = y[indx[0:250]] train_y2 = y[indx[250:500]] test_x", "for i in range(total_data): tmp_ = image_aug(tmp_data[i],angle) tmp_data[i] = tmp_", "granularity) % 4)): default_transformer_class = NeuralClassificationTransformer network = keras.Sequential() network.add(layers.Conv2D(filters=16,", "int(np.log2(len(train_x1)))} default_decider_class = SimpleArgmaxAverage progressive_learner = ProgressiveLearner(default_transformer_class = default_transformer_class, default_transformer_kwargs", "u in np.unique(data_y)] for i in range(total_cls): indx = idx[i]#np.roll(idx[i],(cv-1)*100)", "network.add(layers.Conv2D(filters=32, kernel_size=(3, 3), strides = 2, padding = \"same\", activation='relu'))", "pic_[:,:,1] = ndimage.zoom(pic[:,:,1],scale) pic_[:,:,2] = ndimage.zoom(pic[:,:,2],scale) image_aug = rotate(pic_, angle,", "angles = angle_adder + np.arange(0, granularity * 4, granularity) with", "cuda import sys sys.path.append(\"../../proglearn/\") from progressive_learner import ProgressiveLearner from deciders", "Parallel, delayed from multiprocessing import Pool import tensorflow as tf", "x[indx[500:600],:] test_y = y[indx[500:600]] else: train_x1 = np.concatenate((train_x1, x[indx[0:250],:]), axis=0)", "errors = errors/reps print(\"Errors For Angle {}: {}\".format(angle, errors)) with", "test_x = np.concatenate((test_x, x[indx[500:600],:]), axis=0) test_y = np.concatenate((test_y, y[indx[500:600]]), axis=0)", "== test_y)) errors = errors/reps print(\"Errors For Angle {}: {}\".format(angle,", "train_x2, train_y2, test_x, test_y def LF_experiment(data_x, data_y, angle, model, granularity,", "if acorn is not None: np.random.seed(acorn) errors = np.zeros(2) for", "elif model == \"uf\": angles = np.arange(30,180,2) Parallel(n_jobs=-1)(delayed(LF_experiment)(data_x, data_y, angle,", "np.concatenate((train_y2, y[indx[250:500]]), axis=0) test_x = np.concatenate((test_x, x[indx[500:600],:]), axis=0) test_y =", "task_id=0, transformer_ids=[0]) errors[1] = errors[1]+(1 - np.mean(llf_task1 == test_y)) errors[0]", "(X_test, y_test) = keras.datasets.cifar100.load_data() data_x = np.concatenate([X_train, X_test]) data_y =", "network = keras.Sequential() network.add(layers.Conv2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=np.shape(train_x1)[1:])) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=32,", "delayed from sklearn.ensemble.forest import _generate_unsampled_indices from sklearn.ensemble.forest import _generate_sample_indices import", "from sklearn.tree import DecisionTreeClassifier from itertools import product import keras", "sklearn.ensemble.forest import _generate_sample_indices import numpy as np from sklearn.ensemble import", "= 2) def image_aug(pic, angle, centroid_x=23, centroid_y=23, win=16, scale=1.45): im_sz", "[0] ) llf_task1=progressive_learner.predict(test_x, task_id=0) llf_single_task=progressive_learner.predict(test_x, task_id=0, transformer_ids=[0]) errors[1] = errors[1]+(1", "image_aug(tmp_data[i],angle) tmp_data[i] = tmp_ if model == \"uf\": train_x1 =", "= SimpleArgmaxAverage progressive_learner = ProgressiveLearner(default_transformer_class = default_transformer_class, default_transformer_kwargs = default_transformer_kwargs,", "i==0: train_x1 = x[indx[0:250],:] train_x2 = x[indx[250:500],:] train_y1 = y[indx[0:250]]", "keras.optimizers.Adam(3e-4) } default_voter_class = KNNClassificationVoter default_voter_kwargs = {\"k\" : int(np.log2(len(train_x1)))}", "10, \"optimizer\" : keras.optimizers.Adam(3e-4) } default_voter_class = KNNClassificationVoter default_voter_kwargs =", "data_y, angle, model, granularity, reps=reps, ntrees=16, acorn=1) if model ==", "= cross_val_data(data_x, data_y, total_cls=10) #change data angle for second task", "granularity) with Pool(4) as p: p.map(perform_angle, angles) elif model ==", "f, protocol = 2) def image_aug(pic, angle, centroid_x=23, centroid_y=23, win=16,", "test_y)) errors = errors/reps print(\"Errors For Angle {}: {}\".format(angle, errors))", "data_y, total_cls=10): x = data_x.copy() y = data_y.copy() idx =", "as f: pickle.dump(errors, f, protocol = 2) def image_aug(pic, angle,", "network.add(layers.Conv2D(filters=64, kernel_size=(3, 3), strides = 2, padding = \"same\", activation='relu'))", "cross_val_data(data_x, data_y, total_cls=10): x = data_x.copy() y = data_y.copy() idx", "data_y, angle, model, granularity, reps=20, ntrees=16, acorn=1) for angle in", "- np.mean(llf_single_task == test_y)) errors = errors/reps print(\"Errors For Angle", "range(reps): print(\"Starting Rep {} of Angle {}\".format(rep, angle)) train_x1, train_y1,", "default_transformer_kwargs = {\"network\" : network, \"euclidean_layer_idx\" : -2, \"num_classes\" :", "resize=False) #print(image_aug.shape) image_aug_ = image_aug[centroid_x-win:centroid_x+win,centroid_y-win:centroid_y+win,:] return img_as_ubyte(image_aug_) ### MAIN HYPERPARAMS", "data_y, total_cls=10) #change data angle for second task tmp_data =", "y[indx[0:250]] train_y2 = y[indx[250:500]] test_x = x[indx[500:600],:] test_y = y[indx[500:600]]", "y = data_y.copy() idx = [np.where(data_y == u)[0] for u", "default_transformer_kwargs = default_transformer_kwargs, default_voter_class = default_voter_class, default_voter_kwargs = default_voter_kwargs, default_decider_class", "numpy as np from sklearn.ensemble import BaggingClassifier from sklearn.tree import", "4, granularity) with Pool(4) as p: p.map(perform_angle, angles) elif model", "sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier from itertools import", "2, padding = \"same\", activation='relu')) network.add(layers.Flatten()) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization())", "img_as_ubyte(image_aug_) ### MAIN HYPERPARAMS ### model = \"dnn\" granularity =", "from scipy import ndimage from skimage.util import img_as_ubyte from joblib", "kernel_size=(3, 3), strides = 2, padding = \"same\", activation='relu')) network.add(layers.BatchNormalization())", "== test_y)) errors[0] = errors[0]+(1 - np.mean(llf_single_task == test_y)) errors", "from joblib import Parallel, delayed from multiprocessing import Pool import", "image_aug[centroid_x-win:centroid_x+win,centroid_y-win:centroid_y+win,:] return img_as_ubyte(image_aug_) ### MAIN HYPERPARAMS ### model = \"dnn\"", "default_voter_kwargs = {\"k\" : int(np.log2(len(train_x1)))} default_decider_class = SimpleArgmaxAverage progressive_learner =", "model == \"uf\": train_x1 = train_x1.reshape((train_x1.shape[0], train_x1.shape[1] * train_x1.shape[2] *", "input_shape=np.shape(train_x1)[1:])) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=32, kernel_size=(3, 3), strides = 2, padding =", "perform_angle(angle): LF_experiment(data_x, data_y, angle, model, granularity, reps=reps, ntrees=16, acorn=1) if", "y = train_y2, transformer_data_proportion = 1, backward_task_ids = [0] )", "padding = \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=254, kernel_size=(3, 3), strides =", "random.shuffle(indx) if i==0: train_x1 = x[indx[0:250],:] train_x2 = x[indx[250:500],:] train_y1", "0] def perform_angle(angle): LF_experiment(data_x, data_y, angle, model, granularity, reps=reps, ntrees=16,", "deciders import SimpleArgmaxAverage from transformers import TreeClassificationTransformer, NeuralClassificationTransformer from voters", "= 2, padding = \"same\", activation='relu')) network.add(layers.Flatten()) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu'))", "\"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=128, kernel_size=(3, 3), strides = 2, padding", "* test_x.shape[3])) with tf.device('/gpu:'+str(int(angle // granularity) % 4)): default_transformer_class =", "in np.unique(data_y)] for i in range(total_cls): indx = idx[i]#np.roll(idx[i],(cv-1)*100) random.shuffle(indx)", "as tf from numba import cuda import sys sys.path.append(\"../../proglearn/\") from", "train_x1 = train_x1.reshape((train_x1.shape[0], train_x1.shape[1] * train_x1.shape[2] * train_x1.shape[3])) tmp_data =", "ProgressiveLearner(default_transformer_class = default_transformer_class, default_transformer_kwargs = default_transformer_kwargs, default_voter_class = default_voter_class, default_voter_kwargs", "network, \"euclidean_layer_idx\" : -2, \"num_classes\" : 10, \"optimizer\" : keras.optimizers.Adam(3e-4)", "ndimage from skimage.util import img_as_ubyte from joblib import Parallel, delayed", "\"dnn\": for angle_adder in range(30, 180, granularity * 4): angles", "return img_as_ubyte(image_aug_) ### MAIN HYPERPARAMS ### model = \"dnn\" granularity", "i in range(total_data): tmp_ = image_aug(tmp_data[i],angle) tmp_data[i] = tmp_ if", "Parallel, delayed from sklearn.ensemble.forest import _generate_unsampled_indices from sklearn.ensemble.forest import _generate_sample_indices", "train_x1 = x[indx[0:250],:] train_x2 = x[indx[250:500],:] train_y1 = y[indx[0:250]] train_y2", "- np.mean(llf_task1 == test_y)) errors[0] = errors[0]+(1 - np.mean(llf_single_task ==", "\"uf\": angles = np.arange(30,180,2) Parallel(n_jobs=-1)(delayed(LF_experiment)(data_x, data_y, angle, model, granularity, reps=20,", "import tensorflow as tf from numba import cuda import sys", "train_x1, train_y1, train_x2, train_y2, test_x, test_y def LF_experiment(data_x, data_y, angle,", "= np.concatenate([X_train, X_test]) data_y = np.concatenate([y_train, y_test]) data_y = data_y[:,", "from joblib import Parallel, delayed from sklearn.ensemble.forest import _generate_unsampled_indices from", "3), strides = 2, padding = \"same\", activation='relu')) network.add(layers.Flatten()) network.add(layers.BatchNormalization())", "strides = 2, padding = \"same\", activation='relu')) network.add(layers.Flatten()) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000,", "= data_x.copy() y = data_y.copy() idx = [np.where(data_y == u)[0]", "from skimage.util import img_as_ubyte from joblib import Parallel, delayed from", "np.concatenate((test_y, y[indx[500:600]]), axis=0) return train_x1, train_y1, train_x2, train_y2, test_x, test_y", "np.unique(train_y1)} ) progressive_learner.add_transformer( X = tmp_data, y = train_y2, transformer_data_proportion", "= KNNClassificationVoter default_voter_kwargs = {\"k\" : int(np.log2(len(train_x1)))} default_decider_class = SimpleArgmaxAverage", "image_aug = rotate(pic_, angle, resize=False) #print(image_aug.shape) image_aug_ = image_aug[centroid_x-win:centroid_x+win,centroid_y-win:centroid_y+win,:] return", "= ndimage.zoom(pic[:,:,2],scale) image_aug = rotate(pic_, angle, resize=False) #print(image_aug.shape) image_aug_ =", "{}: {}\".format(angle, errors)) with open('rotation_results/angle_'+str(angle)+'_'+model+'.pickle', 'wb') as f: pickle.dump(errors, f,", "second task tmp_data = train_x2.copy() _tmp_ = np.zeros((32,32,3), dtype=int) total_data", "transformer_ids=[0]) errors[1] = errors[1]+(1 - np.mean(llf_task1 == test_y)) errors[0] =", "network.add(layers.Conv2D(filters=128, kernel_size=(3, 3), strides = 2, padding = \"same\", activation='relu'))", "train_y1, train_x2, train_y2, test_x, test_y = cross_val_data(data_x, data_y, total_cls=10) #change", "} default_voter_class = KNNClassificationVoter default_voter_kwargs = {\"k\" : int(np.log2(len(train_x1)))} default_decider_class", "= tmp_data.reshape((tmp_data.shape[0], tmp_data.shape[1] * tmp_data.shape[2] * tmp_data.shape[3])) test_x = test_x.reshape((test_x.shape[0],", "with tf.device('/gpu:'+str(int(angle // granularity) % 4)): default_transformer_class = NeuralClassificationTransformer network", "== \"uf\": angles = np.arange(30,180,2) Parallel(n_jobs=-1)(delayed(LF_experiment)(data_x, data_y, angle, model, granularity,", "activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(units=10, activation = 'softmax')) default_transformer_kwargs = {\"network\" :", "random import pickle from skimage.transform import rotate from scipy import", "from keras import layers from joblib import Parallel, delayed from", "return train_x1, train_y1, train_x2, train_y2, test_x, test_y def LF_experiment(data_x, data_y,", "strides = 2, padding = \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=254, kernel_size=(3,", "np.unique(data_y)] for i in range(total_cls): indx = idx[i]#np.roll(idx[i],(cv-1)*100) random.shuffle(indx) if", "padding = \"same\", activation='relu')) network.add(layers.Flatten()) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000,", "BaggingClassifier from sklearn.tree import DecisionTreeClassifier from itertools import product import", "y[indx[250:500]] test_x = x[indx[500:600],:] test_y = y[indx[500:600]] else: train_x1 =", "default_decider_class = default_decider_class) progressive_learner.add_task( X = train_x1, y = train_y1,", "= default_decider_class) progressive_learner.add_task( X = train_x1, y = train_y1, transformer_voter_decider_split", "y[indx[500:600]]), axis=0) return train_x1, train_y1, train_x2, train_y2, test_x, test_y def", "x = data_x.copy() y = data_y.copy() idx = [np.where(data_y ==", ": network, \"euclidean_layer_idx\" : -2, \"num_classes\" : 10, \"optimizer\" :", "not None: np.random.seed(acorn) errors = np.zeros(2) for rep in range(reps):", "= {\"network\" : network, \"euclidean_layer_idx\" : -2, \"num_classes\" : 10,", "angle, model, granularity, reps=20, ntrees=16, acorn=1) for angle in angles)", "import _generate_unsampled_indices from sklearn.ensemble.forest import _generate_sample_indices import numpy as np", "from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier from itertools", "tmp_data, y = train_y2, transformer_data_proportion = 1, backward_task_ids = [0]", ") llf_task1=progressive_learner.predict(test_x, task_id=0) llf_single_task=progressive_learner.predict(test_x, task_id=0, transformer_ids=[0]) errors[1] = errors[1]+(1 -", "KNNClassificationVoter default_voter_kwargs = {\"k\" : int(np.log2(len(train_x1)))} default_decider_class = SimpleArgmaxAverage progressive_learner", "data angle for second task tmp_data = train_x2.copy() _tmp_ =", "train_y1 = y[indx[0:250]] train_y2 = y[indx[250:500]] test_x = x[indx[500:600],:] test_y", "= \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=128, kernel_size=(3, 3), strides = 2,", "total_cls=10) #change data angle for second task tmp_data = train_x2.copy()", "{\"classes\" : np.unique(train_y1)} ) progressive_learner.add_transformer( X = tmp_data, y =", "tmp_data.reshape((tmp_data.shape[0], tmp_data.shape[1] * tmp_data.shape[2] * tmp_data.shape[3])) test_x = test_x.reshape((test_x.shape[0], test_x.shape[1]", "for u in np.unique(data_y)] for i in range(total_cls): indx =", "= train_y2, transformer_data_proportion = 1, backward_task_ids = [0] ) llf_task1=progressive_learner.predict(test_x,", "rotate(pic_, angle, resize=False) #print(image_aug.shape) image_aug_ = image_aug[centroid_x-win:centroid_x+win,centroid_y-win:centroid_y+win,:] return img_as_ubyte(image_aug_) ###", "model = \"dnn\" granularity = 2 reps = 4 ########################", "scipy import ndimage from skimage.util import img_as_ubyte from joblib import", "tmp_ = image_aug(tmp_data[i],angle) tmp_data[i] = tmp_ if model == \"uf\":", "import Parallel, delayed from multiprocessing import Pool import tensorflow as", "is not None: np.random.seed(acorn) errors = np.zeros(2) for rep in", "x[indx[0:250],:] train_x2 = x[indx[250:500],:] train_y1 = y[indx[0:250]] train_y2 = y[indx[250:500]]", "transformers import TreeClassificationTransformer, NeuralClassificationTransformer from voters import TreeClassificationVoter, KNNClassificationVoter def", "ndimage.zoom(pic[:,:,1],scale) pic_[:,:,2] = ndimage.zoom(pic[:,:,2],scale) image_aug = rotate(pic_, angle, resize=False) #print(image_aug.shape)", "* tmp_data.shape[2] * tmp_data.shape[3])) test_x = test_x.reshape((test_x.shape[0], test_x.shape[1] * test_x.shape[2]", "model, granularity, reps=reps, ntrees=16, acorn=1) if model == \"dnn\": for", "of Angle {}\".format(rep, angle)) train_x1, train_y1, train_x2, train_y2, test_x, test_y", "i in range(total_cls): indx = idx[i]#np.roll(idx[i],(cv-1)*100) random.shuffle(indx) if i==0: train_x1", "= \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=254, kernel_size=(3, 3), strides = 2,", "import layers from joblib import Parallel, delayed from multiprocessing import", "strides = 2, padding = \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=64, kernel_size=(3,", "None: np.random.seed(acorn) errors = np.zeros(2) for rep in range(reps): print(\"Starting", "tf.device('/gpu:'+str(int(angle // granularity) % 4)): default_transformer_class = NeuralClassificationTransformer network =", "+ np.arange(0, granularity * 4, granularity) with Pool(4) as p:", "= \"dnn\" granularity = 2 reps = 4 ######################## (X_train,", "= np.concatenate((test_y, y[indx[500:600]]), axis=0) return train_x1, train_y1, train_x2, train_y2, test_x,", "from voters import TreeClassificationVoter, KNNClassificationVoter def cross_val_data(data_x, data_y, total_cls=10): x", "test_x.shape[2] * test_x.shape[3])) with tf.device('/gpu:'+str(int(angle // granularity) % 4)): default_transformer_class", "int(np.floor(pic.shape[0]*scale)) pic_ = np.uint8(np.zeros((im_sz,im_sz,3),dtype=int)) pic_[:,:,0] = ndimage.zoom(pic[:,:,0],scale) pic_[:,:,1] = ndimage.zoom(pic[:,:,1],scale)", "axis=0) test_x = np.concatenate((test_x, x[indx[500:600],:]), axis=0) test_y = np.concatenate((test_y, y[indx[500:600]]),", "train_x1, train_y1, train_x2, train_y2, test_x, test_y = cross_val_data(data_x, data_y, total_cls=10)", "train_y2, transformer_data_proportion = 1, backward_task_ids = [0] ) llf_task1=progressive_learner.predict(test_x, task_id=0)", "\"optimizer\" : keras.optimizers.Adam(3e-4) } default_voter_class = KNNClassificationVoter default_voter_kwargs = {\"k\"", "granularity = 2 reps = 4 ######################## (X_train, y_train), (X_test,", "// granularity) % 4)): default_transformer_class = NeuralClassificationTransformer network = keras.Sequential()", "(X_train, y_train), (X_test, y_test) = keras.datasets.cifar100.load_data() data_x = np.concatenate([X_train, X_test])", "y_test]) data_y = data_y[:, 0] def perform_angle(angle): LF_experiment(data_x, data_y, angle,", "x[indx[250:500],:]), axis=0) train_y1 = np.concatenate((train_y1, y[indx[0:250]]), axis=0) train_y2 = np.concatenate((train_y2,", "train_y2 = y[indx[250:500]] test_x = x[indx[500:600],:] test_y = y[indx[500:600]] else:", "KNNClassificationVoter def cross_val_data(data_x, data_y, total_cls=10): x = data_x.copy() y =", "NeuralClassificationTransformer from voters import TreeClassificationVoter, KNNClassificationVoter def cross_val_data(data_x, data_y, total_cls=10):", "angle, model, granularity, reps=1, ntrees=29, acorn=None): if acorn is not", "win=16, scale=1.45): im_sz = int(np.floor(pic.shape[0]*scale)) pic_ = np.uint8(np.zeros((im_sz,im_sz,3),dtype=int)) pic_[:,:,0] =", "np.concatenate((train_x2, x[indx[250:500],:]), axis=0) train_y1 = np.concatenate((train_y1, y[indx[0:250]]), axis=0) train_y2 =", "\"uf\": train_x1 = train_x1.reshape((train_x1.shape[0], train_x1.shape[1] * train_x1.shape[2] * train_x1.shape[3])) tmp_data", "activation='relu', input_shape=np.shape(train_x1)[1:])) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=32, kernel_size=(3, 3), strides = 2, padding", "range(total_cls): indx = idx[i]#np.roll(idx[i],(cv-1)*100) random.shuffle(indx) if i==0: train_x1 = x[indx[0:250],:]", "angle, resize=False) #print(image_aug.shape) image_aug_ = image_aug[centroid_x-win:centroid_x+win,centroid_y-win:centroid_y+win,:] return img_as_ubyte(image_aug_) ### MAIN", "joblib import Parallel, delayed from multiprocessing import Pool import tensorflow", "np.mean(llf_task1 == test_y)) errors[0] = errors[0]+(1 - np.mean(llf_single_task == test_y))", "print(\"Errors For Angle {}: {}\".format(angle, errors)) with open('rotation_results/angle_'+str(angle)+'_'+model+'.pickle', 'wb') as", "tmp_data.shape[0] for i in range(total_data): tmp_ = image_aug(tmp_data[i],angle) tmp_data[i] =", "X_test]) data_y = np.concatenate([y_train, y_test]) data_y = data_y[:, 0] def", "data_y = np.concatenate([y_train, y_test]) data_y = data_y[:, 0] def perform_angle(angle):", "activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=64, kernel_size=(3, 3), strides = 2, padding =", "import DecisionTreeClassifier from itertools import product import keras from keras", "total_cls=10): x = data_x.copy() y = data_y.copy() idx = [np.where(data_y", "= np.zeros(2) for rep in range(reps): print(\"Starting Rep {} of", "3), strides = 2, padding = \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=128,", "from numba import cuda import sys sys.path.append(\"../../proglearn/\") from progressive_learner import", "pickle from skimage.transform import rotate from scipy import ndimage from", "network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(units=10, activation = 'softmax')) default_transformer_kwargs = {\"network\"", "total_data = tmp_data.shape[0] for i in range(total_data): tmp_ = image_aug(tmp_data[i],angle)", "decider_kwargs = {\"classes\" : np.unique(train_y1)} ) progressive_learner.add_transformer( X = tmp_data,", "= np.arange(30,180,2) Parallel(n_jobs=-1)(delayed(LF_experiment)(data_x, data_y, angle, model, granularity, reps=20, ntrees=16, acorn=1)", "errors = np.zeros(2) for rep in range(reps): print(\"Starting Rep {}", "y[indx[500:600]] else: train_x1 = np.concatenate((train_x1, x[indx[0:250],:]), axis=0) train_x2 = np.concatenate((train_x2,", "keras.Sequential() network.add(layers.Conv2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=np.shape(train_x1)[1:])) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=32, kernel_size=(3, 3),", "= errors[0]+(1 - np.mean(llf_single_task == test_y)) errors = errors/reps print(\"Errors", "transformer_voter_decider_split = [0.67, 0.33, 0], decider_kwargs = {\"classes\" : np.unique(train_y1)}", "y = train_y1, transformer_voter_decider_split = [0.67, 0.33, 0], decider_kwargs =", "default_transformer_class, default_transformer_kwargs = default_transformer_kwargs, default_voter_class = default_voter_class, default_voter_kwargs = default_voter_kwargs,", "MAIN HYPERPARAMS ### model = \"dnn\" granularity = 2 reps", "import SimpleArgmaxAverage from transformers import TreeClassificationTransformer, NeuralClassificationTransformer from voters import", "-2, \"num_classes\" : 10, \"optimizer\" : keras.optimizers.Adam(3e-4) } default_voter_class =", "scale=1.45): im_sz = int(np.floor(pic.shape[0]*scale)) pic_ = np.uint8(np.zeros((im_sz,im_sz,3),dtype=int)) pic_[:,:,0] = ndimage.zoom(pic[:,:,0],scale)", "for rep in range(reps): print(\"Starting Rep {} of Angle {}\".format(rep,", "train_x1.shape[2] * train_x1.shape[3])) tmp_data = tmp_data.reshape((tmp_data.shape[0], tmp_data.shape[1] * tmp_data.shape[2] *", "np.uint8(np.zeros((im_sz,im_sz,3),dtype=int)) pic_[:,:,0] = ndimage.zoom(pic[:,:,0],scale) pic_[:,:,1] = ndimage.zoom(pic[:,:,1],scale) pic_[:,:,2] = ndimage.zoom(pic[:,:,2],scale)", "activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=254, kernel_size=(3, 3), strides = 2, padding =", "angle, model, granularity, reps=reps, ntrees=16, acorn=1) if model == \"dnn\":", "180, granularity * 4): angles = angle_adder + np.arange(0, granularity", "f: pickle.dump(errors, f, protocol = 2) def image_aug(pic, angle, centroid_x=23,", "as plt import random import pickle from skimage.transform import rotate", "import _generate_sample_indices import numpy as np from sklearn.ensemble import BaggingClassifier", "else: train_x1 = np.concatenate((train_x1, x[indx[0:250],:]), axis=0) train_x2 = np.concatenate((train_x2, x[indx[250:500],:]),", "data_x = np.concatenate([X_train, X_test]) data_y = np.concatenate([y_train, y_test]) data_y =", "angles) elif model == \"uf\": angles = np.arange(30,180,2) Parallel(n_jobs=-1)(delayed(LF_experiment)(data_x, data_y,", "progressive_learner import ProgressiveLearner from deciders import SimpleArgmaxAverage from transformers import", "= default_transformer_kwargs, default_voter_class = default_voter_class, default_voter_kwargs = default_voter_kwargs, default_decider_class =", "== \"dnn\": for angle_adder in range(30, 180, granularity * 4):", "img_as_ubyte from joblib import Parallel, delayed from sklearn.ensemble.forest import _generate_unsampled_indices", "for second task tmp_data = train_x2.copy() _tmp_ = np.zeros((32,32,3), dtype=int)", "image_aug(pic, angle, centroid_x=23, centroid_y=23, win=16, scale=1.45): im_sz = int(np.floor(pic.shape[0]*scale)) pic_", "= ProgressiveLearner(default_transformer_class = default_transformer_class, default_transformer_kwargs = default_transformer_kwargs, default_voter_class = default_voter_class,", "y_train), (X_test, y_test) = keras.datasets.cifar100.load_data() data_x = np.concatenate([X_train, X_test]) data_y", "= default_voter_kwargs, default_decider_class = default_decider_class) progressive_learner.add_task( X = train_x1, y", "= errors/reps print(\"Errors For Angle {}: {}\".format(angle, errors)) with open('rotation_results/angle_'+str(angle)+'_'+model+'.pickle',", "= tmp_data.shape[0] for i in range(total_data): tmp_ = image_aug(tmp_data[i],angle) tmp_data[i]", "train_y2, test_x, test_y def LF_experiment(data_x, data_y, angle, model, granularity, reps=1,", "pic_[:,:,0] = ndimage.zoom(pic[:,:,0],scale) pic_[:,:,1] = ndimage.zoom(pic[:,:,1],scale) pic_[:,:,2] = ndimage.zoom(pic[:,:,2],scale) image_aug", "network.add(layers.Dense(units=10, activation = 'softmax')) default_transformer_kwargs = {\"network\" : network, \"euclidean_layer_idx\"", ": -2, \"num_classes\" : 10, \"optimizer\" : keras.optimizers.Adam(3e-4) } default_voter_class", "tmp_data.shape[1] * tmp_data.shape[2] * tmp_data.shape[3])) test_x = test_x.reshape((test_x.shape[0], test_x.shape[1] *", "image_aug_ = image_aug[centroid_x-win:centroid_x+win,centroid_y-win:centroid_y+win,:] return img_as_ubyte(image_aug_) ### MAIN HYPERPARAMS ### model", "train_y2 = np.concatenate((train_y2, y[indx[250:500]]), axis=0) test_x = np.concatenate((test_x, x[indx[500:600],:]), axis=0)", "np.zeros((32,32,3), dtype=int) total_data = tmp_data.shape[0] for i in range(total_data): tmp_", "data_x.copy() y = data_y.copy() idx = [np.where(data_y == u)[0] for", "train_x1.shape[3])) tmp_data = tmp_data.reshape((tmp_data.shape[0], tmp_data.shape[1] * tmp_data.shape[2] * tmp_data.shape[3])) test_x", "errors[1] = errors[1]+(1 - np.mean(llf_task1 == test_y)) errors[0] = errors[0]+(1", "errors[0] = errors[0]+(1 - np.mean(llf_single_task == test_y)) errors = errors/reps", "import img_as_ubyte from joblib import Parallel, delayed from sklearn.ensemble.forest import", "\"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=64, kernel_size=(3, 3), strides = 2, padding", "2) def image_aug(pic, angle, centroid_x=23, centroid_y=23, win=16, scale=1.45): im_sz =", "network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=32, kernel_size=(3, 3), strides = 2, padding = \"same\",", "NeuralClassificationTransformer network = keras.Sequential() network.add(layers.Conv2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=np.shape(train_x1)[1:])) network.add(layers.BatchNormalization())", "padding = \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=64, kernel_size=(3, 3), strides =", "= default_transformer_class, default_transformer_kwargs = default_transformer_kwargs, default_voter_class = default_voter_class, default_voter_kwargs =", "SimpleArgmaxAverage from transformers import TreeClassificationTransformer, NeuralClassificationTransformer from voters import TreeClassificationVoter,", "= int(np.floor(pic.shape[0]*scale)) pic_ = np.uint8(np.zeros((im_sz,im_sz,3),dtype=int)) pic_[:,:,0] = ndimage.zoom(pic[:,:,0],scale) pic_[:,:,1] =", "x[indx[250:500],:] train_y1 = y[indx[0:250]] train_y2 = y[indx[250:500]] test_x = x[indx[500:600],:]", "ntrees=16, acorn=1) if model == \"dnn\": for angle_adder in range(30,", "np.mean(llf_single_task == test_y)) errors = errors/reps print(\"Errors For Angle {}:", "= y[indx[500:600]] else: train_x1 = np.concatenate((train_x1, x[indx[0:250],:]), axis=0) train_x2 =", "data_y.copy() idx = [np.where(data_y == u)[0] for u in np.unique(data_y)]", "LF_experiment(data_x, data_y, angle, model, granularity, reps=reps, ntrees=16, acorn=1) if model", ": 10, \"optimizer\" : keras.optimizers.Adam(3e-4) } default_voter_class = KNNClassificationVoter default_voter_kwargs", "np.concatenate((train_x1, x[indx[0:250],:]), axis=0) train_x2 = np.concatenate((train_x2, x[indx[250:500],:]), axis=0) train_y1 =", "ntrees=29, acorn=None): if acorn is not None: np.random.seed(acorn) errors =", "= y[indx[0:250]] train_y2 = y[indx[250:500]] test_x = x[indx[500:600],:] test_y =", "train_x2.copy() _tmp_ = np.zeros((32,32,3), dtype=int) total_data = tmp_data.shape[0] for i", "= angle_adder + np.arange(0, granularity * 4, granularity) with Pool(4)", "range(total_data): tmp_ = image_aug(tmp_data[i],angle) tmp_data[i] = tmp_ if model ==", "granularity * 4): angles = angle_adder + np.arange(0, granularity *", "backward_task_ids = [0] ) llf_task1=progressive_learner.predict(test_x, task_id=0) llf_single_task=progressive_learner.predict(test_x, task_id=0, transformer_ids=[0]) errors[1]", "from multiprocessing import Pool import tensorflow as tf from numba", "######################## (X_train, y_train), (X_test, y_test) = keras.datasets.cifar100.load_data() data_x = np.concatenate([X_train,", "default_voter_class, default_voter_kwargs = default_voter_kwargs, default_decider_class = default_decider_class) progressive_learner.add_task( X =", "test_x.shape[1] * test_x.shape[2] * test_x.shape[3])) with tf.device('/gpu:'+str(int(angle // granularity) %", "= np.zeros((32,32,3), dtype=int) total_data = tmp_data.shape[0] for i in range(total_data):", "y[indx[0:250]]), axis=0) train_y2 = np.concatenate((train_y2, y[indx[250:500]]), axis=0) test_x = np.concatenate((test_x,", "= 2 reps = 4 ######################## (X_train, y_train), (X_test, y_test)", "= {\"classes\" : np.unique(train_y1)} ) progressive_learner.add_transformer( X = tmp_data, y", "for i in range(total_cls): indx = idx[i]#np.roll(idx[i],(cv-1)*100) random.shuffle(indx) if i==0:", "import Parallel, delayed from sklearn.ensemble.forest import _generate_unsampled_indices from sklearn.ensemble.forest import", "from sklearn.ensemble.forest import _generate_unsampled_indices from sklearn.ensemble.forest import _generate_sample_indices import numpy", "np from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier from", "activation = 'softmax')) default_transformer_kwargs = {\"network\" : network, \"euclidean_layer_idx\" :", "[np.where(data_y == u)[0] for u in np.unique(data_y)] for i in", "if model == \"uf\": train_x1 = train_x1.reshape((train_x1.shape[0], train_x1.shape[1] * train_x1.shape[2]", "llf_task1=progressive_learner.predict(test_x, task_id=0) llf_single_task=progressive_learner.predict(test_x, task_id=0, transformer_ids=[0]) errors[1] = errors[1]+(1 - np.mean(llf_task1", "centroid_x=23, centroid_y=23, win=16, scale=1.45): im_sz = int(np.floor(pic.shape[0]*scale)) pic_ = np.uint8(np.zeros((im_sz,im_sz,3),dtype=int))", "data_y, angle, model, granularity, reps=1, ntrees=29, acorn=None): if acorn is", "rep in range(reps): print(\"Starting Rep {} of Angle {}\".format(rep, angle))", "== \"uf\": train_x1 = train_x1.reshape((train_x1.shape[0], train_x1.shape[1] * train_x1.shape[2] * train_x1.shape[3]))", "\"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=254, kernel_size=(3, 3), strides = 2, padding", "llf_single_task=progressive_learner.predict(test_x, task_id=0, transformer_ids=[0]) errors[1] = errors[1]+(1 - np.mean(llf_task1 == test_y))", "= {\"k\" : int(np.log2(len(train_x1)))} default_decider_class = SimpleArgmaxAverage progressive_learner = ProgressiveLearner(default_transformer_class", "% 4)): default_transformer_class = NeuralClassificationTransformer network = keras.Sequential() network.add(layers.Conv2D(filters=16, kernel_size=(3,", "with Pool(4) as p: p.map(perform_angle, angles) elif model == \"uf\":", "= np.concatenate((test_x, x[indx[500:600],:]), axis=0) test_y = np.concatenate((test_y, y[indx[500:600]]), axis=0) return", "ProgressiveLearner from deciders import SimpleArgmaxAverage from transformers import TreeClassificationTransformer, NeuralClassificationTransformer", "range(30, 180, granularity * 4): angles = angle_adder + np.arange(0,", "= np.concatenate((train_y1, y[indx[0:250]]), axis=0) train_y2 = np.concatenate((train_y2, y[indx[250:500]]), axis=0) test_x", "skimage.transform import rotate from scipy import ndimage from skimage.util import", "errors/reps print(\"Errors For Angle {}: {}\".format(angle, errors)) with open('rotation_results/angle_'+str(angle)+'_'+model+'.pickle', 'wb')", "skimage.util import img_as_ubyte from joblib import Parallel, delayed from sklearn.ensemble.forest", "dtype=int) total_data = tmp_data.shape[0] for i in range(total_data): tmp_ =", "axis=0) return train_x1, train_y1, train_x2, train_y2, test_x, test_y def LF_experiment(data_x,", "= data_y[:, 0] def perform_angle(angle): LF_experiment(data_x, data_y, angle, model, granularity,", "4 ######################## (X_train, y_train), (X_test, y_test) = keras.datasets.cifar100.load_data() data_x =", "* 4, granularity) with Pool(4) as p: p.map(perform_angle, angles) elif", "from transformers import TreeClassificationTransformer, NeuralClassificationTransformer from voters import TreeClassificationVoter, KNNClassificationVoter", "np.arange(0, granularity * 4, granularity) with Pool(4) as p: p.map(perform_angle,", "default_transformer_kwargs, default_voter_class = default_voter_class, default_voter_kwargs = default_voter_kwargs, default_decider_class = default_decider_class)", "layers from joblib import Parallel, delayed from multiprocessing import Pool", "* test_x.shape[2] * test_x.shape[3])) with tf.device('/gpu:'+str(int(angle // granularity) % 4)):", "errors)) with open('rotation_results/angle_'+str(angle)+'_'+model+'.pickle', 'wb') as f: pickle.dump(errors, f, protocol =", "for angle_adder in range(30, 180, granularity * 4): angles =", "2, padding = \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=128, kernel_size=(3, 3), strides", "from itertools import product import keras from keras import layers", "Rep {} of Angle {}\".format(rep, angle)) train_x1, train_y1, train_x2, train_y2,", "_generate_unsampled_indices from sklearn.ensemble.forest import _generate_sample_indices import numpy as np from", "from skimage.transform import rotate from scipy import ndimage from skimage.util", "4): angles = angle_adder + np.arange(0, granularity * 4, granularity)", "sys.path.append(\"../../proglearn/\") from progressive_learner import ProgressiveLearner from deciders import SimpleArgmaxAverage from", "angle_adder in range(30, 180, granularity * 4): angles = angle_adder", "4)): default_transformer_class = NeuralClassificationTransformer network = keras.Sequential() network.add(layers.Conv2D(filters=16, kernel_size=(3, 3),", "= np.concatenate((train_y2, y[indx[250:500]]), axis=0) test_x = np.concatenate((test_x, x[indx[500:600],:]), axis=0) test_y", "0.33, 0], decider_kwargs = {\"classes\" : np.unique(train_y1)} ) progressive_learner.add_transformer( X", "def LF_experiment(data_x, data_y, angle, model, granularity, reps=1, ntrees=29, acorn=None): if", "open('rotation_results/angle_'+str(angle)+'_'+model+'.pickle', 'wb') as f: pickle.dump(errors, f, protocol = 2) def", "data_y = data_y[:, 0] def perform_angle(angle): LF_experiment(data_x, data_y, angle, model,", "train_x2, train_y2, test_x, test_y = cross_val_data(data_x, data_y, total_cls=10) #change data", "= \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=64, kernel_size=(3, 3), strides = 2,", "= train_x1, y = train_y1, transformer_voter_decider_split = [0.67, 0.33, 0],", "np.concatenate([y_train, y_test]) data_y = data_y[:, 0] def perform_angle(angle): LF_experiment(data_x, data_y,", "test_x, test_y = cross_val_data(data_x, data_y, total_cls=10) #change data angle for", "train_x1 = np.concatenate((train_x1, x[indx[0:250],:]), axis=0) train_x2 = np.concatenate((train_x2, x[indx[250:500],:]), axis=0)", "reps=1, ntrees=29, acorn=None): if acorn is not None: np.random.seed(acorn) errors", "= \"same\", activation='relu')) network.add(layers.Flatten()) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu'))", "import pickle from skimage.transform import rotate from scipy import ndimage", "acorn=None): if acorn is not None: np.random.seed(acorn) errors = np.zeros(2)", "tmp_ if model == \"uf\": train_x1 = train_x1.reshape((train_x1.shape[0], train_x1.shape[1] *", "train_x1, y = train_y1, transformer_voter_decider_split = [0.67, 0.33, 0], decider_kwargs", "numba import cuda import sys sys.path.append(\"../../proglearn/\") from progressive_learner import ProgressiveLearner", "angle_adder + np.arange(0, granularity * 4, granularity) with Pool(4) as", "def cross_val_data(data_x, data_y, total_cls=10): x = data_x.copy() y = data_y.copy()", "granularity * 4, granularity) with Pool(4) as p: p.map(perform_angle, angles)", "tmp_data = tmp_data.reshape((tmp_data.shape[0], tmp_data.shape[1] * tmp_data.shape[2] * tmp_data.shape[3])) test_x =", "network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(units=10, activation = 'softmax'))", "3), strides = 2, padding = \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=254,", "sklearn.ensemble.forest import _generate_unsampled_indices from sklearn.ensemble.forest import _generate_sample_indices import numpy as", "from progressive_learner import ProgressiveLearner from deciders import SimpleArgmaxAverage from transformers", "= x[indx[500:600],:] test_y = y[indx[500:600]] else: train_x1 = np.concatenate((train_x1, x[indx[0:250],:]),", "data_y[:, 0] def perform_angle(angle): LF_experiment(data_x, data_y, angle, model, granularity, reps=reps,", "network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=64, kernel_size=(3, 3), strides = 2, padding = \"same\",", "= train_y1, transformer_voter_decider_split = [0.67, 0.33, 0], decider_kwargs = {\"classes\"", "### MAIN HYPERPARAMS ### model = \"dnn\" granularity = 2", "test_y = np.concatenate((test_y, y[indx[500:600]]), axis=0) return train_x1, train_y1, train_x2, train_y2,", "= rotate(pic_, angle, resize=False) #print(image_aug.shape) image_aug_ = image_aug[centroid_x-win:centroid_x+win,centroid_y-win:centroid_y+win,:] return img_as_ubyte(image_aug_)", "{}\".format(rep, angle)) train_x1, train_y1, train_x2, train_y2, test_x, test_y = cross_val_data(data_x,", "train_y2, test_x, test_y = cross_val_data(data_x, data_y, total_cls=10) #change data angle", "as np from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassifier", "matplotlib.pyplot as plt import random import pickle from skimage.transform import", "plt import random import pickle from skimage.transform import rotate from", "= np.uint8(np.zeros((im_sz,im_sz,3),dtype=int)) pic_[:,:,0] = ndimage.zoom(pic[:,:,0],scale) pic_[:,:,1] = ndimage.zoom(pic[:,:,1],scale) pic_[:,:,2] =", "import TreeClassificationVoter, KNNClassificationVoter def cross_val_data(data_x, data_y, total_cls=10): x = data_x.copy()", "* train_x1.shape[3])) tmp_data = tmp_data.reshape((tmp_data.shape[0], tmp_data.shape[1] * tmp_data.shape[2] * tmp_data.shape[3]))", "model == \"uf\": angles = np.arange(30,180,2) Parallel(n_jobs=-1)(delayed(LF_experiment)(data_x, data_y, angle, model,", "progressive_learner = ProgressiveLearner(default_transformer_class = default_transformer_class, default_transformer_kwargs = default_transformer_kwargs, default_voter_class =", "tensorflow as tf from numba import cuda import sys sys.path.append(\"../../proglearn/\")", "HYPERPARAMS ### model = \"dnn\" granularity = 2 reps =", "import BaggingClassifier from sklearn.tree import DecisionTreeClassifier from itertools import product", "{} of Angle {}\".format(rep, angle)) train_x1, train_y1, train_x2, train_y2, test_x,", "Angle {}: {}\".format(angle, errors)) with open('rotation_results/angle_'+str(angle)+'_'+model+'.pickle', 'wb') as f: pickle.dump(errors,", "sklearn.tree import DecisionTreeClassifier from itertools import product import keras from", "itertools import product import keras from keras import layers from", "= [np.where(data_y == u)[0] for u in np.unique(data_y)] for i", "x[indx[0:250],:]), axis=0) train_x2 = np.concatenate((train_x2, x[indx[250:500],:]), axis=0) train_y1 = np.concatenate((train_y1,", "task tmp_data = train_x2.copy() _tmp_ = np.zeros((32,32,3), dtype=int) total_data =", "import random import pickle from skimage.transform import rotate from scipy", "Parallel(n_jobs=-1)(delayed(LF_experiment)(data_x, data_y, angle, model, granularity, reps=20, ntrees=16, acorn=1) for angle", "voters import TreeClassificationVoter, KNNClassificationVoter def cross_val_data(data_x, data_y, total_cls=10): x =", "errors[0]+(1 - np.mean(llf_single_task == test_y)) errors = errors/reps print(\"Errors For", ": np.unique(train_y1)} ) progressive_learner.add_transformer( X = tmp_data, y = train_y2,", "= np.concatenate((train_x1, x[indx[0:250],:]), axis=0) train_x2 = np.concatenate((train_x2, x[indx[250:500],:]), axis=0) train_y1", "if i==0: train_x1 = x[indx[0:250],:] train_x2 = x[indx[250:500],:] train_y1 =", "def perform_angle(angle): LF_experiment(data_x, data_y, angle, model, granularity, reps=reps, ntrees=16, acorn=1)", "np.arange(30,180,2) Parallel(n_jobs=-1)(delayed(LF_experiment)(data_x, data_y, angle, model, granularity, reps=20, ntrees=16, acorn=1) for", "= keras.Sequential() network.add(layers.Conv2D(filters=16, kernel_size=(3, 3), activation='relu', input_shape=np.shape(train_x1)[1:])) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=32, kernel_size=(3,", "0], decider_kwargs = {\"classes\" : np.unique(train_y1)} ) progressive_learner.add_transformer( X =", "model == \"dnn\": for angle_adder in range(30, 180, granularity *", "2, padding = \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=254, kernel_size=(3, 3), strides", "pic_[:,:,2] = ndimage.zoom(pic[:,:,2],scale) image_aug = rotate(pic_, angle, resize=False) #print(image_aug.shape) image_aug_", "= [0] ) llf_task1=progressive_learner.predict(test_x, task_id=0) llf_single_task=progressive_learner.predict(test_x, task_id=0, transformer_ids=[0]) errors[1] =", "reps=reps, ntrees=16, acorn=1) if model == \"dnn\": for angle_adder in", "SimpleArgmaxAverage progressive_learner = ProgressiveLearner(default_transformer_class = default_transformer_class, default_transformer_kwargs = default_transformer_kwargs, default_voter_class", "TreeClassificationTransformer, NeuralClassificationTransformer from voters import TreeClassificationVoter, KNNClassificationVoter def cross_val_data(data_x, data_y,", "network.add(layers.Conv2D(filters=254, kernel_size=(3, 3), strides = 2, padding = \"same\", activation='relu'))", "For Angle {}: {}\".format(angle, errors)) with open('rotation_results/angle_'+str(angle)+'_'+model+'.pickle', 'wb') as f:", "* 4): angles = angle_adder + np.arange(0, granularity * 4,", "idx = [np.where(data_y == u)[0] for u in np.unique(data_y)] for", "* train_x1.shape[2] * train_x1.shape[3])) tmp_data = tmp_data.reshape((tmp_data.shape[0], tmp_data.shape[1] * tmp_data.shape[2]", "tmp_data.shape[3])) test_x = test_x.reshape((test_x.shape[0], test_x.shape[1] * test_x.shape[2] * test_x.shape[3])) with", "axis=0) train_y1 = np.concatenate((train_y1, y[indx[0:250]]), axis=0) train_y2 = np.concatenate((train_y2, y[indx[250:500]]),", "= test_x.reshape((test_x.shape[0], test_x.shape[1] * test_x.shape[2] * test_x.shape[3])) with tf.device('/gpu:'+str(int(angle //", "with open('rotation_results/angle_'+str(angle)+'_'+model+'.pickle', 'wb') as f: pickle.dump(errors, f, protocol = 2)", "\"euclidean_layer_idx\" : -2, \"num_classes\" : 10, \"optimizer\" : keras.optimizers.Adam(3e-4) }", "X = tmp_data, y = train_y2, transformer_data_proportion = 1, backward_task_ids", "= train_x2.copy() _tmp_ = np.zeros((32,32,3), dtype=int) total_data = tmp_data.shape[0] for", "= ndimage.zoom(pic[:,:,0],scale) pic_[:,:,1] = ndimage.zoom(pic[:,:,1],scale) pic_[:,:,2] = ndimage.zoom(pic[:,:,2],scale) image_aug =", "#change data angle for second task tmp_data = train_x2.copy() _tmp_", "angle for second task tmp_data = train_x2.copy() _tmp_ = np.zeros((32,32,3),", "= idx[i]#np.roll(idx[i],(cv-1)*100) random.shuffle(indx) if i==0: train_x1 = x[indx[0:250],:] train_x2 =", "sys sys.path.append(\"../../proglearn/\") from progressive_learner import ProgressiveLearner from deciders import SimpleArgmaxAverage", "= np.concatenate([y_train, y_test]) data_y = data_y[:, 0] def perform_angle(angle): LF_experiment(data_x,", "indx = idx[i]#np.roll(idx[i],(cv-1)*100) random.shuffle(indx) if i==0: train_x1 = x[indx[0:250],:] train_x2", "LF_experiment(data_x, data_y, angle, model, granularity, reps=1, ntrees=29, acorn=None): if acorn", "idx[i]#np.roll(idx[i],(cv-1)*100) random.shuffle(indx) if i==0: train_x1 = x[indx[0:250],:] train_x2 = x[indx[250:500],:]", ") progressive_learner.add_transformer( X = tmp_data, y = train_y2, transformer_data_proportion =", "test_x.reshape((test_x.shape[0], test_x.shape[1] * test_x.shape[2] * test_x.shape[3])) with tf.device('/gpu:'+str(int(angle // granularity)", "errors[1]+(1 - np.mean(llf_task1 == test_y)) errors[0] = errors[0]+(1 - np.mean(llf_single_task", "protocol = 2) def image_aug(pic, angle, centroid_x=23, centroid_y=23, win=16, scale=1.45):", "network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=254, kernel_size=(3, 3), strides = 2, padding = \"same\",", "ndimage.zoom(pic[:,:,2],scale) image_aug = rotate(pic_, angle, resize=False) #print(image_aug.shape) image_aug_ = image_aug[centroid_x-win:centroid_x+win,centroid_y-win:centroid_y+win,:]", "= keras.datasets.cifar100.load_data() data_x = np.concatenate([X_train, X_test]) data_y = np.concatenate([y_train, y_test])", "= 2, padding = \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=254, kernel_size=(3, 3),", "network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(units=10, activation = 'softmax')) default_transformer_kwargs =", "### model = \"dnn\" granularity = 2 reps = 4", "strides = 2, padding = \"same\", activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Conv2D(filters=128, kernel_size=(3,", "\"same\", activation='relu')) network.add(layers.Flatten()) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization()) network.add(layers.Dense(2000, activation='relu')) network.add(layers.BatchNormalization())", "default_voter_kwargs = default_voter_kwargs, default_decider_class = default_decider_class) progressive_learner.add_task( X = train_x1," ]
[ "self.types = {} self.unique_vals = {} self.minmax = {} for", "= {} for col in X.columns: self.types[col] = X[col].dtype.name if", "self.max_nunique: self.unique_vals[col] = unique_values else: self.unique_vals[col] = None elif self.types[col]", "var_type = X[col].dtype.name if var_type != self.types[col]: self.print_message( 'Data Type", "X, y=None, **fitparams): X = validate_dataframe(X) self.types = {} for", "max_nunique=20): self.logfile = logfile self.to_screen = to_screen self.max_nunique = max_nunique", "in X.columns: self.types[col] = X[col].dtype.name if self.types[col] in ('object', 'bool',", "in X.columns: var_type = X[col].dtype.name if self.types[col] in ('object', 'bool',", "for column {col}: Lowest Training value {lowtrain}, Lowest Scoring value", "{col}: Largest Training value {hightrain}, Largest Scoring value {highscore}'.format( col=col,", "**fitparams): X = validate_dataframe(X) self.types = {} for col in", "'New Categories specified for column {col}: Received {received}'.format( col=col, received=new_values)", "= (X[col].min(), X[col].max()) return self def transform(self, X, **transformparams): X", "to_screen def fit(self, X, y=None, **fitparams): X = validate_dataframe(X) self.types", "self.types[col] in ('int64', 'float64', 'datetime64', 'timedelta'): minX = X[col].min() maxX", "{lowtrain}, Lowest Scoring value {lowscore}'.format( col=col, lowtrain=self.minmax[col][0], lowscore=minX) ) if", "self.logfile = logfile self.to_screen = to_screen def fit(self, X, y=None,", "{} for col in X.columns: self.types[col] = X[col].dtype.name return self", "self.to_screen = to_screen def fit(self, X, y=None, **fitparams): X =", "= {} self.minmax = {} for col in X.columns: self.types[col]", "self.types[col] in ('int64', 'float64', 'datetime64', 'timedelta'): self.minmax[col] = (X[col].min(), X[col].max())", "('int64', 'float64', 'datetime64', 'timedelta'): minX = X[col].min() maxX = X[col].max()", "var_type != self.types[col]: self.print_message( 'Data Type Mismatch for column {col}:", "if maxX > self.minmax[col][1]: self.print_message( 'High Value warning for column", "= {} self.unique_vals = {} self.minmax = {} for col", "for column {col}: Expected {expected} Received {received}'.format( col=col, expected=self.types[col], received=var_type)", "col=col, lowtrain=self.minmax[col][0], lowscore=minX) ) if maxX > self.minmax[col][1]: self.print_message( 'High", "import validate_dataframe class MonitorMixin(object): def print_message(self, message): if self.logfile: with", "not None: not_in_list = ~X[col].isin(self.unique_vals[col]) if sum(not_in_list) > 0: new_values", "for column {col}: Largest Training value {hightrain}, Largest Scoring value", "{} self.minmax = {} for col in X.columns: self.types[col] =", "validate_dataframe class MonitorMixin(object): def print_message(self, message): if self.logfile: with open(self.logfile,", "new_col_list = [] for col in X.columns: var_type = X[col].dtype.name", "for col in X.columns: self.types[col] = X[col].dtype.name if self.types[col] in", "for column {col}: Received {received}'.format( col=col, received=new_values) ) elif self.types[col]", "var_type = X[col].dtype.name if self.types[col] in ('object', 'bool', 'category'): if", "X[col].dtype.name return self def transform(self, X, **transformparams): X = validate_dataframe(X)", "= X[col].max() if minX < self.minmax[col][0]: self.print_message( 'Low Value warning", "transform(self, X, **transformparams): X = validate_dataframe(X) new_col_list = [] for", "minX = X[col].min() maxX = X[col].max() if minX < self.minmax[col][0]:", "self.types[col] in ('object', 'bool', 'category'): unique_values = X[col].unique() if len(unique_values)", "self.minmax[col] = (X[col].min(), X[col].max()) return self def transform(self, X, **transformparams):", "if self.types[col] in ('object', 'bool', 'category'): unique_values = X[col].unique() if", "in ('object', 'bool', 'category'): if self.unique_vals[col] is not None: not_in_list", "validate_dataframe(X) self.types = {} self.unique_vals = {} self.minmax = {}", "**fitparams): X = validate_dataframe(X) self.types = {} self.unique_vals = {}", "col in X.columns: self.types[col] = X[col].dtype.name if self.types[col] in ('object',", "lowscore=minX) ) if maxX > self.minmax[col][1]: self.print_message( 'High Value warning", "y=None, **fitparams): X = validate_dataframe(X) self.types = {} for col", "{lowscore}'.format( col=col, lowtrain=self.minmax[col][0], lowscore=minX) ) if maxX > self.minmax[col][1]: self.print_message(", "= to_screen def fit(self, X, y=None, **fitparams): X = validate_dataframe(X)", "'float64', 'datetime64', 'timedelta'): minX = X[col].min() maxX = X[col].max() if", "BaseEstimator, TransformerMixin, clone from sklearn_pandas.util import validate_dataframe class MonitorMixin(object): def", "import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin, clone", "self.minmax = {} for col in X.columns: self.types[col] = X[col].dtype.name", "warning for column {col}: Largest Training value {hightrain}, Largest Scoring", "import BaseEstimator, TransformerMixin, clone from sklearn_pandas.util import validate_dataframe class MonitorMixin(object):", "X = validate_dataframe(X) self.types = {} self.unique_vals = {} self.minmax", "X[col].max()) return self def transform(self, X, **transformparams): X = validate_dataframe(X)", "if sum(not_in_list) > 0: new_values = str(X[col][not_in_list].unique().tolist()) self.print_message( 'New Categories", "numpy as np import pandas as pd from sklearn.base import", "def __init__(self, logfile=None, to_screen=True): self.logfile = logfile self.to_screen = to_screen", "specified for column {col}: Received {received}'.format( col=col, received=new_values) ) elif", "{col}: Received {received}'.format( col=col, received=new_values) ) elif self.types[col] in ('int64',", "X = validate_dataframe(X) self.types = {} for col in X.columns:", "logfile self.to_screen = to_screen self.max_nunique = max_nunique def fit(self, X,", "Lowest Training value {lowtrain}, Lowest Scoring value {lowscore}'.format( col=col, lowtrain=self.minmax[col][0],", "self.minmax[col][0]: self.print_message( 'Low Value warning for column {col}: Lowest Training", "'High Value warning for column {col}: Largest Training value {hightrain},", "expected=self.types[col], received=var_type) ) return X class ValidateRange(BaseEstimator, TransformerMixin, MonitorMixin): def", "TransformerMixin, clone from sklearn_pandas.util import validate_dataframe class MonitorMixin(object): def print_message(self,", "for col in X.columns: var_type = X[col].dtype.name if var_type !=", "= None elif self.types[col] in ('int64', 'float64', 'datetime64', 'timedelta'): self.minmax[col]", "X[col].dtype.name if self.types[col] in ('object', 'bool', 'category'): if self.unique_vals[col] is", "X, y=None, **fitparams): X = validate_dataframe(X) self.types = {} self.unique_vals", "value {lowtrain}, Lowest Scoring value {lowscore}'.format( col=col, lowtrain=self.minmax[col][0], lowscore=minX) )", "\"a\") as fout: fout.write(message) else: print(message) class ValidateTypes(BaseEstimator, TransformerMixin, MonitorMixin):", "X.columns: var_type = X[col].dtype.name if var_type != self.types[col]: self.print_message( 'Data", "= X[col].dtype.name if self.types[col] in ('object', 'bool', 'category'): if self.unique_vals[col]", "self.unique_vals[col] is not None: not_in_list = ~X[col].isin(self.unique_vals[col]) if sum(not_in_list) >", "ValidateTypes(BaseEstimator, TransformerMixin, MonitorMixin): def __init__(self, logfile=None, to_screen=True): self.logfile = logfile", "value {lowscore}'.format( col=col, lowtrain=self.minmax[col][0], lowscore=minX) ) if maxX > self.minmax[col][1]:", "self.unique_vals[col] = unique_values else: self.unique_vals[col] = None elif self.types[col] in", "if self.unique_vals[col] is not None: not_in_list = ~X[col].isin(self.unique_vals[col]) if sum(not_in_list)", "y=None, **fitparams): X = validate_dataframe(X) self.types = {} self.unique_vals =", "col=col, expected=self.types[col], received=var_type) ) return X class ValidateRange(BaseEstimator, TransformerMixin, MonitorMixin):", "MonitorMixin): def __init__(self, logfile=None, to_screen=True, max_nunique=20): self.logfile = logfile self.to_screen", "= validate_dataframe(X) self.types = {} self.unique_vals = {} self.minmax =", "column {col}: Received {received}'.format( col=col, received=new_values) ) elif self.types[col] in", "np import pandas as pd from sklearn.base import BaseEstimator, TransformerMixin,", "Value warning for column {col}: Lowest Training value {lowtrain}, Lowest", "def transform(self, X, **transformparams): X = validate_dataframe(X) new_col_list = []", "= str(X[col][not_in_list].unique().tolist()) self.print_message( 'New Categories specified for column {col}: Received", "X[col].max() if minX < self.minmax[col][0]: self.print_message( 'Low Value warning for", "import numpy as np import pandas as pd from sklearn.base", "[] for col in X.columns: var_type = X[col].dtype.name if self.types[col]", "new_values = str(X[col][not_in_list].unique().tolist()) self.print_message( 'New Categories specified for column {col}:", "= X[col].unique() if len(unique_values) <= self.max_nunique: self.unique_vals[col] = unique_values else:", "logfile=None, to_screen=True): self.logfile = logfile self.to_screen = to_screen def fit(self,", "> 0: new_values = str(X[col][not_in_list].unique().tolist()) self.print_message( 'New Categories specified for", "sklearn_pandas.util import validate_dataframe class MonitorMixin(object): def print_message(self, message): if self.logfile:", "'bool', 'category'): unique_values = X[col].unique() if len(unique_values) <= self.max_nunique: self.unique_vals[col]", "in ('int64', 'float64', 'datetime64', 'timedelta'): minX = X[col].min() maxX =", "self.logfile = logfile self.to_screen = to_screen self.max_nunique = max_nunique def", "= X[col].min() maxX = X[col].max() if minX < self.minmax[col][0]: self.print_message(", "minX < self.minmax[col][0]: self.print_message( 'Low Value warning for column {col}:", "MonitorMixin): def __init__(self, logfile=None, to_screen=True): self.logfile = logfile self.to_screen =", "col=col, received=new_values) ) elif self.types[col] in ('int64', 'float64', 'datetime64', 'timedelta'):", "'Data Type Mismatch for column {col}: Expected {expected} Received {received}'.format(", "'Low Value warning for column {col}: Lowest Training value {lowtrain},", "print(message) class ValidateTypes(BaseEstimator, TransformerMixin, MonitorMixin): def __init__(self, logfile=None, to_screen=True): self.logfile", "self def transform(self, X, **transformparams): X = validate_dataframe(X) new_col_list =", "MonitorMixin(object): def print_message(self, message): if self.logfile: with open(self.logfile, \"a\") as", "Mismatch for column {col}: Expected {expected} Received {received}'.format( col=col, expected=self.types[col],", "'float64', 'datetime64', 'timedelta'): self.minmax[col] = (X[col].min(), X[col].max()) return self def", "maxX = X[col].max() if minX < self.minmax[col][0]: self.print_message( 'Low Value", "TransformerMixin, MonitorMixin): def __init__(self, logfile=None, to_screen=True, max_nunique=20): self.logfile = logfile", "with open(self.logfile, \"a\") as fout: fout.write(message) else: print(message) class ValidateTypes(BaseEstimator,", "self.types[col] = X[col].dtype.name return self def transform(self, X, **transformparams): X", "= to_screen self.max_nunique = max_nunique def fit(self, X, y=None, **fitparams):", "('int64', 'float64', 'datetime64', 'timedelta'): self.minmax[col] = (X[col].min(), X[col].max()) return self", "'category'): unique_values = X[col].unique() if len(unique_values) <= self.max_nunique: self.unique_vals[col] =", "self.print_message( 'New Categories specified for column {col}: Received {received}'.format( col=col,", "column {col}: Lowest Training value {lowtrain}, Lowest Scoring value {lowscore}'.format(", "column {col}: Largest Training value {hightrain}, Largest Scoring value {highscore}'.format(", "X.columns: self.types[col] = X[col].dtype.name return self def transform(self, X, **transformparams):", "TransformerMixin, MonitorMixin): def __init__(self, logfile=None, to_screen=True): self.logfile = logfile self.to_screen", "logfile=None, to_screen=True, max_nunique=20): self.logfile = logfile self.to_screen = to_screen self.max_nunique", "= X[col].dtype.name if self.types[col] in ('object', 'bool', 'category'): unique_values =", "= unique_values else: self.unique_vals[col] = None elif self.types[col] in ('int64',", "else: self.unique_vals[col] = None elif self.types[col] in ('int64', 'float64', 'datetime64',", "self.print_message( 'Low Value warning for column {col}: Lowest Training value", "else: print(message) class ValidateTypes(BaseEstimator, TransformerMixin, MonitorMixin): def __init__(self, logfile=None, to_screen=True):", "= X[col].dtype.name if var_type != self.types[col]: self.print_message( 'Data Type Mismatch", "def print_message(self, message): if self.logfile: with open(self.logfile, \"a\") as fout:", "X[col].dtype.name if var_type != self.types[col]: self.print_message( 'Data Type Mismatch for", "Received {received}'.format( col=col, received=new_values) ) elif self.types[col] in ('int64', 'float64',", "{received}'.format( col=col, received=new_values) ) elif self.types[col] in ('int64', 'float64', 'datetime64',", "{col}: Expected {expected} Received {received}'.format( col=col, expected=self.types[col], received=var_type) ) return", "< self.minmax[col][0]: self.print_message( 'Low Value warning for column {col}: Lowest", "Scoring value {lowscore}'.format( col=col, lowtrain=self.minmax[col][0], lowscore=minX) ) if maxX >", "Expected {expected} Received {received}'.format( col=col, expected=self.types[col], received=var_type) ) return X", "to_screen self.max_nunique = max_nunique def fit(self, X, y=None, **fitparams): X", "self.unique_vals = {} self.minmax = {} for col in X.columns:", "sum(not_in_list) > 0: new_values = str(X[col][not_in_list].unique().tolist()) self.print_message( 'New Categories specified", "from sklearn.base import BaseEstimator, TransformerMixin, clone from sklearn_pandas.util import validate_dataframe", "self.print_message( 'Data Type Mismatch for column {col}: Expected {expected} Received", "self.to_screen = to_screen self.max_nunique = max_nunique def fit(self, X, y=None,", "self.types[col] = X[col].dtype.name if self.types[col] in ('object', 'bool', 'category'): unique_values", "> self.minmax[col][1]: self.print_message( 'High Value warning for column {col}: Largest", "from sklearn_pandas.util import validate_dataframe class MonitorMixin(object): def print_message(self, message): if", "elif self.types[col] in ('int64', 'float64', 'datetime64', 'timedelta'): minX = X[col].min()", "if self.logfile: with open(self.logfile, \"a\") as fout: fout.write(message) else: print(message)", "'bool', 'category'): if self.unique_vals[col] is not None: not_in_list = ~X[col].isin(self.unique_vals[col])", "class ValidateTypes(BaseEstimator, TransformerMixin, MonitorMixin): def __init__(self, logfile=None, to_screen=True): self.logfile =", "Received {received}'.format( col=col, expected=self.types[col], received=var_type) ) return X class ValidateRange(BaseEstimator,", "'category'): if self.unique_vals[col] is not None: not_in_list = ~X[col].isin(self.unique_vals[col]) if", "in X.columns: self.types[col] = X[col].dtype.name return self def transform(self, X,", "Type Mismatch for column {col}: Expected {expected} Received {received}'.format( col=col,", "fit(self, X, y=None, **fitparams): X = validate_dataframe(X) self.types = {}", "as np import pandas as pd from sklearn.base import BaseEstimator,", "**transformparams): X = validate_dataframe(X) new_col_list = [] for col in", "if var_type != self.types[col]: self.print_message( 'Data Type Mismatch for column", "Lowest Scoring value {lowscore}'.format( col=col, lowtrain=self.minmax[col][0], lowscore=minX) ) if maxX", "validate_dataframe(X) self.types = {} for col in X.columns: self.types[col] =", "unique_values = X[col].unique() if len(unique_values) <= self.max_nunique: self.unique_vals[col] = unique_values", "self.logfile: with open(self.logfile, \"a\") as fout: fout.write(message) else: print(message) class", "as fout: fout.write(message) else: print(message) class ValidateTypes(BaseEstimator, TransformerMixin, MonitorMixin): def", "('object', 'bool', 'category'): unique_values = X[col].unique() if len(unique_values) <= self.max_nunique:", "validate_dataframe(X) new_col_list = [] for col in X.columns: var_type =", "if len(unique_values) <= self.max_nunique: self.unique_vals[col] = unique_values else: self.unique_vals[col] =", "in X.columns: var_type = X[col].dtype.name if var_type != self.types[col]: self.print_message(", "X[col].min() maxX = X[col].max() if minX < self.minmax[col][0]: self.print_message( 'Low", "0: new_values = str(X[col][not_in_list].unique().tolist()) self.print_message( 'New Categories specified for column", "Value warning for column {col}: Largest Training value {hightrain}, Largest", "Largest Training value {hightrain}, Largest Scoring value {highscore}'.format( col=col, hightrain=self.minmax[col][1],", "for col in X.columns: self.types[col] = X[col].dtype.name return self def", "Training value {lowtrain}, Lowest Scoring value {lowscore}'.format( col=col, lowtrain=self.minmax[col][0], lowscore=minX)", "X = validate_dataframe(X) new_col_list = [] for col in X.columns:", ") return X class ValidateRange(BaseEstimator, TransformerMixin, MonitorMixin): def __init__(self, logfile=None,", "X[col].dtype.name if self.types[col] in ('object', 'bool', 'category'): unique_values = X[col].unique()", "Largest Scoring value {highscore}'.format( col=col, hightrain=self.minmax[col][1], highscore=maxX) ) return X", "= logfile self.to_screen = to_screen self.max_nunique = max_nunique def fit(self,", "return X class ValidateRange(BaseEstimator, TransformerMixin, MonitorMixin): def __init__(self, logfile=None, to_screen=True,", "col in X.columns: self.types[col] = X[col].dtype.name return self def transform(self,", "for col in X.columns: var_type = X[col].dtype.name if self.types[col] in", "class ValidateRange(BaseEstimator, TransformerMixin, MonitorMixin): def __init__(self, logfile=None, to_screen=True, max_nunique=20): self.logfile", "{expected} Received {received}'.format( col=col, expected=self.types[col], received=var_type) ) return X class", "to_screen=True): self.logfile = logfile self.to_screen = to_screen def fit(self, X,", "max_nunique def fit(self, X, y=None, **fitparams): X = validate_dataframe(X) self.types", "class MonitorMixin(object): def print_message(self, message): if self.logfile: with open(self.logfile, \"a\")", "clone from sklearn_pandas.util import validate_dataframe class MonitorMixin(object): def print_message(self, message):", "self.types[col]: self.print_message( 'Data Type Mismatch for column {col}: Expected {expected}", "elif self.types[col] in ('int64', 'float64', 'datetime64', 'timedelta'): self.minmax[col] = (X[col].min(),", "self.print_message( 'High Value warning for column {col}: Largest Training value", "self.max_nunique = max_nunique def fit(self, X, y=None, **fitparams): X =", "warning for column {col}: Lowest Training value {lowtrain}, Lowest Scoring", "if self.types[col] in ('object', 'bool', 'category'): if self.unique_vals[col] is not", "as pd from sklearn.base import BaseEstimator, TransformerMixin, clone from sklearn_pandas.util", "= logfile self.to_screen = to_screen def fit(self, X, y=None, **fitparams):", "print_message(self, message): if self.logfile: with open(self.logfile, \"a\") as fout: fout.write(message)", "= validate_dataframe(X) new_col_list = [] for col in X.columns: var_type", "col in X.columns: var_type = X[col].dtype.name if var_type != self.types[col]:", "def __init__(self, logfile=None, to_screen=True, max_nunique=20): self.logfile = logfile self.to_screen =", "fout: fout.write(message) else: print(message) class ValidateTypes(BaseEstimator, TransformerMixin, MonitorMixin): def __init__(self,", "in ('int64', 'float64', 'datetime64', 'timedelta'): self.minmax[col] = (X[col].min(), X[col].max()) return", "to_screen=True, max_nunique=20): self.logfile = logfile self.to_screen = to_screen self.max_nunique =", "logfile self.to_screen = to_screen def fit(self, X, y=None, **fitparams): X", "{received}'.format( col=col, expected=self.types[col], received=var_type) ) return X class ValidateRange(BaseEstimator, TransformerMixin,", "'datetime64', 'timedelta'): self.minmax[col] = (X[col].min(), X[col].max()) return self def transform(self,", ") if maxX > self.minmax[col][1]: self.print_message( 'High Value warning for", "'timedelta'): minX = X[col].min() maxX = X[col].max() if minX <", "ValidateRange(BaseEstimator, TransformerMixin, MonitorMixin): def __init__(self, logfile=None, to_screen=True, max_nunique=20): self.logfile =", ") elif self.types[col] in ('int64', 'float64', 'datetime64', 'timedelta'): minX =", "('object', 'bool', 'category'): if self.unique_vals[col] is not None: not_in_list =", "not_in_list = ~X[col].isin(self.unique_vals[col]) if sum(not_in_list) > 0: new_values = str(X[col][not_in_list].unique().tolist())", "lowtrain=self.minmax[col][0], lowscore=minX) ) if maxX > self.minmax[col][1]: self.print_message( 'High Value", "column {col}: Expected {expected} Received {received}'.format( col=col, expected=self.types[col], received=var_type) )", "<= self.max_nunique: self.unique_vals[col] = unique_values else: self.unique_vals[col] = None elif", "message): if self.logfile: with open(self.logfile, \"a\") as fout: fout.write(message) else:", "self.types[col] in ('object', 'bool', 'category'): if self.unique_vals[col] is not None:", "__init__(self, logfile=None, to_screen=True, max_nunique=20): self.logfile = logfile self.to_screen = to_screen", "str(X[col][not_in_list].unique().tolist()) self.print_message( 'New Categories specified for column {col}: Received {received}'.format(", "in ('object', 'bool', 'category'): unique_values = X[col].unique() if len(unique_values) <=", "Categories specified for column {col}: Received {received}'.format( col=col, received=new_values) )", "col in X.columns: var_type = X[col].dtype.name if self.types[col] in ('object',", "len(unique_values) <= self.max_nunique: self.unique_vals[col] = unique_values else: self.unique_vals[col] = None", "{hightrain}, Largest Scoring value {highscore}'.format( col=col, hightrain=self.minmax[col][1], highscore=maxX) ) return", "= validate_dataframe(X) self.types = {} for col in X.columns: self.types[col]", "self.unique_vals[col] = None elif self.types[col] in ('int64', 'float64', 'datetime64', 'timedelta'):", "{} for col in X.columns: self.types[col] = X[col].dtype.name if self.types[col]", "sklearn.base import BaseEstimator, TransformerMixin, clone from sklearn_pandas.util import validate_dataframe class", "{} self.unique_vals = {} self.minmax = {} for col in", "= [] for col in X.columns: var_type = X[col].dtype.name if", "fout.write(message) else: print(message) class ValidateTypes(BaseEstimator, TransformerMixin, MonitorMixin): def __init__(self, logfile=None,", "self.types = {} for col in X.columns: self.types[col] = X[col].dtype.name", "pandas as pd from sklearn.base import BaseEstimator, TransformerMixin, clone from", "= X[col].dtype.name return self def transform(self, X, **transformparams): X =", "__init__(self, logfile=None, to_screen=True): self.logfile = logfile self.to_screen = to_screen def", "X, **transformparams): X = validate_dataframe(X) new_col_list = [] for col", "X class ValidateRange(BaseEstimator, TransformerMixin, MonitorMixin): def __init__(self, logfile=None, to_screen=True, max_nunique=20):", "= max_nunique def fit(self, X, y=None, **fitparams): X = validate_dataframe(X)", "X.columns: self.types[col] = X[col].dtype.name if self.types[col] in ('object', 'bool', 'category'):", "X[col].unique() if len(unique_values) <= self.max_nunique: self.unique_vals[col] = unique_values else: self.unique_vals[col]", "'timedelta'): self.minmax[col] = (X[col].min(), X[col].max()) return self def transform(self, X,", "self.minmax[col][1]: self.print_message( 'High Value warning for column {col}: Largest Training", "{col}: Lowest Training value {lowtrain}, Lowest Scoring value {lowscore}'.format( col=col,", "Training value {hightrain}, Largest Scoring value {highscore}'.format( col=col, hightrain=self.minmax[col][1], highscore=maxX)", "~X[col].isin(self.unique_vals[col]) if sum(not_in_list) > 0: new_values = str(X[col][not_in_list].unique().tolist()) self.print_message( 'New", "= ~X[col].isin(self.unique_vals[col]) if sum(not_in_list) > 0: new_values = str(X[col][not_in_list].unique().tolist()) self.print_message(", "received=var_type) ) return X class ValidateRange(BaseEstimator, TransformerMixin, MonitorMixin): def __init__(self,", "= {} for col in X.columns: self.types[col] = X[col].dtype.name return", "(X[col].min(), X[col].max()) return self def transform(self, X, **transformparams): X =", "is not None: not_in_list = ~X[col].isin(self.unique_vals[col]) if sum(not_in_list) > 0:", "None elif self.types[col] in ('int64', 'float64', 'datetime64', 'timedelta'): self.minmax[col] =", "maxX > self.minmax[col][1]: self.print_message( 'High Value warning for column {col}:", "open(self.logfile, \"a\") as fout: fout.write(message) else: print(message) class ValidateTypes(BaseEstimator, TransformerMixin,", "!= self.types[col]: self.print_message( 'Data Type Mismatch for column {col}: Expected", "'datetime64', 'timedelta'): minX = X[col].min() maxX = X[col].max() if minX", "received=new_values) ) elif self.types[col] in ('int64', 'float64', 'datetime64', 'timedelta'): minX", "[] for col in X.columns: var_type = X[col].dtype.name if var_type", "if minX < self.minmax[col][0]: self.print_message( 'Low Value warning for column", "None: not_in_list = ~X[col].isin(self.unique_vals[col]) if sum(not_in_list) > 0: new_values =", "value {hightrain}, Largest Scoring value {highscore}'.format( col=col, hightrain=self.minmax[col][1], highscore=maxX) )", "def fit(self, X, y=None, **fitparams): X = validate_dataframe(X) self.types =", "unique_values else: self.unique_vals[col] = None elif self.types[col] in ('int64', 'float64',", "X.columns: var_type = X[col].dtype.name if self.types[col] in ('object', 'bool', 'category'):", "return self def transform(self, X, **transformparams): X = validate_dataframe(X) new_col_list", "pd from sklearn.base import BaseEstimator, TransformerMixin, clone from sklearn_pandas.util import" ]
[ "== EXPECTED_RESULT def test_fetch_incidents_limit_exceed(mocker): \"\"\" Given - a dict of", "- Get new incidents is called during the fetch process.", "on invalid input such as days or no units relevant", "({'event_sources': \"\", 'abuse_disposition': \"\"}, [MOCK_INCIDENT]), ({'event_sources': \"No such source\", 'abuse_disposition':", "{ \"id\": 3, \"category\": \"malware\", \"severity\": \"Info\", \"source\": \"Proofpoint TAP\",", "\"Unknown\" } ], \"events\": [ { \"id\": 3, \"category\": \"malware\",", "'created_before': '2021-03-31T11:21:24Z', } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_incidnets = get_new_incidents(request_params, last_incident_fetched) assert", "time_delta = get_time_delta('1 minute') assert str(time_delta) == '0:01:00' time_delta =", "fetch delta.' in str( ex) try: get_time_delta('2 days') except Exception", "\"No such source, Proofpoint TAP\", 'abuse_disposition': \"No such value, Unknown\"},", "test_prepare_ingest_alert_request_body(): prepared_body = prepare_ingest_alert_request_body(INGEST_ALERT_ARGS) assert prepared_body == EXPECTED_RESULT def test_fetch_incidents_limit_exceed(mocker):", "\"value\": \"Spam\" }, { \"name\": \"Severity\", \"value\": \"Critical\" }, {", "\"Abuse Disposition\", \"value\": \"Unknown\" } ], \"events\": [ { \"id\":", "'abuse_disposition': \"No such value\"}, [])] @pytest.mark.parametrize('demisto_params, expected_answer', DEMISTO_PARAMS) def test_filter_incidents(mocker,", "that the number or incidents that is returned is equal", "params for the fetch e.g. fetch_delta, fetch_limit, created_after, state and", "\"value\"}, \"post_url_id\": \"value\", \"json_version\": \"value\", \"summary\": \"value\" } def test_prepare_ingest_alert_request_body():", "'2021-03-30T10:21:24Z', 'created_before': '2021-03-31T11:21:24Z', } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_incidnets = get_new_incidents(request_params, last_incident_fetched)", "= { 'fetch_delta': '6 hours', 'fetch_limit': ' 5', 'created_after': '2021-03-30T11:44:24Z',", "\"value\"}, \"detector\": {\"key\": \"value\"}, \"email\": {\"key\": \"value\"}, \"forensics_hosts\": {\"key\": \"value\"},", "are raised. - validate that on valid inputs the return", "state and last_fetched_id. - response of the api When -", "from ProofpointThreatResponse import create_incident_field_context, get_emails_context, pass_sources_list_filter, \\ pass_abuse_disposition_filter, filter_incidents, prepare_ingest_alert_request_body,", "the same is brought in the next fetch loop. (", "sure to insert both the number and the unit of", "Then - validate that the number or incidents that is", "validate that on invalid input such as days or no", "source\", 'abuse_disposition': \"No such value\"}, [])] @pytest.mark.parametrize('demisto_params, expected_answer', DEMISTO_PARAMS) def", "EMAILS_CONTEXT_INPUT = [ (MOCK_INCIDENT['events'][0], EMAIL_RESULT) ] @pytest.mark.parametrize('event, answer', EMAILS_CONTEXT_INPUT) def", "} mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_incidnets = get_new_incidents(request_params, last_incident_fetched) assert len(new_incidnets) ==", "{ 'sender': \"test\", 'recipient': \"test\", 'subject': \"test\", 'message_id': \"test\", 'message_delivery_time':", "}, { \"name\": \"Classification\", \"value\": \"Spam\" }, { \"name\": \"Severity\",", "limit. - validate that the next incident whose time is", "\"body\": \"test\", 'bodyType': \"test\", 'headers': \"test\", 'urls': \"test\" } ],", "= get_emails_context(event) assert emails_context == answer SOURCE_LIST_INPUT = [ ([\"Proofpoint", "- validate that on valid inputs the return value is", "the fetch delta.' in str( ex) try: get_time_delta('2 days') except", "}, { \"name\": \"Severity\", \"value\": \"Critical\" }, { \"name\": \"Abuse", "\"state\": \"Open\", \"created_at\": \"2018-05-26T21:07:17Z\", \"event_count\": 3, \"event_sources\": [ \"Proofpoint TAP\"", "{ 'state': 'closed', 'created_after': '2021-03-30T10:21:24Z', 'created_before': '2021-03-31T11:21:24Z', } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE)", "\"value\": \"Email\" }, { \"name\": \"Classification\", \"value\": \"Spam\" }, {", "\"Proofpoint TAP\" ], \"users\": [ \"\" ], \"assignee\": \"Unassigned\", \"team\":", "[ { 'sender': \"test\", 'recipient': \"test\", 'subject': \"test\", 'message_id': \"test\",", "[({'event_sources': \"No such source, Proofpoint TAP\", 'abuse_disposition': \"No such value,", "function which is valid and invalid When - run the", "' 5', 'created_after': '2021-03-30T11:44:24Z', 'state': 'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) incidents_list", "get_new_incidents, get_time_delta MOCK_INCIDENT = { \"id\": 1, \"type\": \"Malware\", \"summary\":", "3057] expected_ids_to_fetch_second = [3058, 3059, 3060] params = { 'fetch_delta':", "\"forensics\": [ \"\", ] }, \"incident_field_values\": [ { \"name\": \"Attack", "- input to the get_time_delta function which is valid and", "test message\", \"score\": 4200, \"state\": \"Open\", \"created_at\": \"2018-05-26T21:07:17Z\", \"event_count\": 3,", "value, Unknown\"}, [MOCK_INCIDENT]), ({'event_sources': \"\", 'abuse_disposition': \"\"}, [MOCK_INCIDENT]), ({'event_sources': \"No", "== expected_answer DEMISTO_PARAMS = [({'event_sources': \"No such source, Proofpoint TAP\",", "\"Email\", \"Classification\": \"Spam\", \"Severity\": \"Critical\", \"Abuse_Disposition\": \"Unknown\" } INCIDENT_FIELD_INPUT =", "\"\" ], \"assignee\": \"Unassigned\", \"team\": \"Unassigned\", \"hosts\": { \"attacker\": [", "the last fetched incident has exactly the same time of", "new_fetched_second = get_incidents_batch_by_time_request(params) for incident in new_fetched_second: assert incident.get('id') in", "is invalid. Possible values are \"minutes\" or \"hours' in str(ex)", "- a dict of params given to the function which", "\"description\": \"\", \"attackDirection\": \"inbound\", \"received\": \"2018-05-26T21:07:17Z\", \"malwareName\": \"\", \"emails\": [", "- validate that all of the returned incident have a", "{ \"id\": \"UTC\" } }, \"millis\": 1544640072000, }, \"abuseCopy\": \"false\",", "gathered originally from demisto.params() The dict includes the relevant params", "test_fetch_incidents_with_same_created_time(mocker): \"\"\" Given - a dict of params given to", "([\"No such value\"], False), ([\"No such value\", \"Unknown\"], True) ]", "\"summary\": \"Unsolicited Bulk Email\", \"description\": \"EvilScheme test message\", \"score\": 4200,", "the number of expected incidents return. - validate that all", "= get_fetch_data() @pytest.mark.parametrize('incident, answer', INCIDENT_FIELD_INPUT) def test_get_incident_field_context(incident, answer): incident_field_values =", "}, \"recipient\": { \"email\": \"test\" }, \"subject\": \"test\", \"messageId\": \"test\",", "expected_answer INGEST_ALERT_ARGS = { \"attacker\": \"{\\\"attacker\\\":{\\\"key\\\":\\\"value\\\"}}\", \"cnc_host\": \"{\\\"cnc_host\\\":{\\\"key\\\":\\\"value\\\"}}\", \"detector\": \"{\\\"detector\\\":{\\\"key\\\":\\\"value\\\"}}\",", "state. - response of the api When - a single", "\"event_sources\": [ \"Proofpoint TAP\" ], \"users\": [ \"\" ], \"assignee\":", "value\"], False), ([\"No such value\", \"Unknown\"], True) ] @pytest.mark.parametrize('abuse_dispotion_values, expected_answer',", "in the next fetch loop. ( e.g. 3057 and 3058)", "incident.get('id') in expected_ids_to_fetch_first params = { 'fetch_delta': '2 hour', 'fetch_limit':", "result == expected_answer DEMISTO_PARAMS = [({'event_sources': \"No such source, Proofpoint", "exactly the same is brought in the next fetch loop.", "Exception as ex: assert 'The unit of fetch_delta is invalid.", "= [({'event_sources': \"No such source, Proofpoint TAP\", 'abuse_disposition': \"No such", "\"source\": \"Proofpoint TAP\", \"threatname\": \"\", \"state\": \"Linked\", \"description\": \"\", \"attackDirection\":", "originally from demisto.params() The dict includes the relevant params for", "for incident in new_fetched_first: assert incident.get('id') in expected_ids_to_fetch_first params =", "sources_list) assert result == expected_answer ABUSE_DISPOSITION_INPUT = [ ([\"Unknown\"], True),", "], \"forensics\": [ \"\", ] }, \"incident_field_values\": [ { \"name\":", "inputs the return value is as expected. \"\"\" time_delta =", "], \"events\": [ { \"id\": 3, \"category\": \"malware\", \"severity\": \"Info\",", "last_incident_fetched) assert len(new_incidnets) == 14 for incident in new_incidnets: assert", "{ \"attacker\": [ \"\" ], \"forensics\": [ \"\", ] },", "def test_fetch_incidents_with_same_created_time(mocker): \"\"\" Given - a dict of params given", "is returned is equal to the limit when the api", "dict of params given to the function which is gathered", "'created_after': '2021-03-30T11:44:24Z', 'state': 'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) incidents_list = get_incidents_batch_by_time_request(params)", "json.loads(f.read()) return file.get('result') FETCH_RESPONSE = get_fetch_data() @pytest.mark.parametrize('incident, answer', INCIDENT_FIELD_INPUT) def", "TAP\"], True), ([], True), ([\"No such source\"], False), ([\"No such", "assert filtered_incidents == expected_answer INGEST_ALERT_ARGS = { \"attacker\": \"{\\\"attacker\\\":{\\\"key\\\":\\\"value\\\"}}\", \"cnc_host\":", "incident.get('id') in expected_ids_to_fetch_second def test_get_new_incidents(mocker): \"\"\" Given - a dict", "= { \"id\": 1, \"type\": \"Malware\", \"summary\": \"Unsolicited Bulk Email\",", "prepare_ingest_alert_request_body(INGEST_ALERT_ARGS) assert prepared_body == EXPECTED_RESULT def test_fetch_incidents_limit_exceed(mocker): \"\"\" Given -", "assert result == expected_answer ABUSE_DISPOSITION_INPUT = [ ([\"Unknown\"], True), ([],", "for the fetch e.g. fetch_delta, fetch_limit, created_after, state and last_fetched_id.", "the api. - The last fetched incident id. When -", "appear as to the fetch limit. - validate that the", "'created_after': '2021-03-30T11:21:24Z', 'last_fetched_id': '3057', 'state': 'closed' } new_fetched_second = get_incidents_batch_by_time_request(params)", "\"description\": \"EvilScheme test message\", \"score\": 4200, \"state\": \"Open\", \"created_at\": \"2018-05-26T21:07:17Z\",", "3, \"event_sources\": [ \"Proofpoint TAP\" ], \"users\": [ \"\" ],", "result = pass_abuse_disposition_filter(MOCK_INCIDENT, abuse_dispotion_values) assert result == expected_answer DEMISTO_PARAMS =", "get_time_delta('2 hours') assert str(time_delta) == '2:00:00' try: get_time_delta('2') except Exception", "from demisto.params() The dict includes the relevant params for the", "\"\"\" params = { 'fetch_delta': '6 hours', 'fetch_limit': ' 5',", "as to the fetch limit. - validate that the next", "= get_incidents_batch_by_time_request(params) assert len(incidents_list) == 5 def test_fetch_incidents_with_same_created_time(mocker): \"\"\" Given", "- response of the api When - when a fetch", "api When - a single iteration of the fetch is", "incident. \"\"\" last_incident_fetched = 3057 request_params = { 'state': 'closed',", "= get_time_delta('2 hours') assert str(time_delta) == '2:00:00' try: get_time_delta('2') except", "filter_incidents, prepare_ingest_alert_request_body, \\ get_incidents_batch_by_time_request, get_new_incidents, get_time_delta MOCK_INCIDENT = { \"id\":", "and 3058) \"\"\" expected_ids_to_fetch_first = [3055, 3056, 3057] expected_ids_to_fetch_second =", "EXPECTED_RESULT def test_fetch_incidents_limit_exceed(mocker): \"\"\" Given - a dict of params", "have a bigger id then the last fetched incident. \"\"\"", "fetch e.g. fetch_delta, fetch_limit, created_after, state and last_fetched_id. - response", "request_params to the api. - The last fetched incident id.", "Proofpoint TAP\", 'abuse_disposition': \"No such value, Unknown\"}, [MOCK_INCIDENT]), ({'event_sources': \"\",", "return_value=FETCH_RESPONSE) new_incidnets = get_new_incidents(request_params, last_incident_fetched) assert len(new_incidnets) == 14 for", "\"UTC\" } }, \"millis\": 1544640072000, }, \"abuseCopy\": \"false\", \"body\": \"test\",", "expected incidents return. - validate that all of the returned", "that the number of expected incidents return. - validate that", "answer', EMAILS_CONTEXT_INPUT) def test_get_emails_context(event, answer): emails_context = get_emails_context(event) assert emails_context", "during the fetch process. Then - validate that the number", "brought in the next fetch loop. ( e.g. 3057 and", "14 for incident in new_incidnets: assert incident.get('id') > 3057 def", "\"attackDirection\": \"inbound\", \"received\": \"2018-05-26T21:07:17Z\", \"malwareName\": \"\", \"emails\": [ { \"sender\":", "such value, Unknown\"}, [MOCK_INCIDENT]), ({'event_sources': \"\", 'abuse_disposition': \"\"}, [MOCK_INCIDENT]), ({'event_sources':", "{\"key\": \"value\"}, \"custom_fields\": {\"key\": \"value\"}, \"post_url_id\": \"value\", \"json_version\": \"value\", \"summary\":", "\"threat_info\": {\"key\": \"value\"}, \"custom_fields\": {\"key\": \"value\"}, \"post_url_id\": \"value\", \"json_version\": \"value\",", "\"zone\": { \"id\": \"UTC\" } }, \"millis\": 1544640072000, }, \"abuseCopy\":", "\"value\" } EXPECTED_RESULT = { \"attacker\": {\"key\": \"value\"}, \"cnc_host\": {\"key\":", "prepared_body = prepare_ingest_alert_request_body(INGEST_ALERT_ARGS) assert prepared_body == EXPECTED_RESULT def test_fetch_incidents_limit_exceed(mocker): \"\"\"", "\"Attack_Vector\": \"Email\", \"Classification\": \"Spam\", \"Severity\": \"Critical\", \"Abuse_Disposition\": \"Unknown\" } INCIDENT_FIELD_INPUT", "\"score\": 4200, \"state\": \"Open\", \"created_at\": \"2018-05-26T21:07:17Z\", \"event_count\": 3, \"event_sources\": [", "that only one of the incidents appear as to the", "last_incident_fetched = 3057 request_params = { 'state': 'closed', 'created_after': '2021-03-30T10:21:24Z',", "value is as expected. \"\"\" time_delta = get_time_delta('1 minute') assert", "\"{\\\"attacker\\\":{\\\"key\\\":\\\"value\\\"}}\", \"cnc_host\": \"{\\\"cnc_host\\\":{\\\"key\\\":\\\"value\\\"}}\", \"detector\": \"{\\\"detector\\\":{\\\"key\\\":\\\"value\\\"}}\", \"email\": \"{\\\"email\\\":{\\\"key\\\":\\\"value\\\"}}\", \"forensics_hosts\": \"{\\\"forensics_hosts\\\":{\\\"key\\\":\\\"value\\\"}}\", \"target\":", "the fetch e.g. fetch_delta, fetch_limit, created_after, state. - response of", "The last fetched incident id. When - Get new incidents", "validate that the number of expected incidents return. - validate", "last_fetched_id. - response of the api When - when a", "that on invalid input such as days or no units", "\"Attack Vector\", \"value\": \"Email\" }, { \"name\": \"Classification\", \"value\": \"Spam\"", "the fetch e.g. fetch_delta, fetch_limit, created_after, state and last_fetched_id. -", "\"value\", \"summary\": \"value\" } def test_prepare_ingest_alert_request_body(): prepared_body = prepare_ingest_alert_request_body(INGEST_ALERT_ARGS) assert", "Bulk Email\", \"description\": \"EvilScheme test message\", \"score\": 4200, \"state\": \"Open\",", "the function which is gathered originally from demisto.params() The dict", "= [3058, 3059, 3060] params = { 'fetch_delta': '2 hours',", "of the fetch is activated with a fetch limit set", "return value is as expected. \"\"\" time_delta = get_time_delta('1 minute')", "'urls': \"test\" } ] EMAILS_CONTEXT_INPUT = [ (MOCK_INCIDENT['events'][0], EMAIL_RESULT) ]", "api. - The last fetched incident id. When - Get", "\"id\": 3, \"category\": \"malware\", \"severity\": \"Info\", \"source\": \"Proofpoint TAP\", \"threatname\":", "( e.g. 3057 and 3058) \"\"\" expected_ids_to_fetch_first = [3055, 3056,", "'2021-03-31T11:21:24Z', } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_incidnets = get_new_incidents(request_params, last_incident_fetched) assert len(new_incidnets)", "test_fetch_incidents_limit_exceed(mocker): \"\"\" Given - a dict of params given to", "= get_incidents_batch_by_time_request(params) for incident in new_fetched_first: assert incident.get('id') in expected_ids_to_fetch_first", "= { 'fetch_delta': '2 hours', 'fetch_limit': '3', 'created_after': '2021-03-30T10:44:24Z', 'state':", "errors are raised. - validate that on valid inputs the", "- a single iteration of the fetch is activated with", "and the unit of the fetch delta.' in str( ex)", "{ \"name\": \"Attack Vector\", \"value\": \"Email\" }, { \"name\": \"Classification\",", "to the get_time_delta function which is valid and invalid When", "mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) incidents_list = get_incidents_batch_by_time_request(params) assert len(incidents_list) == 5 def", "which is valid and invalid When - run the get_time_delta", "get_time_delta function. Then - validate that on invalid input such", "Please make sure to insert both the number and the", "\"EvilScheme test message\", \"score\": 4200, \"state\": \"Open\", \"created_at\": \"2018-05-26T21:07:17Z\", \"event_count\":", "[ \"Proofpoint TAP\" ], \"users\": [ \"\" ], \"assignee\": \"Unassigned\",", "incident in new_incidnets: assert incident.get('id') > 3057 def test_get_time_delta(): \"\"\"", "assert 'The fetch_delta is invalid. Please make sure to insert", "incident in new_fetched_second: assert incident.get('id') in expected_ids_to_fetch_second def test_get_new_incidents(mocker): \"\"\"", "number and the unit of the fetch delta.' in str(", "function which is gathered originally from demisto.params() The dict includes", "fetch_delta, fetch_limit, created_after, state. - response of the api When", "== '2:00:00' try: get_time_delta('2') except Exception as ex: assert 'The", "[ (MOCK_INCIDENT, INCIDENT_FIELD_CONTEXT) ] def get_fetch_data(): with open('./test_data/raw_response.json', 'r') as", "\"forensics_hosts\": {\"key\": \"value\"}, \"target\": {\"key\": \"value\"}, \"threat_info\": {\"key\": \"value\"}, \"custom_fields\":", "\"Severity\": \"Critical\", \"Abuse_Disposition\": \"Unknown\" } INCIDENT_FIELD_INPUT = [ (MOCK_INCIDENT, INCIDENT_FIELD_CONTEXT)", "'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_fetched_first = get_incidents_batch_by_time_request(params) for incident in", "params = { 'fetch_delta': '6 hours', 'fetch_limit': ' 5', 'created_after':", "@pytest.mark.parametrize('abuse_dispotion_values, expected_answer', ABUSE_DISPOSITION_INPUT) def test_pass_abuse_disposition_filter(abuse_dispotion_values, expected_answer): result = pass_abuse_disposition_filter(MOCK_INCIDENT, abuse_dispotion_values)", "get_time_delta('2 days') except Exception as ex: assert 'The unit of", "expected_answer): result = pass_sources_list_filter(MOCK_INCIDENT, sources_list) assert result == expected_answer ABUSE_DISPOSITION_INPUT", "request_params = { 'state': 'closed', 'created_after': '2021-03-30T10:21:24Z', 'created_before': '2021-03-31T11:21:24Z', }", "\"target\": {\"key\": \"value\"}, \"threat_info\": {\"key\": \"value\"}, \"custom_fields\": {\"key\": \"value\"}, \"post_url_id\":", "\"test\", 'body_type': \"test\", 'headers': \"test\", 'urls': \"test\" } ] EMAILS_CONTEXT_INPUT", "process. Then - validate that the number of expected incidents", "time is exactly the same is brought in the next", "\"name\": \"Abuse Disposition\", \"value\": \"Unknown\" } ], \"events\": [ {", "} new_fetched_second = get_incidents_batch_by_time_request(params) for incident in new_fetched_second: assert incident.get('id')", "\"detector\": \"{\\\"detector\\\":{\\\"key\\\":\\\"value\\\"}}\", \"email\": \"{\\\"email\\\":{\\\"key\\\":\\\"value\\\"}}\", \"forensics_hosts\": \"{\\\"forensics_hosts\\\":{\\\"key\\\":\\\"value\\\"}}\", \"target\": \"{\\\"target\\\":{\\\"key\\\":\\\"value\\\"}}\", \"threat_info\": \"{\\\"threat_info\\\":{\\\"key\\\":\\\"value\\\"}}\",", "more. \"\"\" params = { 'fetch_delta': '6 hours', 'fetch_limit': '", "and invalid When - run the get_time_delta function. Then -", "TAP\"], True) ] @pytest.mark.parametrize('sources_list, expected_answer', SOURCE_LIST_INPUT) def test_pass_sources_list_filter(sources_list, expected_answer): result", "[ { \"sender\": { \"email\": \"test\" }, \"recipient\": { \"email\":", "invalid When - run the get_time_delta function. Then - validate", "INCIDENT_FIELD_INPUT) def test_get_incident_field_context(incident, answer): incident_field_values = create_incident_field_context(incident) assert incident_field_values ==", "= { \"attacker\": {\"key\": \"value\"}, \"cnc_host\": {\"key\": \"value\"}, \"detector\": {\"key\":", "iteration of the fetch is activated with a fetch limit", "on valid inputs the return value is as expected. \"\"\"", "Then - validate that the number of expected incidents return.", "incident_field_values = create_incident_field_context(incident) assert incident_field_values == answer EMAIL_RESULT = [", "([\"No such source\", \"Proofpoint TAP\"], True) ] @pytest.mark.parametrize('sources_list, expected_answer', SOURCE_LIST_INPUT)", "'6 hours', 'fetch_limit': ' 5', 'created_after': '2021-03-30T11:44:24Z', 'state': 'closed' }", "- when a fetch occurs and the last fetched incident", "assert incident.get('id') in expected_ids_to_fetch_second def test_get_new_incidents(mocker): \"\"\" Given - a", "the unit of the fetch delta.' in str( ex) try:", "= get_incidents_batch_by_time_request(params) for incident in new_fetched_second: assert incident.get('id') in expected_ids_to_fetch_second", "True) ] @pytest.mark.parametrize('abuse_dispotion_values, expected_answer', ABUSE_DISPOSITION_INPUT) def test_pass_abuse_disposition_filter(abuse_dispotion_values, expected_answer): result =", "} ], } ], \"quarantine_results\": [], \"successful_quarantines\": 0, \"failed_quarantines\": 0,", "to the function which is gathered originally from demisto.params() The", "create_incident_field_context(incident) assert incident_field_values == answer EMAIL_RESULT = [ { 'sender':", "[ { \"name\": \"Attack Vector\", \"value\": \"Email\" }, { \"name\":", "TAP\", 'abuse_disposition': \"No such value\"}, []), ({'event_sources': \"No such source\",", "\"{\\\"email\\\":{\\\"key\\\":\\\"value\\\"}}\", \"forensics_hosts\": \"{\\\"forensics_hosts\\\":{\\\"key\\\":\\\"value\\\"}}\", \"target\": \"{\\\"target\\\":{\\\"key\\\":\\\"value\\\"}}\", \"threat_info\": \"{\\\"threat_info\\\":{\\\"key\\\":\\\"value\\\"}}\", \"custom_fields\": \"{\\\"custom_fields\\\":{\\\"key\\\":\\\"value\\\"}}\", \"post_url_id\":", "file.get('result') FETCH_RESPONSE = get_fetch_data() @pytest.mark.parametrize('incident, answer', INCIDENT_FIELD_INPUT) def test_get_incident_field_context(incident, answer):", "CommonServerPython import * from ProofpointThreatResponse import create_incident_field_context, get_emails_context, pass_sources_list_filter, \\", "the fetch limit. - validate that the next incident whose", "def test_get_time_delta(): \"\"\" Given - input to the get_time_delta function", "incident whose time is exactly the same is brought in", "Vector\", \"value\": \"Email\" }, { \"name\": \"Classification\", \"value\": \"Spam\" },", "expected_ids_to_fetch_first params = { 'fetch_delta': '2 hour', 'fetch_limit': '3', 'created_after':", "\"custom_fields\": \"{\\\"custom_fields\\\":{\\\"key\\\":\\\"value\\\"}}\", \"post_url_id\": \"value\", \"json_version\": \"value\", \"summary\": \"value\" } EXPECTED_RESULT", "'abuse_disposition': \"No such value, Unknown\"}, [MOCK_INCIDENT]), ({'event_sources': \"\", 'abuse_disposition': \"\"},", "demisto_params, expected_answer): mocker.patch.object(demisto, 'params', return_value=demisto_params) filtered_incidents = filter_incidents([MOCK_INCIDENT]) assert filtered_incidents", "validate that only one of the incidents appear as to", "dict of request_params to the api. - The last fetched", "id then the last fetched incident. \"\"\" last_incident_fetched = 3057", "} EXPECTED_RESULT = { \"attacker\": {\"key\": \"value\"}, \"cnc_host\": {\"key\": \"value\"},", "{\"key\": \"value\"}, \"target\": {\"key\": \"value\"}, \"threat_info\": {\"key\": \"value\"}, \"custom_fields\": {\"key\":", "'sender': \"test\", 'recipient': \"test\", 'subject': \"test\", 'message_id': \"test\", 'message_delivery_time': 1544640072000,", "whose time is exactly the same is brought in the", "'body_type': \"test\", 'headers': \"test\", 'urls': \"test\" } ] EMAILS_CONTEXT_INPUT =", "The dict includes the relevant params for the fetch e.g.", "([\"Unknown\"], True), ([], True), ([\"No such value\"], False), ([\"No such", "len(new_incidnets) == 14 for incident in new_incidnets: assert incident.get('id') >", "unit of the fetch delta.' in str( ex) try: get_time_delta('2", "\"Abuse_Disposition\": \"Unknown\" } INCIDENT_FIELD_INPUT = [ (MOCK_INCIDENT, INCIDENT_FIELD_CONTEXT) ] def", "the fetch is activated with a fetch limit set to", "When - run the get_time_delta function. Then - validate that", "\"failed_quarantines\": 0, \"pending_quarantines\": 0 } INCIDENT_FIELD_CONTEXT = { \"Attack_Vector\": \"Email\",", "\"test\" }, \"subject\": \"test\", \"messageId\": \"test\", \"messageDeliveryTime\": { \"chronology\": {", "} ], \"events\": [ { \"id\": 3, \"category\": \"malware\", \"severity\":", "mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_fetched_first = get_incidents_batch_by_time_request(params) for incident in new_fetched_first: assert", "minute') assert str(time_delta) == '0:01:00' time_delta = get_time_delta('2 hours') assert", "'The unit of fetch_delta is invalid. Possible values are \"minutes\"", "True) ] @pytest.mark.parametrize('sources_list, expected_answer', SOURCE_LIST_INPUT) def test_pass_sources_list_filter(sources_list, expected_answer): result =", "({'event_sources': \"No such source\", 'abuse_disposition': \"No such value, Unknown\"}, []),", "returned incident have a bigger id then the last fetched", "'message_delivery_time': 1544640072000, 'body': \"test\", 'body_type': \"test\", 'headers': \"test\", 'urls': \"test\"", "when the api returned more. \"\"\" params = { 'fetch_delta':", "time_delta = get_time_delta('2 hours') assert str(time_delta) == '2:00:00' try: get_time_delta('2')", "params for the fetch e.g. fetch_delta, fetch_limit, created_after, state. -", "\"{\\\"threat_info\\\":{\\\"key\\\":\\\"value\\\"}}\", \"custom_fields\": \"{\\\"custom_fields\\\":{\\\"key\\\":\\\"value\\\"}}\", \"post_url_id\": \"value\", \"json_version\": \"value\", \"summary\": \"value\" }", "e.g. fetch_delta, fetch_limit, created_after, state. - response of the api", "run the get_time_delta function. Then - validate that on invalid", "\"2018-05-26T21:07:17Z\", \"malwareName\": \"\", \"emails\": [ { \"sender\": { \"email\": \"test\"", "DEMISTO_PARAMS) def test_filter_incidents(mocker, demisto_params, expected_answer): mocker.patch.object(demisto, 'params', return_value=demisto_params) filtered_incidents =", "next incident. Then - validate that only one of the", "'state': 'closed', 'created_after': '2021-03-30T10:21:24Z', 'created_before': '2021-03-31T11:21:24Z', } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_incidnets", "== 5 def test_fetch_incidents_with_same_created_time(mocker): \"\"\" Given - a dict of", "\"users\": [ \"\" ], \"assignee\": \"Unassigned\", \"team\": \"Unassigned\", \"hosts\": {", "\"post_url_id\": \"value\", \"json_version\": \"value\", \"summary\": \"value\" } EXPECTED_RESULT = {", "'state': 'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_fetched_first = get_incidents_batch_by_time_request(params) for incident", "unit of fetch_delta is invalid. Possible values are \"minutes\" or", "\\ pass_abuse_disposition_filter, filter_incidents, prepare_ingest_alert_request_body, \\ get_incidents_batch_by_time_request, get_new_incidents, get_time_delta MOCK_INCIDENT =", "\"test\", \"messageId\": \"test\", \"messageDeliveryTime\": { \"chronology\": { \"zone\": { \"id\":", "validate that the next incident whose time is exactly the", "test_pass_sources_list_filter(sources_list, expected_answer): result = pass_sources_list_filter(MOCK_INCIDENT, sources_list) assert result == expected_answer", "new_fetched_first: assert incident.get('id') in expected_ids_to_fetch_first params = { 'fetch_delta': '2", "== expected_answer INGEST_ALERT_ARGS = { \"attacker\": \"{\\\"attacker\\\":{\\\"key\\\":\\\"value\\\"}}\", \"cnc_host\": \"{\\\"cnc_host\\\":{\\\"key\\\":\\\"value\\\"}}\", \"detector\":", "\"test\", 'urls': \"test\" } ], } ], \"quarantine_results\": [], \"successful_quarantines\":", "\"id\": \"UTC\" } }, \"millis\": 1544640072000, }, \"abuseCopy\": \"false\", \"body\":", "fetch occurs and the last fetched incident has exactly the", "the relevant params for the fetch e.g. fetch_delta, fetch_limit, created_after,", "get_incidents_batch_by_time_request(params) for incident in new_fetched_first: assert incident.get('id') in expected_ids_to_fetch_first params", "] @pytest.mark.parametrize('event, answer', EMAILS_CONTEXT_INPUT) def test_get_emails_context(event, answer): emails_context = get_emails_context(event)", "], \"users\": [ \"\" ], \"assignee\": \"Unassigned\", \"team\": \"Unassigned\", \"hosts\":", "incident.get('id') > 3057 def test_get_time_delta(): \"\"\" Given - input to", "\"value\", \"summary\": \"value\" } EXPECTED_RESULT = { \"attacker\": {\"key\": \"value\"},", "fetch_delta is invalid. Please make sure to insert both the", "\"\"\" time_delta = get_time_delta('1 minute') assert str(time_delta) == '0:01:00' time_delta", "the returned incident have a bigger id then the last", "'3057', 'state': 'closed' } new_fetched_second = get_incidents_batch_by_time_request(params) for incident in", "str(time_delta) == '0:01:00' time_delta = get_time_delta('2 hours') assert str(time_delta) ==", "fetch limit set to 5 Then - validate that the", "of expected incidents return. - validate that all of the", "next incident whose time is exactly the same is brought", "[]), ({'event_sources': \"No such source\", 'abuse_disposition': \"No such value\"}, [])]", "params = { 'fetch_delta': '2 hour', 'fetch_limit': '3', 'created_after': '2021-03-30T11:21:24Z',", "return_value=FETCH_RESPONSE) new_fetched_first = get_incidents_batch_by_time_request(params) for incident in new_fetched_first: assert incident.get('id')", "\"\", ] }, \"incident_field_values\": [ { \"name\": \"Attack Vector\", \"value\":", "fetched incident id. When - Get new incidents is called", "incident has exactly the same time of the next incident.", "pass_abuse_disposition_filter(MOCK_INCIDENT, abuse_dispotion_values) assert result == expected_answer DEMISTO_PARAMS = [({'event_sources': \"No", "], \"quarantine_results\": [], \"successful_quarantines\": 0, \"failed_quarantines\": 0, \"pending_quarantines\": 0 }", "\"assignee\": \"Unassigned\", \"team\": \"Unassigned\", \"hosts\": { \"attacker\": [ \"\" ],", "create_incident_field_context, get_emails_context, pass_sources_list_filter, \\ pass_abuse_disposition_filter, filter_incidents, prepare_ingest_alert_request_body, \\ get_incidents_batch_by_time_request, get_new_incidents,", "{ \"email\": \"test\" }, \"subject\": \"test\", \"messageId\": \"test\", \"messageDeliveryTime\": {", "test_get_new_incidents(mocker): \"\"\" Given - a dict of request_params to the", "filtered_incidents = filter_incidents([MOCK_INCIDENT]) assert filtered_incidents == expected_answer INGEST_ALERT_ARGS = {", "INGEST_ALERT_ARGS = { \"attacker\": \"{\\\"attacker\\\":{\\\"key\\\":\\\"value\\\"}}\", \"cnc_host\": \"{\\\"cnc_host\\\":{\\\"key\\\":\\\"value\\\"}}\", \"detector\": \"{\\\"detector\\\":{\\\"key\\\":\\\"value\\\"}}\", \"email\":", "] }, \"incident_field_values\": [ { \"name\": \"Attack Vector\", \"value\": \"Email\"", "= prepare_ingest_alert_request_body(INGEST_ALERT_ARGS) assert prepared_body == EXPECTED_RESULT def test_fetch_incidents_limit_exceed(mocker): \"\"\" Given", "such value, Unknown\"}, []), ({'event_sources': \"No such source, Proofpoint TAP\",", "such source\", 'abuse_disposition': \"No such value, Unknown\"}, []), ({'event_sources': \"No", "\"attacker\": {\"key\": \"value\"}, \"cnc_host\": {\"key\": \"value\"}, \"detector\": {\"key\": \"value\"}, \"email\":", "new_incidnets: assert incident.get('id') > 3057 def test_get_time_delta(): \"\"\" Given -", "} ], \"quarantine_results\": [], \"successful_quarantines\": 0, \"failed_quarantines\": 0, \"pending_quarantines\": 0", "\"attacker\": \"{\\\"attacker\\\":{\\\"key\\\":\\\"value\\\"}}\", \"cnc_host\": \"{\\\"cnc_host\\\":{\\\"key\\\":\\\"value\\\"}}\", \"detector\": \"{\\\"detector\\\":{\\\"key\\\":\\\"value\\\"}}\", \"email\": \"{\\\"email\\\":{\\\"key\\\":\\\"value\\\"}}\", \"forensics_hosts\": \"{\\\"forensics_hosts\\\":{\\\"key\\\":\\\"value\\\"}}\",", "[3058, 3059, 3060] params = { 'fetch_delta': '2 hours', 'fetch_limit':", "the api returned more. \"\"\" params = { 'fetch_delta': '6", "as days or no units relevant errors are raised. -", "EMAILS_CONTEXT_INPUT) def test_get_emails_context(event, answer): emails_context = get_emails_context(event) assert emails_context ==", "\"threatname\": \"\", \"state\": \"Linked\", \"description\": \"\", \"attackDirection\": \"inbound\", \"received\": \"2018-05-26T21:07:17Z\",", "relevant params for the fetch e.g. fetch_delta, fetch_limit, created_after, state.", "\"No such value, Unknown\"}, []), ({'event_sources': \"No such source, Proofpoint", "filtered_incidents == expected_answer INGEST_ALERT_ARGS = { \"attacker\": \"{\\\"attacker\\\":{\\\"key\\\":\\\"value\\\"}}\", \"cnc_host\": \"{\\\"cnc_host\\\":{\\\"key\\\":\\\"value\\\"}}\",", "], } ], \"quarantine_results\": [], \"successful_quarantines\": 0, \"failed_quarantines\": 0, \"pending_quarantines\":", "test_pass_abuse_disposition_filter(abuse_dispotion_values, expected_answer): result = pass_abuse_disposition_filter(MOCK_INCIDENT, abuse_dispotion_values) assert result == expected_answer", "incidents is called during the fetch process. Then - validate", "= 3057 request_params = { 'state': 'closed', 'created_after': '2021-03-30T10:21:24Z', 'created_before':", "\"test\" }, \"recipient\": { \"email\": \"test\" }, \"subject\": \"test\", \"messageId\":", "== answer SOURCE_LIST_INPUT = [ ([\"Proofpoint TAP\"], True), ([], True),", "loop. ( e.g. 3057 and 3058) \"\"\" expected_ids_to_fetch_first = [3055,", "\"emails\": [ { \"sender\": { \"email\": \"test\" }, \"recipient\": {", "def test_get_emails_context(event, answer): emails_context = get_emails_context(event) assert emails_context == answer", "\"test\", 'bodyType': \"test\", 'headers': \"test\", 'urls': \"test\" } ], }", "such source\", 'abuse_disposition': \"No such value\"}, [])] @pytest.mark.parametrize('demisto_params, expected_answer', DEMISTO_PARAMS)", "of the incidents appear as to the fetch limit. -", "\"Unknown\" } INCIDENT_FIELD_INPUT = [ (MOCK_INCIDENT, INCIDENT_FIELD_CONTEXT) ] def get_fetch_data():", "= { \"Attack_Vector\": \"Email\", \"Classification\": \"Spam\", \"Severity\": \"Critical\", \"Abuse_Disposition\": \"Unknown\"", "'abuse_disposition': \"No such value, Unknown\"}, []), ({'event_sources': \"No such source,", "5', 'created_after': '2021-03-30T11:44:24Z', 'state': 'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) incidents_list =", "{\"key\": \"value\"}, \"forensics_hosts\": {\"key\": \"value\"}, \"target\": {\"key\": \"value\"}, \"threat_info\": {\"key\":", "fetch process. Then - validate that the number of expected", "e.g. fetch_delta, fetch_limit, created_after, state and last_fetched_id. - response of", "Email\", \"description\": \"EvilScheme test message\", \"score\": 4200, \"state\": \"Open\", \"created_at\":", "activated with a fetch limit set to 5 Then -", "get_incidents_batch_by_time_request, get_new_incidents, get_time_delta MOCK_INCIDENT = { \"id\": 1, \"type\": \"Malware\",", "True), ([\"No such source\"], False), ([\"No such source\", \"Proofpoint TAP\"],", "- run the get_time_delta function. Then - validate that on", "(MOCK_INCIDENT['events'][0], EMAIL_RESULT) ] @pytest.mark.parametrize('event, answer', EMAILS_CONTEXT_INPUT) def test_get_emails_context(event, answer): emails_context", "ex: assert 'The fetch_delta is invalid. Please make sure to", "ex) try: get_time_delta('2 days') except Exception as ex: assert 'The", "}, \"subject\": \"test\", \"messageId\": \"test\", \"messageDeliveryTime\": { \"chronology\": { \"zone\":", "valid and invalid When - run the get_time_delta function. Then", "for the fetch e.g. fetch_delta, fetch_limit, created_after, state. - response", "answer): emails_context = get_emails_context(event) assert emails_context == answer SOURCE_LIST_INPUT =", "value\"}, []), ({'event_sources': \"No such source\", 'abuse_disposition': \"No such value\"},", "as expected. \"\"\" time_delta = get_time_delta('1 minute') assert str(time_delta) ==", "limit when the api returned more. \"\"\" params = {", "get_time_delta MOCK_INCIDENT = { \"id\": 1, \"type\": \"Malware\", \"summary\": \"Unsolicited", "[ ([\"Proofpoint TAP\"], True), ([], True), ([\"No such source\"], False),", "message\", \"score\": 4200, \"state\": \"Open\", \"created_at\": \"2018-05-26T21:07:17Z\", \"event_count\": 3, \"event_sources\":", "SOURCE_LIST_INPUT = [ ([\"Proofpoint TAP\"], True), ([], True), ([\"No such", "ABUSE_DISPOSITION_INPUT) def test_pass_abuse_disposition_filter(abuse_dispotion_values, expected_answer): result = pass_abuse_disposition_filter(MOCK_INCIDENT, abuse_dispotion_values) assert result", "[ { \"id\": 3, \"category\": \"malware\", \"severity\": \"Info\", \"source\": \"Proofpoint", "'headers': \"test\", 'urls': \"test\" } ], } ], \"quarantine_results\": [],", "a dict of request_params to the api. - The last", "new_incidnets = get_new_incidents(request_params, last_incident_fetched) assert len(new_incidnets) == 14 for incident", "\"email\": \"test\" }, \"subject\": \"test\", \"messageId\": \"test\", \"messageDeliveryTime\": { \"chronology\":", "\"summary\": \"value\" } def test_prepare_ingest_alert_request_body(): prepared_body = prepare_ingest_alert_request_body(INGEST_ALERT_ARGS) assert prepared_body", "\"malware\", \"severity\": \"Info\", \"source\": \"Proofpoint TAP\", \"threatname\": \"\", \"state\": \"Linked\",", "or incidents that is returned is equal to the limit", "[MOCK_INCIDENT]), ({'event_sources': \"No such source\", 'abuse_disposition': \"No such value, Unknown\"},", "'closed' } new_fetched_second = get_incidents_batch_by_time_request(params) for incident in new_fetched_second: assert", "that all of the returned incident have a bigger id", "= filter_incidents([MOCK_INCIDENT]) assert filtered_incidents == expected_answer INGEST_ALERT_ARGS = { \"attacker\":", "'abuse_disposition': \"\"}, [MOCK_INCIDENT]), ({'event_sources': \"No such source\", 'abuse_disposition': \"No such", "\"json_version\": \"value\", \"summary\": \"value\" } EXPECTED_RESULT = { \"attacker\": {\"key\":", "assert incident.get('id') > 3057 def test_get_time_delta(): \"\"\" Given - input", "\"Unsolicited Bulk Email\", \"description\": \"EvilScheme test message\", \"score\": 4200, \"state\":", "'2:00:00' try: get_time_delta('2') except Exception as ex: assert 'The fetch_delta", "\"test\" } ], } ], \"quarantine_results\": [], \"successful_quarantines\": 0, \"failed_quarantines\":", "[], \"successful_quarantines\": 0, \"failed_quarantines\": 0, \"pending_quarantines\": 0 } INCIDENT_FIELD_CONTEXT =", "\"test\", \"messageDeliveryTime\": { \"chronology\": { \"zone\": { \"id\": \"UTC\" }", "\"successful_quarantines\": 0, \"failed_quarantines\": 0, \"pending_quarantines\": 0 } INCIDENT_FIELD_CONTEXT = {", "3057 def test_get_time_delta(): \"\"\" Given - input to the get_time_delta", "the number and the unit of the fetch delta.' in", "value\"}, [])] @pytest.mark.parametrize('demisto_params, expected_answer', DEMISTO_PARAMS) def test_filter_incidents(mocker, demisto_params, expected_answer): mocker.patch.object(demisto,", "assert len(new_incidnets) == 14 for incident in new_incidnets: assert incident.get('id')", "'3', 'created_after': '2021-03-30T10:44:24Z', 'state': 'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_fetched_first =", "for incident in new_fetched_second: assert incident.get('id') in expected_ids_to_fetch_second def test_get_new_incidents(mocker):", "hours', 'fetch_limit': ' 5', 'created_after': '2021-03-30T11:44:24Z', 'state': 'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request',", "the next fetch loop. ( e.g. 3057 and 3058) \"\"\"", "return. - validate that all of the returned incident have", "\"Unknown\"], True) ] @pytest.mark.parametrize('abuse_dispotion_values, expected_answer', ABUSE_DISPOSITION_INPUT) def test_pass_abuse_disposition_filter(abuse_dispotion_values, expected_answer): result", "relevant params for the fetch e.g. fetch_delta, fetch_limit, created_after, state", "all of the returned incident have a bigger id then", "mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_incidnets = get_new_incidents(request_params, last_incident_fetched) assert len(new_incidnets) == 14", "prepare_ingest_alert_request_body, \\ get_incidents_batch_by_time_request, get_new_incidents, get_time_delta MOCK_INCIDENT = { \"id\": 1,", "the api When - when a fetch occurs and the", "- validate that the next incident whose time is exactly", "'fetch_limit': '3', 'created_after': '2021-03-30T10:44:24Z', 'state': 'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_fetched_first", "raised. - validate that on valid inputs the return value", "try: get_time_delta('2 days') except Exception as ex: assert 'The unit", "'state': 'closed' } new_fetched_second = get_incidents_batch_by_time_request(params) for incident in new_fetched_second:", "expected_ids_to_fetch_second = [3058, 3059, 3060] params = { 'fetch_delta': '2", "answer', INCIDENT_FIELD_INPUT) def test_get_incident_field_context(incident, answer): incident_field_values = create_incident_field_context(incident) assert incident_field_values", "such value\"], False), ([\"No such value\", \"Unknown\"], True) ] @pytest.mark.parametrize('abuse_dispotion_values,", "\"email\": \"{\\\"email\\\":{\\\"key\\\":\\\"value\\\"}}\", \"forensics_hosts\": \"{\\\"forensics_hosts\\\":{\\\"key\\\":\\\"value\\\"}}\", \"target\": \"{\\\"target\\\":{\\\"key\\\":\\\"value\\\"}}\", \"threat_info\": \"{\\\"threat_info\\\":{\\\"key\\\":\\\"value\\\"}}\", \"custom_fields\": \"{\\\"custom_fields\\\":{\\\"key\\\":\\\"value\\\"}}\",", "try: get_time_delta('2') except Exception as ex: assert 'The fetch_delta is", "'recipient': \"test\", 'subject': \"test\", 'message_id': \"test\", 'message_delivery_time': 1544640072000, 'body': \"test\",", "def test_fetch_incidents_limit_exceed(mocker): \"\"\" Given - a dict of params given", "'last_fetched_id': '3057', 'state': 'closed' } new_fetched_second = get_incidents_batch_by_time_request(params) for incident", "a bigger id then the last fetched incident. \"\"\" last_incident_fetched", "returned is equal to the limit when the api returned", "\"pending_quarantines\": 0 } INCIDENT_FIELD_CONTEXT = { \"Attack_Vector\": \"Email\", \"Classification\": \"Spam\",", "fetch e.g. fetch_delta, fetch_limit, created_after, state. - response of the", "the next incident. Then - validate that only one of", "to the fetch limit. - validate that the next incident", "= [3055, 3056, 3057] expected_ids_to_fetch_second = [3058, 3059, 3060] params", "'fetch_delta': '6 hours', 'fetch_limit': ' 5', 'created_after': '2021-03-30T11:44:24Z', 'state': 'closed'", "get_incidents_batch_by_time_request(params) assert len(incidents_list) == 5 def test_fetch_incidents_with_same_created_time(mocker): \"\"\" Given -", "test_get_incident_field_context(incident, answer): incident_field_values = create_incident_field_context(incident) assert incident_field_values == answer EMAIL_RESULT", "incident_field_values == answer EMAIL_RESULT = [ { 'sender': \"test\", 'recipient':", "such value\"}, []), ({'event_sources': \"No such source\", 'abuse_disposition': \"No such", "5 def test_fetch_incidents_with_same_created_time(mocker): \"\"\" Given - a dict of params", "to the api. - The last fetched incident id. When", "], \"assignee\": \"Unassigned\", \"team\": \"Unassigned\", \"hosts\": { \"attacker\": [ \"\"", "= [ { 'sender': \"test\", 'recipient': \"test\", 'subject': \"test\", 'message_id':", "such source, Proofpoint TAP\", 'abuse_disposition': \"No such value, Unknown\"}, [MOCK_INCIDENT]),", "\"inbound\", \"received\": \"2018-05-26T21:07:17Z\", \"malwareName\": \"\", \"emails\": [ { \"sender\": {", "] def get_fetch_data(): with open('./test_data/raw_response.json', 'r') as f: file =", "\"messageDeliveryTime\": { \"chronology\": { \"zone\": { \"id\": \"UTC\" } },", "hour', 'fetch_limit': '3', 'created_after': '2021-03-30T11:21:24Z', 'last_fetched_id': '3057', 'state': 'closed' }", "[MOCK_INCIDENT]), ({'event_sources': \"\", 'abuse_disposition': \"\"}, [MOCK_INCIDENT]), ({'event_sources': \"No such source\",", "Given - a dict of request_params to the api. -", "of the returned incident have a bigger id then the", "> 3057 def test_get_time_delta(): \"\"\" Given - input to the", "as ex: assert 'The unit of fetch_delta is invalid. Possible", "value, Unknown\"}, []), ({'event_sources': \"No such source, Proofpoint TAP\", 'abuse_disposition':", "\"No such value, Unknown\"}, [MOCK_INCIDENT]), ({'event_sources': \"\", 'abuse_disposition': \"\"}, [MOCK_INCIDENT]),", "to the limit when the api returned more. \"\"\" params", "\"Linked\", \"description\": \"\", \"attackDirection\": \"inbound\", \"received\": \"2018-05-26T21:07:17Z\", \"malwareName\": \"\", \"emails\":", "'The fetch_delta is invalid. Please make sure to insert both", "\"millis\": 1544640072000, }, \"abuseCopy\": \"false\", \"body\": \"test\", 'bodyType': \"test\", 'headers':", "\"Critical\" }, { \"name\": \"Abuse Disposition\", \"value\": \"Unknown\" } ],", "\"Open\", \"created_at\": \"2018-05-26T21:07:17Z\", \"event_count\": 3, \"event_sources\": [ \"Proofpoint TAP\" ],", "\"test\", 'urls': \"test\" } ] EMAILS_CONTEXT_INPUT = [ (MOCK_INCIDENT['events'][0], EMAIL_RESULT)", "[ ([\"Unknown\"], True), ([], True), ([\"No such value\"], False), ([\"No", "'abuse_disposition': \"No such value\"}, []), ({'event_sources': \"No such source\", 'abuse_disposition':", "DEMISTO_PARAMS = [({'event_sources': \"No such source, Proofpoint TAP\", 'abuse_disposition': \"No", "5 Then - validate that the number or incidents that", "'0:01:00' time_delta = get_time_delta('2 hours') assert str(time_delta) == '2:00:00' try:", "When - Get new incidents is called during the fetch", "test_filter_incidents(mocker, demisto_params, expected_answer): mocker.patch.object(demisto, 'params', return_value=demisto_params) filtered_incidents = filter_incidents([MOCK_INCIDENT]) assert", "open('./test_data/raw_response.json', 'r') as f: file = json.loads(f.read()) return file.get('result') FETCH_RESPONSE", "prepared_body == EXPECTED_RESULT def test_fetch_incidents_limit_exceed(mocker): \"\"\" Given - a dict", "days or no units relevant errors are raised. - validate", "relevant errors are raised. - validate that on valid inputs", "\"\" ], \"forensics\": [ \"\", ] }, \"incident_field_values\": [ {", "set to 5 Then - validate that the number or", "for incident in new_incidnets: assert incident.get('id') > 3057 def test_get_time_delta():", "0 } INCIDENT_FIELD_CONTEXT = { \"Attack_Vector\": \"Email\", \"Classification\": \"Spam\", \"Severity\":", "([\"Proofpoint TAP\"], True), ([], True), ([\"No such source\"], False), ([\"No", "incident. Then - validate that only one of the incidents", "\"custom_fields\": {\"key\": \"value\"}, \"post_url_id\": \"value\", \"json_version\": \"value\", \"summary\": \"value\" }", "= get_time_delta('1 minute') assert str(time_delta) == '0:01:00' time_delta = get_time_delta('2", "FETCH_RESPONSE = get_fetch_data() @pytest.mark.parametrize('incident, answer', INCIDENT_FIELD_INPUT) def test_get_incident_field_context(incident, answer): incident_field_values", "False), ([\"No such source\", \"Proofpoint TAP\"], True) ] @pytest.mark.parametrize('sources_list, expected_answer',", "3057 request_params = { 'state': 'closed', 'created_after': '2021-03-30T10:21:24Z', 'created_before': '2021-03-31T11:21:24Z',", "ABUSE_DISPOSITION_INPUT = [ ([\"Unknown\"], True), ([], True), ([\"No such value\"],", "\"test\" } ] EMAILS_CONTEXT_INPUT = [ (MOCK_INCIDENT['events'][0], EMAIL_RESULT) ] @pytest.mark.parametrize('event,", "Given - a dict of params given to the function", "no units relevant errors are raised. - validate that on", "\"\"}, [MOCK_INCIDENT]), ({'event_sources': \"No such source\", 'abuse_disposition': \"No such value,", "with a fetch limit set to 5 Then - validate", "validate that the number or incidents that is returned is", "last fetched incident. \"\"\" last_incident_fetched = 3057 request_params = {", "that on valid inputs the return value is as expected.", "\"\"\" Given - a dict of params given to the", "MOCK_INCIDENT = { \"id\": 1, \"type\": \"Malware\", \"summary\": \"Unsolicited Bulk", "expected_answer', DEMISTO_PARAMS) def test_filter_incidents(mocker, demisto_params, expected_answer): mocker.patch.object(demisto, 'params', return_value=demisto_params) filtered_incidents", "{\"key\": \"value\"}, \"cnc_host\": {\"key\": \"value\"}, \"detector\": {\"key\": \"value\"}, \"email\": {\"key\":", "\"\", 'abuse_disposition': \"\"}, [MOCK_INCIDENT]), ({'event_sources': \"No such source\", 'abuse_disposition': \"No", "\"value\" } def test_prepare_ingest_alert_request_body(): prepared_body = prepare_ingest_alert_request_body(INGEST_ALERT_ARGS) assert prepared_body ==", "\"type\": \"Malware\", \"summary\": \"Unsolicited Bulk Email\", \"description\": \"EvilScheme test message\",", "return_value=demisto_params) filtered_incidents = filter_incidents([MOCK_INCIDENT]) assert filtered_incidents == expected_answer INGEST_ALERT_ARGS =", "'urls': \"test\" } ], } ], \"quarantine_results\": [], \"successful_quarantines\": 0,", "params = { 'fetch_delta': '2 hours', 'fetch_limit': '3', 'created_after': '2021-03-30T10:44:24Z',", "import create_incident_field_context, get_emails_context, pass_sources_list_filter, \\ pass_abuse_disposition_filter, filter_incidents, prepare_ingest_alert_request_body, \\ get_incidents_batch_by_time_request,", "fetched incident has exactly the same time of the next", "is valid and invalid When - run the get_time_delta function.", "'subject': \"test\", 'message_id': \"test\", 'message_delivery_time': 1544640072000, 'body': \"test\", 'body_type': \"test\",", "fetched incident. \"\"\" last_incident_fetched = 3057 request_params = { 'state':", "== answer EMAIL_RESULT = [ { 'sender': \"test\", 'recipient': \"test\",", "value\", \"Unknown\"], True) ] @pytest.mark.parametrize('abuse_dispotion_values, expected_answer', ABUSE_DISPOSITION_INPUT) def test_pass_abuse_disposition_filter(abuse_dispotion_values, expected_answer):", "TAP\", \"threatname\": \"\", \"state\": \"Linked\", \"description\": \"\", \"attackDirection\": \"inbound\", \"received\":", "= [ ([\"Proofpoint TAP\"], True), ([], True), ([\"No such source\"],", "([], True), ([\"No such value\"], False), ([\"No such value\", \"Unknown\"],", "get_time_delta('1 minute') assert str(time_delta) == '0:01:00' time_delta = get_time_delta('2 hours')", "\"post_url_id\": \"value\", \"json_version\": \"value\", \"summary\": \"value\" } def test_prepare_ingest_alert_request_body(): prepared_body", "pass_abuse_disposition_filter, filter_incidents, prepare_ingest_alert_request_body, \\ get_incidents_batch_by_time_request, get_new_incidents, get_time_delta MOCK_INCIDENT = {", "mocker.patch.object(demisto, 'params', return_value=demisto_params) filtered_incidents = filter_incidents([MOCK_INCIDENT]) assert filtered_incidents == expected_answer", "3058) \"\"\" expected_ids_to_fetch_first = [3055, 3056, 3057] expected_ids_to_fetch_second = [3058,", "'fetch_delta': '2 hours', 'fetch_limit': '3', 'created_after': '2021-03-30T10:44:24Z', 'state': 'closed' }", "fetch_limit, created_after, state. - response of the api When -", "\"cnc_host\": \"{\\\"cnc_host\\\":{\\\"key\\\":\\\"value\\\"}}\", \"detector\": \"{\\\"detector\\\":{\\\"key\\\":\\\"value\\\"}}\", \"email\": \"{\\\"email\\\":{\\\"key\\\":\\\"value\\\"}}\", \"forensics_hosts\": \"{\\\"forensics_hosts\\\":{\\\"key\\\":\\\"value\\\"}}\", \"target\": \"{\\\"target\\\":{\\\"key\\\":\\\"value\\\"}}\",", "When - a single iteration of the fetch is activated", "{ \"attacker\": \"{\\\"attacker\\\":{\\\"key\\\":\\\"value\\\"}}\", \"cnc_host\": \"{\\\"cnc_host\\\":{\\\"key\\\":\\\"value\\\"}}\", \"detector\": \"{\\\"detector\\\":{\\\"key\\\":\\\"value\\\"}}\", \"email\": \"{\\\"email\\\":{\\\"key\\\":\\\"value\\\"}}\", \"forensics_hosts\":", "\"value\"}, \"forensics_hosts\": {\"key\": \"value\"}, \"target\": {\"key\": \"value\"}, \"threat_info\": {\"key\": \"value\"},", "- response of the api When - a single iteration", "= get_new_incidents(request_params, last_incident_fetched) assert len(new_incidnets) == 14 for incident in", "new_fetched_first = get_incidents_batch_by_time_request(params) for incident in new_fetched_first: assert incident.get('id') in", "the api When - a single iteration of the fetch", "source\"], False), ([\"No such source\", \"Proofpoint TAP\"], True) ] @pytest.mark.parametrize('sources_list,", "number of expected incidents return. - validate that all of", "answer): incident_field_values = create_incident_field_context(incident) assert incident_field_values == answer EMAIL_RESULT =", "EMAIL_RESULT = [ { 'sender': \"test\", 'recipient': \"test\", 'subject': \"test\",", "([], True), ([\"No such source\"], False), ([\"No such source\", \"Proofpoint", "(MOCK_INCIDENT, INCIDENT_FIELD_CONTEXT) ] def get_fetch_data(): with open('./test_data/raw_response.json', 'r') as f:", "make sure to insert both the number and the unit", "\"hosts\": { \"attacker\": [ \"\" ], \"forensics\": [ \"\", ]", "\"test\", 'message_id': \"test\", 'message_delivery_time': 1544640072000, 'body': \"test\", 'body_type': \"test\", 'headers':", "which is gathered originally from demisto.params() The dict includes the", "id. When - Get new incidents is called during the", "such as days or no units relevant errors are raised.", "\"value\", \"json_version\": \"value\", \"summary\": \"value\" } EXPECTED_RESULT = { \"attacker\":", "in new_fetched_first: assert incident.get('id') in expected_ids_to_fetch_first params = { 'fetch_delta':", "response of the api When - when a fetch occurs", "is called during the fetch process. Then - validate that", "units relevant errors are raised. - validate that on valid", "= { 'state': 'closed', 'created_after': '2021-03-30T10:21:24Z', 'created_before': '2021-03-31T11:21:24Z', } mocker.patch('ProofpointThreatResponse.get_incidents_request',", "EXPECTED_RESULT = { \"attacker\": {\"key\": \"value\"}, \"cnc_host\": {\"key\": \"value\"}, \"detector\":", "source, Proofpoint TAP\", 'abuse_disposition': \"No such value, Unknown\"}, [MOCK_INCIDENT]), ({'event_sources':", "\"value\"}, \"custom_fields\": {\"key\": \"value\"}, \"post_url_id\": \"value\", \"json_version\": \"value\", \"summary\": \"value\"", "assert 'The unit of fetch_delta is invalid. Possible values are", "\"created_at\": \"2018-05-26T21:07:17Z\", \"event_count\": 3, \"event_sources\": [ \"Proofpoint TAP\" ], \"users\":", "f: file = json.loads(f.read()) return file.get('result') FETCH_RESPONSE = get_fetch_data() @pytest.mark.parametrize('incident,", "such source\"], False), ([\"No such source\", \"Proofpoint TAP\"], True) ]", "{ 'fetch_delta': '6 hours', 'fetch_limit': ' 5', 'created_after': '2021-03-30T11:44:24Z', 'state':", "= pass_sources_list_filter(MOCK_INCIDENT, sources_list) assert result == expected_answer ABUSE_DISPOSITION_INPUT = [", "\"\", \"attackDirection\": \"inbound\", \"received\": \"2018-05-26T21:07:17Z\", \"malwareName\": \"\", \"emails\": [ {", "False), ([\"No such value\", \"Unknown\"], True) ] @pytest.mark.parametrize('abuse_dispotion_values, expected_answer', ABUSE_DISPOSITION_INPUT)", "\"\"\" Given - a dict of request_params to the api.", "ex: assert 'The unit of fetch_delta is invalid. Possible values", "\"chronology\": { \"zone\": { \"id\": \"UTC\" } }, \"millis\": 1544640072000,", "{ \"zone\": { \"id\": \"UTC\" } }, \"millis\": 1544640072000, },", "get_fetch_data() @pytest.mark.parametrize('incident, answer', INCIDENT_FIELD_INPUT) def test_get_incident_field_context(incident, answer): incident_field_values = create_incident_field_context(incident)", "= json.loads(f.read()) return file.get('result') FETCH_RESPONSE = get_fetch_data() @pytest.mark.parametrize('incident, answer', INCIDENT_FIELD_INPUT)", "Exception as ex: assert 'The fetch_delta is invalid. Please make", "1, \"type\": \"Malware\", \"summary\": \"Unsolicited Bulk Email\", \"description\": \"EvilScheme test", "{ \"name\": \"Severity\", \"value\": \"Critical\" }, { \"name\": \"Abuse Disposition\",", "incidents that is returned is equal to the limit when", "incidents return. - validate that all of the returned incident", "'closed', 'created_after': '2021-03-30T10:21:24Z', 'created_before': '2021-03-31T11:21:24Z', } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_incidnets =", "a single iteration of the fetch is activated with a", "created_after, state. - response of the api When - a", "{ \"id\": 1, \"type\": \"Malware\", \"summary\": \"Unsolicited Bulk Email\", \"description\":", "\"Unassigned\", \"team\": \"Unassigned\", \"hosts\": { \"attacker\": [ \"\" ], \"forensics\":", "def test_filter_incidents(mocker, demisto_params, expected_answer): mocker.patch.object(demisto, 'params', return_value=demisto_params) filtered_incidents = filter_incidents([MOCK_INCIDENT])", "expected_answer): mocker.patch.object(demisto, 'params', return_value=demisto_params) filtered_incidents = filter_incidents([MOCK_INCIDENT]) assert filtered_incidents ==", "as f: file = json.loads(f.read()) return file.get('result') FETCH_RESPONSE = get_fetch_data()", "} INCIDENT_FIELD_CONTEXT = { \"Attack_Vector\": \"Email\", \"Classification\": \"Spam\", \"Severity\": \"Critical\",", "\"events\": [ { \"id\": 3, \"category\": \"malware\", \"severity\": \"Info\", \"source\":", "- validate that only one of the incidents appear as", "the get_time_delta function which is valid and invalid When -", "([\"No such source\"], False), ([\"No such source\", \"Proofpoint TAP\"], True)", "\"Critical\", \"Abuse_Disposition\": \"Unknown\" } INCIDENT_FIELD_INPUT = [ (MOCK_INCIDENT, INCIDENT_FIELD_CONTEXT) ]", "\"json_version\": \"value\", \"summary\": \"value\" } def test_prepare_ingest_alert_request_body(): prepared_body = prepare_ingest_alert_request_body(INGEST_ALERT_ARGS)", "incidents appear as to the fetch limit. - validate that", "Unknown\"}, []), ({'event_sources': \"No such source, Proofpoint TAP\", 'abuse_disposition': \"No", "3056, 3057] expected_ids_to_fetch_second = [3058, 3059, 3060] params = {", "[ \"\" ], \"assignee\": \"Unassigned\", \"team\": \"Unassigned\", \"hosts\": { \"attacker\":", "expected_ids_to_fetch_first = [3055, 3056, 3057] expected_ids_to_fetch_second = [3058, 3059, 3060]", "'created_after': '2021-03-30T10:44:24Z', 'state': 'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_fetched_first = get_incidents_batch_by_time_request(params)", "\"name\": \"Attack Vector\", \"value\": \"Email\" }, { \"name\": \"Classification\", \"value\":", "] @pytest.mark.parametrize('sources_list, expected_answer', SOURCE_LIST_INPUT) def test_pass_sources_list_filter(sources_list, expected_answer): result = pass_sources_list_filter(MOCK_INCIDENT,", "def test_pass_sources_list_filter(sources_list, expected_answer): result = pass_sources_list_filter(MOCK_INCIDENT, sources_list) assert result ==", "{\"key\": \"value\"}, \"email\": {\"key\": \"value\"}, \"forensics_hosts\": {\"key\": \"value\"}, \"target\": {\"key\":", "{ \"attacker\": {\"key\": \"value\"}, \"cnc_host\": {\"key\": \"value\"}, \"detector\": {\"key\": \"value\"},", "result == expected_answer ABUSE_DISPOSITION_INPUT = [ ([\"Unknown\"], True), ([], True),", "@pytest.mark.parametrize('incident, answer', INCIDENT_FIELD_INPUT) def test_get_incident_field_context(incident, answer): incident_field_values = create_incident_field_context(incident) assert", "'fetch_delta': '2 hour', 'fetch_limit': '3', 'created_after': '2021-03-30T11:21:24Z', 'last_fetched_id': '3057', 'state':", "assert emails_context == answer SOURCE_LIST_INPUT = [ ([\"Proofpoint TAP\"], True),", "assert len(incidents_list) == 5 def test_fetch_incidents_with_same_created_time(mocker): \"\"\" Given - a", "\"Info\", \"source\": \"Proofpoint TAP\", \"threatname\": \"\", \"state\": \"Linked\", \"description\": \"\",", "expected_answer', SOURCE_LIST_INPUT) def test_pass_sources_list_filter(sources_list, expected_answer): result = pass_sources_list_filter(MOCK_INCIDENT, sources_list) assert", "'3', 'created_after': '2021-03-30T11:21:24Z', 'last_fetched_id': '3057', 'state': 'closed' } new_fetched_second =", "\"\"\" Given - input to the get_time_delta function which is", "\"No such source\", 'abuse_disposition': \"No such value\"}, [])] @pytest.mark.parametrize('demisto_params, expected_answer',", "get_new_incidents(request_params, last_incident_fetched) assert len(new_incidnets) == 14 for incident in new_incidnets:", "return file.get('result') FETCH_RESPONSE = get_fetch_data() @pytest.mark.parametrize('incident, answer', INCIDENT_FIELD_INPUT) def test_get_incident_field_context(incident,", "When - when a fetch occurs and the last fetched", "[]), ({'event_sources': \"No such source, Proofpoint TAP\", 'abuse_disposition': \"No such", "\"test\", 'headers': \"test\", 'urls': \"test\" } ], } ], \"quarantine_results\":", "@pytest.mark.parametrize('demisto_params, expected_answer', DEMISTO_PARAMS) def test_filter_incidents(mocker, demisto_params, expected_answer): mocker.patch.object(demisto, 'params', return_value=demisto_params)", "params given to the function which is gathered originally from", "{ \"chronology\": { \"zone\": { \"id\": \"UTC\" } }, \"millis\":", "expected_answer DEMISTO_PARAMS = [({'event_sources': \"No such source, Proofpoint TAP\", 'abuse_disposition':", "\"target\": \"{\\\"target\\\":{\\\"key\\\":\\\"value\\\"}}\", \"threat_info\": \"{\\\"threat_info\\\":{\\\"key\\\":\\\"value\\\"}}\", \"custom_fields\": \"{\\\"custom_fields\\\":{\\\"key\\\":\\\"value\\\"}}\", \"post_url_id\": \"value\", \"json_version\": \"value\",", "given to the function which is gathered originally from demisto.params()", "only one of the incidents appear as to the fetch", "} ] EMAILS_CONTEXT_INPUT = [ (MOCK_INCIDENT['events'][0], EMAIL_RESULT) ] @pytest.mark.parametrize('event, answer',", "one of the incidents appear as to the fetch limit.", "assert str(time_delta) == '2:00:00' try: get_time_delta('2') except Exception as ex:", "\"name\": \"Severity\", \"value\": \"Critical\" }, { \"name\": \"Abuse Disposition\", \"value\":", "a dict of params given to the function which is", "\"No such source\", 'abuse_disposition': \"No such value, Unknown\"}, []), ({'event_sources':", "expected_answer): result = pass_abuse_disposition_filter(MOCK_INCIDENT, abuse_dispotion_values) assert result == expected_answer DEMISTO_PARAMS", "\"No such value\"}, [])] @pytest.mark.parametrize('demisto_params, expected_answer', DEMISTO_PARAMS) def test_filter_incidents(mocker, demisto_params,", "fetch_delta is invalid. Possible values are \"minutes\" or \"hours' in", "emails_context == answer SOURCE_LIST_INPUT = [ ([\"Proofpoint TAP\"], True), ([],", "3059, 3060] params = { 'fetch_delta': '2 hours', 'fetch_limit': '3',", "source, Proofpoint TAP\", 'abuse_disposition': \"No such value\"}, []), ({'event_sources': \"No", "\"Proofpoint TAP\"], True) ] @pytest.mark.parametrize('sources_list, expected_answer', SOURCE_LIST_INPUT) def test_pass_sources_list_filter(sources_list, expected_answer):", "@pytest.mark.parametrize('event, answer', EMAILS_CONTEXT_INPUT) def test_get_emails_context(event, answer): emails_context = get_emails_context(event) assert", "is invalid. Please make sure to insert both the number", "response of the api When - a single iteration of", "} def test_prepare_ingest_alert_request_body(): prepared_body = prepare_ingest_alert_request_body(INGEST_ALERT_ARGS) assert prepared_body == EXPECTED_RESULT", "\"cnc_host\": {\"key\": \"value\"}, \"detector\": {\"key\": \"value\"}, \"email\": {\"key\": \"value\"}, \"forensics_hosts\":", "validate that on valid inputs the return value is as", "\"test\", 'subject': \"test\", 'message_id': \"test\", 'message_delivery_time': 1544640072000, 'body': \"test\", 'body_type':", "\\ get_incidents_batch_by_time_request, get_new_incidents, get_time_delta MOCK_INCIDENT = { \"id\": 1, \"type\":", "get_fetch_data(): with open('./test_data/raw_response.json', 'r') as f: file = json.loads(f.read()) return", "\"2018-05-26T21:07:17Z\", \"event_count\": 3, \"event_sources\": [ \"Proofpoint TAP\" ], \"users\": [", "== 14 for incident in new_incidnets: assert incident.get('id') > 3057", "assert prepared_body == EXPECTED_RESULT def test_fetch_incidents_limit_exceed(mocker): \"\"\" Given - a", "\"\", \"emails\": [ { \"sender\": { \"email\": \"test\" }, \"recipient\":", "such source, Proofpoint TAP\", 'abuse_disposition': \"No such value\"}, []), ({'event_sources':", "\"No such value\"}, []), ({'event_sources': \"No such source\", 'abuse_disposition': \"No", "[ (MOCK_INCIDENT['events'][0], EMAIL_RESULT) ] @pytest.mark.parametrize('event, answer', EMAILS_CONTEXT_INPUT) def test_get_emails_context(event, answer):", "{ \"email\": \"test\" }, \"recipient\": { \"email\": \"test\" }, \"subject\":", "such value\"}, [])] @pytest.mark.parametrize('demisto_params, expected_answer', DEMISTO_PARAMS) def test_filter_incidents(mocker, demisto_params, expected_answer):", "same is brought in the next fetch loop. ( e.g.", "({'event_sources': \"No such source\", 'abuse_disposition': \"No such value\"}, [])] @pytest.mark.parametrize('demisto_params,", "answer EMAIL_RESULT = [ { 'sender': \"test\", 'recipient': \"test\", 'subject':", "\"email\": {\"key\": \"value\"}, \"forensics_hosts\": {\"key\": \"value\"}, \"target\": {\"key\": \"value\"}, \"threat_info\":", "new incidents is called during the fetch process. Then -", "\"threat_info\": \"{\\\"threat_info\\\":{\\\"key\\\":\\\"value\\\"}}\", \"custom_fields\": \"{\\\"custom_fields\\\":{\\\"key\\\":\\\"value\\\"}}\", \"post_url_id\": \"value\", \"json_version\": \"value\", \"summary\": \"value\"", "def test_get_new_incidents(mocker): \"\"\" Given - a dict of request_params to", "== '0:01:00' time_delta = get_time_delta('2 hours') assert str(time_delta) == '2:00:00'", "\"value\"}, \"email\": {\"key\": \"value\"}, \"forensics_hosts\": {\"key\": \"value\"}, \"target\": {\"key\": \"value\"},", "\"forensics_hosts\": \"{\\\"forensics_hosts\\\":{\\\"key\\\":\\\"value\\\"}}\", \"target\": \"{\\\"target\\\":{\\\"key\\\":\\\"value\\\"}}\", \"threat_info\": \"{\\\"threat_info\\\":{\\\"key\\\":\\\"value\\\"}}\", \"custom_fields\": \"{\\\"custom_fields\\\":{\\\"key\\\":\\\"value\\\"}}\", \"post_url_id\": \"value\",", "} mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) incidents_list = get_incidents_batch_by_time_request(params) assert len(incidents_list) == 5", "of the api When - a single iteration of the", "filter_incidents([MOCK_INCIDENT]) assert filtered_incidents == expected_answer INGEST_ALERT_ARGS = { \"attacker\": \"{\\\"attacker\\\":{\\\"key\\\":\\\"value\\\"}}\",", "] @pytest.mark.parametrize('abuse_dispotion_values, expected_answer', ABUSE_DISPOSITION_INPUT) def test_pass_abuse_disposition_filter(abuse_dispotion_values, expected_answer): result = pass_abuse_disposition_filter(MOCK_INCIDENT,", "\"value\": \"Unknown\" } ], \"events\": [ { \"id\": 3, \"category\":", "'created_after': '2021-03-30T10:21:24Z', 'created_before': '2021-03-31T11:21:24Z', } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_incidnets = get_new_incidents(request_params,", "\"Malware\", \"summary\": \"Unsolicited Bulk Email\", \"description\": \"EvilScheme test message\", \"score\":", "as ex: assert 'The fetch_delta is invalid. Please make sure", "pytest from CommonServerPython import * from ProofpointThreatResponse import create_incident_field_context, get_emails_context,", "}, \"abuseCopy\": \"false\", \"body\": \"test\", 'bodyType': \"test\", 'headers': \"test\", 'urls':", "} }, \"millis\": 1544640072000, }, \"abuseCopy\": \"false\", \"body\": \"test\", 'bodyType':", "\"\", \"state\": \"Linked\", \"description\": \"\", \"attackDirection\": \"inbound\", \"received\": \"2018-05-26T21:07:17Z\", \"malwareName\":", "\"value\"}, \"cnc_host\": {\"key\": \"value\"}, \"detector\": {\"key\": \"value\"}, \"email\": {\"key\": \"value\"},", "- validate that the number or incidents that is returned", "'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) incidents_list = get_incidents_batch_by_time_request(params) assert len(incidents_list) ==", "incident in new_fetched_first: assert incident.get('id') in expected_ids_to_fetch_first params = {", "incident have a bigger id then the last fetched incident.", "time of the next incident. Then - validate that only", "in str( ex) try: get_time_delta('2 days') except Exception as ex:", "[3055, 3056, 3057] expected_ids_to_fetch_second = [3058, 3059, 3060] params =", "'2021-03-30T10:44:24Z', 'state': 'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_fetched_first = get_incidents_batch_by_time_request(params) for", "- a dict of request_params to the api. - The", "the number or incidents that is returned is equal to", "test_get_time_delta(): \"\"\" Given - input to the get_time_delta function which", "the last fetched incident. \"\"\" last_incident_fetched = 3057 request_params =", "validate that all of the returned incident have a bigger", "that the next incident whose time is exactly the same", "}, \"millis\": 1544640072000, }, \"abuseCopy\": \"false\", \"body\": \"test\", 'bodyType': \"test\",", "\"recipient\": { \"email\": \"test\" }, \"subject\": \"test\", \"messageId\": \"test\", \"messageDeliveryTime\":", "'r') as f: file = json.loads(f.read()) return file.get('result') FETCH_RESPONSE =", "\"No such source, Proofpoint TAP\", 'abuse_disposition': \"No such value\"}, []),", "input such as days or no units relevant errors are", "limit set to 5 Then - validate that the number", "of the fetch delta.' in str( ex) try: get_time_delta('2 days')", "\"{\\\"forensics_hosts\\\":{\\\"key\\\":\\\"value\\\"}}\", \"target\": \"{\\\"target\\\":{\\\"key\\\":\\\"value\\\"}}\", \"threat_info\": \"{\\\"threat_info\\\":{\\\"key\\\":\\\"value\\\"}}\", \"custom_fields\": \"{\\\"custom_fields\\\":{\\\"key\\\":\\\"value\\\"}}\", \"post_url_id\": \"value\", \"json_version\":", "= [ (MOCK_INCIDENT, INCIDENT_FIELD_CONTEXT) ] def get_fetch_data(): with open('./test_data/raw_response.json', 'r')", "{ \"Attack_Vector\": \"Email\", \"Classification\": \"Spam\", \"Severity\": \"Critical\", \"Abuse_Disposition\": \"Unknown\" }", "3060] params = { 'fetch_delta': '2 hours', 'fetch_limit': '3', 'created_after':", "def test_prepare_ingest_alert_request_body(): prepared_body = prepare_ingest_alert_request_body(INGEST_ALERT_ARGS) assert prepared_body == EXPECTED_RESULT def", "the return value is as expected. \"\"\" time_delta = get_time_delta('1", "called during the fetch process. Then - validate that the", "TAP\", 'abuse_disposition': \"No such value, Unknown\"}, [MOCK_INCIDENT]), ({'event_sources': \"\", 'abuse_disposition':", "in new_fetched_second: assert incident.get('id') in expected_ids_to_fetch_second def test_get_new_incidents(mocker): \"\"\" Given", "is gathered originally from demisto.params() The dict includes the relevant", "- The last fetched incident id. When - Get new", "assert result == expected_answer DEMISTO_PARAMS = [({'event_sources': \"No such source,", "next fetch loop. ( e.g. 3057 and 3058) \"\"\" expected_ids_to_fetch_first", "incident id. When - Get new incidents is called during", "invalid input such as days or no units relevant errors", "fetch_limit, created_after, state and last_fetched_id. - response of the api", "get_incidents_batch_by_time_request(params) for incident in new_fetched_second: assert incident.get('id') in expected_ids_to_fetch_second def", "days') except Exception as ex: assert 'The unit of fetch_delta", "bigger id then the last fetched incident. \"\"\" last_incident_fetched =", "Given - input to the get_time_delta function which is valid", "is exactly the same is brought in the next fetch", "1544640072000, 'body': \"test\", 'body_type': \"test\", 'headers': \"test\", 'urls': \"test\" }", "get_time_delta function which is valid and invalid When - run", "new_fetched_second: assert incident.get('id') in expected_ids_to_fetch_second def test_get_new_incidents(mocker): \"\"\" Given -", "valid inputs the return value is as expected. \"\"\" time_delta", "that is returned is equal to the limit when the", "\"\"\" last_incident_fetched = 3057 request_params = { 'state': 'closed', 'created_after':", "delta.' in str( ex) try: get_time_delta('2 days') except Exception as", "\"test\", 'recipient': \"test\", 'subject': \"test\", 'message_id': \"test\", 'message_delivery_time': 1544640072000, 'body':", "return_value=FETCH_RESPONSE) incidents_list = get_incidents_batch_by_time_request(params) assert len(incidents_list) == 5 def test_fetch_incidents_with_same_created_time(mocker):", "{ \"name\": \"Abuse Disposition\", \"value\": \"Unknown\" } ], \"events\": [", "\"detector\": {\"key\": \"value\"}, \"email\": {\"key\": \"value\"}, \"forensics_hosts\": {\"key\": \"value\"}, \"target\":", "\"received\": \"2018-05-26T21:07:17Z\", \"malwareName\": \"\", \"emails\": [ { \"sender\": { \"email\":", "'bodyType': \"test\", 'headers': \"test\", 'urls': \"test\" } ], } ],", "\"event_count\": 3, \"event_sources\": [ \"Proofpoint TAP\" ], \"users\": [ \"\"", "single iteration of the fetch is activated with a fetch", "'params', return_value=demisto_params) filtered_incidents = filter_incidents([MOCK_INCIDENT]) assert filtered_incidents == expected_answer INGEST_ALERT_ARGS", "\"{\\\"cnc_host\\\":{\\\"key\\\":\\\"value\\\"}}\", \"detector\": \"{\\\"detector\\\":{\\\"key\\\":\\\"value\\\"}}\", \"email\": \"{\\\"email\\\":{\\\"key\\\":\\\"value\\\"}}\", \"forensics_hosts\": \"{\\\"forensics_hosts\\\":{\\\"key\\\":\\\"value\\\"}}\", \"target\": \"{\\\"target\\\":{\\\"key\\\":\\\"value\\\"}}\", \"threat_info\":", "api When - when a fetch occurs and the last", "function. Then - validate that on invalid input such as", "INCIDENT_FIELD_CONTEXT = { \"Attack_Vector\": \"Email\", \"Classification\": \"Spam\", \"Severity\": \"Critical\", \"Abuse_Disposition\":", "{\"key\": \"value\"}, \"threat_info\": {\"key\": \"value\"}, \"custom_fields\": {\"key\": \"value\"}, \"post_url_id\": \"value\",", "the next incident whose time is exactly the same is", "}, { \"name\": \"Abuse Disposition\", \"value\": \"Unknown\" } ], \"events\":", "\"incident_field_values\": [ { \"name\": \"Attack Vector\", \"value\": \"Email\" }, {", "get_emails_context, pass_sources_list_filter, \\ pass_abuse_disposition_filter, filter_incidents, prepare_ingest_alert_request_body, \\ get_incidents_batch_by_time_request, get_new_incidents, get_time_delta", "\"value\", \"json_version\": \"value\", \"summary\": \"value\" } def test_prepare_ingest_alert_request_body(): prepared_body =", "'message_id': \"test\", 'message_delivery_time': 1544640072000, 'body': \"test\", 'body_type': \"test\", 'headers': \"test\",", "def get_fetch_data(): with open('./test_data/raw_response.json', 'r') as f: file = json.loads(f.read())", "([\"No such value\", \"Unknown\"], True) ] @pytest.mark.parametrize('abuse_dispotion_values, expected_answer', ABUSE_DISPOSITION_INPUT) def", "0, \"failed_quarantines\": 0, \"pending_quarantines\": 0 } INCIDENT_FIELD_CONTEXT = { \"Attack_Vector\":", "of request_params to the api. - The last fetched incident", "\"id\": 1, \"type\": \"Malware\", \"summary\": \"Unsolicited Bulk Email\", \"description\": \"EvilScheme", "\"Spam\", \"Severity\": \"Critical\", \"Abuse_Disposition\": \"Unknown\" } INCIDENT_FIELD_INPUT = [ (MOCK_INCIDENT,", "\"state\": \"Linked\", \"description\": \"\", \"attackDirection\": \"inbound\", \"received\": \"2018-05-26T21:07:17Z\", \"malwareName\": \"\",", "source\", 'abuse_disposition': \"No such value, Unknown\"}, []), ({'event_sources': \"No such", "demisto.params() The dict includes the relevant params for the fetch", "= [ (MOCK_INCIDENT['events'][0], EMAIL_RESULT) ] @pytest.mark.parametrize('event, answer', EMAILS_CONTEXT_INPUT) def test_get_emails_context(event,", "} INCIDENT_FIELD_INPUT = [ (MOCK_INCIDENT, INCIDENT_FIELD_CONTEXT) ] def get_fetch_data(): with", "[])] @pytest.mark.parametrize('demisto_params, expected_answer', DEMISTO_PARAMS) def test_filter_incidents(mocker, demisto_params, expected_answer): mocker.patch.object(demisto, 'params',", "({'event_sources': \"No such source, Proofpoint TAP\", 'abuse_disposition': \"No such value\"},", "the incidents appear as to the fetch limit. - validate", "4200, \"state\": \"Open\", \"created_at\": \"2018-05-26T21:07:17Z\", \"event_count\": 3, \"event_sources\": [ \"Proofpoint", "last fetched incident has exactly the same time of the", "source\", \"Proofpoint TAP\"], True) ] @pytest.mark.parametrize('sources_list, expected_answer', SOURCE_LIST_INPUT) def test_pass_sources_list_filter(sources_list,", "pass_sources_list_filter, \\ pass_abuse_disposition_filter, filter_incidents, prepare_ingest_alert_request_body, \\ get_incidents_batch_by_time_request, get_new_incidents, get_time_delta MOCK_INCIDENT", "Then - validate that only one of the incidents appear", "* from ProofpointThreatResponse import create_incident_field_context, get_emails_context, pass_sources_list_filter, \\ pass_abuse_disposition_filter, filter_incidents,", "'2021-03-30T11:21:24Z', 'last_fetched_id': '3057', 'state': 'closed' } new_fetched_second = get_incidents_batch_by_time_request(params) for", "when a fetch occurs and the last fetched incident has", "\"malwareName\": \"\", \"emails\": [ { \"sender\": { \"email\": \"test\" },", "a fetch occurs and the last fetched incident has exactly", "returned more. \"\"\" params = { 'fetch_delta': '6 hours', 'fetch_limit':", "\"Email\" }, { \"name\": \"Classification\", \"value\": \"Spam\" }, { \"name\":", "of fetch_delta is invalid. Possible values are \"minutes\" or \"hours'", "'state': 'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) incidents_list = get_incidents_batch_by_time_request(params) assert len(incidents_list)", "is as expected. \"\"\" time_delta = get_time_delta('1 minute') assert str(time_delta)", "import * from ProofpointThreatResponse import create_incident_field_context, get_emails_context, pass_sources_list_filter, \\ pass_abuse_disposition_filter,", "answer SOURCE_LIST_INPUT = [ ([\"Proofpoint TAP\"], True), ([], True), ([\"No", "== expected_answer ABUSE_DISPOSITION_INPUT = [ ([\"Unknown\"], True), ([], True), ([\"No", "TAP\" ], \"users\": [ \"\" ], \"assignee\": \"Unassigned\", \"team\": \"Unassigned\",", "{ \"name\": \"Classification\", \"value\": \"Spam\" }, { \"name\": \"Severity\", \"value\":", "or no units relevant errors are raised. - validate that", "number or incidents that is returned is equal to the", "\"Unassigned\", \"hosts\": { \"attacker\": [ \"\" ], \"forensics\": [ \"\",", "with open('./test_data/raw_response.json', 'r') as f: file = json.loads(f.read()) return file.get('result')", "expected_answer', ABUSE_DISPOSITION_INPUT) def test_pass_abuse_disposition_filter(abuse_dispotion_values, expected_answer): result = pass_abuse_disposition_filter(MOCK_INCIDENT, abuse_dispotion_values) assert", "fetch is activated with a fetch limit set to 5", "'fetch_limit': ' 5', 'created_after': '2021-03-30T11:44:24Z', 'state': 'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE)", "\"{\\\"target\\\":{\\\"key\\\":\\\"value\\\"}}\", \"threat_info\": \"{\\\"threat_info\\\":{\\\"key\\\":\\\"value\\\"}}\", \"custom_fields\": \"{\\\"custom_fields\\\":{\\\"key\\\":\\\"value\\\"}}\", \"post_url_id\": \"value\", \"json_version\": \"value\", \"summary\":", "\"Spam\" }, { \"name\": \"Severity\", \"value\": \"Critical\" }, { \"name\":", "assert str(time_delta) == '0:01:00' time_delta = get_time_delta('2 hours') assert str(time_delta)", "of the next incident. Then - validate that only one", "\"sender\": { \"email\": \"test\" }, \"recipient\": { \"email\": \"test\" },", "except Exception as ex: assert 'The fetch_delta is invalid. Please", "the fetch process. Then - validate that the number of", "occurs and the last fetched incident has exactly the same", "and the last fetched incident has exactly the same time", "dict includes the relevant params for the fetch e.g. fetch_delta,", "def test_pass_abuse_disposition_filter(abuse_dispotion_values, expected_answer): result = pass_abuse_disposition_filter(MOCK_INCIDENT, abuse_dispotion_values) assert result ==", "the get_time_delta function. Then - validate that on invalid input", "api returned more. \"\"\" params = { 'fetch_delta': '6 hours',", "in expected_ids_to_fetch_first params = { 'fetch_delta': '2 hour', 'fetch_limit': '3',", "get_emails_context(event) assert emails_context == answer SOURCE_LIST_INPUT = [ ([\"Proofpoint TAP\"],", "\"messageId\": \"test\", \"messageDeliveryTime\": { \"chronology\": { \"zone\": { \"id\": \"UTC\"", "= pass_abuse_disposition_filter(MOCK_INCIDENT, abuse_dispotion_values) assert result == expected_answer DEMISTO_PARAMS = [({'event_sources':", "such source\", \"Proofpoint TAP\"], True) ] @pytest.mark.parametrize('sources_list, expected_answer', SOURCE_LIST_INPUT) def", "then the last fetched incident. \"\"\" last_incident_fetched = 3057 request_params", "1544640072000, }, \"abuseCopy\": \"false\", \"body\": \"test\", 'bodyType': \"test\", 'headers': \"test\",", "3057 and 3058) \"\"\" expected_ids_to_fetch_first = [3055, 3056, 3057] expected_ids_to_fetch_second", "has exactly the same time of the next incident. Then", "except Exception as ex: assert 'The unit of fetch_delta is", "a fetch limit set to 5 Then - validate that", "EMAIL_RESULT) ] @pytest.mark.parametrize('event, answer', EMAILS_CONTEXT_INPUT) def test_get_emails_context(event, answer): emails_context =", "file = json.loads(f.read()) return file.get('result') FETCH_RESPONSE = get_fetch_data() @pytest.mark.parametrize('incident, answer',", "def test_get_incident_field_context(incident, answer): incident_field_values = create_incident_field_context(incident) assert incident_field_values == answer", "True), ([\"No such value\"], False), ([\"No such value\", \"Unknown\"], True)", "e.g. 3057 and 3058) \"\"\" expected_ids_to_fetch_first = [3055, 3056, 3057]", "= [ ([\"Unknown\"], True), ([], True), ([\"No such value\"], False),", "the limit when the api returned more. \"\"\" params =", "\"quarantine_results\": [], \"successful_quarantines\": 0, \"failed_quarantines\": 0, \"pending_quarantines\": 0 } INCIDENT_FIELD_CONTEXT", "emails_context = get_emails_context(event) assert emails_context == answer SOURCE_LIST_INPUT = [", "assert incident.get('id') in expected_ids_to_fetch_first params = { 'fetch_delta': '2 hour',", "expected_ids_to_fetch_second def test_get_new_incidents(mocker): \"\"\" Given - a dict of request_params", "\"name\": \"Classification\", \"value\": \"Spam\" }, { \"name\": \"Severity\", \"value\": \"Critical\"", "\"test\", 'message_delivery_time': 1544640072000, 'body': \"test\", 'body_type': \"test\", 'headers': \"test\", 'urls':", "created_after, state and last_fetched_id. - response of the api When", "'fetch_limit': '3', 'created_after': '2021-03-30T11:21:24Z', 'last_fetched_id': '3057', 'state': 'closed' } new_fetched_second", "\"abuseCopy\": \"false\", \"body\": \"test\", 'bodyType': \"test\", 'headers': \"test\", 'urls': \"test\"", "'headers': \"test\", 'urls': \"test\" } ] EMAILS_CONTEXT_INPUT = [ (MOCK_INCIDENT['events'][0],", "abuse_dispotion_values) assert result == expected_answer DEMISTO_PARAMS = [({'event_sources': \"No such", "the same time of the next incident. Then - validate", "to insert both the number and the unit of the", "\"value\"}, \"threat_info\": {\"key\": \"value\"}, \"custom_fields\": {\"key\": \"value\"}, \"post_url_id\": \"value\", \"json_version\":", "str(time_delta) == '2:00:00' try: get_time_delta('2') except Exception as ex: assert", "such value\", \"Unknown\"], True) ] @pytest.mark.parametrize('abuse_dispotion_values, expected_answer', ABUSE_DISPOSITION_INPUT) def test_pass_abuse_disposition_filter(abuse_dispotion_values,", "includes the relevant params for the fetch e.g. fetch_delta, fetch_limit,", "to 5 Then - validate that the number or incidents", "[ \"\", ] }, \"incident_field_values\": [ { \"name\": \"Attack Vector\",", "{ \"sender\": { \"email\": \"test\" }, \"recipient\": { \"email\": \"test\"", "is equal to the limit when the api returned more.", "Disposition\", \"value\": \"Unknown\" } ], \"events\": [ { \"id\": 3,", "}, \"incident_field_values\": [ { \"name\": \"Attack Vector\", \"value\": \"Email\" },", "fetch loop. ( e.g. 3057 and 3058) \"\"\" expected_ids_to_fetch_first =", "\"value\"}, \"target\": {\"key\": \"value\"}, \"threat_info\": {\"key\": \"value\"}, \"custom_fields\": {\"key\": \"value\"},", "= { 'fetch_delta': '2 hour', 'fetch_limit': '3', 'created_after': '2021-03-30T11:21:24Z', 'last_fetched_id':", "- validate that on invalid input such as days or", "hours') assert str(time_delta) == '2:00:00' try: get_time_delta('2') except Exception as", "in new_incidnets: assert incident.get('id') > 3057 def test_get_time_delta(): \"\"\" Given", "and last_fetched_id. - response of the api When - when", "invalid. Please make sure to insert both the number and", "Unknown\"}, [MOCK_INCIDENT]), ({'event_sources': \"\", 'abuse_disposition': \"\"}, [MOCK_INCIDENT]), ({'event_sources': \"No such", "{\"key\": \"value\"}, \"detector\": {\"key\": \"value\"}, \"email\": {\"key\": \"value\"}, \"forensics_hosts\": {\"key\":", "'2 hour', 'fetch_limit': '3', 'created_after': '2021-03-30T11:21:24Z', 'last_fetched_id': '3057', 'state': 'closed'", "'2 hours', 'fetch_limit': '3', 'created_after': '2021-03-30T10:44:24Z', 'state': 'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request',", "= create_incident_field_context(incident) assert incident_field_values == answer EMAIL_RESULT = [ {", "hours', 'fetch_limit': '3', 'created_after': '2021-03-30T10:44:24Z', 'state': 'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE)", "of the api When - when a fetch occurs and", "\"Classification\": \"Spam\", \"Severity\": \"Critical\", \"Abuse_Disposition\": \"Unknown\" } INCIDENT_FIELD_INPUT = [", "SOURCE_LIST_INPUT) def test_pass_sources_list_filter(sources_list, expected_answer): result = pass_sources_list_filter(MOCK_INCIDENT, sources_list) assert result", "result = pass_sources_list_filter(MOCK_INCIDENT, sources_list) assert result == expected_answer ABUSE_DISPOSITION_INPUT =", "input to the get_time_delta function which is valid and invalid", "\"email\": \"test\" }, \"recipient\": { \"email\": \"test\" }, \"subject\": \"test\",", "ProofpointThreatResponse import create_incident_field_context, get_emails_context, pass_sources_list_filter, \\ pass_abuse_disposition_filter, filter_incidents, prepare_ingest_alert_request_body, \\", "\"\"\" expected_ids_to_fetch_first = [3055, 3056, 3057] expected_ids_to_fetch_second = [3058, 3059,", "in expected_ids_to_fetch_second def test_get_new_incidents(mocker): \"\"\" Given - a dict of", "test_get_emails_context(event, answer): emails_context = get_emails_context(event) assert emails_context == answer SOURCE_LIST_INPUT", "= { \"attacker\": \"{\\\"attacker\\\":{\\\"key\\\":\\\"value\\\"}}\", \"cnc_host\": \"{\\\"cnc_host\\\":{\\\"key\\\":\\\"value\\\"}}\", \"detector\": \"{\\\"detector\\\":{\\\"key\\\":\\\"value\\\"}}\", \"email\": \"{\\\"email\\\":{\\\"key\\\":\\\"value\\\"}}\",", "\"attacker\": [ \"\" ], \"forensics\": [ \"\", ] }, \"incident_field_values\":", "\"Proofpoint TAP\", \"threatname\": \"\", \"state\": \"Linked\", \"description\": \"\", \"attackDirection\": \"inbound\",", "] EMAILS_CONTEXT_INPUT = [ (MOCK_INCIDENT['events'][0], EMAIL_RESULT) ] @pytest.mark.parametrize('event, answer', EMAILS_CONTEXT_INPUT)", "\"{\\\"custom_fields\\\":{\\\"key\\\":\\\"value\\\"}}\", \"post_url_id\": \"value\", \"json_version\": \"value\", \"summary\": \"value\" } EXPECTED_RESULT =", "fetch limit. - validate that the next incident whose time", "\"severity\": \"Info\", \"source\": \"Proofpoint TAP\", \"threatname\": \"\", \"state\": \"Linked\", \"description\":", "\"test\", 'headers': \"test\", 'urls': \"test\" } ] EMAILS_CONTEXT_INPUT = [", "import pytest from CommonServerPython import * from ProofpointThreatResponse import create_incident_field_context,", "\"Classification\", \"value\": \"Spam\" }, { \"name\": \"Severity\", \"value\": \"Critical\" },", "Get new incidents is called during the fetch process. Then", "- validate that the number of expected incidents return. -", "last fetched incident id. When - Get new incidents is", "{ 'fetch_delta': '2 hour', 'fetch_limit': '3', 'created_after': '2021-03-30T11:21:24Z', 'last_fetched_id': '3057',", "\"subject\": \"test\", \"messageId\": \"test\", \"messageDeliveryTime\": { \"chronology\": { \"zone\": {", "Then - validate that on invalid input such as days", "insert both the number and the unit of the fetch", "True), ([], True), ([\"No such value\"], False), ([\"No such value\",", "INCIDENT_FIELD_CONTEXT) ] def get_fetch_data(): with open('./test_data/raw_response.json', 'r') as f: file", "str( ex) try: get_time_delta('2 days') except Exception as ex: assert", "\"value\": \"Critical\" }, { \"name\": \"Abuse Disposition\", \"value\": \"Unknown\" }", "'body': \"test\", 'body_type': \"test\", 'headers': \"test\", 'urls': \"test\" } ]", "INCIDENT_FIELD_INPUT = [ (MOCK_INCIDENT, INCIDENT_FIELD_CONTEXT) ] def get_fetch_data(): with open('./test_data/raw_response.json',", "\"Severity\", \"value\": \"Critical\" }, { \"name\": \"Abuse Disposition\", \"value\": \"Unknown\"", "Proofpoint TAP\", 'abuse_disposition': \"No such value\"}, []), ({'event_sources': \"No such", "fetch_delta, fetch_limit, created_after, state and last_fetched_id. - response of the", "exactly the same time of the next incident. Then -", "same time of the next incident. Then - validate that", "\"category\": \"malware\", \"severity\": \"Info\", \"source\": \"Proofpoint TAP\", \"threatname\": \"\", \"state\":", "incidents_list = get_incidents_batch_by_time_request(params) assert len(incidents_list) == 5 def test_fetch_incidents_with_same_created_time(mocker): \"\"\"", "3, \"category\": \"malware\", \"severity\": \"Info\", \"source\": \"Proofpoint TAP\", \"threatname\": \"\",", "of params given to the function which is gathered originally", "assert incident_field_values == answer EMAIL_RESULT = [ { 'sender': \"test\",", "pass_sources_list_filter(MOCK_INCIDENT, sources_list) assert result == expected_answer ABUSE_DISPOSITION_INPUT = [ ([\"Unknown\"],", "@pytest.mark.parametrize('sources_list, expected_answer', SOURCE_LIST_INPUT) def test_pass_sources_list_filter(sources_list, expected_answer): result = pass_sources_list_filter(MOCK_INCIDENT, sources_list)", "expected_answer ABUSE_DISPOSITION_INPUT = [ ([\"Unknown\"], True), ([], True), ([\"No such", "is activated with a fetch limit set to 5 Then", "from CommonServerPython import * from ProofpointThreatResponse import create_incident_field_context, get_emails_context, pass_sources_list_filter,", "equal to the limit when the api returned more. \"\"\"", "get_time_delta('2') except Exception as ex: assert 'The fetch_delta is invalid.", "0, \"pending_quarantines\": 0 } INCIDENT_FIELD_CONTEXT = { \"Attack_Vector\": \"Email\", \"Classification\":", "\"team\": \"Unassigned\", \"hosts\": { \"attacker\": [ \"\" ], \"forensics\": [", "is brought in the next fetch loop. ( e.g. 3057", "{ 'fetch_delta': '2 hours', 'fetch_limit': '3', 'created_after': '2021-03-30T10:44:24Z', 'state': 'closed'", "expected. \"\"\" time_delta = get_time_delta('1 minute') assert str(time_delta) == '0:01:00'", "True), ([], True), ([\"No such source\"], False), ([\"No such source\",", "[ \"\" ], \"forensics\": [ \"\", ] }, \"incident_field_values\": [", "\"summary\": \"value\" } EXPECTED_RESULT = { \"attacker\": {\"key\": \"value\"}, \"cnc_host\":", "'2021-03-30T11:44:24Z', 'state': 'closed' } mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) incidents_list = get_incidents_batch_by_time_request(params) assert", "len(incidents_list) == 5 def test_fetch_incidents_with_same_created_time(mocker): \"\"\" Given - a dict", "{\"key\": \"value\"}, \"post_url_id\": \"value\", \"json_version\": \"value\", \"summary\": \"value\" } def", "both the number and the unit of the fetch delta.'", "} mocker.patch('ProofpointThreatResponse.get_incidents_request', return_value=FETCH_RESPONSE) new_fetched_first = get_incidents_batch_by_time_request(params) for incident in new_fetched_first:", "\"{\\\"detector\\\":{\\\"key\\\":\\\"value\\\"}}\", \"email\": \"{\\\"email\\\":{\\\"key\\\":\\\"value\\\"}}\", \"forensics_hosts\": \"{\\\"forensics_hosts\\\":{\\\"key\\\":\\\"value\\\"}}\", \"target\": \"{\\\"target\\\":{\\\"key\\\":\\\"value\\\"}}\", \"threat_info\": \"{\\\"threat_info\\\":{\\\"key\\\":\\\"value\\\"}}\", \"custom_fields\":", "\"false\", \"body\": \"test\", 'bodyType': \"test\", 'headers': \"test\", 'urls': \"test\" }" ]
[ "os.path.isfile(methname_json): raise(\"passing not exist file \" + methname_json) if output_dir", "with different length may break the mach-o file, ori: \"", "from enum import Enum from .mach_o import LC_SYMTAB from macholib", "find __objc_methname section\") sect.section_data = replace_in_bytes( sect.section_data, name_dict, ReplaceType.objc_methname) header.mod_dict[lc]", "== ReplaceType.symbol_table: method_bytes = method_bytes.replace( b' ' + key.encode('utf-8') +", "= command_tuple[0] cmd = command_tuple[1] data = command_tuple[2] if lc.cmd", "method_bytes.replace( empty_byte + key.encode('utf-8') + empty_byte, empty_byte + value.encode('utf-8') +", "output = os.path.join(output_dir, filename) try: copy2(macho_file, output_dir) except SameFileError: pass", "break the mach-o file, ori: \" + key + \",", "method_bytes = method_bytes.replace( empty_byte + key.encode('utf-8') + empty_byte, empty_byte +", "name_dict, ReplaceType.objc_methname) header.mod_dict[lc] = [sect] def ch_symtab(header, name_dict): commands =", "not exist file \" + macho_file) if not os.path.isfile(methname_json): raise(\"passing", "for key, value in name_dict.items(): if len(key) != len(value): raise(\"replace", "tmp_sect in data: if tmp_sect.sectname.rstrip(b'\\x00') == b'__objc_methname': lc = command_tuple[0]", "_, command_tuple in enumerate(commands): seg = command_tuple[1] data = command_tuple[2]", "os.path.split(macho_file) if output_dir is None: output_dir = ori_dir output =", "open(output, 'r+b') as fp: macho.write(fp) os.chmod(output, 0o755) def main(): replace_methname(sys.argv[0],", "filename = os.path.split(macho_file) if output_dir is None: output_dir = ori_dir", "open(methname_json) as json_file: name_dict = json.load(json_file) for header in macho.headers:", "output_dir is not None and not os.path.isdir(output_dir): raise(\"passing not exist", "MachO.MachO(macho_file) name_dict = None with open(methname_json) as json_file: name_dict =", "output_dir) except SameFileError: pass with open(output, 'r+b') as fp: macho.write(fp)", "if tmp_sect.sectname.rstrip(b'\\x00') == b'__objc_methname': lc = command_tuple[0] sect = tmp_sect", "name_dict): commands = header.commands for idx, command_tuple in enumerate(commands): lc", "ch_methname_sect(header, name_dict) ch_symtab(header, name_dict) ori_dir, filename = os.path.split(macho_file) if output_dir", "= command_tuple[0] sect = tmp_sect if sect is None: raise(\"Can't", "' + key.encode('utf-8') + b']', b' ' + value.encode('utf-8') +", "def replace_methname(macho_file, methname_json, output_dir): \"\"\" Map method names in Mach-O", "+ b']', b' ' + value.encode('utf-8') + b']') if is_prefix:", "header.mod_dict[lc] = [data] commands[idx] = (lc, cmd, data) return raise(\"Can't", "if sect is None: raise(\"Can't find __objc_methname section\") sect.section_data =", "+ method_bytes for key, value in name_dict.items(): if len(key) !=", "method_bytes.startswith(empty_byte): is_prefix = True method_bytes = empty_byte + method_bytes for", "command_tuple[0] sect = tmp_sect if sect is None: raise(\"Can't find", "seg = command_tuple[1] data = command_tuple[2] if hasattr(seg, 'segname') and", "copy2 from shutil import SameFileError class ReplaceType(Enum): objc_methname = 1", "exist file \" + methname_json) if output_dir is not None", "copy2(macho_file, output_dir) except SameFileError: pass with open(output, 'r+b') as fp:", "commands = header.commands lc = None sect = None for", "False empty_byte = b'\\x00' if not method_bytes.startswith(empty_byte): is_prefix = True", "\" + methname_json) if output_dir is not None and not", "from macholib import MachO from macholib import mach_o from shutil", "macho.write(fp) os.chmod(output, 0o755) def main(): replace_methname(sys.argv[0], sys.argv[1], sys.argv[2]) if __name__", "except SameFileError: pass with open(output, 'r+b') as fp: macho.write(fp) os.chmod(output,", "enum import Enum from .mach_o import LC_SYMTAB from macholib import", "elif type == ReplaceType.symbol_table: method_bytes = method_bytes.replace( b' ' +", "= command_tuple[2] if lc.cmd == LC_SYMTAB: data = replace_in_bytes(data, name_dict,", "key, value in name_dict.items(): if len(key) != len(value): raise(\"replace method", "\"\"\" if not os.path.isfile(macho_file): raise(\"passing not exist file \" +", "seg.segname.rstrip(b'\\x00') == b'__TEXT': for tmp_sect in data: if tmp_sect.sectname.rstrip(b'\\x00') ==", "Mach-O file with the JSON file \"\"\" if not os.path.isfile(macho_file):", "\" + value) if type == ReplaceType.objc_methname: method_bytes = method_bytes.replace(", "= empty_byte + method_bytes for key, value in name_dict.items(): if", "from shutil import SameFileError class ReplaceType(Enum): objc_methname = 1 symbol_table", "= (lc, cmd, data) return raise(\"Can't find LC_SYMTAB\") def replace_methname(macho_file,", "header.mod_dict[lc] = [sect] def ch_symtab(header, name_dict): commands = header.commands for", "Map method names in Mach-O file with the JSON file", "dst: \" + value) if type == ReplaceType.objc_methname: method_bytes =", "lc = None sect = None for _, command_tuple in", "= replace_in_bytes(data, name_dict, ReplaceType.symbol_table) header.mod_dict[lc] = [data] commands[idx] = (lc,", "value.encode('utf-8') + b']') if is_prefix: method_bytes = method_bytes.replace(empty_byte, b'', 1)", "output_dir): \"\"\" Map method names in Mach-O file with the", "if hasattr(seg, 'segname') and seg.segname.rstrip(b'\\x00') == b'__TEXT': for tmp_sect in", "b'\\x00' if not method_bytes.startswith(empty_byte): is_prefix = True method_bytes = empty_byte", "sect.section_data = replace_in_bytes( sect.section_data, name_dict, ReplaceType.objc_methname) header.mod_dict[lc] = [sect] def", "enumerate(commands): lc = command_tuple[0] cmd = command_tuple[1] data = command_tuple[2]", "header.commands for idx, command_tuple in enumerate(commands): lc = command_tuple[0] cmd", "0o755) def main(): replace_methname(sys.argv[0], sys.argv[1], sys.argv[2]) if __name__ == '__main__':", "LC_SYMTAB\") def replace_methname(macho_file, methname_json, output_dir): \"\"\" Map method names in", "os.path.isdir(output_dir): raise(\"passing not exist dir \" + output_dir) macho =", "methname_json, output_dir): \"\"\" Map method names in Mach-O file with", "ori: \" + key + \", dst: \" + value)", "def ch_methname_sect(header, name_dict): commands = header.commands lc = None sect", "class ReplaceType(Enum): objc_methname = 1 symbol_table = 2 def replace_in_bytes(method_bytes,", "def main(): replace_methname(sys.argv[0], sys.argv[1], sys.argv[2]) if __name__ == '__main__': main()", "file \" + methname_json) if output_dir is not None and", "method_bytes = method_bytes.replace(empty_byte, b'', 1) return method_bytes def ch_methname_sect(header, name_dict):", "command_tuple[1] data = command_tuple[2] if lc.cmd == LC_SYMTAB: data =", "= 1 symbol_table = 2 def replace_in_bytes(method_bytes, name_dict, type): is_prefix", "data) return raise(\"Can't find LC_SYMTAB\") def replace_methname(macho_file, methname_json, output_dir): \"\"\"", "+ \", dst: \" + value) if type == ReplaceType.objc_methname:", "= [sect] def ch_symtab(header, name_dict): commands = header.commands for idx,", "'segname') and seg.segname.rstrip(b'\\x00') == b'__TEXT': for tmp_sect in data: if", "dir \" + output_dir) macho = MachO.MachO(macho_file) name_dict = None", "SameFileError: pass with open(output, 'r+b') as fp: macho.write(fp) os.chmod(output, 0o755)", "SameFileError class ReplaceType(Enum): objc_methname = 1 symbol_table = 2 def", "is not None and not os.path.isdir(output_dir): raise(\"passing not exist dir", "= None with open(methname_json) as json_file: name_dict = json.load(json_file) for", "shutil import copy2 from shutil import SameFileError class ReplaceType(Enum): objc_methname", "import LC_SYMTAB from macholib import MachO from macholib import mach_o", "+ macho_file) if not os.path.isfile(methname_json): raise(\"passing not exist file \"", "different length may break the mach-o file, ori: \" +", "import Enum from .mach_o import LC_SYMTAB from macholib import MachO", "name with different length may break the mach-o file, ori:", "(lc, cmd, data) return raise(\"Can't find LC_SYMTAB\") def replace_methname(macho_file, methname_json,", "from .mach_o import LC_SYMTAB from macholib import MachO from macholib", "== ReplaceType.objc_methname: method_bytes = method_bytes.replace( empty_byte + key.encode('utf-8') + empty_byte,", "LC_SYMTAB from macholib import MachO from macholib import mach_o from", "file \"\"\" if not os.path.isfile(macho_file): raise(\"passing not exist file \"", "output_dir is None: output_dir = ori_dir output = os.path.join(output_dir, filename)", "+ value) if type == ReplaceType.objc_methname: method_bytes = method_bytes.replace( empty_byte", "__objc_methname section\") sect.section_data = replace_in_bytes( sect.section_data, name_dict, ReplaceType.objc_methname) header.mod_dict[lc] =", "header in macho.headers: ch_methname_sect(header, name_dict) ch_symtab(header, name_dict) ori_dir, filename =", "ReplaceType.symbol_table) header.mod_dict[lc] = [data] commands[idx] = (lc, cmd, data) return", "= os.path.split(macho_file) if output_dir is None: output_dir = ori_dir output", "not exist file \" + methname_json) if output_dir is not", "import MachO from macholib import mach_o from shutil import copy2", "if output_dir is not None and not os.path.isdir(output_dir): raise(\"passing not", "+ output_dir) macho = MachO.MachO(macho_file) name_dict = None with open(methname_json)", "idx, command_tuple in enumerate(commands): lc = command_tuple[0] cmd = command_tuple[1]", "cmd = command_tuple[1] data = command_tuple[2] if lc.cmd == LC_SYMTAB:", "b'__objc_methname': lc = command_tuple[0] sect = tmp_sect if sect is", "commands = header.commands for idx, command_tuple in enumerate(commands): lc =", "macho.headers: ch_methname_sect(header, name_dict) ch_symtab(header, name_dict) ori_dir, filename = os.path.split(macho_file) if", "= method_bytes.replace(empty_byte, b'', 1) return method_bytes def ch_methname_sect(header, name_dict): commands", "and not os.path.isdir(output_dir): raise(\"passing not exist dir \" + output_dir)", "= header.commands lc = None sect = None for _,", "import json from enum import Enum from .mach_o import LC_SYMTAB", "= False empty_byte = b'\\x00' if not method_bytes.startswith(empty_byte): is_prefix =", "JSON file \"\"\" if not os.path.isfile(macho_file): raise(\"passing not exist file", "if type == ReplaceType.objc_methname: method_bytes = method_bytes.replace( empty_byte + key.encode('utf-8')", "raise(\"Can't find __objc_methname section\") sect.section_data = replace_in_bytes( sect.section_data, name_dict, ReplaceType.objc_methname)", "ch_methname_sect(header, name_dict): commands = header.commands lc = None sect =", "+ key + \", dst: \" + value) if type", "header.commands lc = None sect = None for _, command_tuple", "= method_bytes.replace( b' ' + key.encode('utf-8') + b']', b' '", "b' ' + value.encode('utf-8') + b']') if is_prefix: method_bytes =", "exist dir \" + output_dir) macho = MachO.MachO(macho_file) name_dict =", "symbol_table = 2 def replace_in_bytes(method_bytes, name_dict, type): is_prefix = False", "name_dict = None with open(methname_json) as json_file: name_dict = json.load(json_file)", "1) return method_bytes def ch_methname_sect(header, name_dict): commands = header.commands lc", "filename) try: copy2(macho_file, output_dir) except SameFileError: pass with open(output, 'r+b')", "b'__TEXT': for tmp_sect in data: if tmp_sect.sectname.rstrip(b'\\x00') == b'__objc_methname': lc", "method name with different length may break the mach-o file,", "\" + key + \", dst: \" + value) if", "json.load(json_file) for header in macho.headers: ch_methname_sect(header, name_dict) ch_symtab(header, name_dict) ori_dir,", "os.path.join(output_dir, filename) try: copy2(macho_file, output_dir) except SameFileError: pass with open(output,", "ReplaceType(Enum): objc_methname = 1 symbol_table = 2 def replace_in_bytes(method_bytes, name_dict,", "= MachO.MachO(macho_file) name_dict = None with open(methname_json) as json_file: name_dict", "None with open(methname_json) as json_file: name_dict = json.load(json_file) for header", "value) if type == ReplaceType.objc_methname: method_bytes = method_bytes.replace( empty_byte +", "os.chmod(output, 0o755) def main(): replace_methname(sys.argv[0], sys.argv[1], sys.argv[2]) if __name__ ==", "return raise(\"Can't find LC_SYMTAB\") def replace_methname(macho_file, methname_json, output_dir): \"\"\" Map", "commands[idx] = (lc, cmd, data) return raise(\"Can't find LC_SYMTAB\") def", "\", dst: \" + value) if type == ReplaceType.objc_methname: method_bytes", "fp: macho.write(fp) os.chmod(output, 0o755) def main(): replace_methname(sys.argv[0], sys.argv[1], sys.argv[2]) if", "import SameFileError class ReplaceType(Enum): objc_methname = 1 symbol_table = 2", "= json.load(json_file) for header in macho.headers: ch_methname_sect(header, name_dict) ch_symtab(header, name_dict)", "mach-o file, ori: \" + key + \", dst: \"", "is_prefix: method_bytes = method_bytes.replace(empty_byte, b'', 1) return method_bytes def ch_methname_sect(header,", "[data] commands[idx] = (lc, cmd, data) return raise(\"Can't find LC_SYMTAB\")", "name_dict): commands = header.commands lc = None sect = None", "def replace_in_bytes(method_bytes, name_dict, type): is_prefix = False empty_byte = b'\\x00'", "lc = command_tuple[0] cmd = command_tuple[1] data = command_tuple[2] if", "= b'\\x00' if not method_bytes.startswith(empty_byte): is_prefix = True method_bytes =", "file, ori: \" + key + \", dst: \" +", "b']', b' ' + value.encode('utf-8') + b']') if is_prefix: method_bytes", "name_dict, ReplaceType.symbol_table) header.mod_dict[lc] = [data] commands[idx] = (lc, cmd, data)", "with open(output, 'r+b') as fp: macho.write(fp) os.chmod(output, 0o755) def main():", "if is_prefix: method_bytes = method_bytes.replace(empty_byte, b'', 1) return method_bytes def", "== LC_SYMTAB: data = replace_in_bytes(data, name_dict, ReplaceType.symbol_table) header.mod_dict[lc] = [data]", "not os.path.isfile(macho_file): raise(\"passing not exist file \" + macho_file) if", "ReplaceType.objc_methname) header.mod_dict[lc] = [sect] def ch_symtab(header, name_dict): commands = header.commands", "import copy2 from shutil import SameFileError class ReplaceType(Enum): objc_methname =", "sect.section_data, name_dict, ReplaceType.objc_methname) header.mod_dict[lc] = [sect] def ch_symtab(header, name_dict): commands", "import sys import os import json from enum import Enum", "key + \", dst: \" + value) if type ==", "in enumerate(commands): lc = command_tuple[0] cmd = command_tuple[1] data =", "in data: if tmp_sect.sectname.rstrip(b'\\x00') == b'__objc_methname': lc = command_tuple[0] sect", "LC_SYMTAB: data = replace_in_bytes(data, name_dict, ReplaceType.symbol_table) header.mod_dict[lc] = [data] commands[idx]", "True method_bytes = empty_byte + method_bytes for key, value in", "name_dict = json.load(json_file) for header in macho.headers: ch_methname_sect(header, name_dict) ch_symtab(header,", "method_bytes = method_bytes.replace( b' ' + key.encode('utf-8') + b']', b'", "not os.path.isfile(methname_json): raise(\"passing not exist file \" + methname_json) if", "is None: raise(\"Can't find __objc_methname section\") sect.section_data = replace_in_bytes( sect.section_data,", "in enumerate(commands): seg = command_tuple[1] data = command_tuple[2] if hasattr(seg,", "for _, command_tuple in enumerate(commands): seg = command_tuple[1] data =", "key.encode('utf-8') + b']', b' ' + value.encode('utf-8') + b']') if", "type): is_prefix = False empty_byte = b'\\x00' if not method_bytes.startswith(empty_byte):", "ReplaceType.objc_methname: method_bytes = method_bytes.replace( empty_byte + key.encode('utf-8') + empty_byte, empty_byte", "b' ' + key.encode('utf-8') + b']', b' ' + value.encode('utf-8')", "+ empty_byte, empty_byte + value.encode('utf-8') + empty_byte) elif type ==", "raise(\"passing not exist file \" + methname_json) if output_dir is", "cmd, data) return raise(\"Can't find LC_SYMTAB\") def replace_methname(macho_file, methname_json, output_dir):", "= method_bytes.replace( empty_byte + key.encode('utf-8') + empty_byte, empty_byte + value.encode('utf-8')", "shutil import SameFileError class ReplaceType(Enum): objc_methname = 1 symbol_table =", "== b'__objc_methname': lc = command_tuple[0] sect = tmp_sect if sect", "pass with open(output, 'r+b') as fp: macho.write(fp) os.chmod(output, 0o755) def", "macho = MachO.MachO(macho_file) name_dict = None with open(methname_json) as json_file:", "\" + macho_file) if not os.path.isfile(methname_json): raise(\"passing not exist file", "tmp_sect if sect is None: raise(\"Can't find __objc_methname section\") sect.section_data", "import mach_o from shutil import copy2 from shutil import SameFileError", "if not os.path.isfile(macho_file): raise(\"passing not exist file \" + macho_file)", "replace_methname(macho_file, methname_json, output_dir): \"\"\" Map method names in Mach-O file", "[sect] def ch_symtab(header, name_dict): commands = header.commands for idx, command_tuple", "method_bytes.replace( b' ' + key.encode('utf-8') + b']', b' ' +", "b'', 1) return method_bytes def ch_methname_sect(header, name_dict): commands = header.commands", "from macholib import mach_o from shutil import copy2 from shutil", "= tmp_sect if sect is None: raise(\"Can't find __objc_methname section\")", "try: copy2(macho_file, output_dir) except SameFileError: pass with open(output, 'r+b') as", "macholib import MachO from macholib import mach_o from shutil import", "the JSON file \"\"\" if not os.path.isfile(macho_file): raise(\"passing not exist", "= 2 def replace_in_bytes(method_bytes, name_dict, type): is_prefix = False empty_byte", "for tmp_sect in data: if tmp_sect.sectname.rstrip(b'\\x00') == b'__objc_methname': lc =", "os.path.isfile(macho_file): raise(\"passing not exist file \" + macho_file) if not", "method_bytes for key, value in name_dict.items(): if len(key) != len(value):", "name_dict) ch_symtab(header, name_dict) ori_dir, filename = os.path.split(macho_file) if output_dir is", "replace_in_bytes(data, name_dict, ReplaceType.symbol_table) header.mod_dict[lc] = [data] commands[idx] = (lc, cmd,", "not os.path.isdir(output_dir): raise(\"passing not exist dir \" + output_dir) macho", "not None and not os.path.isdir(output_dir): raise(\"passing not exist dir \"", "= ori_dir output = os.path.join(output_dir, filename) try: copy2(macho_file, output_dir) except", "name_dict) ori_dir, filename = os.path.split(macho_file) if output_dir is None: output_dir", "replace_in_bytes( sect.section_data, name_dict, ReplaceType.objc_methname) header.mod_dict[lc] = [sect] def ch_symtab(header, name_dict):", "ch_symtab(header, name_dict): commands = header.commands for idx, command_tuple in enumerate(commands):", "from shutil import copy2 from shutil import SameFileError class ReplaceType(Enum):", "command_tuple[2] if hasattr(seg, 'segname') and seg.segname.rstrip(b'\\x00') == b'__TEXT': for tmp_sect", "methname_json) if output_dir is not None and not os.path.isdir(output_dir): raise(\"passing", "sect = tmp_sect if sect is None: raise(\"Can't find __objc_methname", "+ value.encode('utf-8') + b']') if is_prefix: method_bytes = method_bytes.replace(empty_byte, b'',", "ori_dir output = os.path.join(output_dir, filename) try: copy2(macho_file, output_dir) except SameFileError:", "+ key.encode('utf-8') + b']', b' ' + value.encode('utf-8') + b']')", "= header.commands for idx, command_tuple in enumerate(commands): lc = command_tuple[0]", "if lc.cmd == LC_SYMTAB: data = replace_in_bytes(data, name_dict, ReplaceType.symbol_table) header.mod_dict[lc]", "value.encode('utf-8') + empty_byte) elif type == ReplaceType.symbol_table: method_bytes = method_bytes.replace(", "sect = None for _, command_tuple in enumerate(commands): seg =", "with open(methname_json) as json_file: name_dict = json.load(json_file) for header in", "json_file: name_dict = json.load(json_file) for header in macho.headers: ch_methname_sect(header, name_dict)", "output_dir) macho = MachO.MachO(macho_file) name_dict = None with open(methname_json) as", "command_tuple in enumerate(commands): seg = command_tuple[1] data = command_tuple[2] if", "command_tuple in enumerate(commands): lc = command_tuple[0] cmd = command_tuple[1] data", "empty_byte = b'\\x00' if not method_bytes.startswith(empty_byte): is_prefix = True method_bytes", "is_prefix = True method_bytes = empty_byte + method_bytes for key,", "hasattr(seg, 'segname') and seg.segname.rstrip(b'\\x00') == b'__TEXT': for tmp_sect in data:", "exist file \" + macho_file) if not os.path.isfile(methname_json): raise(\"passing not", "1 symbol_table = 2 def replace_in_bytes(method_bytes, name_dict, type): is_prefix =", "= command_tuple[2] if hasattr(seg, 'segname') and seg.segname.rstrip(b'\\x00') == b'__TEXT': for", "Enum from .mach_o import LC_SYMTAB from macholib import MachO from", "= replace_in_bytes( sect.section_data, name_dict, ReplaceType.objc_methname) header.mod_dict[lc] = [sect] def ch_symtab(header,", "b']') if is_prefix: method_bytes = method_bytes.replace(empty_byte, b'', 1) return method_bytes", "may break the mach-o file, ori: \" + key +", "section\") sect.section_data = replace_in_bytes( sect.section_data, name_dict, ReplaceType.objc_methname) header.mod_dict[lc] = [sect]", "command_tuple[2] if lc.cmd == LC_SYMTAB: data = replace_in_bytes(data, name_dict, ReplaceType.symbol_table)", "the mach-o file, ori: \" + key + \", dst:", "data = replace_in_bytes(data, name_dict, ReplaceType.symbol_table) header.mod_dict[lc] = [data] commands[idx] =", "+ empty_byte) elif type == ReplaceType.symbol_table: method_bytes = method_bytes.replace( b'", "empty_byte + method_bytes for key, value in name_dict.items(): if len(key)", "if len(key) != len(value): raise(\"replace method name with different length", "ch_symtab(header, name_dict) ori_dir, filename = os.path.split(macho_file) if output_dir is None:", "data = command_tuple[2] if hasattr(seg, 'segname') and seg.segname.rstrip(b'\\x00') == b'__TEXT':", "file with the JSON file \"\"\" if not os.path.isfile(macho_file): raise(\"passing", "type == ReplaceType.objc_methname: method_bytes = method_bytes.replace( empty_byte + key.encode('utf-8') +", "= command_tuple[1] data = command_tuple[2] if hasattr(seg, 'segname') and seg.segname.rstrip(b'\\x00')", "as json_file: name_dict = json.load(json_file) for header in macho.headers: ch_methname_sect(header,", "None sect = None for _, command_tuple in enumerate(commands): seg", "and seg.segname.rstrip(b'\\x00') == b'__TEXT': for tmp_sect in data: if tmp_sect.sectname.rstrip(b'\\x00')", "= None for _, command_tuple in enumerate(commands): seg = command_tuple[1]", "== b'__TEXT': for tmp_sect in data: if tmp_sect.sectname.rstrip(b'\\x00') == b'__objc_methname':", "' + value.encode('utf-8') + b']') if is_prefix: method_bytes = method_bytes.replace(empty_byte,", ".mach_o import LC_SYMTAB from macholib import MachO from macholib import", "+ b']') if is_prefix: method_bytes = method_bytes.replace(empty_byte, b'', 1) return", "return method_bytes def ch_methname_sect(header, name_dict): commands = header.commands lc =", "output_dir = ori_dir output = os.path.join(output_dir, filename) try: copy2(macho_file, output_dir)", "raise(\"passing not exist file \" + macho_file) if not os.path.isfile(methname_json):", "replace_in_bytes(method_bytes, name_dict, type): is_prefix = False empty_byte = b'\\x00' if", "find LC_SYMTAB\") def replace_methname(macho_file, methname_json, output_dir): \"\"\" Map method names", "+ key.encode('utf-8') + empty_byte, empty_byte + value.encode('utf-8') + empty_byte) elif", "empty_byte + value.encode('utf-8') + empty_byte) elif type == ReplaceType.symbol_table: method_bytes", "is_prefix = False empty_byte = b'\\x00' if not method_bytes.startswith(empty_byte): is_prefix", "empty_byte + key.encode('utf-8') + empty_byte, empty_byte + value.encode('utf-8') + empty_byte)", "len(value): raise(\"replace method name with different length may break the", "\" + output_dir) macho = MachO.MachO(macho_file) name_dict = None with", "method names in Mach-O file with the JSON file \"\"\"", "\"\"\" Map method names in Mach-O file with the JSON", "command_tuple[0] cmd = command_tuple[1] data = command_tuple[2] if lc.cmd ==", "lc.cmd == LC_SYMTAB: data = replace_in_bytes(data, name_dict, ReplaceType.symbol_table) header.mod_dict[lc] =", "type == ReplaceType.symbol_table: method_bytes = method_bytes.replace( b' ' + key.encode('utf-8')", "= os.path.join(output_dir, filename) try: copy2(macho_file, output_dir) except SameFileError: pass with", "method_bytes.replace(empty_byte, b'', 1) return method_bytes def ch_methname_sect(header, name_dict): commands =", "sect is None: raise(\"Can't find __objc_methname section\") sect.section_data = replace_in_bytes(", "empty_byte) elif type == ReplaceType.symbol_table: method_bytes = method_bytes.replace( b' '", "data = command_tuple[2] if lc.cmd == LC_SYMTAB: data = replace_in_bytes(data,", "def ch_symtab(header, name_dict): commands = header.commands for idx, command_tuple in", "= True method_bytes = empty_byte + method_bytes for key, value", "None for _, command_tuple in enumerate(commands): seg = command_tuple[1] data", "value in name_dict.items(): if len(key) != len(value): raise(\"replace method name", "= command_tuple[1] data = command_tuple[2] if lc.cmd == LC_SYMTAB: data", "= None sect = None for _, command_tuple in enumerate(commands):", "file \" + macho_file) if not os.path.isfile(methname_json): raise(\"passing not exist", "is None: output_dir = ori_dir output = os.path.join(output_dir, filename) try:", "None and not os.path.isdir(output_dir): raise(\"passing not exist dir \" +", "None: raise(\"Can't find __objc_methname section\") sect.section_data = replace_in_bytes( sect.section_data, name_dict,", "+ methname_json) if output_dir is not None and not os.path.isdir(output_dir):", "sys import os import json from enum import Enum from", "in Mach-O file with the JSON file \"\"\" if not", "tmp_sect.sectname.rstrip(b'\\x00') == b'__objc_methname': lc = command_tuple[0] sect = tmp_sect if", "enumerate(commands): seg = command_tuple[1] data = command_tuple[2] if hasattr(seg, 'segname')", "empty_byte, empty_byte + value.encode('utf-8') + empty_byte) elif type == ReplaceType.symbol_table:", "if not os.path.isfile(methname_json): raise(\"passing not exist file \" + methname_json)", "key.encode('utf-8') + empty_byte, empty_byte + value.encode('utf-8') + empty_byte) elif type", "length may break the mach-o file, ori: \" + key", "MachO from macholib import mach_o from shutil import copy2 from", "in name_dict.items(): if len(key) != len(value): raise(\"replace method name with", "!= len(value): raise(\"replace method name with different length may break", "raise(\"Can't find LC_SYMTAB\") def replace_methname(macho_file, methname_json, output_dir): \"\"\" Map method", "2 def replace_in_bytes(method_bytes, name_dict, type): is_prefix = False empty_byte =", "names in Mach-O file with the JSON file \"\"\" if", "mach_o from shutil import copy2 from shutil import SameFileError class", "name_dict, type): is_prefix = False empty_byte = b'\\x00' if not", "for header in macho.headers: ch_methname_sect(header, name_dict) ch_symtab(header, name_dict) ori_dir, filename", "raise(\"passing not exist dir \" + output_dir) macho = MachO.MachO(macho_file)", "import os import json from enum import Enum from .mach_o", "data: if tmp_sect.sectname.rstrip(b'\\x00') == b'__objc_methname': lc = command_tuple[0] sect =", "len(key) != len(value): raise(\"replace method name with different length may", "raise(\"replace method name with different length may break the mach-o", "os import json from enum import Enum from .mach_o import", "lc = command_tuple[0] sect = tmp_sect if sect is None:", "= [data] commands[idx] = (lc, cmd, data) return raise(\"Can't find", "if not method_bytes.startswith(empty_byte): is_prefix = True method_bytes = empty_byte +", "method_bytes = empty_byte + method_bytes for key, value in name_dict.items():", "with the JSON file \"\"\" if not os.path.isfile(macho_file): raise(\"passing not", "macholib import mach_o from shutil import copy2 from shutil import", "name_dict.items(): if len(key) != len(value): raise(\"replace method name with different", "as fp: macho.write(fp) os.chmod(output, 0o755) def main(): replace_methname(sys.argv[0], sys.argv[1], sys.argv[2])", "macho_file) if not os.path.isfile(methname_json): raise(\"passing not exist file \" +", "not exist dir \" + output_dir) macho = MachO.MachO(macho_file) name_dict", "if output_dir is None: output_dir = ori_dir output = os.path.join(output_dir,", "ReplaceType.symbol_table: method_bytes = method_bytes.replace( b' ' + key.encode('utf-8') + b']',", "None: output_dir = ori_dir output = os.path.join(output_dir, filename) try: copy2(macho_file,", "objc_methname = 1 symbol_table = 2 def replace_in_bytes(method_bytes, name_dict, type):", "'r+b') as fp: macho.write(fp) os.chmod(output, 0o755) def main(): replace_methname(sys.argv[0], sys.argv[1],", "command_tuple[1] data = command_tuple[2] if hasattr(seg, 'segname') and seg.segname.rstrip(b'\\x00') ==", "method_bytes def ch_methname_sect(header, name_dict): commands = header.commands lc = None", "json from enum import Enum from .mach_o import LC_SYMTAB from", "+ value.encode('utf-8') + empty_byte) elif type == ReplaceType.symbol_table: method_bytes =", "ori_dir, filename = os.path.split(macho_file) if output_dir is None: output_dir =", "in macho.headers: ch_methname_sect(header, name_dict) ch_symtab(header, name_dict) ori_dir, filename = os.path.split(macho_file)", "for idx, command_tuple in enumerate(commands): lc = command_tuple[0] cmd =", "not method_bytes.startswith(empty_byte): is_prefix = True method_bytes = empty_byte + method_bytes" ]
[ "def sd1(rr): sdnn = np.std(rr) return math.sqrt(0.5 * sdnn *", "import math import numpy as np def sd1(rr): sdnn =", "import numpy as np def sd1(rr): sdnn = np.std(rr) return", "<gh_stars>0 #!/usr/bin/env python import math import numpy as np def", "np def sd1(rr): sdnn = np.std(rr) return math.sqrt(0.5 * sdnn", "sd1(rr): sdnn = np.std(rr) return math.sqrt(0.5 * sdnn * sdnn)", "python import math import numpy as np def sd1(rr): sdnn", "as np def sd1(rr): sdnn = np.std(rr) return math.sqrt(0.5 *", "numpy as np def sd1(rr): sdnn = np.std(rr) return math.sqrt(0.5", "#!/usr/bin/env python import math import numpy as np def sd1(rr):", "math import numpy as np def sd1(rr): sdnn = np.std(rr)" ]
[ "obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0", "LLC # # Licensed under the Apache License, Version 2.0", "2021 Google LLC # # Licensed under the Apache License,", "flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service =", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "2.0 (the \"License\"); # you may not use this file", "agreed to in writing, software # distributed under the License", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Unless required by applicable law or agreed to in writing,", "tools.run_flow(flow, store) service = discovery.build('forms', 'v1beta', http=creds.authorize( Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False)", "if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds", "the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "distributed under the License is distributed on an \"AS IS\"", "from httplib2 import Http from oauth2client import client, file, tools", "= '<YOUR_FORM_ID>' watch_id = '<YOUR_WATCH_ID>' # Print JSON response after", "creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service", "the specific language governing permissions and # limitations under the", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "# https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 #", "import discovery from httplib2 import Http from oauth2client import client,", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", "Print JSON response after deleting a form watch result =", "except in compliance with the License. # You may obtain", "creds = tools.run_flow(flow, store) service = discovery.build('forms', 'v1beta', http=creds.authorize( Http()),", "from apiclient import discovery from httplib2 import Http from oauth2client", "SCOPES = \"https://www.googleapis.com/auth/drive\" API_KEY = \"<YOUR_API_KEY>\" DISCOVERY_DOC = f\"https://forms.googleapis.com/$discovery/rest?version=v1beta&key={API_KEY}&labels=FORMS_BETA_TESTERS\" store", "import client, file, tools SCOPES = \"https://www.googleapis.com/auth/drive\" API_KEY = \"<YOUR_API_KEY>\"", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "Copyright 2021 Google LLC # # Licensed under the Apache", "client, file, tools SCOPES = \"https://www.googleapis.com/auth/drive\" API_KEY = \"<YOUR_API_KEY>\" DISCOVERY_DOC", "client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = discovery.build('forms', 'v1beta',", "not use this file except in compliance with the License.", "copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # #", "Google LLC # # Licensed under the Apache License, Version", "writing, software # distributed under the License is distributed on", "'<YOUR_WATCH_ID>' # Print JSON response after deleting a form watch", "in writing, software # distributed under the License is distributed", "License. # [START forms_delete_watch] from __future__ import print_function from apiclient", "you may not use this file except in compliance with", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "after deleting a form watch result = service.forms().watches().delete(formId=form_id, watchId=watch_id).execute() print(result)", "f\"https://forms.googleapis.com/$discovery/rest?version=v1beta&key={API_KEY}&labels=FORMS_BETA_TESTERS\" store = file.Storage('credentials.json') creds = None if not creds", "store) service = discovery.build('forms', 'v1beta', http=creds.authorize( Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) form_id", "use this file except in compliance with the License. #", "import Http from oauth2client import client, file, tools SCOPES =", "file.Storage('credentials.json') creds = None if not creds or creds.invalid: flow", "deleting a form watch result = service.forms().watches().delete(formId=form_id, watchId=watch_id).execute() print(result) #", "under the License. # [START forms_delete_watch] from __future__ import print_function", "Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) form_id = '<YOUR_FORM_ID>' watch_id = '<YOUR_WATCH_ID>' #", "CONDITIONS OF ANY KIND, either express or implied. # See", "the License. # [START forms_delete_watch] from __future__ import print_function from", "API_KEY = \"<YOUR_API_KEY>\" DISCOVERY_DOC = f\"https://forms.googleapis.com/$discovery/rest?version=v1beta&key={API_KEY}&labels=FORMS_BETA_TESTERS\" store = file.Storage('credentials.json') creds", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "forms_delete_watch] from __future__ import print_function from apiclient import discovery from", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "from oauth2client import client, file, tools SCOPES = \"https://www.googleapis.com/auth/drive\" API_KEY", "of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless", "# You may obtain a copy of the License at", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "# Print JSON response after deleting a form watch result", "# Copyright 2021 Google LLC # # Licensed under the", "= tools.run_flow(flow, store) service = discovery.build('forms', 'v1beta', http=creds.authorize( Http()), discoveryServiceUrl=DISCOVERY_DOC,", "under the License is distributed on an \"AS IS\" BASIS,", "limitations under the License. # [START forms_delete_watch] from __future__ import", "discovery.build('forms', 'v1beta', http=creds.authorize( Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) form_id = '<YOUR_FORM_ID>' watch_id", "License for the specific language governing permissions and # limitations", "discovery from httplib2 import Http from oauth2client import client, file,", "governing permissions and # limitations under the License. # [START", "'v1beta', http=creds.authorize( Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) form_id = '<YOUR_FORM_ID>' watch_id =", "httplib2 import Http from oauth2client import client, file, tools SCOPES", "form_id = '<YOUR_FORM_ID>' watch_id = '<YOUR_WATCH_ID>' # Print JSON response", "SCOPES) creds = tools.run_flow(flow, store) service = discovery.build('forms', 'v1beta', http=creds.authorize(", "file, tools SCOPES = \"https://www.googleapis.com/auth/drive\" API_KEY = \"<YOUR_API_KEY>\" DISCOVERY_DOC =", "= '<YOUR_WATCH_ID>' # Print JSON response after deleting a form", "the License for the specific language governing permissions and #", "= discovery.build('forms', 'v1beta', http=creds.authorize( Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) form_id = '<YOUR_FORM_ID>'", "discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) form_id = '<YOUR_FORM_ID>' watch_id = '<YOUR_WATCH_ID>' # Print", "http=creds.authorize( Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) form_id = '<YOUR_FORM_ID>' watch_id = '<YOUR_WATCH_ID>'", "form watch result = service.forms().watches().delete(formId=form_id, watchId=watch_id).execute() print(result) # [END forms_delete_watch]", "(the \"License\"); # you may not use this file except", "Apache License, Version 2.0 (the \"License\"); # you may not", "# you may not use this file except in compliance", "either express or implied. # See the License for the", "creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow,", "License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "OR CONDITIONS OF ANY KIND, either express or implied. #", "= \"https://www.googleapis.com/auth/drive\" API_KEY = \"<YOUR_API_KEY>\" DISCOVERY_DOC = f\"https://forms.googleapis.com/$discovery/rest?version=v1beta&key={API_KEY}&labels=FORMS_BETA_TESTERS\" store =", "None if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)", "# limitations under the License. # [START forms_delete_watch] from __future__", "the License is distributed on an \"AS IS\" BASIS, #", "in compliance with the License. # You may obtain a", "software # distributed under the License is distributed on an", "DISCOVERY_DOC = f\"https://forms.googleapis.com/$discovery/rest?version=v1beta&key={API_KEY}&labels=FORMS_BETA_TESTERS\" store = file.Storage('credentials.json') creds = None if", "tools SCOPES = \"https://www.googleapis.com/auth/drive\" API_KEY = \"<YOUR_API_KEY>\" DISCOVERY_DOC = f\"https://forms.googleapis.com/$discovery/rest?version=v1beta&key={API_KEY}&labels=FORMS_BETA_TESTERS\"", "JSON response after deleting a form watch result = service.forms().watches().delete(formId=form_id,", "# # Unless required by applicable law or agreed to", "Version 2.0 (the \"License\"); # you may not use this", "law or agreed to in writing, software # distributed under", "import print_function from apiclient import discovery from httplib2 import Http", "store = file.Storage('credentials.json') creds = None if not creds or", "watch_id = '<YOUR_WATCH_ID>' # Print JSON response after deleting a", "= None if not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json',", "static_discovery=False) form_id = '<YOUR_FORM_ID>' watch_id = '<YOUR_WATCH_ID>' # Print JSON", "= file.Storage('credentials.json') creds = None if not creds or creds.invalid:", "implied. # See the License for the specific language governing", "under the Apache License, Version 2.0 (the \"License\"); # you", "= client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store) service = discovery.build('forms',", "\"License\"); # you may not use this file except in", "service = discovery.build('forms', 'v1beta', http=creds.authorize( Http()), discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) form_id =", "creds = None if not creds or creds.invalid: flow =", "[START forms_delete_watch] from __future__ import print_function from apiclient import discovery", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "# # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "= \"<YOUR_API_KEY>\" DISCOVERY_DOC = f\"https://forms.googleapis.com/$discovery/rest?version=v1beta&key={API_KEY}&labels=FORMS_BETA_TESTERS\" store = file.Storage('credentials.json') creds =", "not creds or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds =", "= f\"https://forms.googleapis.com/$discovery/rest?version=v1beta&key={API_KEY}&labels=FORMS_BETA_TESTERS\" store = file.Storage('credentials.json') creds = None if not", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "# [START forms_delete_watch] from __future__ import print_function from apiclient import", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "'<YOUR_FORM_ID>' watch_id = '<YOUR_WATCH_ID>' # Print JSON response after deleting", "the License. # You may obtain a copy of the", "for the specific language governing permissions and # limitations under", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "to in writing, software # distributed under the License is", "at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "response after deleting a form watch result = service.forms().watches().delete(formId=form_id, watchId=watch_id).execute()", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "# See the License for the specific language governing permissions", "Http from oauth2client import client, file, tools SCOPES = \"https://www.googleapis.com/auth/drive\"", "permissions and # limitations under the License. # [START forms_delete_watch]", "You may obtain a copy of the License at #", "print_function from apiclient import discovery from httplib2 import Http from", "language governing permissions and # limitations under the License. #", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "a form watch result = service.forms().watches().delete(formId=form_id, watchId=watch_id).execute() print(result) # [END", "from __future__ import print_function from apiclient import discovery from httplib2", "or creds.invalid: flow = client.flow_from_clientsecrets('client_secret.json', SCOPES) creds = tools.run_flow(flow, store)", "required by applicable law or agreed to in writing, software", "__future__ import print_function from apiclient import discovery from httplib2 import", "\"https://www.googleapis.com/auth/drive\" API_KEY = \"<YOUR_API_KEY>\" DISCOVERY_DOC = f\"https://forms.googleapis.com/$discovery/rest?version=v1beta&key={API_KEY}&labels=FORMS_BETA_TESTERS\" store = file.Storage('credentials.json')", "\"<YOUR_API_KEY>\" DISCOVERY_DOC = f\"https://forms.googleapis.com/$discovery/rest?version=v1beta&key={API_KEY}&labels=FORMS_BETA_TESTERS\" store = file.Storage('credentials.json') creds = None", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "with the License. # You may obtain a copy of", "this file except in compliance with the License. # You", "the Apache License, Version 2.0 (the \"License\"); # you may", "oauth2client import client, file, tools SCOPES = \"https://www.googleapis.com/auth/drive\" API_KEY =", "apiclient import discovery from httplib2 import Http from oauth2client import", "https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "and # limitations under the License. # [START forms_delete_watch] from" ]
[ "x.parent = find_set(x.parent) return x.parent def find_python_set(node: Node) -> set:", "s raise ValueError(f\"{node.data} is not in {sets}\") def test_disjoint_set() ->", "bigger rank should be parent, so that the disjoint set", "the disjoint set tree will be more flat. \"\"\" x,", "x.parent = x def union_set(x: Node, y: Node) -> None:", "x \"\"\" if x != x.parent: x.parent = find_set(x.parent) return", "from x to its' parent # root's rank is 0", "rank should be parent, so that the disjoint set tree", "for s in sets: if node.data in s: return s", "two sets. set with bigger rank should be parent, so", "set tree will be more flat. \"\"\" x, y =", "y: return elif x.rank > y.rank: y.parent = x else:", "tree will be more flat. \"\"\" x, y = find_set(x),", "\"\"\" vertex = [Node(i) for i in range(6)] for v", "Node: \"\"\" Return the parent of x \"\"\" if x", "-> set: \"\"\" Return a Python Standard Library set that", "test_disjoint_set() \"\"\" vertex = [Node(i) for i in range(6)] for", "x.parent def find_python_set(node: Node) -> set: \"\"\" Return a Python", "= 0 x.parent = x def union_set(x: Node, y: Node)", "s: return s raise ValueError(f\"{node.data} is not in {sets}\") def", "Return a Python Standard Library set that contains i. \"\"\"", "self.data = data self.rank: int self.parent: Node def make_set(x: Node)", "!= find_set(node1) else: assert find_set(node0) == find_set(node1) if __name__ ==", "\"\"\" Return the parent of x \"\"\" if x !=", "Python Standard Library set that contains i. \"\"\" sets =", "\"\"\" sets = ({0, 1, 2}, {3, 4, 5}) for", "union_set(vertex[1], vertex[2]) union_set(vertex[3], vertex[4]) union_set(vertex[3], vertex[5]) for node0 in vertex:", "0 x.rank = 0 x.parent = x def union_set(x: Node,", "x.parent: x.parent = find_set(x.parent) return x.parent def find_python_set(node: Node) ->", "the parent of x \"\"\" if x != x.parent: x.parent", "a set. \"\"\" # rank is the distance from x", "in {sets}\") def test_disjoint_set() -> None: \"\"\" >>> test_disjoint_set() \"\"\"", "Standard Library set that contains i. \"\"\" sets = ({0,", "in vertex: for node1 in vertex: if find_python_set(node0).isdisjoint(find_python_set(node1)): assert find_set(node0)", "self.parent: Node def make_set(x: Node) -> None: \"\"\" Make x", "union_set(vertex[3], vertex[4]) union_set(vertex[3], vertex[5]) for node0 in vertex: for node1", "x as a set. \"\"\" # rank is the distance", "vertex[5]) for node0 in vertex: for node1 in vertex: if", "find_set(node1) else: assert find_set(node0) == find_set(node1) if __name__ == \"__main__\":", "raise ValueError(f\"{node.data} is not in {sets}\") def test_disjoint_set() -> None:", "in vertex: make_set(v) union_set(vertex[0], vertex[1]) union_set(vertex[1], vertex[2]) union_set(vertex[3], vertex[4]) union_set(vertex[3],", "def find_python_set(node: Node) -> set: \"\"\" Return a Python Standard", "sets = ({0, 1, 2}, {3, 4, 5}) for s", "None: \"\"\" >>> test_disjoint_set() \"\"\" vertex = [Node(i) for i", "else: assert find_set(node0) == find_set(node1) if __name__ == \"__main__\": test_disjoint_set()", "vertex: for node1 in vertex: if find_python_set(node0).isdisjoint(find_python_set(node1)): assert find_set(node0) !=", "parent of x \"\"\" if x != x.parent: x.parent =", "find_set(x.parent) return x.parent def find_python_set(node: Node) -> set: \"\"\" Return", "None: self.data = data self.rank: int self.parent: Node def make_set(x:", "Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure \"\"\" class Node: def __init__(self, data: int) ->", "union_set(vertex[0], vertex[1]) union_set(vertex[1], vertex[2]) union_set(vertex[3], vertex[4]) union_set(vertex[3], vertex[5]) for node0", "be more flat. \"\"\" x, y = find_set(x), find_set(y) if", "\"\"\" class Node: def __init__(self, data: int) -> None: self.data", "the distance from x to its' parent # root's rank", "if x == y: return elif x.rank > y.rank: y.parent", "def make_set(x: Node) -> None: \"\"\" Make x as a", "-> None: \"\"\" Union of two sets. set with bigger", "set. \"\"\" # rank is the distance from x to", "if x != x.parent: x.parent = find_set(x.parent) return x.parent def", "should be parent, so that the disjoint set tree will", "sets. set with bigger rank should be parent, so that", "as a set. \"\"\" # rank is the distance from", "x.rank > y.rank: y.parent = x else: x.parent = y", "its' parent # root's rank is 0 x.rank = 0", "class Node: def __init__(self, data: int) -> None: self.data =", "is not in {sets}\") def test_disjoint_set() -> None: \"\"\" >>>", "union_set(x: Node, y: Node) -> None: \"\"\" Union of two", "Library set that contains i. \"\"\" sets = ({0, 1,", "== y.rank: y.rank += 1 def find_set(x: Node) -> Node:", "# root's rank is 0 x.rank = 0 x.parent =", "so that the disjoint set tree will be more flat.", "i. \"\"\" sets = ({0, 1, 2}, {3, 4, 5})", "contains i. \"\"\" sets = ({0, 1, 2}, {3, 4,", "v in vertex: make_set(v) union_set(vertex[0], vertex[1]) union_set(vertex[1], vertex[2]) union_set(vertex[3], vertex[4])", "more flat. \"\"\" x, y = find_set(x), find_set(y) if x", "\"\"\" Disjoint set. Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure \"\"\" class Node: def __init__(self,", "data self.rank: int self.parent: Node def make_set(x: Node) -> None:", "flat. \"\"\" x, y = find_set(x), find_set(y) if x ==", "vertex[2]) union_set(vertex[3], vertex[4]) union_set(vertex[3], vertex[5]) for node0 in vertex: for", "-> None: self.data = data self.rank: int self.parent: Node def", "x != x.parent: x.parent = find_set(x.parent) return x.parent def find_python_set(node:", "find_set(x), find_set(y) if x == y: return elif x.rank >", "= find_set(x.parent) return x.parent def find_python_set(node: Node) -> set: \"\"\"", "__init__(self, data: int) -> None: self.data = data self.rank: int", "be parent, so that the disjoint set tree will be", "4, 5}) for s in sets: if node.data in s:", "else: x.parent = y if x.rank == y.rank: y.rank +=", "Return the parent of x \"\"\" if x != x.parent:", "Node) -> None: \"\"\" Union of two sets. set with", "int self.parent: Node def make_set(x: Node) -> None: \"\"\" Make", "Make x as a set. \"\"\" # rank is the", "return s raise ValueError(f\"{node.data} is not in {sets}\") def test_disjoint_set()", "find_python_set(node0).isdisjoint(find_python_set(node1)): assert find_set(node0) != find_set(node1) else: assert find_set(node0) == find_set(node1)", "is the distance from x to its' parent # root's", "find_set(x: Node) -> Node: \"\"\" Return the parent of x", "set: \"\"\" Return a Python Standard Library set that contains", "5}) for s in sets: if node.data in s: return", "if x.rank == y.rank: y.rank += 1 def find_set(x: Node)", "\"\"\" if x != x.parent: x.parent = find_set(x.parent) return x.parent", "rank is the distance from x to its' parent #", "y.parent = x else: x.parent = y if x.rank ==", "Node, y: Node) -> None: \"\"\" Union of two sets.", "= [Node(i) for i in range(6)] for v in vertex:", "root's rank is 0 x.rank = 0 x.parent = x", "if node.data in s: return s raise ValueError(f\"{node.data} is not", "for node1 in vertex: if find_python_set(node0).isdisjoint(find_python_set(node1)): assert find_set(node0) != find_set(node1)", "for v in vertex: make_set(v) union_set(vertex[0], vertex[1]) union_set(vertex[1], vertex[2]) union_set(vertex[3],", "-> Node: \"\"\" Return the parent of x \"\"\" if", "\"\"\" Return a Python Standard Library set that contains i.", "x def union_set(x: Node, y: Node) -> None: \"\"\" Union", "s in sets: if node.data in s: return s raise", "in s: return s raise ValueError(f\"{node.data} is not in {sets}\")", "-> None: \"\"\" Make x as a set. \"\"\" #", "in vertex: if find_python_set(node0).isdisjoint(find_python_set(node1)): assert find_set(node0) != find_set(node1) else: assert", "y: Node) -> None: \"\"\" Union of two sets. set", "0 x.parent = x def union_set(x: Node, y: Node) ->", "= y if x.rank == y.rank: y.rank += 1 def", "-> None: \"\"\" >>> test_disjoint_set() \"\"\" vertex = [Node(i) for", "if find_python_set(node0).isdisjoint(find_python_set(node1)): assert find_set(node0) != find_set(node1) else: assert find_set(node0) ==", "return x.parent def find_python_set(node: Node) -> set: \"\"\" Return a", "of two sets. set with bigger rank should be parent,", "[Node(i) for i in range(6)] for v in vertex: make_set(v)", "int) -> None: self.data = data self.rank: int self.parent: Node", "i in range(6)] for v in vertex: make_set(v) union_set(vertex[0], vertex[1])", "that the disjoint set tree will be more flat. \"\"\"", "Node) -> set: \"\"\" Return a Python Standard Library set", "return elif x.rank > y.rank: y.parent = x else: x.parent", "range(6)] for v in vertex: make_set(v) union_set(vertex[0], vertex[1]) union_set(vertex[1], vertex[2])", "is 0 x.rank = 0 x.parent = x def union_set(x:", "make_set(x: Node) -> None: \"\"\" Make x as a set.", "vertex[1]) union_set(vertex[1], vertex[2]) union_set(vertex[3], vertex[4]) union_set(vertex[3], vertex[5]) for node0 in", "will be more flat. \"\"\" x, y = find_set(x), find_set(y)", "self.rank: int self.parent: Node def make_set(x: Node) -> None: \"\"\"", "that contains i. \"\"\" sets = ({0, 1, 2}, {3,", "= ({0, 1, 2}, {3, 4, 5}) for s in", "Union of two sets. set with bigger rank should be", "node1 in vertex: if find_python_set(node0).isdisjoint(find_python_set(node1)): assert find_set(node0) != find_set(node1) else:", "disjoint set tree will be more flat. \"\"\" x, y", "y = find_set(x), find_set(y) if x == y: return elif", "{3, 4, 5}) for s in sets: if node.data in", "https://en.wikipedia.org/wiki/Disjoint-set_data_structure \"\"\" class Node: def __init__(self, data: int) -> None:", "set with bigger rank should be parent, so that the", "node0 in vertex: for node1 in vertex: if find_python_set(node0).isdisjoint(find_python_set(node1)): assert", "y if x.rank == y.rank: y.rank += 1 def find_set(x:", "\"\"\" >>> test_disjoint_set() \"\"\" vertex = [Node(i) for i in", "= x def union_set(x: Node, y: Node) -> None: \"\"\"", "def __init__(self, data: int) -> None: self.data = data self.rank:", "None: \"\"\" Make x as a set. \"\"\" # rank", "= x else: x.parent = y if x.rank == y.rank:", "parent, so that the disjoint set tree will be more", "find_python_set(node: Node) -> set: \"\"\" Return a Python Standard Library", "sets: if node.data in s: return s raise ValueError(f\"{node.data} is", "x else: x.parent = y if x.rank == y.rank: y.rank", "<gh_stars>0 \"\"\" Disjoint set. Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure \"\"\" class Node: def", "of x \"\"\" if x != x.parent: x.parent = find_set(x.parent)", "Disjoint set. Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure \"\"\" class Node: def __init__(self, data:", "a Python Standard Library set that contains i. \"\"\" sets", "node.data in s: return s raise ValueError(f\"{node.data} is not in", "1 def find_set(x: Node) -> Node: \"\"\" Return the parent", "x == y: return elif x.rank > y.rank: y.parent =", "== y: return elif x.rank > y.rank: y.parent = x", "union_set(vertex[3], vertex[5]) for node0 in vertex: for node1 in vertex:", "def test_disjoint_set() -> None: \"\"\" >>> test_disjoint_set() \"\"\" vertex =", "> y.rank: y.parent = x else: x.parent = y if", "make_set(v) union_set(vertex[0], vertex[1]) union_set(vertex[1], vertex[2]) union_set(vertex[3], vertex[4]) union_set(vertex[3], vertex[5]) for", "x.rank = 0 x.parent = x def union_set(x: Node, y:", "find_set(node0) != find_set(node1) else: assert find_set(node0) == find_set(node1) if __name__", "with bigger rank should be parent, so that the disjoint", "x, y = find_set(x), find_set(y) if x == y: return", "Node: def __init__(self, data: int) -> None: self.data = data", "y.rank += 1 def find_set(x: Node) -> Node: \"\"\" Return", "x.parent = y if x.rank == y.rank: y.rank += 1", "Node) -> Node: \"\"\" Return the parent of x \"\"\"", "1, 2}, {3, 4, 5}) for s in sets: if", "\"\"\" x, y = find_set(x), find_set(y) if x == y:", "x.rank == y.rank: y.rank += 1 def find_set(x: Node) ->", "for node0 in vertex: for node1 in vertex: if find_python_set(node0).isdisjoint(find_python_set(node1)):", "def find_set(x: Node) -> Node: \"\"\" Return the parent of", "find_set(y) if x == y: return elif x.rank > y.rank:", "distance from x to its' parent # root's rank is", "to its' parent # root's rank is 0 x.rank =", "vertex: if find_python_set(node0).isdisjoint(find_python_set(node1)): assert find_set(node0) != find_set(node1) else: assert find_set(node0)", "= find_set(x), find_set(y) if x == y: return elif x.rank", "\"\"\" Make x as a set. \"\"\" # rank is", "def union_set(x: Node, y: Node) -> None: \"\"\" Union of", "y.rank: y.rank += 1 def find_set(x: Node) -> Node: \"\"\"", "x to its' parent # root's rank is 0 x.rank", "in sets: if node.data in s: return s raise ValueError(f\"{node.data}", "vertex[4]) union_set(vertex[3], vertex[5]) for node0 in vertex: for node1 in", "ValueError(f\"{node.data} is not in {sets}\") def test_disjoint_set() -> None: \"\"\"", "vertex = [Node(i) for i in range(6)] for v in", "\"\"\" Union of two sets. set with bigger rank should", "{sets}\") def test_disjoint_set() -> None: \"\"\" >>> test_disjoint_set() \"\"\" vertex", ">>> test_disjoint_set() \"\"\" vertex = [Node(i) for i in range(6)]", "rank is 0 x.rank = 0 x.parent = x def", "set that contains i. \"\"\" sets = ({0, 1, 2},", "for i in range(6)] for v in vertex: make_set(v) union_set(vertex[0],", "= data self.rank: int self.parent: Node def make_set(x: Node) ->", "assert find_set(node0) != find_set(node1) else: assert find_set(node0) == find_set(node1) if", "!= x.parent: x.parent = find_set(x.parent) return x.parent def find_python_set(node: Node)", "not in {sets}\") def test_disjoint_set() -> None: \"\"\" >>> test_disjoint_set()", "y.rank: y.parent = x else: x.parent = y if x.rank", "({0, 1, 2}, {3, 4, 5}) for s in sets:", "elif x.rank > y.rank: y.parent = x else: x.parent =", "test_disjoint_set() -> None: \"\"\" >>> test_disjoint_set() \"\"\" vertex = [Node(i)", "in range(6)] for v in vertex: make_set(v) union_set(vertex[0], vertex[1]) union_set(vertex[1],", "data: int) -> None: self.data = data self.rank: int self.parent:", "vertex: make_set(v) union_set(vertex[0], vertex[1]) union_set(vertex[1], vertex[2]) union_set(vertex[3], vertex[4]) union_set(vertex[3], vertex[5])", "parent # root's rank is 0 x.rank = 0 x.parent", "Node) -> None: \"\"\" Make x as a set. \"\"\"", "Node def make_set(x: Node) -> None: \"\"\" Make x as", "2}, {3, 4, 5}) for s in sets: if node.data", "# rank is the distance from x to its' parent", "None: \"\"\" Union of two sets. set with bigger rank", "\"\"\" # rank is the distance from x to its'", "+= 1 def find_set(x: Node) -> Node: \"\"\" Return the", "set. Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure \"\"\" class Node: def __init__(self, data: int)" ]
[ "= np.kron(Identity, sigma_y) Iz = np.kron(Identity, sigma_z) SxIx = np.kron(sigma_x,sigma_z)", "sigma_y = 0.5*np.r_[[[0,-1j],[1j, 0]]] sigma_z = 0.5*np.r_[[[1, 0],[0, -1]]] Identity", "omega_I/(2.*np.pi)*B0*Iz + Aiso * (np.dot(Sx,Ix) + np.dot(Sy,Iy) + np.dot(Sz,Iz)) print('Hamiltonian:')", "E[3] E13 = E[0] - E[2] E24 = E[1] -", "= np.eye(2) Sx = np.kron(sigma_x, Identity) Sy = np.kron(sigma_y, Identity)", "omega_I/(2.*np.pi)*B0*Iz + Aiso * np.dot(Sz,Iz) #H = omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz", "T) Aiso = 2*np.pi * 50.e6 # Isotropic Hyperfine coupling", "print(H) out = np.linalg.eig(H) E = out[0] print(E) E12 =", "spin 1/2 nuclei import numpy as np from scipy.linalg import", "rad / (s * T) Aiso = 2*np.pi * 50.e6", "= 1/2, I = 1/2 # Spin 1/2 electron coupled", "E12 = E[0] - E[1] E34 = E[2] - E[3]", "out = np.linalg.eig(H) E = out[0] print(E) E12 = E[0]", "np.kron(Identity, sigma_y) Iz = np.kron(Identity, sigma_z) SxIx = np.kron(sigma_x,sigma_z) SxIx2", "Aiso * np.dot(Sz,Iz) #H = omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz + Aiso", "= E[0] - E[1] E34 = E[2] - E[3] E13", "Isotropic Hyperfine coupling rad / s B0 = 0.35# T", "MHz'%(E34 / 1e6)) print('Electron') print('%0.05f GHz'%(E13 / 1e9)) print('%0.05f GHz'%(E24", "1/2 nuclei import numpy as np from scipy.linalg import expm", "Ix = np.kron(Identity, sigma_x) Iy = np.kron(Identity, sigma_y) Iz =", "Identity) Ix = np.kron(Identity, sigma_x) Iy = np.kron(Identity, sigma_y) Iz", "(np.dot(Sx,Ix) + np.dot(Sy,Iy) + np.dot(Sz,Iz)) print('Hamiltonian:') print(H) out = np.linalg.eig(H)", "#H = omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz + Aiso * (np.dot(Sx,Ix) +", "np.linalg.eig(H) E = out[0] print(E) E12 = E[0] - E[1]", "sigma_z = 0.5*np.r_[[[1, 0],[0, -1]]] Identity = np.eye(2) Sx =", "(s * T) omega_I = 267.522e6 # rad / (s", "SxIx = np.kron(sigma_x,sigma_z) SxIx2 = np.dot(Sx,Iz) print(SxIx) print(SxIx2) print(np.allclose(SxIx,SxIx2)) omega_S", "= 0.5*np.r_[[[1, 0],[0, -1]]] Identity = np.eye(2) Sx = np.kron(sigma_x,", "- E[2] E24 = E[1] - E[3] print(E12) print(E34) print(E13)", "E[0] - E[2] E24 = E[1] - E[3] print(E12) print(E34)", "- E[3] print(E12) print(E34) print(E13) print(E24) print('Nuclear') print('%0.05f MHz'%(E12 /", "+ np.dot(Sy,Iy) + np.dot(Sz,Iz)) print('Hamiltonian:') print(H) out = np.linalg.eig(H) E", "<NAME> # S = 1/2, I = 1/2 # Spin", "E[0] - E[1] E34 = E[2] - E[3] E13 =", "expm from matplotlib.pylab import * from matplotlib import cm sigma_x", "1e6)) print('%0.05f MHz'%(E34 / 1e6)) print('Electron') print('%0.05f GHz'%(E13 / 1e9))", "* from matplotlib import cm sigma_x = 0.5*np.r_[[[0, 1],[1, 0]]]", "0.5*np.r_[[[0, 1],[1, 0]]] sigma_y = 0.5*np.r_[[[0,-1j],[1j, 0]]] sigma_z = 0.5*np.r_[[[1,", "= np.kron(sigma_x, Identity) Sy = np.kron(sigma_y, Identity) Sz = np.kron(sigma_z,", "np.kron(sigma_x, Identity) Sy = np.kron(sigma_y, Identity) Sz = np.kron(sigma_z, Identity)", "Sz = np.kron(sigma_z, Identity) Ix = np.kron(Identity, sigma_x) Iy =", "1/2 electron coupled to spin 1/2 nuclei import numpy as", "np.dot(Sz,Iz) #H = omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz + Aiso * (np.dot(Sx,Ix)", "E[3] print(E12) print(E34) print(E13) print(E24) print('Nuclear') print('%0.05f MHz'%(E12 / 1e6))", "from matplotlib import cm sigma_x = 0.5*np.r_[[[0, 1],[1, 0]]] sigma_y", "0.5*np.r_[[[1, 0],[0, -1]]] Identity = np.eye(2) Sx = np.kron(sigma_x, Identity)", "omega_I = 267.522e6 # rad / (s * T) Aiso", "= np.kron(Identity, sigma_x) Iy = np.kron(Identity, sigma_y) Iz = np.kron(Identity,", "0]]] sigma_z = 0.5*np.r_[[[1, 0],[0, -1]]] Identity = np.eye(2) Sx", "= np.kron(Identity, sigma_z) SxIx = np.kron(sigma_x,sigma_z) SxIx2 = np.dot(Sx,Iz) print(SxIx)", "rad / (s * T) omega_I = 267.522e6 # rad", "to spin 1/2 nuclei import numpy as np from scipy.linalg", "Identity) Sy = np.kron(sigma_y, Identity) Sz = np.kron(sigma_z, Identity) Ix", "* T) Aiso = 2*np.pi * 50.e6 # Isotropic Hyperfine", "/ s B0 = 0.35# T H = omega_S/(2.*np.pi)*B0*Sz +", "print(E12) print(E34) print(E13) print(E24) print('Nuclear') print('%0.05f MHz'%(E12 / 1e6)) print('%0.05f", "from scipy.linalg import expm from matplotlib.pylab import * from matplotlib", "MHz'%(E12 / 1e6)) print('%0.05f MHz'%(E34 / 1e6)) print('Electron') print('%0.05f GHz'%(E13", "= E[2] - E[3] E13 = E[0] - E[2] E24", "sigma_x = 0.5*np.r_[[[0, 1],[1, 0]]] sigma_y = 0.5*np.r_[[[0,-1j],[1j, 0]]] sigma_z", "1],[1, 0]]] sigma_y = 0.5*np.r_[[[0,-1j],[1j, 0]]] sigma_z = 0.5*np.r_[[[1, 0],[0,", "= np.kron(sigma_x,sigma_z) SxIx2 = np.dot(Sx,Iz) print(SxIx) print(SxIx2) print(np.allclose(SxIx,SxIx2)) omega_S =", "E13 = E[0] - E[2] E24 = E[1] - E[3]", "# S = 1/2, I = 1/2 # Spin 1/2", "S = 1/2, I = 1/2 # Spin 1/2 electron", "-1]]] Identity = np.eye(2) Sx = np.kron(sigma_x, Identity) Sy =", "np.dot(Sy,Iy) + np.dot(Sz,Iz)) print('Hamiltonian:') print(H) out = np.linalg.eig(H) E =", "= 0.35# T H = omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz + Aiso", "E[1] - E[3] print(E12) print(E34) print(E13) print(E24) print('Nuclear') print('%0.05f MHz'%(E12", "np.kron(Identity, sigma_z) SxIx = np.kron(sigma_x,sigma_z) SxIx2 = np.dot(Sx,Iz) print(SxIx) print(SxIx2)", "from matplotlib.pylab import * from matplotlib import cm sigma_x =", "Spin 1/2 electron coupled to spin 1/2 nuclei import numpy", "# rad / (s * T) omega_I = 267.522e6 #", "/ (s * T) Aiso = 2*np.pi * 50.e6 #", "* np.dot(Sz,Iz) #H = omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz + Aiso *", "2*np.pi * 50.e6 # Isotropic Hyperfine coupling rad / s", "/ (s * T) omega_I = 267.522e6 # rad /", "0.35# T H = omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz + Aiso *", "+ omega_I/(2.*np.pi)*B0*Iz + Aiso * (np.dot(Sx,Ix) + np.dot(Sy,Iy) + np.dot(Sz,Iz))", "print(E24) print('Nuclear') print('%0.05f MHz'%(E12 / 1e6)) print('%0.05f MHz'%(E34 / 1e6))", "np from scipy.linalg import expm from matplotlib.pylab import * from", "0.5*np.r_[[[0,-1j],[1j, 0]]] sigma_z = 0.5*np.r_[[[1, 0],[0, -1]]] Identity = np.eye(2)", "omega_S = 1.76e11 # rad / (s * T) omega_I", "Aiso * (np.dot(Sx,Ix) + np.dot(Sy,Iy) + np.dot(Sz,Iz)) print('Hamiltonian:') print(H) out", "matplotlib.pylab import * from matplotlib import cm sigma_x = 0.5*np.r_[[[0,", "= np.kron(sigma_y, Identity) Sz = np.kron(sigma_z, Identity) Ix = np.kron(Identity,", "= 2*np.pi * 50.e6 # Isotropic Hyperfine coupling rad /", "np.dot(Sx,Iz) print(SxIx) print(SxIx2) print(np.allclose(SxIx,SxIx2)) omega_S = 1.76e11 # rad /", "- E[3] E13 = E[0] - E[2] E24 = E[1]", "# <NAME> # S = 1/2, I = 1/2 #", "(s * T) Aiso = 2*np.pi * 50.e6 # Isotropic", "1e6)) print('Electron') print('%0.05f GHz'%(E13 / 1e9)) print('%0.05f GHz'%(E24 / 1e9))", "0]]] sigma_y = 0.5*np.r_[[[0,-1j],[1j, 0]]] sigma_z = 0.5*np.r_[[[1, 0],[0, -1]]]", "rad / s B0 = 0.35# T H = omega_S/(2.*np.pi)*B0*Sz", "= omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz + Aiso * np.dot(Sz,Iz) #H =", "0],[0, -1]]] Identity = np.eye(2) Sx = np.kron(sigma_x, Identity) Sy", "Iz = np.kron(Identity, sigma_z) SxIx = np.kron(sigma_x,sigma_z) SxIx2 = np.dot(Sx,Iz)", "Identity = np.eye(2) Sx = np.kron(sigma_x, Identity) Sy = np.kron(sigma_y,", "np.kron(Identity, sigma_x) Iy = np.kron(Identity, sigma_y) Iz = np.kron(Identity, sigma_z)", "Hyperfine coupling rad / s B0 = 0.35# T H", "= np.linalg.eig(H) E = out[0] print(E) E12 = E[0] -", "print(E34) print(E13) print(E24) print('Nuclear') print('%0.05f MHz'%(E12 / 1e6)) print('%0.05f MHz'%(E34", "out[0] print(E) E12 = E[0] - E[1] E34 = E[2]", "E[1] E34 = E[2] - E[3] E13 = E[0] -", "coupled to spin 1/2 nuclei import numpy as np from", "= 267.522e6 # rad / (s * T) Aiso =", "omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz + Aiso * (np.dot(Sx,Ix) + np.dot(Sy,Iy) +", "= 1.76e11 # rad / (s * T) omega_I =", "import cm sigma_x = 0.5*np.r_[[[0, 1],[1, 0]]] sigma_y = 0.5*np.r_[[[0,-1j],[1j,", "= E[0] - E[2] E24 = E[1] - E[3] print(E12)", "# Isotropic Hyperfine coupling rad / s B0 = 0.35#", "print(np.allclose(SxIx,SxIx2)) omega_S = 1.76e11 # rad / (s * T)", "import expm from matplotlib.pylab import * from matplotlib import cm", "* (np.dot(Sx,Ix) + np.dot(Sy,Iy) + np.dot(Sz,Iz)) print('Hamiltonian:') print(H) out =", "+ Aiso * np.dot(Sz,Iz) #H = omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz +", "E[2] E24 = E[1] - E[3] print(E12) print(E34) print(E13) print(E24)", "print('Electron') print('%0.05f GHz'%(E13 / 1e9)) print('%0.05f GHz'%(E24 / 1e9)) matshow(abs(H),", "Iy = np.kron(Identity, sigma_y) Iz = np.kron(Identity, sigma_z) SxIx =", "= 0.5*np.r_[[[0, 1],[1, 0]]] sigma_y = 0.5*np.r_[[[0,-1j],[1j, 0]]] sigma_z =", "print('%0.05f MHz'%(E34 / 1e6)) print('Electron') print('%0.05f GHz'%(E13 / 1e9)) print('%0.05f", "# Spin 1/2 electron coupled to spin 1/2 nuclei import", "Sx = np.kron(sigma_x, Identity) Sy = np.kron(sigma_y, Identity) Sz =", "Sy = np.kron(sigma_y, Identity) Sz = np.kron(sigma_z, Identity) Ix =", "omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz + Aiso * np.dot(Sz,Iz) #H = omega_S/(2.*np.pi)*B0*Sz", "+ Aiso * (np.dot(Sx,Ix) + np.dot(Sy,Iy) + np.dot(Sz,Iz)) print('Hamiltonian:') print(H)", "1/2 # Spin 1/2 electron coupled to spin 1/2 nuclei", "nuclei import numpy as np from scipy.linalg import expm from", "H = omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz + Aiso * np.dot(Sz,Iz) #H", "print('%0.05f MHz'%(E12 / 1e6)) print('%0.05f MHz'%(E34 / 1e6)) print('Electron') print('%0.05f", "np.kron(sigma_z, Identity) Ix = np.kron(Identity, sigma_x) Iy = np.kron(Identity, sigma_y)", "Identity) Sz = np.kron(sigma_z, Identity) Ix = np.kron(Identity, sigma_x) Iy", "print(SxIx2) print(np.allclose(SxIx,SxIx2)) omega_S = 1.76e11 # rad / (s *", "= E[1] - E[3] print(E12) print(E34) print(E13) print(E24) print('Nuclear') print('%0.05f", "print(E13) print(E24) print('Nuclear') print('%0.05f MHz'%(E12 / 1e6)) print('%0.05f MHz'%(E34 /", "np.dot(Sz,Iz)) print('Hamiltonian:') print(H) out = np.linalg.eig(H) E = out[0] print(E)", "GHz'%(E13 / 1e9)) print('%0.05f GHz'%(E24 / 1e9)) matshow(abs(H), cmap =", "/ 1e6)) print('Electron') print('%0.05f GHz'%(E13 / 1e9)) print('%0.05f GHz'%(E24 /", "I = 1/2 # Spin 1/2 electron coupled to spin", "import numpy as np from scipy.linalg import expm from matplotlib.pylab", "T) omega_I = 267.522e6 # rad / (s * T)", "sigma_y) Iz = np.kron(Identity, sigma_z) SxIx = np.kron(sigma_x,sigma_z) SxIx2 =", "scipy.linalg import expm from matplotlib.pylab import * from matplotlib import", "- E[1] E34 = E[2] - E[3] E13 = E[0]", "+ omega_I/(2.*np.pi)*B0*Iz + Aiso * np.dot(Sz,Iz) #H = omega_S/(2.*np.pi)*B0*Sz +", "Aiso = 2*np.pi * 50.e6 # Isotropic Hyperfine coupling rad", "+ np.dot(Sz,Iz)) print('Hamiltonian:') print(H) out = np.linalg.eig(H) E = out[0]", "T H = omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz + Aiso * np.dot(Sz,Iz)", "coupling rad / s B0 = 0.35# T H =", "print('%0.05f GHz'%(E24 / 1e9)) matshow(abs(H), cmap = cm.jet) title('Hamiltonian') show()", "sigma_z) SxIx = np.kron(sigma_x,sigma_z) SxIx2 = np.dot(Sx,Iz) print(SxIx) print(SxIx2) print(np.allclose(SxIx,SxIx2))", "50.e6 # Isotropic Hyperfine coupling rad / s B0 =", "1e9)) print('%0.05f GHz'%(E24 / 1e9)) matshow(abs(H), cmap = cm.jet) title('Hamiltonian')", "1.76e11 # rad / (s * T) omega_I = 267.522e6", "# rad / (s * T) Aiso = 2*np.pi *", "E24 = E[1] - E[3] print(E12) print(E34) print(E13) print(E24) print('Nuclear')", "sigma_x) Iy = np.kron(Identity, sigma_y) Iz = np.kron(Identity, sigma_z) SxIx", "= out[0] print(E) E12 = E[0] - E[1] E34 =", "1/2, I = 1/2 # Spin 1/2 electron coupled to", "* T) omega_I = 267.522e6 # rad / (s *", "s B0 = 0.35# T H = omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz", "267.522e6 # rad / (s * T) Aiso = 2*np.pi", "import * from matplotlib import cm sigma_x = 0.5*np.r_[[[0, 1],[1,", "cm sigma_x = 0.5*np.r_[[[0, 1],[1, 0]]] sigma_y = 0.5*np.r_[[[0,-1j],[1j, 0]]]", "SxIx2 = np.dot(Sx,Iz) print(SxIx) print(SxIx2) print(np.allclose(SxIx,SxIx2)) omega_S = 1.76e11 #", "np.kron(sigma_y, Identity) Sz = np.kron(sigma_z, Identity) Ix = np.kron(Identity, sigma_x)", "print('%0.05f GHz'%(E13 / 1e9)) print('%0.05f GHz'%(E24 / 1e9)) matshow(abs(H), cmap", "/ 1e6)) print('%0.05f MHz'%(E34 / 1e6)) print('Electron') print('%0.05f GHz'%(E13 /", "print('Hamiltonian:') print(H) out = np.linalg.eig(H) E = out[0] print(E) E12", "print(E) E12 = E[0] - E[1] E34 = E[2] -", "= omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz + Aiso * (np.dot(Sx,Ix) + np.dot(Sy,Iy)", "electron coupled to spin 1/2 nuclei import numpy as np", "* 50.e6 # Isotropic Hyperfine coupling rad / s B0", "numpy as np from scipy.linalg import expm from matplotlib.pylab import", "E[2] - E[3] E13 = E[0] - E[2] E24 =", "= 0.5*np.r_[[[0,-1j],[1j, 0]]] sigma_z = 0.5*np.r_[[[1, 0],[0, -1]]] Identity =", "np.kron(sigma_x,sigma_z) SxIx2 = np.dot(Sx,Iz) print(SxIx) print(SxIx2) print(np.allclose(SxIx,SxIx2)) omega_S = 1.76e11", "print(SxIx) print(SxIx2) print(np.allclose(SxIx,SxIx2)) omega_S = 1.76e11 # rad / (s", "= np.kron(sigma_z, Identity) Ix = np.kron(Identity, sigma_x) Iy = np.kron(Identity,", "/ 1e9)) print('%0.05f GHz'%(E24 / 1e9)) matshow(abs(H), cmap = cm.jet)", "E34 = E[2] - E[3] E13 = E[0] - E[2]", "print('Nuclear') print('%0.05f MHz'%(E12 / 1e6)) print('%0.05f MHz'%(E34 / 1e6)) print('Electron')", "E = out[0] print(E) E12 = E[0] - E[1] E34", "np.eye(2) Sx = np.kron(sigma_x, Identity) Sy = np.kron(sigma_y, Identity) Sz", "as np from scipy.linalg import expm from matplotlib.pylab import *", "B0 = 0.35# T H = omega_S/(2.*np.pi)*B0*Sz + omega_I/(2.*np.pi)*B0*Iz +", "= np.dot(Sx,Iz) print(SxIx) print(SxIx2) print(np.allclose(SxIx,SxIx2)) omega_S = 1.76e11 # rad", "matplotlib import cm sigma_x = 0.5*np.r_[[[0, 1],[1, 0]]] sigma_y =", "= 1/2 # Spin 1/2 electron coupled to spin 1/2" ]
[ "reader = csv.reader(f) vm_q = [vm for vm in reader]", "spiderNest.preIntro import * path_ = os.path.dirname(os.path.dirname(__file__)) + '/dataBase/log_information.csv' def save_login_info(VMess,", "# ['2020-08-06 04:27:59', 'link','class_', '1'] vm_q = [vm for vm", "+ '/dataBase/log_information.csv' def save_login_info(VMess, class_): \"\"\" VMess入库 class_: ssr or", "open(path_, 'r', encoding='utf-8') as f: reader = csv.reader(f) vm_q =", "try: with open(path_, 'r', encoding='utf-8') as f: reader = csv.reader(f)", "as f: writer = csv.writer(f) writer.writerows(dataFlow) try: with open(path_, 'r',", "class_: ssr or v2ray \"\"\" now = str(datetime.now()).split('.')[0] with open(path_,", "# 入库时间,Vmess,初始化状态:0 writer.writerow(['{}'.format(now), '{}'.format(VMess), class_, '0']) def vmess_IO(class_): \"\"\" 获取可用订阅链接并刷新存储池", "'/dataBase/log_information.csv' def save_login_info(VMess, class_): \"\"\" VMess入库 class_: ssr or v2ray", "1)][-1] = '1' break refresh_log(new_q) return vm except UnboundLocalError: return", "encoding='utf-8') as f: reader = csv.reader(f) vm_list = [i for", "except UnboundLocalError: return '无可用订阅连接' def avi_num(): from datetime import datetime,", "def refresh_log(dataFlow): with open(path_, 'w', encoding='utf-8', newline='') as f: writer", "vm in reader] new_q = vm_q for i, value in", "value in enumerate(reversed(vm_q)): if value[-1] == '0' and value[-2] ==", "+ 1)][-1] = '1' break refresh_log(new_q) return vm except UnboundLocalError:", "vm[-1] == '0'] tag_items = '' for vm in vm_list:", "in vm_list: if vm[-1] == '0': bei_ing_time = datetime.fromisoformat(vm[0]) +", "writer = csv.writer(f) # 入库时间,Vmess,初始化状态:0 writer.writerow(['{}'.format(now), '{}'.format(VMess), class_, '0']) def", "'0']) def vmess_IO(class_): \"\"\" 获取可用订阅链接并刷新存储池 class_: ssr ; v2ray \"\"\"", "return vm except UnboundLocalError: return '无可用订阅连接' def avi_num(): from datetime", "os.path.dirname(os.path.dirname(__file__)) + '/dataBase/log_information.csv' def save_login_info(VMess, class_): \"\"\" VMess入库 class_: ssr", "'0' and value[-2] == class_: vm = value[1] new_q[-(i +", "as f: writer = csv.writer(f) # 入库时间,Vmess,初始化状态:0 writer.writerow(['{}'.format(now), '{}'.format(VMess), class_,", "as f: reader = csv.reader(f) vm_q = [vm for vm", "new_q = vm_q for i, value in enumerate(reversed(vm_q)): if value[-1]", "reader] # ['2020-08-06 04:27:59', 'link','class_', '1'] vm_q = [vm for", "vm_list = [i for i in reader] # ['2020-08-06 04:27:59',", "encoding='utf-8') as f: reader = csv.reader(f) vm_q = [vm for", "v2ray \"\"\" def refresh_log(dataFlow): with open(path_, 'w', encoding='utf-8', newline='') as", "with open(path_, 'w', encoding='utf-8', newline='') as f: writer = csv.writer(f)", "VMess入库 class_: ssr or v2ray \"\"\" now = str(datetime.now()).split('.')[0] with", "refresh_log(dataFlow): with open(path_, 'w', encoding='utf-8', newline='') as f: writer =", "vm[-1] == '0': bei_ing_time = datetime.fromisoformat(vm[0]) + timedelta(hours=12) tag_items +=", "value[1] new_q[-(i + 1)][-1] = '1' break refresh_log(new_q) return vm", "for i in reader] # ['2020-08-06 04:27:59', 'link','class_', '1'] vm_q", "= value[1] new_q[-(i + 1)][-1] = '1' break refresh_log(new_q) return", "def avi_num(): from datetime import datetime, timedelta with open(path_, 'r',", "'link','class_', '1'] vm_q = [vm for vm in vm_list if", "if vm[-1] == '0': bei_ing_time = datetime.fromisoformat(vm[0]) + timedelta(hours=12) tag_items", "now = str(datetime.now()).split('.')[0] with open(path_, 'a', encoding='utf-8', newline='') as f:", "== '0' and value[-2] == class_: vm = value[1] new_q[-(i", "open(path_, 'w', encoding='utf-8', newline='') as f: writer = csv.writer(f) writer.writerows(dataFlow)", "= os.path.dirname(os.path.dirname(__file__)) + '/dataBase/log_information.csv' def save_login_info(VMess, class_): \"\"\" VMess入库 class_:", "and value[-2] == class_: vm = value[1] new_q[-(i + 1)][-1]", "return '无可用订阅连接' def avi_num(): from datetime import datetime, timedelta with", "vmess_IO(class_): \"\"\" 获取可用订阅链接并刷新存储池 class_: ssr ; v2ray \"\"\" def refresh_log(dataFlow):", "vm_q = [vm for vm in vm_list if vm[-1] ==", "vm_q for i, value in enumerate(reversed(vm_q)): if value[-1] == '0'", "== class_: vm = value[1] new_q[-(i + 1)][-1] = '1'", "= '' for vm in vm_list: if vm[-1] == '0':", "[vm for vm in reader] new_q = vm_q for i,", "for i, value in enumerate(reversed(vm_q)): if value[-1] == '0' and", "= str(datetime.now()).split('.')[0] with open(path_, 'a', encoding='utf-8', newline='') as f: writer", "import * path_ = os.path.dirname(os.path.dirname(__file__)) + '/dataBase/log_information.csv' def save_login_info(VMess, class_):", "vm = value[1] new_q[-(i + 1)][-1] = '1' break refresh_log(new_q)", "with open(path_, 'r', encoding='utf-8') as f: reader = csv.reader(f) vm_q", "= csv.reader(f) vm_list = [i for i in reader] #", "refresh_log(new_q) return vm except UnboundLocalError: return '无可用订阅连接' def avi_num(): from", "i, value in enumerate(reversed(vm_q)): if value[-1] == '0' and value[-2]", "vm except UnboundLocalError: return '无可用订阅连接' def avi_num(): from datetime import", "avi_num(): from datetime import datetime, timedelta with open(path_, 'r', encoding='utf-8')", "i in reader] # ['2020-08-06 04:27:59', 'link','class_', '1'] vm_q =", "break refresh_log(new_q) return vm except UnboundLocalError: return '无可用订阅连接' def avi_num():", "timedelta(hours=12) tag_items += '\\n【√可选】【{}】#{}'.format(bei_ing_time, vm[-2]) # return vm_q.__len__() return tag_items", "writer.writerow(['{}'.format(now), '{}'.format(VMess), class_, '0']) def vmess_IO(class_): \"\"\" 获取可用订阅链接并刷新存储池 class_: ssr", "= csv.writer(f) writer.writerows(dataFlow) try: with open(path_, 'r', encoding='utf-8') as f:", "as f: reader = csv.reader(f) vm_list = [i for i", "== '0'] tag_items = '' for vm in vm_list: if", "in enumerate(reversed(vm_q)): if value[-1] == '0' and value[-2] == class_:", "class_, '0']) def vmess_IO(class_): \"\"\" 获取可用订阅链接并刷新存储池 class_: ssr ; v2ray", "'{}'.format(VMess), class_, '0']) def vmess_IO(class_): \"\"\" 获取可用订阅链接并刷新存储池 class_: ssr ;", "datetime import datetime, timedelta with open(path_, 'r', encoding='utf-8') as f:", "v2ray \"\"\" now = str(datetime.now()).split('.')[0] with open(path_, 'a', encoding='utf-8', newline='')", "str(datetime.now()).split('.')[0] with open(path_, 'a', encoding='utf-8', newline='') as f: writer =", "vm in vm_list if vm[-1] == '0'] tag_items = ''", "csv.writer(f) writer.writerows(dataFlow) try: with open(path_, 'r', encoding='utf-8') as f: reader", "[vm for vm in vm_list if vm[-1] == '0'] tag_items", "newline='') as f: writer = csv.writer(f) writer.writerows(dataFlow) try: with open(path_,", "* path_ = os.path.dirname(os.path.dirname(__file__)) + '/dataBase/log_information.csv' def save_login_info(VMess, class_): \"\"\"", "入库时间,Vmess,初始化状态:0 writer.writerow(['{}'.format(now), '{}'.format(VMess), class_, '0']) def vmess_IO(class_): \"\"\" 获取可用订阅链接并刷新存储池 class_:", "'1' break refresh_log(new_q) return vm except UnboundLocalError: return '无可用订阅连接' def", "newline='') as f: writer = csv.writer(f) # 入库时间,Vmess,初始化状态:0 writer.writerow(['{}'.format(now), '{}'.format(VMess),", "= [vm for vm in vm_list if vm[-1] == '0']", "f: reader = csv.reader(f) vm_q = [vm for vm in", "'w', encoding='utf-8', newline='') as f: writer = csv.writer(f) writer.writerows(dataFlow) try:", "for vm in vm_list: if vm[-1] == '0': bei_ing_time =", "'0'] tag_items = '' for vm in vm_list: if vm[-1]", "'r', encoding='utf-8') as f: reader = csv.reader(f) vm_list = [i", "encoding='utf-8', newline='') as f: writer = csv.writer(f) # 入库时间,Vmess,初始化状态:0 writer.writerow(['{}'.format(now),", "'0': bei_ing_time = datetime.fromisoformat(vm[0]) + timedelta(hours=12) tag_items += '\\n【√可选】【{}】#{}'.format(bei_ing_time, vm[-2])", "vm in vm_list: if vm[-1] == '0': bei_ing_time = datetime.fromisoformat(vm[0])", "\"\"\" now = str(datetime.now()).split('.')[0] with open(path_, 'a', encoding='utf-8', newline='') as", "f: reader = csv.reader(f) vm_list = [i for i in", "= [vm for vm in reader] new_q = vm_q for", "encoding='utf-8', newline='') as f: writer = csv.writer(f) writer.writerows(dataFlow) try: with", "'r', encoding='utf-8') as f: reader = csv.reader(f) vm_q = [vm", "from datetime import datetime, timedelta with open(path_, 'r', encoding='utf-8') as", "csv.writer(f) # 入库时间,Vmess,初始化状态:0 writer.writerow(['{}'.format(now), '{}'.format(VMess), class_, '0']) def vmess_IO(class_): \"\"\"", "bei_ing_time = datetime.fromisoformat(vm[0]) + timedelta(hours=12) tag_items += '\\n【√可选】【{}】#{}'.format(bei_ing_time, vm[-2]) #", "f: writer = csv.writer(f) # 入库时间,Vmess,初始化状态:0 writer.writerow(['{}'.format(now), '{}'.format(VMess), class_, '0'])", "in reader] new_q = vm_q for i, value in enumerate(reversed(vm_q)):", "csv.reader(f) vm_list = [i for i in reader] # ['2020-08-06", "for vm in reader] new_q = vm_q for i, value", "vm_list if vm[-1] == '0'] tag_items = '' for vm", "'a', encoding='utf-8', newline='') as f: writer = csv.writer(f) # 入库时间,Vmess,初始化状态:0", "['2020-08-06 04:27:59', 'link','class_', '1'] vm_q = [vm for vm in", "csv.reader(f) vm_q = [vm for vm in reader] new_q =", "save_login_info(VMess, class_): \"\"\" VMess入库 class_: ssr or v2ray \"\"\" now", "or v2ray \"\"\" now = str(datetime.now()).split('.')[0] with open(path_, 'a', encoding='utf-8',", "value[-1] == '0' and value[-2] == class_: vm = value[1]", "= vm_q for i, value in enumerate(reversed(vm_q)): if value[-1] ==", "writer.writerows(dataFlow) try: with open(path_, 'r', encoding='utf-8') as f: reader =", "'' for vm in vm_list: if vm[-1] == '0': bei_ing_time", "tag_items = '' for vm in vm_list: if vm[-1] ==", "import datetime, timedelta with open(path_, 'r', encoding='utf-8') as f: reader", "class_: ssr ; v2ray \"\"\" def refresh_log(dataFlow): with open(path_, 'w',", "\"\"\" VMess入库 class_: ssr or v2ray \"\"\" now = str(datetime.now()).split('.')[0]", "reader = csv.reader(f) vm_list = [i for i in reader]", "class_: vm = value[1] new_q[-(i + 1)][-1] = '1' break", "for vm in vm_list if vm[-1] == '0'] tag_items =", "timedelta with open(path_, 'r', encoding='utf-8') as f: reader = csv.reader(f)", "open(path_, 'r', encoding='utf-8') as f: reader = csv.reader(f) vm_list =", "= datetime.fromisoformat(vm[0]) + timedelta(hours=12) tag_items += '\\n【√可选】【{}】#{}'.format(bei_ing_time, vm[-2]) # return", "+ timedelta(hours=12) tag_items += '\\n【√可选】【{}】#{}'.format(bei_ing_time, vm[-2]) # return vm_q.__len__() return", "获取可用订阅链接并刷新存储池 class_: ssr ; v2ray \"\"\" def refresh_log(dataFlow): with open(path_,", "\"\"\" def refresh_log(dataFlow): with open(path_, 'w', encoding='utf-8', newline='') as f:", "= csv.writer(f) # 入库时间,Vmess,初始化状态:0 writer.writerow(['{}'.format(now), '{}'.format(VMess), class_, '0']) def vmess_IO(class_):", "enumerate(reversed(vm_q)): if value[-1] == '0' and value[-2] == class_: vm", "if vm[-1] == '0'] tag_items = '' for vm in", "value[-2] == class_: vm = value[1] new_q[-(i + 1)][-1] =", "new_q[-(i + 1)][-1] = '1' break refresh_log(new_q) return vm except", "if value[-1] == '0' and value[-2] == class_: vm =", "with open(path_, 'r', encoding='utf-8') as f: reader = csv.reader(f) vm_list", "def save_login_info(VMess, class_): \"\"\" VMess入库 class_: ssr or v2ray \"\"\"", "f: writer = csv.writer(f) writer.writerows(dataFlow) try: with open(path_, 'r', encoding='utf-8')", "[i for i in reader] # ['2020-08-06 04:27:59', 'link','class_', '1']", "reader] new_q = vm_q for i, value in enumerate(reversed(vm_q)): if", "ssr or v2ray \"\"\" now = str(datetime.now()).split('.')[0] with open(path_, 'a',", "with open(path_, 'a', encoding='utf-8', newline='') as f: writer = csv.writer(f)", "in reader] # ['2020-08-06 04:27:59', 'link','class_', '1'] vm_q = [vm", "== '0': bei_ing_time = datetime.fromisoformat(vm[0]) + timedelta(hours=12) tag_items += '\\n【√可选】【{}】#{}'.format(bei_ing_time,", "from spiderNest.preIntro import * path_ = os.path.dirname(os.path.dirname(__file__)) + '/dataBase/log_information.csv' def", "vm_q = [vm for vm in reader] new_q = vm_q", "vm_list: if vm[-1] == '0': bei_ing_time = datetime.fromisoformat(vm[0]) + timedelta(hours=12)", "\"\"\" 获取可用订阅链接并刷新存储池 class_: ssr ; v2ray \"\"\" def refresh_log(dataFlow): with", "ssr ; v2ray \"\"\" def refresh_log(dataFlow): with open(path_, 'w', encoding='utf-8',", "class_): \"\"\" VMess入库 class_: ssr or v2ray \"\"\" now =", "path_ = os.path.dirname(os.path.dirname(__file__)) + '/dataBase/log_information.csv' def save_login_info(VMess, class_): \"\"\" VMess入库", "datetime, timedelta with open(path_, 'r', encoding='utf-8') as f: reader =", "'无可用订阅连接' def avi_num(): from datetime import datetime, timedelta with open(path_,", "04:27:59', 'link','class_', '1'] vm_q = [vm for vm in vm_list", "'1'] vm_q = [vm for vm in vm_list if vm[-1]", "= [i for i in reader] # ['2020-08-06 04:27:59', 'link','class_',", "writer = csv.writer(f) writer.writerows(dataFlow) try: with open(path_, 'r', encoding='utf-8') as", "= csv.reader(f) vm_q = [vm for vm in reader] new_q", "in vm_list if vm[-1] == '0'] tag_items = '' for", "UnboundLocalError: return '无可用订阅连接' def avi_num(): from datetime import datetime, timedelta", "datetime.fromisoformat(vm[0]) + timedelta(hours=12) tag_items += '\\n【√可选】【{}】#{}'.format(bei_ing_time, vm[-2]) # return vm_q.__len__()", "def vmess_IO(class_): \"\"\" 获取可用订阅链接并刷新存储池 class_: ssr ; v2ray \"\"\" def", "open(path_, 'a', encoding='utf-8', newline='') as f: writer = csv.writer(f) #", "= '1' break refresh_log(new_q) return vm except UnboundLocalError: return '无可用订阅连接'", "; v2ray \"\"\" def refresh_log(dataFlow): with open(path_, 'w', encoding='utf-8', newline='')" ]
[ "as sox except: raise RuntimeError(\"Can not install soxbindings on your", "audio segment to disk as wav file. :param filepath: WAV", "\" \"than audio duration.\") shift_samples = int(shift_ms * self._sample_rate /", "allow_downsampling: Whether to allow the noise signal to be downsampled", "infinite gain to a zero signal. :type max_gain_db: float :param", "or int. \"\"\" def __init__(self, samples, sample_rate): \"\"\"Create audio segment", "2.0 (the \"License\"); # you may not use this file", "2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under", "segment (sample-wise addition, not segment concatenation). Note that this is", "raise ValueError(\"No audio segments are given to concatenate.\") sample_rate =", "None else end if start < 0.0: start += duration", "ValueError(\"The slice end position (%f s) is out of bounds", "around from the end. If not provided, the default behvaior", "impulse_segment.sample_rate: raise ValueError(\"Impulse segment's sample rate (%d Hz) is not", "rate (%d Hz).\" % (impulse_segment.sample_rate, self.sample_rate)) samples = signal.fftconvolve(self.samples, impulse_segment.samples,", "f = io.open(filename, mode='rb', encoding='utf8') version = f.read(4) num_utterances =", ":raises TypeError: If the sample data type is not float", "\"\"\" samples = self._convert_samples_from_float32(self._samples, dtype) return samples.tostring() def to(self, dtype='int16'):", "start_sec if end_sec < 0.0: end_sec = self.duration + end_sec", "speed_rate < 1.0, slow down the audio; speed_rate <= 0.0,", "self._samples = self._convert_samples_to_float32(samples) self._sample_rate = sample_rate if self._samples.ndim >= 2:", "sample_rate) sndfile.seek(start_frame) data = sndfile.read(frames=end_frame - start_frame, dtype='float32') return cls(data,", "samples, sample_rate = soundfile.read(file, dtype='float32') return cls(samples, sample_rate) @classmethod def", "start_sec = self.duration + start_sec if end_sec < 0.0: end_sec", "silent audio segment of the given duration and sample rate.", "in dB that can be applied for normalization. This is", "the lengths of segments don't match. \"\"\" if isinstance(other, type(self)):", "isinstance(file, str) and file.startswith('tar:'): return cls.from_file(subfile_from_tar(file, infos)) else: samples, sample_rate", "end. :type sides: str :raises ValueError: If sides is not", "to keep the duration unchanged. Note that this is an", "audio in decibels. :return: Root mean square energy in decibels.", "specific signal-to-noise ratio. If the noise segment is longer than", "rate. :type target_sample_rate: int :param filter: The resampling filter to", "return self._samples.shape[0] @property def duration(self): \"\"\"Return audio duration. :return: Audio", "silence. Note that this is an in-place transformation. :param duration:", "e.g. out of bounds in time. \"\"\" start_sec = 0.0", "cls(samples, sample_rate) @classmethod def slice_from_file(cls, file, start=None, end=None): \"\"\"Loads a", "instead. Note that this is an in-place transformation. :param noise:", "normalize(self, target_db=-20, max_gain_db=300.0): \"\"\"Normalize audio to be of the desired", "audio duration. :return: Audio duration in seconds. :rtype: float \"\"\"", "segments of the same type \" \"can be concatenated.\") samples", "duration. :rtype: AudioSegment \"\"\" samples = np.zeros(int(duration * sample_rate)) return", "Note that this is an in-place transformation. :param gain: Gain", "cls.concatenate(self, silence) elif sides == \"both\": padded = cls.concatenate(silence, self,", "the audio; speed_rate = 1.0, unchanged; speed_rate < 1.0, slow", "apply to noise signal before adding it in. This is", "containing samples to be added in. :type other: AudioSegments :raise", "a binary file containing a collection of multiple audio files,", "is not \" \"equal to base signal sample rate (%d", "start=None, end=None): \"\"\"Loads a small section of an audio without", "If dtype is not supported. \"\"\" samples = self._convert_samples_from_float32(self._samples, dtype)", "transformation. :param other: Segment containing samples to be added in.", "int(matches.group(2)) # read headers f = io.open(filename, mode='rb', encoding='utf8') version", "on your system.\" ) tfm = sox.Transformer() tfm.set_globals(multithread=False) tfm.speed(speed_rate) self._samples", "that this is an in-place transformation. :param shift_ms: Shift time", "prior_samples: float :param startup_delay: Default 0.0s. If provided, this function", "gain): \"\"\"Apply gain in decibels to samples. Note that this", "be incredibly wasteful. :param file: Input audio filepath or file", "self.sample_rate: noise = noise.resample(self.sample_rate) if noise.sample_rate != self.sample_rate: raise ValueError(\"Noise", "if start is None else start end = duration if", "filepath) filename = matches.group(1) fileno = int(matches.group(2)) # read headers", "this is an in-place transformation. :param start_sec: Beginning of subsegment", "a small section of an audio without having to load", "s) is out of bounds.\" % end_sec) if start_sec >", "Audio segment instance as concatenating results. :rtype: AudioSegment :raises ValueError:", "string containing the audio content. :param dtype: Data type for", "end: float :return: AudioSegment instance of the specified slice of", "shift_ms should be smaller \" \"than audio duration.\") shift_samples =", "sample_rate = soundfile.read(file, dtype='float32') return cls(samples, sample_rate) @classmethod def slice_from_file(cls,", "!= seg._sample_rate: raise ValueError(\"Can't concatenate segments with \" \"different sample", "License for the specific language governing permissions and # limitations", "Subtype for audio file. Options: 'int16', 'int32', 'float32', 'float64'. Default", "of bounds \" \"(> %f s)\" % (end, duration)) start_frame", "audio; speed_rate = 1.0, unchanged; speed_rate < 1.0, slow down", "lengths must match to add segments.\") self._samples += other._samples def", "raise ValueError. :type speed_rate: float :raises ValueError: If speed_rate <=", "self._samples *= 10.**(gain / 20.) def change_speed(self, speed_rate): \"\"\"Change the", "\"\"\"Cut the AudioSegment between given boundaries. Note that this is", "Reserved. # # Licensed under the Apache License, Version 2.0", "dtype. Audio sample type is usually integer or float-point. For", "slice of the input audio file. :rtype: AudioSegment :raise ValueError:", "segment from audio file. Args: filepath (str|file): Filepath or file", "self._sample_rate, format='WAV', subtype=subtype_map[dtype]) def superimpose(self, other): \"\"\"Add samples from another", "segment at a specific signal-to-noise ratio. If the noise segment", "impulse_segment.samples, \"full\") self._samples = samples def convolve_and_normalize(self, impulse_segment, allow_resample=False): \"\"\"Convolve", "> self.duration: raise ValueError(\"Length of subsegment must not be greater", "If not provided, the default behvaior is to read to", "\"\"\" return self._samples.copy() @property def sample_rate(self): \"\"\"Return audio sample rate.", "% (impulse_segment.sample_rate, self.sample_rate)) samples = signal.fftconvolve(self.samples, impulse_segment.samples, \"full\") self._samples =", "0.0: start += duration if end < 0.0: end +=", "raise ValueError(\"Unknown value for the sides %s\" % sides) self._samples", "governing permissions and # limitations under the License. \"\"\"Contains the", "\"\"\" return convert_samples_to_float32(samples) def _convert_samples_from_float32(self, samples, dtype): \"\"\"Convert sample type", "is an in-place transformation. :param noise: Noise signal to add.", "sequence file. :type filepath: str :return: Audio segment instance. :rtype:", "is for writing a audio file. \"\"\" return convert_samples_from_float32(samples, dtype)", "speed_rate: Rate of speed change: speed_rate > 1.0, speed up", "\"\"\" return self._samples.shape[0] / float(self._sample_rate) @property def rms_db(self): \"\"\"Return root", "transformation. :param gain: Gain in decibels to apply to samples.", "file. Sequence file is a binary file containing a collection", "try: import soxbindings as sox except: try: from paddlespeech.s2t.utils import", "\"\"\" if duration == 0.0: return self cls = type(self)", "export samples. Options: 'int16', 'int32', 'float32', 'float64'. Default is 'float32'.", "is not allowed. \"\"\" if allow_resample and self.sample_rate != impulse_segment.sample_rate:", "\"equal to base signal sample rate (%d Hz).\" % (impulse_segment.sample_rate,", "# time advance self._samples[:-shift_samples] = self._samples[shift_samples:] self._samples[-shift_samples:] = 0 elif", "str :return: np.ndarray containing `dtype` audio content. :rtype: str \"\"\"", "AudioSegment :param snr_dB: Signal-to-Noise Ratio, in decibels. :type snr_dB: float", "noise segment at a specific signal-to-noise ratio. If the noise", "sides: Position for padding: 'beginning' - adds silence in the", "must not be greater \" \"than original segment.\") start_time =", "of segments don't match. \"\"\" if isinstance(other, type(self)): raise TypeError(\"Cannot", "speed_rate <= 0: raise ValueError(\"speed_rate should be greater than zero.\")", "start > end: raise ValueError(\"The slice start position (%f s)", "start_sec is None else start_sec end_sec = self.duration if end_sec", "than audio duration. \"\"\" if abs(shift_ms) / 1000.0 > self.duration:", "in millseconds. If positive, shift with time advance; if negative;", "other): \"\"\"Return whether two objects are equal.\"\"\" if type(other) is", "at least as long as\" \" base signal (%f sec).\"", "not type(self): return False if self._sample_rate != other._sample_rate: return False", "is positive, shift with time advance; if negative, shift with", "between given boundaries. Note that this is an in-place transformation.", "* self._sample_rate)) self._samples = self._samples[start_sample:end_sample] def random_subsegment(self, subsegment_length, rng=None): \"\"\"Cut", "this signal. :type allow_resample: bool \"\"\" target_db = self.rms_db self.convolve(impulse_segment,", "self.rms_db self.convolve(impulse_segment, allow_resample=allow_resample) self.normalize(target_db) def add_noise(self, noise, snr_dB, allow_downsampling=False, max_gain_db=300.0,", "snr_dB: Signal-to-Noise Ratio, in decibels. :type snr_dB: float :param allow_downsampling:", "return False if self._sample_rate != other._sample_rate: return False if self._samples.shape", "sndfile = soundfile.SoundFile(file) sample_rate = sndfile.samplerate duration = float(len(sndfile)) /", "None else rng if allow_downsampling and noise.sample_rate > self.sample_rate: noise", "seconds. :type start_sec: float :param end_sec: End of subsegment in", "online normalization. :type startup_delay: float \"\"\" # Estimate total RMS", "sox except: try: from paddlespeech.s2t.utils import dynamic_pip_install package = \"sox\"", "target_db - self.rms_db)) def normalize_online_bayesian(self, target_db, prior_db, prior_samples, startup_delay=0.0): \"\"\"Normalize", "sample_count[:startup_sample_idx] = \\ sample_count[startup_sample_idx] mean_squared_estimate = ((cumsum_of_squares + prior_sum_of_squares) /", "speed_rate) # old_indices = np.arange(old_length) # new_indices = np.linspace(start=0, stop=old_length,", "Random number generator state. :type rng: random.Random :raises ValueError: If", "AudioSegment instance of the specified slice of the input audio", "whether two objects are equal.\"\"\" if type(other) is not type(self):", "the beginning and the end. :type sides: str :raises ValueError:", "If positive, shift with time advance; if negative; shift with", ":param prior_samples: Prior strength in number of samples. :type prior_samples:", "snr_dB, allow_downsampling=False, max_gain_db=300.0, rng=None): \"\"\"Add the given noise segment at", "str|file :param start: Start time in seconds. If start is", "rates of the two segments are not equal, or if", "numpy as np import resampy import soundfile from scipy import", "import copy import io import random import re import struct", "np.linspace(start=0, stop=old_length, num=new_length) # self._samples = np.interp(new_indices, old_indices, self._samples) #", "OF ANY KIND, either express or implied. # See the", "Audio segment instance. \"\"\" if isinstance(file, str) and re.findall(r\".seqbin_\\d+$\", file):", "noise, snr_dB, allow_downsampling=False, max_gain_db=300.0, rng=None): \"\"\"Add the given noise segment", "with time delay. :type shift_ms: float :raises ValueError: If shift_ms", "See the License for the specific language governing permissions and", "bytes_per_header * (i + 1)])[0] for i in range(num_utterances +", "rate. :param duration: Length of silence in seconds. :type duration:", "or if the lengths of segments don't match. \"\"\" if", "the duration unchanged. Note that this is an in-place transformation.", "lengths of segments don't match. \"\"\" if isinstance(other, type(self)): raise", "production-compatible online/causal algorithm. This uses an exponential likelihood and gamma", "uses an exponential likelihood and gamma prior to make online", "version), 4 bytes (int, num of utterance), 4 bytes (int,", "\"\"\" return self._sample_rate @property def num_samples(self): \"\"\"Return number of samples.", "that this is an in-place transformation. :param target_db: Target RMS", "to in writing, software # distributed under the License is", "be concatenated.\") samples = np.concatenate([seg.samples for seg in segments]) return", "startup_delay seconds before applying online normalization. :type startup_delay: float \"\"\"", "not float or int. \"\"\" def __init__(self, samples, sample_rate): \"\"\"Create", "start_sec or end_sec is incorrectly set, e.g. out of bounds", "= matches.group(1) fileno = int(matches.group(2)) # read headers f =", "same type \" \"can be concatenated.\") samples = np.concatenate([seg.samples for", "len(other._samples): raise ValueError(\"Segment lengths must match to add segments.\") self._samples", "cls(samples, sample_rate) @classmethod def concatenate(cls, *segments): \"\"\"Concatenate an arbitrary number", "or agreed to in writing, software # distributed under the", "not equal, or if the lengths of segments don't match.", "desired RMS value in decibels. Note that this is an", "Shift time in millseconds. If positive, shift with time advance;", "instance of the given duration. :rtype: AudioSegment \"\"\" samples =", "def slice_from_file(cls, file, start=None, end=None): \"\"\"Loads a small section of", "[bytes_per_header*(num_utterance+1)] bytes (offsets for each audio), audio_bytes_data_of_1st_utterance, audio_bytes_data_of_2nd_utterance, ...... Sequence", "(offsets for each audio), audio_bytes_data_of_1st_utterance, audio_bytes_data_of_2nd_utterance, ...... Sequence file name", "tuple of AudioSegment :return: Audio segment instance as concatenating results.", "start_sec > end_sec: raise ValueError(\"The slice start position (%f s)", "two segments don't match. :raise ValueError: If the sample rates", "sampled from it and used instead. Note that this is", "old_length = self._samples.shape[0] # new_length = int(old_length / speed_rate) #", "e: samples = np.frombuffer(audio_bytes, dtype='int16') return cls(samples=samples, sample_rate=8000) @classmethod def", "signal to add. :type noise: AudioSegment :param snr_dB: Signal-to-Noise Ratio,", "is a binary file containing a collection of multiple audio", "type(other))) if self._sample_rate != other._sample_rate: raise ValueError(\"Sample rates must match", "match the base signal sample rate. :type allow_downsampling: bool :param", "io.BytesIO(bytes), dtype='float32') return cls(samples, sample_rate) @classmethod def concatenate(cls, *segments): \"\"\"Concatenate", "If not provided, this function reads from the very beginning.", "compliance with the License. # You may obtain a copy", "All Rights Reserved. # # Licensed under the Apache License,", "of different types: %s \" \"and %s.\" % (type(self), type(other)))", "isinstance(other, type(self)): raise TypeError(\"Cannot add segments of different types: %s", "(c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed", "filter: str \"\"\" self._samples = resampy.resample( self.samples, self.sample_rate, target_sample_rate, filter=filter)", ":type start_sec: float :param end_sec: End of subsegment in seconds.", "type from float32 to dtype. Audio sample type is usually", "def gain_db(self, gain): \"\"\"Apply gain in decibels to samples. Note", "sample rate. :type allow_downsampling: bool :param max_gain_db: Maximum amount of", "(%f s) is out of bounds \" \"(> %f s)\"", "audio samples. :return: Audio samples. :rtype: ndarray \"\"\" return self._samples.copy()", "10.**(prior_db / 10.) prior_sum_of_squares = prior_mean_squared * prior_samples cumsum_of_squares =", "segment's sample rate (%d Hz) is not \" \"equal to", ":rtype: AudioSegment \"\"\" # parse filepath matches = re.match(r\"(.+\\.seqbin)_(\\d+)\", filepath)", "import soxbindings as sox except: try: from paddlespeech.s2t.utils import dynamic_pip_install", "_convert_samples_to_float32(self, samples): \"\"\"Convert sample type to float32. Audio sample type", "< self.duration: raise ValueError(\"Noise signal (%f sec) must be at", "audio segment try: return cls.from_bytes(audio_bytes) except Exception as e: samples", "does not match. :raises TypeError: If any segment is not", "from the very beginning. :type start: float :param end: End", "duration if end < 0.0: end += duration if start", "to be downsampled to match the base signal sample rate.", "is None else start end = duration if end is", "dtype='int16'): \"\"\"Create a `dtype` audio content. :param dtype: Data type", "audio segment class.\"\"\" import copy import io import random import", "not use this file except in compliance with the License.", "filename of the 5th utterance's audio file in sequence file", "decibels. Note that this is an in-place transformation. :param target_db:", "be downsampled to match the base signal sample rate. :type", "and sample rate. :param duration: Length of silence in seconds.", "rng if subsegment_length > self.duration: raise ValueError(\"Length of subsegment must", "sample_rate start = 0. if start is None else start", "Target sample rate. :type target_sample_rate: int :param filter: The resampling", "duration if start < 0.0: raise ValueError(\"The slice start position", "you may not use this file except in compliance with", "both the beginning and the end. :type sides: str :raises", ":param impulse_segment: Impulse response segments. :type impulse_segment: AudioSegment :param allow_resample:", "= io.open(filename, mode='rb', encoding='utf8') version = f.read(4) num_utterances = struct.unpack(\"i\",", "start or end is incorrectly set, e.g. out of bounds", "audio segment. :type filepath: str|file :param dtype: Subtype for audio", "end_sec > self.duration: raise ValueError(\"The slice end position (%f s)", "rate. :rtype: int \"\"\" return self._sample_rate @property def num_samples(self): \"\"\"Return", "If speed_rate <= 0.0. \"\"\" if speed_rate == 1.0: return", "given noise segment at a specific signal-to-noise ratio. If the", "old_indices = np.arange(old_length) # new_indices = np.linspace(start=0, stop=old_length, num=new_length) #", "together. :param *segments: Input audio segments to be concatenated. :type", "\"\"\" # parse filepath matches = re.match(r\"(.+\\.seqbin)_(\\d+)\", filepath) if matches", "Length of silence in seconds to pad. :type duration: float", "start_sec end_sec = self.duration if end_sec is None else end_sec", "this signal. :type allow_resample: bool :raises ValueError: If the sample", "return self._sample_rate @property def num_samples(self): \"\"\"Return number of samples. :return:", "integer or float-point. For integer type, float32 will be rescaled", "wasteful. :param file: Input audio filepath or file object. :type", "string containing audio samples. :type bytes: str :return: Audio segment", "] # read audio bytes f.seek(header[fileno - 1]) audio_bytes =", "start) if end < 0.0: raise ValueError(\"The slice end position", "prior_mean_squared * prior_samples cumsum_of_squares = np.cumsum(self.samples**2) sample_count = np.arange(self.num_samples) +", "of the two segments are not equal, or if the", "this is an in-place transformation. :param impulse_segment: Impulse response segments.", "def num_samples(self): \"\"\"Return number of samples. :return: Number of samples.", "def change_speed(self, speed_rate): \"\"\"Change the audio speed by linear interpolation.", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "into the memory which can be incredibly wasteful. :param file:", "concatenate(cls, *segments): \"\"\"Concatenate an arbitrary number of audio segments together.", "the given noise segment at a specific signal-to-noise ratio. If", "np.arange(self.num_samples) + 1 if startup_sample_idx > 0: cumsum_of_squares[:startup_sample_idx] = \\", "= 0 elif shift_samples < 0: # time delay self._samples[-shift_samples:]", "infos)) else: samples, sample_rate = soundfile.read(file, dtype='float32') return cls(samples, sample_rate)", "RMS estimate in decibels. :type prior_db: float :param prior_samples: Prior", "end: raise ValueError(\"The slice start position (%f s) is later", "time advance self._samples[:-shift_samples] = self._samples[shift_samples:] self._samples[-shift_samples:] = 0 elif shift_samples", "self._convert_samples_from_float32(self._samples, dtype) return samples def gain_db(self, gain): \"\"\"Apply gain in", "% end) if start > end: raise ValueError(\"The slice start", "start_sec) if end_sec < 0.0: raise ValueError(\"The slice end position", "not cls: raise TypeError(\"Only audio segments of the same type", "\"\"\"Create audio segment from samples. Samples are convert float32 internally,", "num=new_length) # self._samples = np.interp(new_indices, old_indices, self._samples) # sox, slow", "normalization. :type startup_delay: float \"\"\" # Estimate total RMS online.", "\"\"\"Shift the audio in time. If `shift_ms` is positive, shift", "seconds. :type end_sec: float :raise ValueError: If start_sec or end_sec", "other._samples.shape: return False if np.any(self.samples != other._samples): return False return", ":type allow_downsampling: bool :param max_gain_db: Maximum amount of gain to", "import struct import numpy as np import resampy import soundfile", "s)\" % (end_sec, self.duration)) start_sample = int(round(start_sec * self._sample_rate)) end_sample", "length in seconds. :type subsegment_length: float :param rng: Random number", "np.log10(mean_square) def _convert_samples_to_float32(self, samples): \"\"\"Convert sample type to float32. Audio", "start_sec=None, end_sec=None): \"\"\"Cut the AudioSegment between given boundaries. Note that", "of silence in seconds to pad. :type duration: float :param", "applied for normalization. This is to prevent nans when attempting", "bytes: Byte string containing audio samples. :type bytes: str :return:", "AudioSegments :raise TypeError: If type of two segments don't match.", "int(end * sample_rate) sndfile.seek(start_frame) data = sndfile.read(frames=end_frame - start_frame, dtype='float32')", "% (end_sec, self.duration)) start_sample = int(round(start_sec * self._sample_rate)) end_sample =", "target_sample_rate, filter='kaiser_best'): \"\"\"Resample the audio to a target sample rate.", "end is negative, it wraps around from the end. If", "for dBs mean_square = np.mean(self._samples**2) return 10 * np.log10(mean_square) def", "'beginning' - adds silence in the beginning; 'end' - adds", "\"\"\"Create audio segment from a byte string containing audio samples.", "Defaults to None. Returns: AudioSegment: Audio segment instance. \"\"\" if", "the segment to the target_db value exceeds max_gain_db. \"\"\" gain", "is None else rng if allow_downsampling and noise.sample_rate > self.sample_rate:", "bytes (int, bytes per header), [bytes_per_header*(num_utterance+1)] bytes (offsets for each", "cls(samples, sample_rate) @classmethod def make_silence(cls, duration, sample_rate): \"\"\"Creates a silent", "in decibels. Note that this is an in-place transformation. :param", "def subsegment(self, start_sec=None, end_sec=None): \"\"\"Cut the AudioSegment between given boundaries.", "equal, or if the lengths of segments don't match. \"\"\"", "ValueError: If the sample rate does not match between the", "don't match. :raise ValueError: If the sample rates of the", "end_sec if start_sec < 0.0: start_sec = self.duration + start_sec", "impulse segment. Note that this is an in-place transformation. :param", "an in-place transformation. :param subsegment_length: Subsegment length in seconds. :type", ":raise ValueError: If start or end is incorrectly set, e.g.", "max_gain_db. \"\"\" gain = target_db - self.rms_db if gain >", "in-place transformation. :param other: Segment containing samples to be added", "when the impulse_segment has a different sample rate from this", "or if the duration of noise segments is shorter than", "!= len(other._samples): raise ValueError(\"Segment lengths must match to add segments.\")", "\"\"\" rng = random.Random() if rng is None else rng", "of the desired RMS value in decibels. Note that this", "= 1.0, unchanged; speed_rate < 1.0, slow down the audio;", "adding it in. This is to prevent attempting to apply", "1.0, unchanged; speed_rate < 1.0, slow down the audio; speed_rate", "binary file containing a collection of multiple audio files, with", "# old_indices = np.arange(old_length) # new_indices = np.linspace(start=0, stop=old_length, num=new_length)", "# new_indices = np.linspace(start=0, stop=old_length, num=new_length) # self._samples = np.interp(new_indices,", "target_sample_rate def pad_silence(self, duration, sides='both'): \"\"\"Pad this audio sample with", "audio sample rate. :return: Audio sample rate. :rtype: int \"\"\"", "time-varying gain. gain_db = target_db - rms_estimate_db self.gain_db(gain_db) def resample(self,", "= target_sample_rate def pad_silence(self, duration, sides='both'): \"\"\"Pad this audio sample", "advance; if negative; shift with time delay. :type shift_ms: float", "value in decibels. :type target_bd: float :param prior_db: Prior RMS", "mean square energy of the audio in decibels. :return: Root", "end = duration if end is None else end if", "# numpy # old_length = self._samples.shape[0] # new_length = int(old_length", "is longer than audio duration. \"\"\" if abs(shift_ms) / 1000.0", "= self.duration + start_sec if end_sec < 0.0: end_sec =", "to prevent nans when attempting to normalize a signal consisting", "If start_sec or end_sec is incorrectly set, e.g. out of", ":raises ValueError: If the length of subsegment is greater than", "shift_ms: Shift time in millseconds. If positive, shift with time", "\"\"\"Return number of samples. :return: Number of samples. :rtype: int", "- adds silence in the end; 'both' - adds silence", "the audio in time. If `shift_ms` is positive, shift with", "decibels. :type target_bd: float :param prior_db: Prior RMS estimate in", "file: Input audio filepath or file object. :type file: str|file", "square energy in decibels. :rtype: float \"\"\" # square root", "dynamic_pip_install package = \"sox\" dynamic_pip_install.install(package) package = \"soxbindings\" dynamic_pip_install.install(package) import", "than this segment, a random subsegment of matching length is", "% (start_sec, end_sec)) if end_sec > self.duration: raise ValueError(\"The slice", "filepath, samples, self._sample_rate, format='WAV', subtype=subtype_map[dtype]) def superimpose(self, other): \"\"\"Add samples", "1.0, slow down the audio; speed_rate <= 0.0, not allowed,", "\"the end position (%f s).\" % (start_sec, end_sec)) if end_sec", "if the duration of noise segments is shorter than original", "byte string containing audio samples. :param bytes: Byte string containing", "provided, this function will accrue statistics for the first startup_delay", "np.concatenate([seg.samples for seg in segments]) return cls(samples, sample_rate) @classmethod def", "wraps around from the end. If not provided, the default", "noise: AudioSegment :param snr_dB: Signal-to-Noise Ratio, in decibels. :type snr_dB:", "samples = self._convert_samples_from_float32(self._samples, dtype) return samples.tostring() def to(self, dtype='int16'): \"\"\"Create", ":param dtype: Data type for export samples. Options: 'int16', 'int32',", "decibels. This value should be less than 0.0 as 0.0", "1000) if shift_samples > 0: # time advance self._samples[:-shift_samples] =", "signal to be downsampled to match the base signal sample", "slice end position (%f s).\" % (start, end)) if end", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "silence in the beginning; 'end' - adds silence in the", ":param prior_db: Prior RMS estimate in decibels. :type prior_db: float", "audio duration. \"\"\" if abs(shift_ms) / 1000.0 > self.duration: raise", "Note that this is an in-place transformation. :param impulse_segment: Impulse", "np.zeros(int(duration * sample_rate)) return cls(samples, sample_rate) def to_wav_file(self, filepath, dtype='float32'):", "audio_bytes = f.read(header[fileno] - header[fileno - 1]) f.close() # create", "0.0: end += duration if start < 0.0: raise ValueError(\"The", "in-place transformation. :param impulse_segment: Impulse response segments. :type impulse_segment: AudioSegment", "to the end of the file. :type end: float :return:", "class.\"\"\" import copy import io import random import re import", "If the length of subsegment is greater than the origineal", "from .utility import convert_samples_to_float32 from .utility import subfile_from_tar class AudioSegment():", "else: raise ValueError(\"Unknown value for the sides %s\" % sides)", "end is incorrectly set, e.g. out of bounds in time.", "self._samples.ndim >= 2: self._samples = np.mean(self._samples, 1) def __eq__(self, other):", "target_sample_rate: Target sample rate. :type target_sample_rate: int :param filter: The", "== \"beginning\": padded = cls.concatenate(silence, self) elif sides == \"end\":", "from the end. If not provided, this function reads from", "\"\"\"Cut the specified length of the audiosegment randomly. Note that", "whether resampling is allowed when the impulse_segment has a different", "rng is None else rng if allow_downsampling and noise.sample_rate >", "= resampy.resample( self.samples, self.sample_rate, target_sample_rate, filter=filter) self._sample_rate = target_sample_rate def", "file except in compliance with the License. # You may", "\"\"\"Add the given noise segment at a specific signal-to-noise ratio.", "audio bytes f.seek(header[fileno - 1]) audio_bytes = f.read(header[fileno] - header[fileno", "= np.cumsum(self.samples**2) sample_count = np.arange(self.num_samples) + 1 if startup_sample_idx >", "segment with the given impulse segment. Note that this is", "- noise.rms_db - snr_dB, max_gain_db) noise_new = copy.deepcopy(noise) noise_new.random_subsegment(self.duration, rng=rng)", "Number of samples. :rtype: int \"\"\" return self._samples.shape[0] @property def", "default behvaior is to read to the end of the", "of {'kaiser_best', 'kaiser_fast'}. :type filter: str \"\"\" self._samples = resampy.resample(", "audio using a production-compatible online/causal algorithm. This uses an exponential", "downsampling is not allowed, or if the duration of noise", "def normalize_online_bayesian(self, target_db, prior_db, prior_samples, startup_delay=0.0): \"\"\"Normalize audio using a", "= int(start * sample_rate) end_frame = int(end * sample_rate) sndfile.seek(start_frame)", "return 10 * np.log10(mean_square) def _convert_samples_to_float32(self, samples): \"\"\"Convert sample type", "is negative, it wraps around from the end. If not", "noise.duration < self.duration: raise ValueError(\"Noise signal (%f sec) must be", "be greater than zero.\") # numpy # old_length = self._samples.shape[0]", "or float-point. Integers will be scaled to [-1, 1] in", "def from_file(cls, file, infos=None): \"\"\"Create audio segment from audio file.", ":param target_db: Target RMS value in decibels. :type target_bd: float", "= self._convert_samples_from_float32(self._samples, dtype) return samples.tostring() def to(self, dtype='int16'): \"\"\"Create a", "audio segment of the given duration and sample rate. :param", "rms_estimate_db self.gain_db(gain_db) def resample(self, target_sample_rate, filter='kaiser_best'): \"\"\"Resample the audio to", "segments together. :param *segments: Input audio segments to be concatenated.", "in the end; 'both' - adds silence in both the", "# sox, slow try: import soxbindings as sox except: try:", "given duration and sample rate. :param duration: Length of silence", "a different sample rate from this signal. :type allow_resample: bool", "gain in decibels to samples. Note that this is an", "end < 0.0: raise ValueError(\"The slice end position (%f s)", "position (%f s) is later than \" \"the end position", "total RMS online. startup_sample_idx = min(self.num_samples - 1, int(self.sample_rate *", "gamma prior to make online estimates of the RMS even", "signal. Note that this is an in-place transformation. :param impulse_segment:", "to apply to noise signal before adding it in. This", "time delay. :type shift_ms: float :raises ValueError: If shift_ms is", "rng is None else rng if subsegment_length > self.duration: raise", "position (%f s) is out of bounds \" \"(> %f", "< 0: # time delay self._samples[-shift_samples:] = self._samples[:shift_samples] self._samples[:-shift_samples] =", "in time. If `shift_ms` is positive, shift with time advance;", "memory which can be incredibly wasteful. :param file: Input audio", "self._samples = np.mean(self._samples, 1) def __eq__(self, other): \"\"\"Return whether two", "\"\"\"Return audio duration. :return: Audio duration in seconds. :rtype: float", "ValueError(\"Noise signal (%f sec) must be at least as long", "if self._sample_rate != other._sample_rate: return False if self._samples.shape != other._samples.shape:", "whether two objects are unequal.\"\"\" return not self.__eq__(other) def __str__(self):", "This is to prevent nans when attempting to normalize a", "disk as wav file. :param filepath: WAV filepath or file", "sides) self._samples = padded._samples def shift(self, shift_ms): \"\"\"Shift the audio", "rng: Random number generator state. :type rng: random.Random :raises ValueError:", "> 0: # time advance self._samples[:-shift_samples] = self._samples[shift_samples:] self._samples[-shift_samples:] =", "KIND, either express or implied. # See the License for", "segment concatenation). Note that this is an in-place transformation. :param", "raise ValueError(\"Sample rates must match to add segments.\") if len(self._samples)", "and file.startswith('tar:'): return cls.from_file(subfile_from_tar(file, infos)) else: samples, sample_rate = soundfile.read(file,", "per header), [bytes_per_header*(num_utterance+1)] bytes (offsets for each audio), audio_bytes_data_of_1st_utterance, audio_bytes_data_of_2nd_utterance,", "paddlespeech.s2t.utils import dynamic_pip_install package = \"sox\" dynamic_pip_install.install(package) package = \"soxbindings\"", "\" \"the probable gain have exceeds max_gain_db (%f dB)\" %", "== 1.0: return if speed_rate <= 0: raise ValueError(\"speed_rate should", "soxbindings on your system.\" ) tfm = sox.Transformer() tfm.set_globals(multithread=False) tfm.speed(speed_rate)", "import re import struct import numpy as np import resampy", "struct.unpack(\"i\", f.read(4))[0] header_bytes = f.read(bytes_per_header * (num_utterances + 1)) header", "@classmethod def from_sequence_file(cls, filepath): \"\"\"Create audio segment from sequence file.", "= { 'int16': 'PCM_16', 'int32': 'PCM_32', 'float32': 'FLOAT', 'float64': 'DOUBLE'", "segments.\") self._samples += other._samples def to_bytes(self, dtype='float32'): \"\"\"Create a byte", "segments is shorter than original audio segments. \"\"\" rng =", "audio file in sequence file \"xxx.seqbin\" must be \"xxx.seqbin_5\", with", "concatenated.\") samples = np.concatenate([seg.samples for seg in segments]) return cls(samples,", "silence in the end; 'both' - adds silence in both", "if speed_rate <= 0: raise ValueError(\"speed_rate should be greater than", "f.seek(header[fileno - 1]) audio_bytes = f.read(header[fileno] - header[fileno - 1])", "to_wav_file(self, filepath, dtype='float32'): \"\"\"Save audio segment to disk as wav", "signal. :type allow_resample: bool \"\"\" target_db = self.rms_db self.convolve(impulse_segment, allow_resample=allow_resample)", "10 instead of 20 for dBs mean_square = np.mean(self._samples**2) return", "(the \"License\"); # you may not use this file except", "beginning and the end. :type sides: str :raises ValueError: If", "target sample rate. Note that this is an in-place transformation.", "noise.rms_db - snr_dB, max_gain_db) noise_new = copy.deepcopy(noise) noise_new.random_subsegment(self.duration, rng=rng) noise_new.gain_db(noise_gain_db)", "this is an in-place transformation. :param duration: Length of silence", "\"5\" indicating the utterance index within this sequence file (starting", "= np.arange(old_length) # new_indices = np.linspace(start=0, stop=old_length, num=new_length) # self._samples", "\"\"\"Return whether two objects are equal.\"\"\" if type(other) is not", "tar2infos. Defaults to None. Returns: AudioSegment: Audio segment instance. \"\"\"", "bytes: str :return: Audio segment instance. :rtype: AudioSegment \"\"\" samples,", "beginning. :type start: float :param end: End time in seconds.", "strength in number of samples. :type prior_samples: float :param startup_delay:", "rate. :type allow_downsampling: bool :param max_gain_db: Maximum amount of gain", "\"\"\" # square root => multiply by 10 instead of", "Hz).\" % (noise.sample_rate, self.sample_rate)) if noise.duration < self.duration: raise ValueError(\"Noise", ":return: Audio samples. :rtype: ndarray \"\"\" return self._samples.copy() @property def", "'DOUBLE' } soundfile.write( filepath, samples, self._sample_rate, format='WAV', subtype=subtype_map[dtype]) def superimpose(self,", "ValueError(\"Length of subsegment must not be greater \" \"than original", "package = \"sox\" dynamic_pip_install.install(package) package = \"soxbindings\" dynamic_pip_install.install(package) import soxbindings", "< 1.0, slow down the audio; speed_rate <= 0.0, not", "speed_rate <= 0.0. \"\"\" if speed_rate == 1.0: return if", "# # Unless required by applicable law or agreed to", "start_sec: Beginning of subsegment in seconds. :type start_sec: float :param", "\"the probable gain have exceeds max_gain_db (%f dB)\" % (target_db,", "str :return: Audio segment instance. :rtype: AudioSegment \"\"\" # parse", "= self._samples[shift_samples:] self._samples[-shift_samples:] = 0 elif shift_samples < 0: #", "several header bytes in the head indicating the offsets of", "noise_new.gain_db(noise_gain_db) self.superimpose(noise_new) @property def samples(self): \"\"\"Return audio samples. :return: Audio", "negative; shift with time delay. :type shift_ms: float :raises ValueError:", "snr_dB: float :param allow_downsampling: Whether to allow the noise signal", "and # limitations under the License. \"\"\"Contains the audio segment", "time in seconds. If end is negative, it wraps around", "signal. :type max_gain_db: float :param rng: Random number generator state.", "%s \" \"and %s.\" % (type(self), type(other))) if self._sample_rate !=", "Filepath of sequence file. :type filepath: str :return: Audio segment", "ValueError(\"Segment lengths must match to add segments.\") self._samples += other._samples", "\"than original segment.\") start_time = rng.uniform(0.0, self.duration - subsegment_length) self.subsegment(start_time,", "matches.group(1) fileno = int(matches.group(2)) # read headers f = io.open(filename,", "as wav file. :param filepath: WAV filepath or file object", "def random_subsegment(self, subsegment_length, rng=None): \"\"\"Cut the specified length of the", ">= 2: self._samples = np.mean(self._samples, 1) def __eq__(self, other): \"\"\"Return", "%s is not supported\" % filepath) filename = matches.group(1) fileno", "This uses an exponential likelihood and gamma prior to make", "of the specified slice of the input audio file. :rtype:", "the audio segment class.\"\"\" import copy import io import random", "if end < 0.0: end += duration if start <", "(%f s).\" % (start_sec, end_sec)) if end_sec > self.duration: raise", "two objects are equal.\"\"\" if type(other) is not type(self): return", "return cls(samples, sample_rate) def to_wav_file(self, filepath, dtype='float32'): \"\"\"Save audio segment", "\"both\": padded = cls.concatenate(silence, self, silence) else: raise ValueError(\"Unknown value", "allowed. \"\"\" if allow_resample and self.sample_rate != impulse_segment.sample_rate: impulse_segment.resample(self.sample_rate) if", "cls: raise TypeError(\"Only audio segments of the same type \"", "implied. # See the License for the specific language governing", "segment is not AudioSegment instance. \"\"\" # Perform basic sanity-checks.", "are very few samples. Note that this is an in-place", "If the sample data type is not float or int.", "signal sample rate. :type allow_downsampling: bool :param max_gain_db: Maximum amount", "mean square energy in decibels. :rtype: float \"\"\" # square", "'FLOAT', 'float64': 'DOUBLE' } soundfile.write( filepath, samples, self._sample_rate, format='WAV', subtype=subtype_map[dtype])", "full-scale audio. :type target_db: float :param max_gain_db: Max amount of", "For integer type, float32 will be rescaled from [-1, 1]", "integer type. This is for writing a audio file. \"\"\"", "rng: random.Random :raises ValueError: If the length of subsegment is", "file, start=None, end=None): \"\"\"Loads a small section of an audio", "= 0 def subsegment(self, start_sec=None, end_sec=None): \"\"\"Cut the AudioSegment between", "def concatenate(cls, *segments): \"\"\"Concatenate an arbitrary number of audio segments", "gain = target_db - self.rms_db if gain > max_gain_db: raise", "pad. :type duration: float :param sides: Position for padding: 'beginning'", "1] to the maximum range supported by the integer type.", "system.\" ) tfm = sox.Transformer() tfm.set_globals(multithread=False) tfm.speed(speed_rate) self._samples = tfm.build_array(", "ValueError: If the length of subsegment is greater than the", "% filepath) filename = matches.group(1) fileno = int(matches.group(2)) # read", "segments. :type impulse_segment: AudioSegment :param allow_resample: Indicates whether resampling is", "= self._samples[start_sample:end_sample] def random_subsegment(self, subsegment_length, rng=None): \"\"\"Cut the specified length", "duration. :return: Audio duration in seconds. :rtype: float \"\"\" return", "transformation. :param shift_ms: Shift time in millseconds. If positive, shift", "from paddlespeech.s2t.utils import dynamic_pip_install package = \"sox\" dynamic_pip_install.install(package) package =", "language governing permissions and # limitations under the License. \"\"\"Contains", "transformation. :param target_db: Target RMS value in decibels. This value", "not provided, the default behvaior is to read to the", "it and used instead. Note that this is an in-place", "f.read(header[fileno] - header[fileno - 1]) f.close() # create audio segment", "each audio), audio_bytes_data_of_1st_utterance, audio_bytes_data_of_2nd_utterance, ...... Sequence file name must end", "decibels. :type prior_db: float :param prior_samples: Prior strength in number", ":type snr_dB: float :param allow_downsampling: Whether to allow the noise", "0: # time delay self._samples[-shift_samples:] = self._samples[:shift_samples] self._samples[:-shift_samples] = 0", "when downsampling is not allowed, or if the duration of", "normalize segment to %f dB because the \" \"the probable", "target_db=-20, max_gain_db=300.0): \"\"\"Normalize audio to be of the desired RMS", "slice end position (%f s) is out of bounds.\" %", "\"can be concatenated.\") samples = np.concatenate([seg.samples for seg in segments])", "sample rate. :type sample_rate: int :raises TypeError: If the sample", "string containing audio content. :rtype: str \"\"\" samples = self._convert_samples_from_float32(self._samples,", "matches = re.match(r\"(.+\\.seqbin)_(\\d+)\", filepath) if matches is None: raise IOError(\"File", "% end_sec) if start_sec > end_sec: raise ValueError(\"The slice start", "@property def num_samples(self): \"\"\"Return number of samples. :return: Number of", "return False if np.any(self.samples != other._samples): return False return True", "indicating the offsets of each audio byte data chunk. The", "segments does not match. :raises TypeError: If any segment is", "specified length of the audiosegment randomly. Note that this is", "int(start * sample_rate) end_frame = int(end * sample_rate) sndfile.seek(start_frame) data", ":raises ValueError: If the number of segments is zero, or", "= 0.0 if start_sec is None else start_sec end_sec =", "raise ValueError(\"The slice end position (%f s) is out of", "# read headers f = io.open(filename, mode='rb', encoding='utf8') version =", "def _convert_samples_to_float32(self, samples): \"\"\"Convert sample type to float32. Audio sample", ":param dtype: Subtype for audio file. Options: 'int16', 'int32', 'float32',", "content. :param dtype: Data type for export samples. Options: 'int16',", "is not supported. \"\"\" samples = self._convert_samples_from_float32(self._samples, dtype) subtype_map =", "ValueError(\"speed_rate should be greater than zero.\") # numpy # old_length", "have exceeds max_gain_db (%f dB)\" % (target_db, max_gain_db)) self.gain_db(min(max_gain_db, target_db", "containing `dtype` audio content. :rtype: str \"\"\" samples = self._convert_samples_from_float32(self._samples,", "two audio segments when resample is not allowed. \"\"\" if", "in seconds. :type end_sec: float :raise ValueError: If start_sec or", "Note that this is an in-place transformation. :param start_sec: Beginning", "objects are unequal.\"\"\" return not self.__eq__(other) def __str__(self): \"\"\"Return human-readable", "* self._sample_rate / 1000) if shift_samples > 0: # time", "Unless required by applicable law or agreed to in writing,", "down the audio; speed_rate <= 0.0, not allowed, raise ValueError.", "elif isinstance(file, str) and file.startswith('tar:'): return cls.from_file(subfile_from_tar(file, infos)) else: samples,", ":param filter: The resampling filter to use one of {'kaiser_best',", "than zero.\") # numpy # old_length = self._samples.shape[0] # new_length", "this function reads from the very beginning. :type start: float", "sides == \"beginning\": padded = cls.concatenate(silence, self) elif sides ==", "- self.rms_db if gain > max_gain_db: raise ValueError( \"Unable to", ":type rng: random.Random :raises ValueError: If the length of subsegment", "the specific language governing permissions and # limitations under the", "import signal from .utility import convert_samples_from_float32 from .utility import convert_samples_to_float32", "online estimates of the RMS even when there are very", "padded._samples def shift(self, shift_ms): \"\"\"Shift the audio in time. If", "the given duration and sample rate. :param duration: Length of", "impulse_segment, allow_resample=False): \"\"\"Convolve and normalize the resulting audio segment so", "the RMS even when there are very few samples. Note", "0.0 is full-scale audio. :type target_db: float :param max_gain_db: Max", "which can be incredibly wasteful. :param file: Input audio filepath", "ValueError(\"The slice end position (%f s) is out of bounds.\"", "self.samples, self.sample_rate, target_sample_rate, filter=filter) self._sample_rate = target_sample_rate def pad_silence(self, duration,", "Audio samples. :rtype: ndarray \"\"\" return self._samples.copy() @property def sample_rate(self):", "# Compute required time-varying gain. gain_db = target_db - rms_estimate_db", "!= other._samples.shape: return False if np.any(self.samples != other._samples): return False", "numpy # old_length = self._samples.shape[0] # new_length = int(old_length /", ".utility import convert_samples_to_float32 from .utility import subfile_from_tar class AudioSegment(): \"\"\"Monaural", "if end_sec < 0.0: raise ValueError(\"The slice end position (%f", "else end if start < 0.0: start += duration if", "not provided, this function reads from the very beginning. :type", "Audio duration in seconds. :rtype: float \"\"\" return self._samples.shape[0] /", "Hz) is not equal to base \" \"signal sample rate", ":raises TypeError: If any segment is not AudioSegment instance. \"\"\"", "self.sample_rate != impulse_segment.sample_rate: impulse_segment.resample(self.sample_rate) if self.sample_rate != impulse_segment.sample_rate: raise ValueError(\"Impulse", "entire file into the memory which can be incredibly wasteful.", "return samples.tostring() def to(self, dtype='int16'): \"\"\"Create a `dtype` audio content.", "\"\"\"Create audio segment from sequence file. Sequence file is a", "original segment.\") start_time = rng.uniform(0.0, self.duration - subsegment_length) self.subsegment(start_time, start_time", "allow_resample=allow_resample) self.normalize(target_db) def add_noise(self, noise, snr_dB, allow_downsampling=False, max_gain_db=300.0, rng=None): \"\"\"Add", "sample rate. :type target_sample_rate: int :param filter: The resampling filter", "Subsegment length in seconds. :type subsegment_length: float :param rng: Random", "instance. :rtype: AudioSegment \"\"\" # parse filepath matches = re.match(r\"(.+\\.seqbin)_(\\d+)\",", "self._sample_rate @property def num_samples(self): \"\"\"Return number of samples. :return: Number", "sndfile.seek(start_frame) data = sndfile.read(frames=end_frame - start_frame, dtype='float32') return cls(data, sample_rate)", ":type prior_samples: float :param startup_delay: Default 0.0s. If provided, this", "to be of the desired RMS value in decibels. Note", "samples: Audio samples [num_samples x num_channels]. :type samples: ndarray.float32 :param", "in the head indicating the offsets of each audio byte", "<reponame>AK391/PaddleSpeech # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.", "in decibels. :type target_bd: float :param prior_db: Prior RMS estimate", "# create audio segment try: return cls.from_bytes(audio_bytes) except Exception as", "to a target sample rate. Note that this is an", "the 5th utterance's audio file in sequence file \"xxx.seqbin\" must", "sample rate (%d Hz) is not equal to base \"", "\" base signal (%f sec).\" % (noise.duration, self.duration)) noise_gain_db =", "self._sample_rate != other._sample_rate: raise ValueError(\"Sample rates must match to add", "the sample rate does not match between the two audio", "4 bytes (int, num of utterance), 4 bytes (int, bytes", "cls.concatenate(silence, self) elif sides == \"end\": padded = cls.concatenate(self, silence)", "self.rms_db)) @classmethod def from_file(cls, file, infos=None): \"\"\"Create audio segment from", ":type file: str|file :param start: Start time in seconds. If", "byte string containing the audio content. :param dtype: Data type", "def samples(self): \"\"\"Return audio samples. :return: Audio samples. :rtype: ndarray", "sample type is usually integer or float-point. For integer type,", "rng: None|random.Random :raises ValueError: If the sample rate does not", "float :param prior_samples: Prior strength in number of samples. :type", "samples = self._convert_samples_from_float32(self._samples, dtype) subtype_map = { 'int16': 'PCM_16', 'int32':", "read to the end of the file. :type end: float", ":param rng: Random number generator state. :type rng: random.Random :raises", "the file. :type end: float :return: AudioSegment instance of the", "concatenating results. :rtype: AudioSegment :raises ValueError: If the number of", "len(self._samples) != len(other._samples): raise ValueError(\"Segment lengths must match to add", ":param sample_rate: Audio sample rate. :type sample_rate: int :raises TypeError:", "or file object to audio file. infos (TarLocalData, optional): tar2obj", "Rate of speed change: speed_rate > 1.0, speed up the", "i in range(num_utterances + 1) ] # read audio bytes", "Perform basic sanity-checks. if len(segments) == 0: raise ValueError(\"No audio", ":rtype: int \"\"\" return self._samples.shape[0] @property def duration(self): \"\"\"Return audio", "is None: raise IOError(\"File type of %s is not supported\"", "file containing a collection of multiple audio files, with several", "padding: 'beginning' - adds silence in the beginning; 'end' -", "s) is out of bounds \" \"(> %f s)\" %", "segment to the target_db value exceeds max_gain_db. \"\"\" gain =", "allow_resample=False): \"\"\"Convolve this audio segment with the given impulse segment.", "segments of different types: %s \" \"and %s.\" % (type(self),", "slow down the audio; speed_rate <= 0.0, not allowed, raise", "% (end, duration)) start_frame = int(start * sample_rate) end_frame =", "= sox.Transformer() tfm.set_globals(multithread=False) tfm.speed(speed_rate) self._samples = tfm.build_array( input_array=self._samples, sample_rate_in=self._sample_rate).squeeze(-1).astype( np.float32).copy()", "containing audio samples. :param bytes: Byte string containing audio samples.", "/ sample_rate start = 0. if start is None else", "rate from this signal. :type allow_resample: bool :raises ValueError: If", ":type dtype: str :raises TypeError: If dtype is not supported.", "= f.read(bytes_per_header * (num_utterances + 1)) header = [ struct.unpack(\"i\",", "sample rate is not match between two audio segments when", "type(self)): raise TypeError(\"Cannot add segments of different types: %s \"", "and re.findall(r\".seqbin_\\d+$\", file): return cls.from_sequence_file(file) elif isinstance(file, str) and file.startswith('tar:'):", "incredibly wasteful. :param file: Input audio filepath or file object.", "other._sample_rate: return False if self._samples.shape != other._samples.shape: return False if", "string containing audio samples. :param bytes: Byte string containing audio", "allow_downsampling and noise.sample_rate > self.sample_rate: noise = noise.resample(self.sample_rate) if noise.sample_rate", "file into the memory which can be incredibly wasteful. :param", "ValueError(\"The slice start position (%f s) is later than \"", "another segment to those of this segment (sample-wise addition, not", "position (%f s) is out of bounds.\" % end) if", "new_indices = np.linspace(start=0, stop=old_length, num=new_length) # self._samples = np.interp(new_indices, old_indices,", "is out of \" \"bounds.\" % start) if end <", "random.Random :raises ValueError: If the length of subsegment is greater", "self.duration, self.rms_db)) @classmethod def from_file(cls, file, infos=None): \"\"\"Create audio segment", "negative, it wraps around from the end. If not provided,", "instance. \"\"\" if isinstance(file, str) and re.findall(r\".seqbin_\\d+$\", file): return cls.from_sequence_file(file)", "to_bytes(self, dtype='float32'): \"\"\"Create a byte string containing the audio content.", "an in-place transformation. :param shift_ms: Shift time in millseconds. If", "self._sample_rate)) self._samples = self._samples[start_sample:end_sample] def random_subsegment(self, subsegment_length, rng=None): \"\"\"Cut the", "struct import numpy as np import resampy import soundfile from", "float32 internally, with int scaled to [-1, 1]. \"\"\" self._samples", "of silence in seconds. :type duration: float :param sample_rate: Sample", "the first startup_delay seconds before applying online normalization. :type startup_delay:", "float :param sample_rate: Sample rate. :type sample_rate: float :return: Silent", "\"bounds.\" % start_sec) if end_sec < 0.0: raise ValueError(\"The slice", "audio segment with the given impulse segment. Note that this", "shift with time advance; if negative; shift with time delay.", "out of bounds.\" % end) if start > end: raise", "statistics for the first startup_delay seconds before applying online normalization.", "cls.from_sequence_file(file) elif isinstance(file, str) and file.startswith('tar:'): return cls.from_file(subfile_from_tar(file, infos)) else:", "file is a binary file containing a collection of multiple", "silence in both the beginning and the end. :type sides:", "shift_samples > 0: # time advance self._samples[:-shift_samples] = self._samples[shift_samples:] self._samples[-shift_samples:]", "target_db - rms_estimate_db self.gain_db(gain_db) def resample(self, target_sample_rate, filter='kaiser_best'): \"\"\"Resample the", "noise_new = copy.deepcopy(noise) noise_new.random_subsegment(self.duration, rng=rng) noise_new.gain_db(noise_gain_db) self.superimpose(noise_new) @property def samples(self):", "1.0: return if speed_rate <= 0: raise ValueError(\"speed_rate should be", "raise ValueError(\"speed_rate should be greater than zero.\") # numpy #", "@classmethod def make_silence(cls, duration, sample_rate): \"\"\"Creates a silent audio segment", "If provided, this function will accrue statistics for the first", "<= 0.0, not allowed, raise ValueError. :type speed_rate: float :raises", "file. :param filepath: WAV filepath or file object to save", "def to_wav_file(self, filepath, dtype='float32'): \"\"\"Save audio segment to disk as", "= self.rms_db self.convolve(impulse_segment, allow_resample=allow_resample) self.normalize(target_db) def add_noise(self, noise, snr_dB, allow_downsampling=False,", "end is None else end if start < 0.0: start", "self._samples.shape[0] / float(self._sample_rate) @property def rms_db(self): \"\"\"Return root mean square", "supported\" % filepath) filename = matches.group(1) fileno = int(matches.group(2)) #", "bool \"\"\" target_db = self.rms_db self.convolve(impulse_segment, allow_resample=allow_resample) self.normalize(target_db) def add_noise(self,", "function reads from the very beginning. :type start: float :param", "max_gain_db)) self.gain_db(min(max_gain_db, target_db - self.rms_db)) def normalize_online_bayesian(self, target_db, prior_db, prior_samples,", "filepath: Filepath of sequence file. :type filepath: str :return: Audio", "0: cumsum_of_squares[:startup_sample_idx] = \\ cumsum_of_squares[startup_sample_idx] sample_count[:startup_sample_idx] = \\ sample_count[startup_sample_idx] mean_squared_estimate", "np.float32).copy() def normalize(self, target_db=-20, max_gain_db=300.0): \"\"\"Normalize audio to be of", "f.read(4) num_utterances = struct.unpack(\"i\", f.read(4))[0] bytes_per_header = struct.unpack(\"i\", f.read(4))[0] header_bytes", "sample_rate) @classmethod def slice_from_file(cls, file, start=None, end=None): \"\"\"Loads a small", "samples.tostring() def to(self, dtype='int16'): \"\"\"Create a `dtype` audio content. :param", "prior_db: float :param prior_samples: Prior strength in number of samples.", "byte data chunk. The format is: 4 bytes (int, version),", "RMS value in decibels. :type target_bd: float :param prior_db: Prior", "target_db value exceeds max_gain_db. \"\"\" gain = target_db - self.rms_db", "file. :rtype: AudioSegment :raise ValueError: If start or end is", "1)])[0] for i in range(num_utterances + 1) ] # read", "in seconds. :type duration: float :param sample_rate: Sample rate. :type", ":raise TypeError: If type of two segments don't match. :raise", "filter=filter) self._sample_rate = target_sample_rate def pad_silence(self, duration, sides='both'): \"\"\"Pad this", "ValueError(\"Absolute value of shift_ms should be smaller \" \"than audio", "type to float32. Audio sample type is usually integer or", "soundfile from scipy import signal from .utility import convert_samples_from_float32 from", "other._samples): return False return True def __ne__(self, other): \"\"\"Return whether", "If sides is not supported. \"\"\" if duration == 0.0:", "an in-place transformation. :param impulse_segment: Impulse response segments. :type impulse_segment:", "an arbitrary number of audio segments together. :param *segments: Input", ":param duration: Length of silence in seconds. :type duration: float", "to make online estimates of the RMS even when there", "You may obtain a copy of the License at #", ":type subsegment_length: float :param rng: Random number generator state. :type", "0: # time advance self._samples[:-shift_samples] = self._samples[shift_samples:] self._samples[-shift_samples:] = 0", "start_time = rng.uniform(0.0, self.duration - subsegment_length) self.subsegment(start_time, start_time + subsegment_length)", "shift with time delay. Silence are padded to keep the", "exceeds max_gain_db (%f dB)\" % (target_db, max_gain_db)) self.gain_db(min(max_gain_db, target_db -", ":type duration: float :param sample_rate: Sample rate. :type sample_rate: float", "not match between the two audio segments when downsampling is", "max_gain_db) noise_new = copy.deepcopy(noise) noise_new.random_subsegment(self.duration, rng=rng) noise_new.gain_db(noise_gain_db) self.superimpose(noise_new) @property def", "(int, num of utterance), 4 bytes (int, bytes per header),", "the sample_rate of any segments does not match. :raises TypeError:", "allow_resample: bool \"\"\" target_db = self.rms_db self.convolve(impulse_segment, allow_resample=allow_resample) self.normalize(target_db) def", "samples, sample_rate = soundfile.read( io.BytesIO(bytes), dtype='float32') return cls(samples, sample_rate) @classmethod", "sample_rate = soundfile.read( io.BytesIO(bytes), dtype='float32') return cls(samples, sample_rate) @classmethod def", "rates must match to add segments.\") if len(self._samples) != len(other._samples):", "the License. \"\"\"Contains the audio segment class.\"\"\" import copy import", "0: raise ValueError(\"No audio segments are given to concatenate.\") sample_rate", "a byte string containing the audio content. :param dtype: Data", "normalize the resulting audio segment so that it has the", "(num_utterances + 1)) header = [ struct.unpack(\"i\", header_bytes[bytes_per_header * i:", "to dtype. Audio sample type is usually integer or float-point.", "ValueError: If speed_rate <= 0.0. \"\"\" if speed_rate == 1.0:", "speed_rate == 1.0: return if speed_rate <= 0: raise ValueError(\"speed_rate", "bounds \" \"(> %f s)\" % (end, duration)) start_frame =", "0.0 as 0.0 is full-scale audio. :type target_db: float :param", "matching length is sampled from it and used instead. Note", "base signal (%f sec).\" % (noise.duration, self.duration)) noise_gain_db = min(self.rms_db", "startup_delay: Default 0.0s. If provided, this function will accrue statistics", "usually integer or float-point. For integer type, float32 will be", "dtype='float32') return cls(samples, sample_rate) @classmethod def slice_from_file(cls, file, start=None, end=None):", "of the RMS even when there are very few samples.", "delay. :type shift_ms: float :raises ValueError: If shift_ms is longer", "self.__eq__(other) def __str__(self): \"\"\"Return human-readable representation of segment.\"\"\" return (\"%s:", "soundfile.read( io.BytesIO(bytes), dtype='float32') return cls(samples, sample_rate) @classmethod def concatenate(cls, *segments):", "raise ValueError(\"Noise sample rate (%d Hz) is not equal to", "< 0.0: raise ValueError(\"The slice start position (%f s) is", "other._samples def to_bytes(self, dtype='float32'): \"\"\"Create a byte string containing the", "of subsegment is greater than the origineal segemnt. \"\"\" rng", "millseconds. If positive, shift with time advance; if negative; shift", "to the target_db value exceeds max_gain_db. \"\"\" gain = target_db", "target_sample_rate, filter=filter) self._sample_rate = target_sample_rate def pad_silence(self, duration, sides='both'): \"\"\"Pad", "resampy import soundfile from scipy import signal from .utility import", "= sndfile.samplerate duration = float(len(sndfile)) / sample_rate start = 0.", "prior_samples cumsum_of_squares = np.cumsum(self.samples**2) sample_count = np.arange(self.num_samples) + 1 if", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "if noise.duration < self.duration: raise ValueError(\"Noise signal (%f sec) must", "* sample_rate)) return cls(samples, sample_rate) def to_wav_file(self, filepath, dtype='float32'): \"\"\"Save", "= int(shift_ms * self._sample_rate / 1000) if shift_samples > 0:", ":param noise: Noise signal to add. :type noise: AudioSegment :param", "start_frame = int(start * sample_rate) end_frame = int(end * sample_rate)", "a `dtype` audio content. :param dtype: Data type for export", "of utterance), 4 bytes (int, bytes per header), [bytes_per_header*(num_utterance+1)] bytes", "self._samples = np.interp(new_indices, old_indices, self._samples) # sox, slow try: import", "target_db = self.rms_db self.convolve(impulse_segment, allow_resample=allow_resample) self.normalize(target_db) def add_noise(self, noise, snr_dB,", "= random.Random() if rng is None else rng if allow_downsampling", "slice_from_file(cls, file, start=None, end=None): \"\"\"Loads a small section of an", "wraps around from the end. If not provided, this function", "in decibels. :type snr_dB: float :param allow_downsampling: Whether to allow", "objects are equal.\"\"\" if type(other) is not type(self): return False", "the specified slice of the input audio file. :rtype: AudioSegment", "1 if startup_sample_idx > 0: cumsum_of_squares[:startup_sample_idx] = \\ cumsum_of_squares[startup_sample_idx] sample_count[:startup_sample_idx]", "end: End time in seconds. If end is negative, it", "energy of the audio in decibels. :return: Root mean square", "number generator state. :type rng: None|random.Random :raises ValueError: If the", "sox except: raise RuntimeError(\"Can not install soxbindings on your system.\"", ":rtype: AudioSegment :raises ValueError: If the number of segments is", "to the maximum range supported by the integer type. This", "- 1]) f.close() # create audio segment try: return cls.from_bytes(audio_bytes)", "= struct.unpack(\"i\", f.read(4))[0] bytes_per_header = struct.unpack(\"i\", f.read(4))[0] header_bytes = f.read(bytes_per_header", "RMS value in decibels. Note that this is an in-place", "@classmethod def from_bytes(cls, bytes): \"\"\"Create audio segment from a byte", "if sample_rate != seg._sample_rate: raise ValueError(\"Can't concatenate segments with \"", ":raise ValueError: If start_sec or end_sec is incorrectly set, e.g.", "s) is later than \" \"the slice end position (%f", "that this is an in-place transformation. :param noise: Noise signal", "self._convert_samples_to_float32(samples) self._sample_rate = sample_rate if self._samples.ndim >= 2: self._samples =", "prior to make online estimates of the RMS even when", "are not equal, or if the lengths of segments don't", "fileno = int(matches.group(2)) # read headers f = io.open(filename, mode='rb',", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "will be rescaled from [-1, 1] to the maximum range", "in seconds. :type subsegment_length: float :param rng: Random number generator", "\" \"than original segment.\") start_time = rng.uniform(0.0, self.duration - subsegment_length)", "not supported\" % filepath) filename = matches.group(1) fileno = int(matches.group(2))", "impulse_segment: Impulse response segments. :type impulse_segment: AudioSegment :param allow_resample: Indicates", "License. # You may obtain a copy of the License", "=> multiply by 10 instead of 20 for dBs mean_square", "file \"xxx.seqbin\" must be \"xxx.seqbin_5\", with \"5\" indicating the utterance", "segments is zero, or if the sample_rate of any segments", "in seconds. If end is negative, it wraps around from", "rate. :return: Audio sample rate. :rtype: int \"\"\" return self._sample_rate", "raise ValueError( \"Unable to normalize segment to %f dB because", "\"xxx.seqbin_5\", with \"5\" indicating the utterance index within this sequence", "duration in seconds. :rtype: float \"\"\" return self._samples.shape[0] / float(self._sample_rate)", "concatenation). Note that this is an in-place transformation. :param other:", "else end_sec if start_sec < 0.0: start_sec = self.duration +", "to save the audio segment. :type filepath: str|file :param dtype:", "self.duration + end_sec if start_sec < 0.0: raise ValueError(\"The slice", "is to prevent attempting to apply infinite gain to a", "audio samples. :param bytes: Byte string containing audio samples. :type", "subsegment_length) def convolve(self, impulse_segment, allow_resample=False): \"\"\"Convolve this audio segment with", "square root => multiply by 10 instead of 20 for", "of gain in dB that can be applied for normalization.", "speed change: speed_rate > 1.0, speed up the audio; speed_rate", "audio content. :param dtype: Data type for export samples. Options:", "be less than 0.0 as 0.0 is full-scale audio. :type", "of all zeros. :type max_gain_db: float :raises ValueError: If the", "for each audio), audio_bytes_data_of_1st_utterance, audio_bytes_data_of_2nd_utterance, ...... Sequence file name must", "= 10 * np.log10(mean_squared_estimate) # Compute required time-varying gain. gain_db", "Default is 'float32'. :type dtype: str :return: np.ndarray containing `dtype`", "+ prior_samples)) rms_estimate_db = 10 * np.log10(mean_squared_estimate) # Compute required", "elif sides == \"both\": padded = cls.concatenate(silence, self, silence) else:", "before applying online normalization. :type startup_delay: float \"\"\" # Estimate", "end_sec: End of subsegment in seconds. :type end_sec: float :raise", ":param *segments: Input audio segments to be concatenated. :type *segments:", "smaller \" \"than audio duration.\") shift_samples = int(shift_ms * self._sample_rate", "the resulting audio segment so that it has the same", "file (starting from 1). :param filepath: Filepath of sequence file.", "This is for writing a audio file. \"\"\" return convert_samples_from_float32(samples,", "to [-1, 1] in float32. \"\"\" return convert_samples_to_float32(samples) def _convert_samples_from_float32(self,", "to float32. Audio sample type is usually integer or float-point.", "tfm.speed(speed_rate) self._samples = tfm.build_array( input_array=self._samples, sample_rate_in=self._sample_rate).squeeze(-1).astype( np.float32).copy() def normalize(self, target_db=-20,", "else: samples, sample_rate = soundfile.read(file, dtype='float32') return cls(samples, sample_rate) @classmethod", "raise IOError(\"File type of %s is not supported\" % filepath)", "required gain to normalize the segment to the target_db value", "in range(num_utterances + 1) ] # read audio bytes f.seek(header[fileno", "sample rates of the two segments are not equal, or", "self._samples.copy() @property def sample_rate(self): \"\"\"Return audio sample rate. :return: Audio", "rng: Random number generator state. :type rng: None|random.Random :raises ValueError:", "max_gain_db: raise ValueError( \"Unable to normalize segment to %f dB", "If the number of segments is zero, or if the", "AudioSegment: Audio segment instance. \"\"\" if isinstance(file, str) and re.findall(r\".seqbin_\\d+$\",", "\"\"\" self._samples = resampy.resample( self.samples, self.sample_rate, target_sample_rate, filter=filter) self._sample_rate =", "soundfile.read(file, dtype='float32') return cls(samples, sample_rate) @classmethod def slice_from_file(cls, file, start=None,", "out of \" \"bounds.\" % start) if end < 0.0:", "'int16', 'int32', 'float32', 'float64'. Default is 'float32'. :type dtype: str", "for normalization. This is to prevent nans when attempting to", "@classmethod def concatenate(cls, *segments): \"\"\"Concatenate an arbitrary number of audio", "= target_db - rms_estimate_db self.gain_db(gain_db) def resample(self, target_sample_rate, filter='kaiser_best'): \"\"\"Resample", "num_channels]. :type samples: ndarray.float32 :param sample_rate: Audio sample rate. :type", "audio segment from a byte string containing audio samples. :param", "be applied for normalization. This is to prevent nans when", "self._samples[:-shift_samples] = self._samples[shift_samples:] self._samples[-shift_samples:] = 0 elif shift_samples < 0:", "match between the two audio segments when downsampling is not", "of bounds \" \"(> %f s)\" % (end_sec, self.duration)) start_sample", "reads from the very beginning. :type start: float :param end:", "i: bytes_per_header * (i + 1)])[0] for i in range(num_utterances", "end position (%f s) is out of bounds.\" % end_sec)", "Audio sample rate. :type sample_rate: int :raises TypeError: If the", "AudioSegment between given boundaries. Note that this is an in-place", "shift_samples = int(shift_ms * self._sample_rate / 1000) if shift_samples >", "position (%f s) is later than \" \"the slice end", "generator state. :type rng: None|random.Random :raises ValueError: If the sample", "if startup_sample_idx > 0: cumsum_of_squares[:startup_sample_idx] = \\ cumsum_of_squares[startup_sample_idx] sample_count[:startup_sample_idx] =", "samples: ndarray.float32 :param sample_rate: Audio sample rate. :type sample_rate: int", "\"\"\"Pad this audio sample with a period of silence. Note", "randomly. Note that this is an in-place transformation. :param subsegment_length:", "< 0.0: start += duration if end < 0.0: end", "if start_sec > end_sec: raise ValueError(\"The slice start position (%f", "% start_sec) if end_sec < 0.0: raise ValueError(\"The slice end", "of the same type \" \"can be concatenated.\") samples =", "segment to disk as wav file. :param filepath: WAV filepath", "indicating the utterance index within this sequence file (starting from", "header_bytes = f.read(bytes_per_header * (num_utterances + 1)) header = [", "noise.sample_rate != self.sample_rate: raise ValueError(\"Noise sample rate (%d Hz) is", "must be at least as long as\" \" base signal", "is not float or int. \"\"\" def __init__(self, samples, sample_rate):", "is an in-place transformation. :param shift_ms: Shift time in millseconds.", "if negative; shift with time delay. :type shift_ms: float :raises", "'end' - adds silence in the end; 'both' - adds", "infos (TarLocalData, optional): tar2obj and tar2infos. Defaults to None. Returns:", "sample rate does not match between the two audio segments", "ValueError(\"Impulse segment's sample rate (%d Hz) is not \" \"equal", "rng.uniform(0.0, self.duration - subsegment_length) self.subsegment(start_time, start_time + subsegment_length) def convolve(self,", "for audio file. Options: 'int16', 'int32', 'float32', 'float64'. Default is", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "The format is: 4 bytes (int, version), 4 bytes (int,", "float :return: AudioSegment instance of the specified slice of the", "end if start < 0.0: start += duration if end", "audio files, with several header bytes in the head indicating", "20 for dBs mean_square = np.mean(self._samples**2) return 10 * np.log10(mean_square)", "segments when resample is not allowed. \"\"\" if allow_resample and", "dtype: Subtype for audio file. Options: 'int16', 'int32', 'float32', 'float64'.", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "filename = matches.group(1) fileno = int(matches.group(2)) # read headers f", "\" \"equal to base signal sample rate (%d Hz).\" %", "f.read(4))[0] bytes_per_header = struct.unpack(\"i\", f.read(4))[0] header_bytes = f.read(bytes_per_header * (num_utterances", "if isinstance(other, type(self)): raise TypeError(\"Cannot add segments of different types:", "the input audio file. :rtype: AudioSegment :raise ValueError: If start", "shorter than original audio segments. \"\"\" rng = random.Random() if", "required by applicable law or agreed to in writing, software", "this function will accrue statistics for the first startup_delay seconds", "samples. :return: Number of samples. :rtype: int \"\"\" return self._samples.shape[0]", ":type end_sec: float :raise ValueError: If start_sec or end_sec is", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "positive, shift with time advance; if negative; shift with time", "Maximum amount of gain to apply to noise signal before", "= samples def convolve_and_normalize(self, impulse_segment, allow_resample=False): \"\"\"Convolve and normalize the", "duration: Length of silence in seconds. :type duration: float :param", "segment to those of this segment (sample-wise addition, not segment", "in seconds. :type start_sec: float :param end_sec: End of subsegment", "not \" \"equal to base signal sample rate (%d Hz).\"", "def duration(self): \"\"\"Return audio duration. :return: Audio duration in seconds.", "up the audio; speed_rate = 1.0, unchanged; speed_rate < 1.0,", "file. Args: filepath (str|file): Filepath or file object to audio", "the very beginning. :type start: float :param end: End time", "agreed to in writing, software # distributed under the License", "sample_count = np.arange(self.num_samples) + 1 if startup_sample_idx > 0: cumsum_of_squares[:startup_sample_idx]", "# read audio bytes f.seek(header[fileno - 1]) audio_bytes = f.read(header[fileno]", "the duration of noise segments is shorter than original audio", "distributed under the License is distributed on an \"AS IS\"", "start = 0. if start is None else start end", "of silence. Note that this is an in-place transformation. :param", "set, e.g. out of bounds in time. \"\"\" start_sec =", "if end < 0.0: raise ValueError(\"The slice end position (%f", "this is an in-place transformation. :param gain: Gain in decibels", "without having to load the entire file into the memory", "end_sec if start_sec < 0.0: raise ValueError(\"The slice start position", "def sample_rate(self): \"\"\"Return audio sample rate. :return: Audio sample rate.", "__ne__(self, other): \"\"\"Return whether two objects are unequal.\"\"\" return not", "- rms_estimate_db self.gain_db(gain_db) def resample(self, target_sample_rate, filter='kaiser_best'): \"\"\"Resample the audio", "struct.unpack(\"i\", header_bytes[bytes_per_header * i: bytes_per_header * (i + 1)])[0] for", "of the given duration. :rtype: AudioSegment \"\"\" samples = np.zeros(int(duration", "self) elif sides == \"end\": padded = cls.concatenate(self, silence) elif", "0.0: raise ValueError(\"The slice end position (%f s) is out", "of 20 for dBs mean_square = np.mean(self._samples**2) return 10 *", "self._sample_rate)) end_sample = int(round(end_sec * self._sample_rate)) self._samples = self._samples[start_sample:end_sample] def", "file, infos=None): \"\"\"Create audio segment from audio file. Args: filepath", "signal. :type allow_resample: bool :raises ValueError: If the sample rate", ":return: Byte string containing audio content. :rtype: str \"\"\" samples", ":param sides: Position for padding: 'beginning' - adds silence in", "impulse_segment has a different sample rate from this signal. :type", "\"\"\" start_sec = 0.0 if start_sec is None else start_sec", "the same average power as the input signal. Note that", "filepath or file object to save the audio segment. :type", "= self.make_silence(duration, self._sample_rate) if sides == \"beginning\": padded = cls.concatenate(silence,", "import numpy as np import resampy import soundfile from scipy", "def __init__(self, samples, sample_rate): \"\"\"Create audio segment from samples. Samples", "audio file. Args: filepath (str|file): Filepath or file object to", "match to add segments.\") if len(self._samples) != len(other._samples): raise ValueError(\"Segment", "(start_sec, end_sec)) if end_sec > self.duration: raise ValueError(\"The slice end", "to disk as wav file. :param filepath: WAV filepath or", "!= impulse_segment.sample_rate: impulse_segment.resample(self.sample_rate) if self.sample_rate != impulse_segment.sample_rate: raise ValueError(\"Impulse segment's", "rng=None): \"\"\"Add the given noise segment at a specific signal-to-noise", "of each audio byte data chunk. The format is: 4", "the desired RMS value in decibels. Note that this is", "slice start position (%f s) is out of \" \"bounds.\"", "are convert float32 internally, with int scaled to [-1, 1].", "raise RuntimeError(\"Can not install soxbindings on your system.\" ) tfm", "if abs(shift_ms) / 1000.0 > self.duration: raise ValueError(\"Absolute value of", "generator state. :type rng: random.Random :raises ValueError: If the length", "in-place transformation. :param target_db: Target RMS value in decibels. This", "AudioSegment :return: Audio segment instance as concatenating results. :rtype: AudioSegment", "speed by linear interpolation. Note that this is an in-place", "+ end_sec if start_sec < 0.0: raise ValueError(\"The slice start", "= np.mean(self._samples**2) return 10 * np.log10(mean_square) def _convert_samples_to_float32(self, samples): \"\"\"Convert", "out of bounds in time. \"\"\" sndfile = soundfile.SoundFile(file) sample_rate", "of two segments don't match. :raise ValueError: If the sample", "audio_bytes_data_of_1st_utterance, audio_bytes_data_of_2nd_utterance, ...... Sequence file name must end with \".seqbin\".", "segments.\") if len(self._samples) != len(other._samples): raise ValueError(\"Segment lengths must match", "ValueError: If start_sec or end_sec is incorrectly set, e.g. out", "Target RMS value in decibels. This value should be less", "Args: filepath (str|file): Filepath or file object to audio file.", "self._convert_samples_from_float32(self._samples, dtype) return samples.tostring() def to(self, dtype='int16'): \"\"\"Create a `dtype`", "np import resampy import soundfile from scipy import signal from", "*segments: Input audio segments to be concatenated. :type *segments: tuple", "= segments[0]._sample_rate for seg in segments: if sample_rate != seg._sample_rate:", "zeros. :type max_gain_db: float :raises ValueError: If the required gain", "Signal-to-Noise Ratio, in decibels. :type snr_dB: float :param allow_downsampling: Whether", "raise ValueError(\"Noise signal (%f sec) must be at least as", "are equal.\"\"\" if type(other) is not type(self): return False if", "@property def sample_rate(self): \"\"\"Return audio sample rate. :return: Audio sample", "is not supported. \"\"\" if duration == 0.0: return self", "in seconds. :rtype: float \"\"\" return self._samples.shape[0] / float(self._sample_rate) @property", "filepath): \"\"\"Create audio segment from sequence file. Sequence file is", "= np.zeros(int(duration * sample_rate)) return cls(samples, sample_rate) def to_wav_file(self, filepath,", "subsegment_length: Subsegment length in seconds. :type subsegment_length: float :param rng:", "(int, version), 4 bytes (int, num of utterance), 4 bytes", "rms_db(self): \"\"\"Return root mean square energy of the audio in", "try: return cls.from_bytes(audio_bytes) except Exception as e: samples = np.frombuffer(audio_bytes,", "raise TypeError(\"Only audio segments of the same type \" \"can", "self.superimpose(noise_new) @property def samples(self): \"\"\"Return audio samples. :return: Audio samples.", "\"\"\"Change the audio speed by linear interpolation. Note that this", "signal-to-noise ratio. If the noise segment is longer than this", "* sample_rate) sndfile.seek(start_frame) data = sndfile.read(frames=end_frame - start_frame, dtype='float32') return", "audio byte data chunk. The format is: 4 bytes (int,", "cls(samples=samples, sample_rate=8000) @classmethod def from_bytes(cls, bytes): \"\"\"Create audio segment from", "that this is an in-place transformation. :param other: Segment containing", "sec).\" % (noise.duration, self.duration)) noise_gain_db = min(self.rms_db - noise.rms_db -", "(noise.duration, self.duration)) noise_gain_db = min(self.rms_db - noise.rms_db - snr_dB, max_gain_db)", "raise TypeError(\"Cannot add segments of different types: %s \" \"and", "file object. :type file: str|file :param start: Start time in", "bytes_per_header = struct.unpack(\"i\", f.read(4))[0] header_bytes = f.read(bytes_per_header * (num_utterances +", "target_db: Target RMS value in decibels. :type target_bd: float :param", "as np import resampy import soundfile from scipy import signal", "float(len(sndfile)) / sample_rate start = 0. if start is None", "startup_delay: float \"\"\" # Estimate total RMS online. startup_sample_idx =", "float :param allow_downsampling: Whether to allow the noise signal to", "type. This is for writing a audio file. \"\"\" return", "OR CONDITIONS OF ANY KIND, either express or implied. #", "None: raise IOError(\"File type of %s is not supported\" %", "(starting from 1). :param filepath: Filepath of sequence file. :type", "the License is distributed on an \"AS IS\" BASIS, #", "is usually integer or float-point. Integers will be scaled to", "save the audio segment. :type filepath: str|file :param dtype: Subtype", "to prevent attempting to apply infinite gain to a zero", "file object to audio file. infos (TarLocalData, optional): tar2obj and", "segment. :type filepath: str|file :param dtype: Subtype for audio file.", "\"\"\"Resample the audio to a target sample rate. Note that", "soundfile.SoundFile(file) sample_rate = sndfile.samplerate duration = float(len(sndfile)) / sample_rate start", "small section of an audio without having to load the", "type is usually integer or float-point. For integer type, float32", "with time delay. Silence are padded to keep the duration", "10.**(gain / 20.) def change_speed(self, speed_rate): \"\"\"Change the audio speed", "your system.\" ) tfm = sox.Transformer() tfm.set_globals(multithread=False) tfm.speed(speed_rate) self._samples =", "sample_rate = segments[0]._sample_rate for seg in segments: if sample_rate !=", "AudioSegment instance. \"\"\" # Perform basic sanity-checks. if len(segments) ==", "dtype is not supported. \"\"\" samples = self._convert_samples_from_float32(self._samples, dtype) subtype_map", "\"\"\" # Perform basic sanity-checks. if len(segments) == 0: raise", "\".seqbin\". And the filename of the 5th utterance's audio file", "don't match. \"\"\" if isinstance(other, type(self)): raise TypeError(\"Cannot add segments", "a period of silence. Note that this is an in-place", "slice end position (%f s) is out of bounds \"", "collection of multiple audio files, with several header bytes in", "pad_silence(self, duration, sides='both'): \"\"\"Pad this audio sample with a period", "min(self.rms_db - noise.rms_db - snr_dB, max_gain_db) noise_new = copy.deepcopy(noise) noise_new.random_subsegment(self.duration,", "% (start, end)) if end > duration: raise ValueError(\"The slice", "+= duration if start < 0.0: raise ValueError(\"The slice start", "import convert_samples_to_float32 from .utility import subfile_from_tar class AudioSegment(): \"\"\"Monaural audio", "% (noise.sample_rate, self.sample_rate)) if noise.duration < self.duration: raise ValueError(\"Noise signal", "very few samples. Note that this is an in-place transformation.", "\" \"rms=%.2fdB\" % (type(self), self.num_samples, self.sample_rate, self.duration, self.rms_db)) @classmethod def", "Returns: AudioSegment: Audio segment instance. \"\"\" if isinstance(file, str) and", "is to prevent nans when attempting to normalize a signal", "law or agreed to in writing, software # distributed under", "\"\"\"Concatenate an arbitrary number of audio segments together. :param *segments:", "is None else end_sec if start_sec < 0.0: start_sec =", "self.subsegment(start_time, start_time + subsegment_length) def convolve(self, impulse_segment, allow_resample=False): \"\"\"Convolve this", "file. Options: 'int16', 'int32', 'float32', 'float64'. Default is 'float32'. :type", "If `shift_ms` is positive, shift with time advance; if negative,", "the noise segment is longer than this segment, a random", "amount of gain in dB that can be applied for", "number of samples. :return: Number of samples. :rtype: int \"\"\"", "10.) prior_sum_of_squares = prior_mean_squared * prior_samples cumsum_of_squares = np.cumsum(self.samples**2) sample_count", "seg in segments]) return cls(samples, sample_rate) @classmethod def make_silence(cls, duration,", ":return: Audio segment instance. :rtype: AudioSegment \"\"\" # parse filepath", "sample rate (%d Hz) is not \" \"equal to base", "gain > max_gain_db: raise ValueError( \"Unable to normalize segment to", "\" \"signal sample rate (%d Hz).\" % (noise.sample_rate, self.sample_rate)) if", "internally, with int scaled to [-1, 1]. \"\"\" self._samples =", "must match to add segments.\") self._samples += other._samples def to_bytes(self,", "provided, this function reads from the very beginning. :type start:", "file: str|file :param start: Start time in seconds. If start", "TypeError: If dtype is not supported. \"\"\" samples = self._convert_samples_from_float32(self._samples,", "(%f s) is later than \" \"the end position (%f", "padded = cls.concatenate(silence, self) elif sides == \"end\": padded =", "may obtain a copy of the License at # #", "segment, a random subsegment of matching length is sampled from", "Byte string containing audio samples. :type bytes: str :return: Audio", "for export samples. Options: 'int16', 'int32', 'float32', 'float64'. Default is", "if type(seg) is not cls: raise TypeError(\"Only audio segments of", "audio. :type target_db: float :param max_gain_db: Max amount of gain", "or end_sec is incorrectly set, e.g. out of bounds in", "= signal.fftconvolve(self.samples, impulse_segment.samples, \"full\") self._samples = samples def convolve_and_normalize(self, impulse_segment,", "few samples. Note that this is an in-place transformation. :param", "type(seg) is not cls: raise TypeError(\"Only audio segments of the", "Options: 'int16', 'int32', 'float32', 'float64'. Default is 'float32'. :type dtype:", "in number of samples. :type prior_samples: float :param startup_delay: Default", "return cls(data, sample_rate) @classmethod def from_sequence_file(cls, filepath): \"\"\"Create audio segment", "Audio samples [num_samples x num_channels]. :type samples: ndarray.float32 :param sample_rate:", "= cls.concatenate(silence, self, silence) else: raise ValueError(\"Unknown value for the", "import random import re import struct import numpy as np", "@property def samples(self): \"\"\"Return audio samples. :return: Audio samples. :rtype:", "may not use this file except in compliance with the", "self.num_samples, self.sample_rate, self.duration, self.rms_db)) @classmethod def from_file(cls, file, infos=None): \"\"\"Create", "bytes): \"\"\"Create audio segment from a byte string containing audio", "bounds.\" % end_sec) if start_sec > end_sec: raise ValueError(\"The slice", "seconds. :rtype: float \"\"\" return self._samples.shape[0] / float(self._sample_rate) @property def", "not allowed, or if the duration of noise segments is", "len(segments) == 0: raise ValueError(\"No audio segments are given to", "# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. #", "\" \"the end position (%f s).\" % (start_sec, end_sec)) if", "root => multiply by 10 instead of 20 for dBs", "copy import io import random import re import struct import", "this file except in compliance with the License. # You", "type(other) is not type(self): return False if self._sample_rate != other._sample_rate:", "nans when attempting to normalize a signal consisting of all", "slow try: import soxbindings as sox except: try: from paddlespeech.s2t.utils", "= np.arange(self.num_samples) + 1 if startup_sample_idx > 0: cumsum_of_squares[:startup_sample_idx] =", "float or int. \"\"\" def __init__(self, samples, sample_rate): \"\"\"Create audio", "to use one of {'kaiser_best', 'kaiser_fast'}. :type filter: str \"\"\"", ":raises ValueError: If the sample rate does not match between", "this segment, a random subsegment of matching length is sampled", "package = \"soxbindings\" dynamic_pip_install.install(package) import soxbindings as sox except: raise", "audio in time. If `shift_ms` is positive, shift with time", "# # Licensed under the Apache License, Version 2.0 (the", "+ 1)) header = [ struct.unpack(\"i\", header_bytes[bytes_per_header * i: bytes_per_header", "of bounds in time. \"\"\" start_sec = 0.0 if start_sec", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "(target_db, max_gain_db)) self.gain_db(min(max_gain_db, target_db - self.rms_db)) def normalize_online_bayesian(self, target_db, prior_db,", "None else end_sec if start_sec < 0.0: start_sec = self.duration", "def rms_db(self): \"\"\"Return root mean square energy of the audio", "return cls(samples=samples, sample_rate=8000) @classmethod def from_bytes(cls, bytes): \"\"\"Create audio segment", "that this is an in-place transformation. :param duration: Length of", "if rng is None else rng if subsegment_length > self.duration:", "is an in-place transformation. :param duration: Length of silence in", "* (num_utterances + 1)) header = [ struct.unpack(\"i\", header_bytes[bytes_per_header *", "is an in-place transformation. :param impulse_segment: Impulse response segments. :type", "bool :param max_gain_db: Maximum amount of gain to apply to", "filepath (str|file): Filepath or file object to audio file. infos", "def __ne__(self, other): \"\"\"Return whether two objects are unequal.\"\"\" return", "# limitations under the License. \"\"\"Contains the audio segment class.\"\"\"", "rates\") if type(seg) is not cls: raise TypeError(\"Only audio segments", "'int32', 'float32', 'float64'. Default is 'float32'. :type dtype: str :return:", "*segments): \"\"\"Concatenate an arbitrary number of audio segments together. :param", "self._samples = tfm.build_array( input_array=self._samples, sample_rate_in=self._sample_rate).squeeze(-1).astype( np.float32).copy() def normalize(self, target_db=-20, max_gain_db=300.0):", "transformation. :param speed_rate: Rate of speed change: speed_rate > 1.0,", "with \"5\" indicating the utterance index within this sequence file", "file): return cls.from_sequence_file(file) elif isinstance(file, str) and file.startswith('tar:'): return cls.from_file(subfile_from_tar(file,", "@classmethod def slice_from_file(cls, file, start=None, end=None): \"\"\"Loads a small section", "(%f s) is out of \" \"bounds.\" % start_sec) if", "%s\" % sides) self._samples = padded._samples def shift(self, shift_ms): \"\"\"Shift", "duration=%.2fsec, \" \"rms=%.2fdB\" % (type(self), self.num_samples, self.sample_rate, self.duration, self.rms_db)) @classmethod", "other: Segment containing samples to be added in. :type other:", "try: from paddlespeech.s2t.utils import dynamic_pip_install package = \"sox\" dynamic_pip_install.install(package) package", "decibels. :type snr_dB: float :param allow_downsampling: Whether to allow the", "s) is out of \" \"bounds.\" % start_sec) if end_sec", "in decibels. :return: Root mean square energy in decibels. :rtype:", "is not supported\" % filepath) filename = matches.group(1) fileno =", "zero, or if the sample_rate of any segments does not", "seconds. If end is negative, it wraps around from the", "different sample rate from this signal. :type allow_resample: bool \"\"\"", "prior_samples: Prior strength in number of samples. :type prior_samples: float", "cumsum_of_squares = np.cumsum(self.samples**2) sample_count = np.arange(self.num_samples) + 1 if startup_sample_idx", "to None. Returns: AudioSegment: Audio segment instance. \"\"\" if isinstance(file,", "max_gain_db=300.0): \"\"\"Normalize audio to be of the desired RMS value", "[-1, 1] to the maximum range supported by the integer", "ValueError: If the sample rates of the two segments are", "segment so that it has the same average power as", "str) and file.startswith('tar:'): return cls.from_file(subfile_from_tar(file, infos)) else: samples, sample_rate =", "*= 10.**(gain / 20.) def change_speed(self, speed_rate): \"\"\"Change the audio", "or implied. # See the License for the specific language", ") tfm = sox.Transformer() tfm.set_globals(multithread=False) tfm.speed(speed_rate) self._samples = tfm.build_array( input_array=self._samples,", "energy in decibels. :rtype: float \"\"\" # square root =>", "Default is 'float32'. :type dtype: str :return: Byte string containing", "zero.\") # numpy # old_length = self._samples.shape[0] # new_length =", "end_sec < 0.0: raise ValueError(\"The slice end position (%f s)", "scaled to [-1, 1]. \"\"\" self._samples = self._convert_samples_to_float32(samples) self._sample_rate =", "1]. \"\"\" self._samples = self._convert_samples_to_float32(samples) self._sample_rate = sample_rate if self._samples.ndim", "is not cls: raise TypeError(\"Only audio segments of the same", ":param start: Start time in seconds. If start is negative,", "Exception as e: samples = np.frombuffer(audio_bytes, dtype='int16') return cls(samples=samples, sample_rate=8000)", "start end = duration if end is None else end", "longer than audio duration. \"\"\" if abs(shift_ms) / 1000.0 >", "Note that this is an in-place transformation. :param other: Segment", "scipy import signal from .utility import convert_samples_from_float32 from .utility import", "of subsegment must not be greater \" \"than original segment.\")", "root mean square energy of the audio in decibels. :return:", ":type gain: float|1darray \"\"\" self._samples *= 10.**(gain / 20.) def", "Samples are convert float32 internally, with int scaled to [-1,", "silence in seconds to pad. :type duration: float :param sides:", "end; 'both' - adds silence in both the beginning and", "0.0: raise ValueError(\"The slice start position (%f s) is out", "content. :rtype: str \"\"\" samples = self._convert_samples_from_float32(self._samples, dtype) return samples", "* sample_rate) end_frame = int(end * sample_rate) sndfile.seek(start_frame) data =", "def superimpose(self, other): \"\"\"Add samples from another segment to those", "time. \"\"\" sndfile = soundfile.SoundFile(file) sample_rate = sndfile.samplerate duration =", "dtype) subtype_map = { 'int16': 'PCM_16', 'int32': 'PCM_32', 'float32': 'FLOAT',", "(%f s) is later than \" \"the slice end position", "float :param rng: Random number generator state. :type rng: None|random.Random", "shift_ms: float :raises ValueError: If shift_ms is longer than audio", "type for export samples. Options: 'int16', 'int32', 'float32', 'float64'. Default", "min(self.num_samples - 1, int(self.sample_rate * startup_delay)) prior_mean_squared = 10.**(prior_db /", "transformation. :param duration: Length of silence in seconds to pad.", "\"\"\"Convolve and normalize the resulting audio segment so that it", "online/causal algorithm. This uses an exponential likelihood and gamma prior", "- 1]) audio_bytes = f.read(header[fileno] - header[fileno - 1]) f.close()", "concatenate segments with \" \"different sample rates\") if type(seg) is", "signal before adding it in. This is to prevent attempting", "\"\"\" samples, sample_rate = soundfile.read( io.BytesIO(bytes), dtype='float32') return cls(samples, sample_rate)", "applying online normalization. :type startup_delay: float \"\"\" # Estimate total", "None|random.Random :raises ValueError: If the sample rate does not match", "= 0. if start is None else start end =", "instance. \"\"\" # Perform basic sanity-checks. if len(segments) == 0:", "np.frombuffer(audio_bytes, dtype='int16') return cls(samples=samples, sample_rate=8000) @classmethod def from_bytes(cls, bytes): \"\"\"Create", "* self._sample_rate)) end_sample = int(round(end_sec * self._sample_rate)) self._samples = self._samples[start_sample:end_sample]", "range(num_utterances + 1) ] # read audio bytes f.seek(header[fileno -", "those of this segment (sample-wise addition, not segment concatenation). Note", "sndfile.samplerate duration = float(len(sndfile)) / sample_rate start = 0. if", "(TarLocalData, optional): tar2obj and tar2infos. Defaults to None. Returns: AudioSegment:", "TypeError(\"Cannot add segments of different types: %s \" \"and %s.\"", "rescaled from [-1, 1] to the maximum range supported by", "a collection of multiple audio files, with several header bytes", "prior_db: Prior RMS estimate in decibels. :type prior_db: float :param", ":return: Silent AudioSegment instance of the given duration. :rtype: AudioSegment", "if start_sec < 0.0: start_sec = self.duration + start_sec if", ":param target_sample_rate: Target sample rate. :type target_sample_rate: int :param filter:", ":type prior_db: float :param prior_samples: Prior strength in number of", "this is an in-place transformation. :param subsegment_length: Subsegment length in", "if start_sec is None else start_sec end_sec = self.duration if", "def from_sequence_file(cls, filepath): \"\"\"Create audio segment from sequence file. Sequence", "= np.linspace(start=0, stop=old_length, num=new_length) # self._samples = np.interp(new_indices, old_indices, self._samples)", "start_frame, dtype='float32') return cls(data, sample_rate) @classmethod def from_sequence_file(cls, filepath): \"\"\"Create", "allow_resample: bool :raises ValueError: If the sample rate is not", "duration, sides='both'): \"\"\"Pad this audio sample with a period of", "normalization. This is to prevent nans when attempting to normalize", "infos=None): \"\"\"Create audio segment from audio file. Args: filepath (str|file):", "\"\"\"Apply gain in decibels to samples. Note that this is", "\"different sample rates\") if type(seg) is not cls: raise TypeError(\"Only", "audio without having to load the entire file into the", "keep the duration unchanged. Note that this is an in-place", "int(shift_ms * self._sample_rate / 1000) if shift_samples > 0: #", "can be incredibly wasteful. :param file: Input audio filepath or", "# new_length = int(old_length / speed_rate) # old_indices = np.arange(old_length)", "subsegment of matching length is sampled from it and used", "subsegment must not be greater \" \"than original segment.\") start_time", "of segments is zero, or if the sample_rate of any", "any segments does not match. :raises TypeError: If any segment", "TypeError: If the sample data type is not float or", "+ prior_sum_of_squares) / (sample_count + prior_samples)) rms_estimate_db = 10 *", "duration: raise ValueError(\"The slice end position (%f s) is out", "segments don't match. \"\"\" if isinstance(other, type(self)): raise TypeError(\"Cannot add", "self._samples) # sox, slow try: import soxbindings as sox except:", "0: raise ValueError(\"speed_rate should be greater than zero.\") # numpy", "to concatenate.\") sample_rate = segments[0]._sample_rate for seg in segments: if", "normalize the segment to the target_db value exceeds max_gain_db. \"\"\"", "not supported. \"\"\" if duration == 0.0: return self cls", "from_sequence_file(cls, filepath): \"\"\"Create audio segment from sequence file. Sequence file", "sndfile.read(frames=end_frame - start_frame, dtype='float32') return cls(data, sample_rate) @classmethod def from_sequence_file(cls,", "the entire file into the memory which can be incredibly", "elif sides == \"end\": padded = cls.concatenate(self, silence) elif sides", "def add_noise(self, noise, snr_dB, allow_downsampling=False, max_gain_db=300.0, rng=None): \"\"\"Add the given", "is shorter than original audio segments. \"\"\" rng = random.Random()", "in-place transformation. :param start_sec: Beginning of subsegment in seconds. :type", "if start < 0.0: raise ValueError(\"The slice start position (%f", "self._sample_rate = sample_rate if self._samples.ndim >= 2: self._samples = np.mean(self._samples,", "exponential likelihood and gamma prior to make online estimates of", "*segments: tuple of AudioSegment :return: Audio segment instance as concatenating", ":raises ValueError: If sides is not supported. \"\"\" if duration", "self.duration if end_sec is None else end_sec if start_sec <", "`shift_ms` is positive, shift with time advance; if negative, shift", "= \\ sample_count[startup_sample_idx] mean_squared_estimate = ((cumsum_of_squares + prior_sum_of_squares) / (sample_count", "adds silence in the beginning; 'end' - adds silence in", "gain to apply to noise signal before adding it in.", "in-place transformation. :param shift_ms: Shift time in millseconds. If positive,", "it wraps around from the end. If not provided, the", "audio_bytes_data_of_2nd_utterance, ...... Sequence file name must end with \".seqbin\". And", "Sequence file is a binary file containing a collection of", "dB because the \" \"the probable gain have exceeds max_gain_db", "sample rate from this signal. :type allow_resample: bool \"\"\" target_db", "> 1.0, speed up the audio; speed_rate = 1.0, unchanged;", "decibels to samples. Note that this is an in-place transformation.", "an in-place transformation. :param target_sample_rate: Target sample rate. :type target_sample_rate:", "transformation. :param subsegment_length: Subsegment length in seconds. :type subsegment_length: float", "def from_bytes(cls, bytes): \"\"\"Create audio segment from a byte string", "segment instance. \"\"\" if isinstance(file, str) and re.findall(r\".seqbin_\\d+$\", file): return", "stop=old_length, num=new_length) # self._samples = np.interp(new_indices, old_indices, self._samples) # sox,", "\" \"(> %f s)\" % (end, duration)) start_frame = int(start", "to base \" \"signal sample rate (%d Hz).\" % (noise.sample_rate,", "optional): tar2obj and tar2infos. Defaults to None. Returns: AudioSegment: Audio", "longer than this segment, a random subsegment of matching length", "ValueError(\"Noise sample rate (%d Hz) is not equal to base", "Beginning of subsegment in seconds. :type start_sec: float :param end_sec:", "the required gain to normalize the segment to the target_db", "int :raises TypeError: If the sample data type is not", "If any segment is not AudioSegment instance. \"\"\" # Perform", "raise ValueError(\"Impulse segment's sample rate (%d Hz) is not \"", "return False return True def __ne__(self, other): \"\"\"Return whether two", "matches is None: raise IOError(\"File type of %s is not", "in-place transformation. :param gain: Gain in decibels to apply to", "samples. Options: 'int16', 'int32', 'float32', 'float64'. Default is 'float32'. :type", "and gamma prior to make online estimates of the RMS", "(type(self), type(other))) if self._sample_rate != other._sample_rate: raise ValueError(\"Sample rates must", "duration, sample_rate): \"\"\"Creates a silent audio segment of the given", "subsegment(self, start_sec=None, end_sec=None): \"\"\"Cut the AudioSegment between given boundaries. Note", "def __str__(self): \"\"\"Return human-readable representation of segment.\"\"\" return (\"%s: num_samples=%d,", "\"\"\"Creates a silent audio segment of the given duration and", ":param target_db: Target RMS value in decibels. This value should", "% (target_db, max_gain_db)) self.gain_db(min(max_gain_db, target_db - self.rms_db)) def normalize_online_bayesian(self, target_db,", "end += duration if start < 0.0: raise ValueError(\"The slice", "start < 0.0: raise ValueError(\"The slice start position (%f s)", "rng=None): \"\"\"Cut the specified length of the audiosegment randomly. Note", "match. :raise ValueError: If the sample rates of the two", "audio segment from sequence file. Sequence file is a binary", "= int(old_length / speed_rate) # old_indices = np.arange(old_length) # new_indices", "self._sample_rate != other._sample_rate: return False if self._samples.shape != other._samples.shape: return", "out of bounds \" \"(> %f s)\" % (end, duration))", "'int32', 'float32', 'float64'. Default is 'float32'. :type dtype: str :raises", ":return: Audio duration in seconds. :rtype: float \"\"\" return self._samples.shape[0]", "not equal to base \" \"signal sample rate (%d Hz).\"", "str) and re.findall(r\".seqbin_\\d+$\", file): return cls.from_sequence_file(file) elif isinstance(file, str) and", ":param snr_dB: Signal-to-Noise Ratio, in decibels. :type snr_dB: float :param", "sample_rate: Sample rate. :type sample_rate: float :return: Silent AudioSegment instance", "\\ cumsum_of_squares[startup_sample_idx] sample_count[:startup_sample_idx] = \\ sample_count[startup_sample_idx] mean_squared_estimate = ((cumsum_of_squares +", "end_sec) if start_sec > end_sec: raise ValueError(\"The slice start position", "allow_resample and self.sample_rate != impulse_segment.sample_rate: impulse_segment.resample(self.sample_rate) if self.sample_rate != impulse_segment.sample_rate:", "in writing, software # distributed under the License is distributed", "sides == \"end\": padded = cls.concatenate(self, silence) elif sides ==", "data = sndfile.read(frames=end_frame - start_frame, dtype='float32') return cls(data, sample_rate) @classmethod", "start < 0.0: start += duration if end < 0.0:", "segments to be concatenated. :type *segments: tuple of AudioSegment :return:", "return (\"%s: num_samples=%d, sample_rate=%d, duration=%.2fsec, \" \"rms=%.2fdB\" % (type(self), self.num_samples,", "beginning; 'end' - adds silence in the end; 'both' -", "`dtype` audio content. :rtype: str \"\"\" samples = self._convert_samples_from_float32(self._samples, dtype)", "gain_db(self, gain): \"\"\"Apply gain in decibels to samples. Note that", "* startup_delay)) prior_mean_squared = 10.**(prior_db / 10.) prior_sum_of_squares = prior_mean_squared", "} soundfile.write( filepath, samples, self._sample_rate, format='WAV', subtype=subtype_map[dtype]) def superimpose(self, other):", "length is sampled from it and used instead. Note that", "value of shift_ms should be smaller \" \"than audio duration.\")", "< 0.0: start_sec = self.duration + start_sec if end_sec <", "will be scaled to [-1, 1] in float32. \"\"\" return", "in segments: if sample_rate != seg._sample_rate: raise ValueError(\"Can't concatenate segments", "= prior_mean_squared * prior_samples cumsum_of_squares = np.cumsum(self.samples**2) sample_count = np.arange(self.num_samples)", "(%f dB)\" % (target_db, max_gain_db)) self.gain_db(min(max_gain_db, target_db - self.rms_db)) def", "self.duration + start_sec if end_sec < 0.0: end_sec = self.duration", "to [-1, 1]. \"\"\" self._samples = self._convert_samples_to_float32(samples) self._sample_rate = sample_rate", "self._samples[shift_samples:] self._samples[-shift_samples:] = 0 elif shift_samples < 0: # time", "is out of bounds \" \"(> %f s)\" % (end_sec,", ":type *segments: tuple of AudioSegment :return: Audio segment instance as", "str \"\"\" self._samples = resampy.resample( self.samples, self.sample_rate, target_sample_rate, filter=filter) self._sample_rate", "before adding it in. This is to prevent attempting to", "cls.from_file(subfile_from_tar(file, infos)) else: samples, sample_rate = soundfile.read(file, dtype='float32') return cls(samples,", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "None else start end = duration if end is None", "\"bounds.\" % start) if end < 0.0: raise ValueError(\"The slice", "given duration. :rtype: AudioSegment \"\"\" samples = np.zeros(int(duration * sample_rate))", "be smaller \" \"than audio duration.\") shift_samples = int(shift_ms *", "License, Version 2.0 (the \"License\"); # you may not use", "if rng is None else rng if allow_downsampling and noise.sample_rate", "(%d Hz) is not equal to base \" \"signal sample", "supported by the integer type. This is for writing a", "sample_rate of any segments does not match. :raises TypeError: If", "file. :type end: float :return: AudioSegment instance of the specified", ":type filepath: str|file :param dtype: Subtype for audio file. Options:", "Sequence file name must end with \".seqbin\". And the filename", "audio segments of the same type \" \"can be concatenated.\")", "segment. Note that this is an in-place transformation. :param impulse_segment:", "if gain > max_gain_db: raise ValueError( \"Unable to normalize segment", "float|1darray \"\"\" self._samples *= 10.**(gain / 20.) def change_speed(self, speed_rate):", "Hz) is not \" \"equal to base signal sample rate", "to allow the noise signal to be downsampled to match", "int(old_length / speed_rate) # old_indices = np.arange(old_length) # new_indices =", "state. :type rng: None|random.Random :raises ValueError: If the sample rate", "\"\"\" return self._samples.shape[0] @property def duration(self): \"\"\"Return audio duration. :return:", "5th utterance's audio file in sequence file \"xxx.seqbin\" must be", "Input audio segments to be concatenated. :type *segments: tuple of", "(sample_count + prior_samples)) rms_estimate_db = 10 * np.log10(mean_squared_estimate) # Compute", "'kaiser_fast'}. :type filter: str \"\"\" self._samples = resampy.resample( self.samples, self.sample_rate,", "end_sample = int(round(end_sec * self._sample_rate)) self._samples = self._samples[start_sample:end_sample] def random_subsegment(self,", "If start is negative, it wraps around from the end.", "# Perform basic sanity-checks. if len(segments) == 0: raise ValueError(\"No", "sample type from float32 to dtype. Audio sample type is", "the License for the specific language governing permissions and #", "sample_rate) def to_wav_file(self, filepath, dtype='float32'): \"\"\"Save audio segment to disk", "wav file. :param filepath: WAV filepath or file object to", "in decibels to apply to samples. :type gain: float|1darray \"\"\"", "to pad. :type duration: float :param sides: Position for padding:", "of gain to apply to noise signal before adding it", "sample_rate=8000) @classmethod def from_bytes(cls, bytes): \"\"\"Create audio segment from a", "If the sample rate does not match between the two", "\"(> %f s)\" % (end, duration)) start_frame = int(start *", "self.duration: raise ValueError(\"Absolute value of shift_ms should be smaller \"", "bytes (offsets for each audio), audio_bytes_data_of_1st_utterance, audio_bytes_data_of_2nd_utterance, ...... Sequence file", "match to add segments.\") self._samples += other._samples def to_bytes(self, dtype='float32'):", "this is an in-place transformation. :param speed_rate: Rate of speed", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "sox.Transformer() tfm.set_globals(multithread=False) tfm.speed(speed_rate) self._samples = tfm.build_array( input_array=self._samples, sample_rate_in=self._sample_rate).squeeze(-1).astype( np.float32).copy() def", "num of utterance), 4 bytes (int, bytes per header), [bytes_per_header*(num_utterance+1)]", "utterance's audio file in sequence file \"xxx.seqbin\" must be \"xxx.seqbin_5\",", "segemnt. \"\"\" rng = random.Random() if rng is None else", "AudioSegment \"\"\" samples, sample_rate = soundfile.read( io.BytesIO(bytes), dtype='float32') return cls(samples,", "from it and used instead. Note that this is an", "instance of the specified slice of the input audio file.", "if self._samples.ndim >= 2: self._samples = np.mean(self._samples, 1) def __eq__(self,", "\"\"\"Normalize audio to be of the desired RMS value in", "rng = random.Random() if rng is None else rng if", "else start end = duration if end is None else", "\"\"\"Monaural audio segment abstraction. :param samples: Audio samples [num_samples x", "supported. \"\"\" if duration == 0.0: return self cls =", "ndarray \"\"\" return self._samples.copy() @property def sample_rate(self): \"\"\"Return audio sample", "delay. Silence are padded to keep the duration unchanged. Note", "start_sample = int(round(start_sec * self._sample_rate)) end_sample = int(round(end_sec * self._sample_rate))", "\"\"\" if speed_rate == 1.0: return if speed_rate <= 0:", "except: try: from paddlespeech.s2t.utils import dynamic_pip_install package = \"sox\" dynamic_pip_install.install(package)", "samples. :param bytes: Byte string containing audio samples. :type bytes:", "prior_samples, startup_delay=0.0): \"\"\"Normalize audio using a production-compatible online/causal algorithm. This", "resampling is allowed when the impulse_segment has a different sample", "subsegment in seconds. :type end_sec: float :raise ValueError: If start_sec", "self._samples[:shift_samples] self._samples[:-shift_samples] = 0 def subsegment(self, start_sec=None, end_sec=None): \"\"\"Cut the", "= target_db - self.rms_db if gain > max_gain_db: raise ValueError(", "startup_sample_idx = min(self.num_samples - 1, int(self.sample_rate * startup_delay)) prior_mean_squared =", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "seconds. If start is negative, it wraps around from the", "\"\"\" # Estimate total RMS online. startup_sample_idx = min(self.num_samples -", "multiply by 10 instead of 20 for dBs mean_square =", "Start time in seconds. If start is negative, it wraps", "# self._samples = np.interp(new_indices, old_indices, self._samples) # sox, slow try:", "from .utility import convert_samples_from_float32 from .utility import convert_samples_to_float32 from .utility", "= random.Random() if rng is None else rng if subsegment_length", "re.match(r\"(.+\\.seqbin)_(\\d+)\", filepath) if matches is None: raise IOError(\"File type of", "start position (%f s) is later than \" \"the slice", "of subsegment in seconds. :type end_sec: float :raise ValueError: If", "= np.concatenate([seg.samples for seg in segments]) return cls(samples, sample_rate) @classmethod", "used instead. Note that this is an in-place transformation. :param", "\"xxx.seqbin\" must be \"xxx.seqbin_5\", with \"5\" indicating the utterance index", "in seconds to pad. :type duration: float :param sides: Position", ":raises ValueError: If shift_ms is longer than audio duration. \"\"\"", "filepath, dtype='float32'): \"\"\"Save audio segment to disk as wav file.", "prevent nans when attempting to normalize a signal consisting of", ":rtype: float \"\"\" return self._samples.shape[0] / float(self._sample_rate) @property def rms_db(self):", "slice start position (%f s) is later than \" \"the", "(sample-wise addition, not segment concatenation). Note that this is an", "square energy of the audio in decibels. :return: Root mean", "1). :param filepath: Filepath of sequence file. :type filepath: str", ":type noise: AudioSegment :param snr_dB: Signal-to-Noise Ratio, in decibels. :type", "type \" \"can be concatenated.\") samples = np.concatenate([seg.samples for seg", "end_sec is incorrectly set, e.g. out of bounds in time.", "return cls(samples, sample_rate) @classmethod def slice_from_file(cls, file, start=None, end=None): \"\"\"Loads", ":return: Audio sample rate. :rtype: int \"\"\" return self._sample_rate @property", "\"\"\" target_db = self.rms_db self.convolve(impulse_segment, allow_resample=allow_resample) self.normalize(target_db) def add_noise(self, noise,", ":param samples: Audio samples [num_samples x num_channels]. :type samples: ndarray.float32", "sample_rate)) return cls(samples, sample_rate) def to_wav_file(self, filepath, dtype='float32'): \"\"\"Save audio", "# distributed under the License is distributed on an \"AS", "# Unless required by applicable law or agreed to in", "position (%f s) is out of \" \"bounds.\" % start)", "normalize a signal consisting of all zeros. :type max_gain_db: float", "ValueError: If shift_ms is longer than audio duration. \"\"\" if", ":param bytes: Byte string containing audio samples. :type bytes: str", "in-place transformation. :param subsegment_length: Subsegment length in seconds. :type subsegment_length:", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "target_db: Target RMS value in decibels. This value should be", "by 10 instead of 20 for dBs mean_square = np.mean(self._samples**2)", "\"\"\" samples = np.zeros(int(duration * sample_rate)) return cls(samples, sample_rate) def", "offsets of each audio byte data chunk. The format is:", "\" \"can be concatenated.\") samples = np.concatenate([seg.samples for seg in", "self, silence) else: raise ValueError(\"Unknown value for the sides %s\"", "is an in-place transformation. :param target_sample_rate: Target sample rate. :type", ":return: Audio segment instance as concatenating results. :rtype: AudioSegment :raises", "allow the noise signal to be downsampled to match the", "not AudioSegment instance. \"\"\" # Perform basic sanity-checks. if len(segments)", "if matches is None: raise IOError(\"File type of %s is", "samples. :return: Audio samples. :rtype: ndarray \"\"\" return self._samples.copy() @property", "(%f sec) must be at least as long as\" \"", "if the lengths of segments don't match. \"\"\" if isinstance(other,", "the Apache License, Version 2.0 (the \"License\"); # you may", "make online estimates of the RMS even when there are", "of AudioSegment :return: Audio segment instance as concatenating results. :rtype:", "Segment containing samples to be added in. :type other: AudioSegments", "def __eq__(self, other): \"\"\"Return whether two objects are equal.\"\"\" if", "\"\"\" gain = target_db - self.rms_db if gain > max_gain_db:", "and the end. :type sides: str :raises ValueError: If sides", "the offsets of each audio byte data chunk. The format", "None. Returns: AudioSegment: Audio segment instance. \"\"\" if isinstance(file, str)", "subsegment_length, rng=None): \"\"\"Cut the specified length of the audiosegment randomly.", "impulse_segment.resample(self.sample_rate) if self.sample_rate != impulse_segment.sample_rate: raise ValueError(\"Impulse segment's sample rate", "files, with several header bytes in the head indicating the", "not install soxbindings on your system.\" ) tfm = sox.Transformer()", "the specified length of the audiosegment randomly. Note that this", "end position (%f s) is out of bounds \" \"(>", "duration: float :param sample_rate: Sample rate. :type sample_rate: float :return:", "> end_sec: raise ValueError(\"The slice start position (%f s) is", "# square root => multiply by 10 instead of 20", "Data type for export samples. Options: 'int16', 'int32', 'float32', 'float64'.", "advance self._samples[:-shift_samples] = self._samples[shift_samples:] self._samples[-shift_samples:] = 0 elif shift_samples <", "bytes (int, num of utterance), 4 bytes (int, bytes per", "sample_rate != seg._sample_rate: raise ValueError(\"Can't concatenate segments with \" \"different", "str :return: Audio segment instance. :rtype: AudioSegment \"\"\" samples, sample_rate", "filepath: str|file :param dtype: Subtype for audio file. Options: 'int16',", "((cumsum_of_squares + prior_sum_of_squares) / (sample_count + prior_samples)) rms_estimate_db = 10", "allow_resample=False): \"\"\"Convolve and normalize the resulting audio segment so that", "silence) else: raise ValueError(\"Unknown value for the sides %s\" %", "number of segments is zero, or if the sample_rate of", "sample rate. :param duration: Length of silence in seconds. :type", "input signal. Note that this is an in-place transformation. :param", "ValueError( \"Unable to normalize segment to %f dB because the", "the audio speed by linear interpolation. Note that this is", ":param shift_ms: Shift time in millseconds. If positive, shift with", "to samples. Note that this is an in-place transformation. :param", "convert_samples_from_float32 from .utility import convert_samples_to_float32 from .utility import subfile_from_tar class", "sequence file (starting from 1). :param filepath: Filepath of sequence", "= copy.deepcopy(noise) noise_new.random_subsegment(self.duration, rng=rng) noise_new.gain_db(noise_gain_db) self.superimpose(noise_new) @property def samples(self): \"\"\"Return", "cls.concatenate(silence, self, silence) else: raise ValueError(\"Unknown value for the sides", "self._sample_rate = target_sample_rate def pad_silence(self, duration, sides='both'): \"\"\"Pad this audio", "noise signal to be downsampled to match the base signal", "shift with time delay. :type shift_ms: float :raises ValueError: If", "containing audio content. :rtype: str \"\"\" samples = self._convert_samples_from_float32(self._samples, dtype)", "the two segments are not equal, or if the lengths", "filepath or file object. :type file: str|file :param start: Start", "noise segments is shorter than original audio segments. \"\"\" rng", ":raises ValueError: If the required gain to normalize the segment", "ValueError(\"Sample rates must match to add segments.\") if len(self._samples) !=", "object to save the audio segment. :type filepath: str|file :param", "segments don't match. :raise ValueError: If the sample rates of", "!= other._samples): return False return True def __ne__(self, other): \"\"\"Return", "the integer type. This is for writing a audio file.", "from another segment to those of this segment (sample-wise addition,", "that it has the same average power as the input", "of the given duration and sample rate. :param duration: Length", "gain in dB that can be applied for normalization. This", "return if speed_rate <= 0: raise ValueError(\"speed_rate should be greater", "the memory which can be incredibly wasteful. :param file: Input", "duration if end is None else end if start <", "else rng if subsegment_length > self.duration: raise ValueError(\"Length of subsegment", "is sampled from it and used instead. Note that this", "sample_rate: int :raises TypeError: If the sample data type is", "input audio file. :rtype: AudioSegment :raise ValueError: If start or", "AudioSegment \"\"\" # parse filepath matches = re.match(r\"(.+\\.seqbin)_(\\d+)\", filepath) if", "filter='kaiser_best'): \"\"\"Resample the audio to a target sample rate. Note", "different types: %s \" \"and %s.\" % (type(self), type(other))) if", "Note that this is an in-place transformation. :param shift_ms: Shift", "of this segment (sample-wise addition, not segment concatenation). Note that", "not allowed. \"\"\" if allow_resample and self.sample_rate != impulse_segment.sample_rate: impulse_segment.resample(self.sample_rate)", "__init__(self, samples, sample_rate): \"\"\"Create audio segment from samples. Samples are", "self.gain_db(min(max_gain_db, target_db - self.rms_db)) def normalize_online_bayesian(self, target_db, prior_db, prior_samples, startup_delay=0.0):", ":return: Number of samples. :rtype: int \"\"\" return self._samples.shape[0] @property", "negative, shift with time delay. Silence are padded to keep", "\"\"\"Return audio sample rate. :return: Audio sample rate. :rtype: int", "audio duration.\") shift_samples = int(shift_ms * self._sample_rate / 1000) if", "If start or end is incorrectly set, e.g. out of", "'PCM_32', 'float32': 'FLOAT', 'float64': 'DOUBLE' } soundfile.write( filepath, samples, self._sample_rate,", "start_time + subsegment_length) def convolve(self, impulse_segment, allow_resample=False): \"\"\"Convolve this audio", "segments]) return cls(samples, sample_rate) @classmethod def make_silence(cls, duration, sample_rate): \"\"\"Creates", "__eq__(self, other): \"\"\"Return whether two objects are equal.\"\"\" if type(other)", "Max amount of gain in dB that can be applied", "self._samples = resampy.resample( self.samples, self.sample_rate, target_sample_rate, filter=filter) self._sample_rate = target_sample_rate", "under the License is distributed on an \"AS IS\" BASIS,", "the audio content. :param dtype: Data type for export samples.", "segment try: return cls.from_bytes(audio_bytes) except Exception as e: samples =", "= self._convert_samples_from_float32(self._samples, dtype) return samples def gain_db(self, gain): \"\"\"Apply gain", "\"\"\" self._samples = self._convert_samples_to_float32(samples) self._sample_rate = sample_rate if self._samples.ndim >=", "this sequence file (starting from 1). :param filepath: Filepath of", "end position (%f s) is out of bounds.\" % end)", "time delay. Silence are padded to keep the duration unchanged.", "'both' - adds silence in both the beginning and the", "= np.frombuffer(audio_bytes, dtype='int16') return cls(samples=samples, sample_rate=8000) @classmethod def from_bytes(cls, bytes):", "str|file :param dtype: Subtype for audio file. Options: 'int16', 'int32',", "likelihood and gamma prior to make online estimates of the", "1) ] # read audio bytes f.seek(header[fileno - 1]) audio_bytes", "= soundfile.SoundFile(file) sample_rate = sndfile.samplerate duration = float(len(sndfile)) / sample_rate", "if duration == 0.0: return self cls = type(self) silence", "gain: Gain in decibels to apply to samples. :type gain:", "must end with \".seqbin\". And the filename of the 5th", "= soundfile.read( io.BytesIO(bytes), dtype='float32') return cls(samples, sample_rate) @classmethod def concatenate(cls,", "must match to add segments.\") if len(self._samples) != len(other._samples): raise", "not supported. \"\"\" samples = self._convert_samples_from_float32(self._samples, dtype) subtype_map = {", "an in-place transformation. :param noise: Noise signal to add. :type", "self._convert_samples_from_float32(self._samples, dtype) subtype_map = { 'int16': 'PCM_16', 'int32': 'PCM_32', 'float32':", "IOError(\"File type of %s is not supported\" % filepath) filename", "amount of gain to apply to noise signal before adding", "in-place transformation. :param target_sample_rate: Target sample rate. :type target_sample_rate: int", ":type filepath: str :return: Audio segment instance. :rtype: AudioSegment \"\"\"", "> duration: raise ValueError(\"The slice end position (%f s) is", "allowed when the impulse_segment has a different sample rate from", "noise segment is longer than this segment, a random subsegment", "the sample data type is not float or int. \"\"\"", "other): \"\"\"Return whether two objects are unequal.\"\"\" return not self.__eq__(other)", "- header[fileno - 1]) f.close() # create audio segment try:", "other: AudioSegments :raise TypeError: If type of two segments don't", "the end of the file. :type end: float :return: AudioSegment", "Audio segment instance. :rtype: AudioSegment \"\"\" samples, sample_rate = soundfile.read(", "+= duration if end < 0.0: end += duration if", "containing a collection of multiple audio files, with several header", "dtype): \"\"\"Convert sample type from float32 to dtype. Audio sample", ":raises ValueError: If the sample rate is not match between", "not match between two audio segments when resample is not", "gain: float|1darray \"\"\" self._samples *= 10.**(gain / 20.) def change_speed(self,", "of \" \"bounds.\" % start) if end < 0.0: raise", "segment is longer than this segment, a random subsegment of", "sample_rate: float :return: Silent AudioSegment instance of the given duration.", "io import random import re import struct import numpy as", "positive, shift with time advance; if negative, shift with time", "filepath: WAV filepath or file object to save the audio", "all zeros. :type max_gain_db: float :raises ValueError: If the required", "(end, duration)) start_frame = int(start * sample_rate) end_frame = int(end", "sample_rate=%d, duration=%.2fsec, \" \"rms=%.2fdB\" % (type(self), self.num_samples, self.sample_rate, self.duration, self.rms_db))", "return cls.from_bytes(audio_bytes) except Exception as e: samples = np.frombuffer(audio_bytes, dtype='int16')", "content. :rtype: str \"\"\" samples = self._convert_samples_from_float32(self._samples, dtype) return samples.tostring()", "the audio; speed_rate <= 0.0, not allowed, raise ValueError. :type", "is out of bounds.\" % end_sec) if start_sec > end_sec:", "end < 0.0: end += duration if start < 0.0:", "the base signal sample rate. :type allow_downsampling: bool :param max_gain_db:", "max_gain_db: Maximum amount of gain to apply to noise signal", "self.duration: raise ValueError(\"The slice end position (%f s) is out", "Length of silence in seconds. :type duration: float :param sample_rate:", "- adds silence in the beginning; 'end' - adds silence", "+ subsegment_length) def convolve(self, impulse_segment, allow_resample=False): \"\"\"Convolve this audio segment", "an in-place transformation. :param gain: Gain in decibels to apply", ":type duration: float :param sides: Position for padding: 'beginning' -", "length of the audiosegment randomly. Note that this is an", "and used instead. Note that this is an in-place transformation.", "20.) def change_speed(self, speed_rate): \"\"\"Change the audio speed by linear", "signal sample rate (%d Hz).\" % (impulse_segment.sample_rate, self.sample_rate)) samples =", "1]) f.close() # create audio segment try: return cls.from_bytes(audio_bytes) except", "add segments of different types: %s \" \"and %s.\" %", "Input audio filepath or file object. :type file: str|file :param", "== \"both\": padded = cls.concatenate(silence, self, silence) else: raise ValueError(\"Unknown", "to be concatenated. :type *segments: tuple of AudioSegment :return: Audio", "time. If `shift_ms` is positive, shift with time advance; if", "isinstance(file, str) and re.findall(r\".seqbin_\\d+$\", file): return cls.from_sequence_file(file) elif isinstance(file, str)", "float :raises ValueError: If shift_ms is longer than audio duration.", "float :param sides: Position for padding: 'beginning' - adds silence", "sample rate. :rtype: int \"\"\" return self._sample_rate @property def num_samples(self):", "resample is not allowed. \"\"\" if allow_resample and self.sample_rate !=", "ANY KIND, either express or implied. # See the License", "is 'float32'. :type dtype: str :return: Byte string containing audio", "or end is incorrectly set, e.g. out of bounds in", "= duration if end is None else end if start", "the License. # You may obtain a copy of the", "= type(self) silence = self.make_silence(duration, self._sample_rate) if sides == \"beginning\":", "multiple audio files, with several header bytes in the head", "# See the License for the specific language governing permissions", "sides is not supported. \"\"\" if duration == 0.0: return", ":raises ValueError: If speed_rate <= 0.0. \"\"\" if speed_rate ==", "def to(self, dtype='int16'): \"\"\"Create a `dtype` audio content. :param dtype:", "advance; if negative, shift with time delay. Silence are padded", "file. :type filepath: str :return: Audio segment instance. :rtype: AudioSegment", "samples, sample_rate): \"\"\"Create audio segment from samples. Samples are convert", "> self.sample_rate: noise = noise.resample(self.sample_rate) if noise.sample_rate != self.sample_rate: raise", "human-readable representation of segment.\"\"\" return (\"%s: num_samples=%d, sample_rate=%d, duration=%.2fsec, \"", "\"sox\" dynamic_pip_install.install(package) package = \"soxbindings\" dynamic_pip_install.install(package) import soxbindings as sox", "Impulse response segments. :type impulse_segment: AudioSegment :param allow_resample: Indicates whether", "return self cls = type(self) silence = self.make_silence(duration, self._sample_rate) if", "equal to base \" \"signal sample rate (%d Hz).\" %", "@property def rms_db(self): \"\"\"Return root mean square energy of the", "def _convert_samples_from_float32(self, samples, dtype): \"\"\"Convert sample type from float32 to", "Ratio, in decibels. :type snr_dB: float :param allow_downsampling: Whether to", "tfm.set_globals(multithread=False) tfm.speed(speed_rate) self._samples = tfm.build_array( input_array=self._samples, sample_rate_in=self._sample_rate).squeeze(-1).astype( np.float32).copy() def normalize(self,", "allowed, or if the duration of noise segments is shorter", "to a zero signal. :type max_gain_db: float :param rng: Random", "random.Random() if rng is None else rng if allow_downsampling and", "float \"\"\" # square root => multiply by 10 instead", "if sides == \"beginning\": padded = cls.concatenate(silence, self) elif sides", "rms_estimate_db = 10 * np.log10(mean_squared_estimate) # Compute required time-varying gain.", "noise.sample_rate > self.sample_rate: noise = noise.resample(self.sample_rate) if noise.sample_rate != self.sample_rate:", "startup_delay)) prior_mean_squared = 10.**(prior_db / 10.) prior_sum_of_squares = prior_mean_squared *", "\"\"\"Create a byte string containing the audio content. :param dtype:", "a production-compatible online/causal algorithm. This uses an exponential likelihood and", "samples. :type prior_samples: float :param startup_delay: Default 0.0s. If provided,", "estimates of the RMS even when there are very few", "2: self._samples = np.mean(self._samples, 1) def __eq__(self, other): \"\"\"Return whether", "target_sample_rate: int :param filter: The resampling filter to use one", "power as the input signal. Note that this is an", "self._samples.shape != other._samples.shape: return False if np.any(self.samples != other._samples): return", "self.normalize(target_db) def add_noise(self, noise, snr_dB, allow_downsampling=False, max_gain_db=300.0, rng=None): \"\"\"Add the", "base \" \"signal sample rate (%d Hz).\" % (noise.sample_rate, self.sample_rate))", "start is None else start end = duration if end", "superimpose(self, other): \"\"\"Add samples from another segment to those of", ":param end: End time in seconds. If end is negative,", "rate (%d Hz).\" % (noise.sample_rate, self.sample_rate)) if noise.duration < self.duration:", "audio segment so that it has the same average power", "float(self._sample_rate) @property def rms_db(self): \"\"\"Return root mean square energy of", "transformation. :param impulse_segment: Impulse response segments. :type impulse_segment: AudioSegment :param", ":param speed_rate: Rate of speed change: speed_rate > 1.0, speed", "read audio bytes f.seek(header[fileno - 1]) audio_bytes = f.read(header[fileno] -", "end position (%f s).\" % (start, end)) if end >", "(%d Hz) is not \" \"equal to base signal sample", "if allow_resample and self.sample_rate != impulse_segment.sample_rate: impulse_segment.resample(self.sample_rate) if self.sample_rate !=", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "audio to be of the desired RMS value in decibels.", "/ (sample_count + prior_samples)) rms_estimate_db = 10 * np.log10(mean_squared_estimate) #", "value for the sides %s\" % sides) self._samples = padded._samples", "writing, software # distributed under the License is distributed on", "0.0, not allowed, raise ValueError. :type speed_rate: float :raises ValueError:", "addition, not segment concatenation). Note that this is an in-place", "algorithm. This uses an exponential likelihood and gamma prior to", "noise_new.random_subsegment(self.duration, rng=rng) noise_new.gain_db(noise_gain_db) self.superimpose(noise_new) @property def samples(self): \"\"\"Return audio samples.", "cls(samples, sample_rate) def to_wav_file(self, filepath, dtype='float32'): \"\"\"Save audio segment to", "are given to concatenate.\") sample_rate = segments[0]._sample_rate for seg in", "startup_sample_idx > 0: cumsum_of_squares[:startup_sample_idx] = \\ cumsum_of_squares[startup_sample_idx] sample_count[:startup_sample_idx] = \\", "np.arange(old_length) # new_indices = np.linspace(start=0, stop=old_length, num=new_length) # self._samples =", "time delay self._samples[-shift_samples:] = self._samples[:shift_samples] self._samples[:-shift_samples] = 0 def subsegment(self,", "end_sec: float :raise ValueError: If start_sec or end_sec is incorrectly", "padded to keep the duration unchanged. Note that this is", "an in-place transformation. :param start_sec: Beginning of subsegment in seconds.", "If the noise segment is longer than this segment, a", "Audio segment instance. :rtype: AudioSegment \"\"\" # parse filepath matches", "start_sec < 0.0: raise ValueError(\"The slice start position (%f s)", "with a period of silence. Note that this is an", "RMS even when there are very few samples. Note that", ":rtype: float \"\"\" # square root => multiply by 10", ":param subsegment_length: Subsegment length in seconds. :type subsegment_length: float :param", "gain. gain_db = target_db - rms_estimate_db self.gain_db(gain_db) def resample(self, target_sample_rate,", "> max_gain_db: raise ValueError( \"Unable to normalize segment to %f", "target_db, prior_db, prior_samples, startup_delay=0.0): \"\"\"Normalize audio using a production-compatible online/causal", "the input signal. Note that this is an in-place transformation.", ":type target_db: float :param max_gain_db: Max amount of gain in", "if np.any(self.samples != other._samples): return False return True def __ne__(self,", "the audio to a target sample rate. Note that this", "\"\"\"Add samples from another segment to those of this segment", "type(self) silence = self.make_silence(duration, self._sample_rate) if sides == \"beginning\": padded", "abstraction. :param samples: Audio samples [num_samples x num_channels]. :type samples:", "True def __ne__(self, other): \"\"\"Return whether two objects are unequal.\"\"\"", ":type end: float :return: AudioSegment instance of the specified slice", "struct.unpack(\"i\", f.read(4))[0] bytes_per_header = struct.unpack(\"i\", f.read(4))[0] header_bytes = f.read(bytes_per_header *", "num_utterances = struct.unpack(\"i\", f.read(4))[0] bytes_per_header = struct.unpack(\"i\", f.read(4))[0] header_bytes =", "dtype='int16') return cls(samples=samples, sample_rate=8000) @classmethod def from_bytes(cls, bytes): \"\"\"Create audio", "if the sample_rate of any segments does not match. :raises", "> 0: cumsum_of_squares[:startup_sample_idx] = \\ cumsum_of_squares[startup_sample_idx] sample_count[:startup_sample_idx] = \\ sample_count[startup_sample_idx]", "tfm.build_array( input_array=self._samples, sample_rate_in=self._sample_rate).squeeze(-1).astype( np.float32).copy() def normalize(self, target_db=-20, max_gain_db=300.0): \"\"\"Normalize audio", "\"\"\" samples = self._convert_samples_from_float32(self._samples, dtype) return samples def gain_db(self, gain):", ":param file: Input audio filepath or file object. :type file:", "self.sample_rate)) samples = signal.fftconvolve(self.samples, impulse_segment.samples, \"full\") self._samples = samples def", "max_gain_db: float :param rng: Random number generator state. :type rng:", "np.mean(self._samples, 1) def __eq__(self, other): \"\"\"Return whether two objects are", "import dynamic_pip_install package = \"sox\" dynamic_pip_install.install(package) package = \"soxbindings\" dynamic_pip_install.install(package)", "the sample rate is not match between two audio segments", "a random subsegment of matching length is sampled from it", "sample rate from this signal. :type allow_resample: bool :raises ValueError:", "in. This is to prevent attempting to apply infinite gain", "with int scaled to [-1, 1]. \"\"\" self._samples = self._convert_samples_to_float32(samples)", "'float32': 'FLOAT', 'float64': 'DOUBLE' } soundfile.write( filepath, samples, self._sample_rate, format='WAV',", "convert_samples_to_float32 from .utility import subfile_from_tar class AudioSegment(): \"\"\"Monaural audio segment", "audio sample with a period of silence. Note that this", "end_frame = int(end * sample_rate) sndfile.seek(start_frame) data = sndfile.read(frames=end_frame -", "be of the desired RMS value in decibels. Note that", "- self.rms_db)) def normalize_online_bayesian(self, target_db, prior_db, prior_samples, startup_delay=0.0): \"\"\"Normalize audio", "transformation. :param noise: Noise signal to add. :type noise: AudioSegment", "than \" \"the end position (%f s).\" % (start_sec, end_sec))", "gain to a zero signal. :type max_gain_db: float :param rng:", "bounds in time. \"\"\" start_sec = 0.0 if start_sec is", "decibels. :return: Root mean square energy in decibels. :rtype: float", "the two audio segments when downsampling is not allowed, or", "prior_mean_squared = 10.**(prior_db / 10.) prior_sum_of_squares = prior_mean_squared * prior_samples", "signal consisting of all zeros. :type max_gain_db: float :raises ValueError:", "to apply to samples. :type gain: float|1darray \"\"\" self._samples *=", "to those of this segment (sample-wise addition, not segment concatenation).", "import soxbindings as sox except: raise RuntimeError(\"Can not install soxbindings", "samples def convolve_and_normalize(self, impulse_segment, allow_resample=False): \"\"\"Convolve and normalize the resulting", "this is an in-place transformation. :param noise: Noise signal to", "if self._samples.shape != other._samples.shape: return False if np.any(self.samples != other._samples):", "instance as concatenating results. :rtype: AudioSegment :raises ValueError: If the", "to be added in. :type other: AudioSegments :raise TypeError: If", "other._sample_rate: raise ValueError(\"Sample rates must match to add segments.\") if", "are padded to keep the duration unchanged. Note that this", "position (%f s).\" % (start_sec, end_sec)) if end_sec > self.duration:", "the end; 'both' - adds silence in both the beginning", "the end. If not provided, this function reads from the", "the audio segment. :type filepath: str|file :param dtype: Subtype for", "'int32': 'PCM_32', 'float32': 'FLOAT', 'float64': 'DOUBLE' } soundfile.write( filepath, samples,", "header bytes in the head indicating the offsets of each", "not segment concatenation). Note that this is an in-place transformation.", ":type shift_ms: float :raises ValueError: If shift_ms is longer than", ":param filepath: Filepath of sequence file. :type filepath: str :return:", "!= self.sample_rate: raise ValueError(\"Noise sample rate (%d Hz) is not", "to match the base signal sample rate. :type allow_downsampling: bool", "is an in-place transformation. :param gain: Gain in decibels to", "sides == \"both\": padded = cls.concatenate(silence, self, silence) else: raise", "in decibels. This value should be less than 0.0 as", "s).\" % (start, end)) if end > duration: raise ValueError(\"The", "def normalize(self, target_db=-20, max_gain_db=300.0): \"\"\"Normalize audio to be of the", "file.startswith('tar:'): return cls.from_file(subfile_from_tar(file, infos)) else: samples, sample_rate = soundfile.read(file, dtype='float32')", "dynamic_pip_install.install(package) import soxbindings as sox except: raise RuntimeError(\"Can not install", "Note that this is an in-place transformation. :param duration: Length", "noise: Noise signal to add. :type noise: AudioSegment :param snr_dB:", "of bounds.\" % end) if start > end: raise ValueError(\"The", "gain to normalize the segment to the target_db value exceeds", "end)) if end > duration: raise ValueError(\"The slice end position", "impulse_segment, allow_resample=False): \"\"\"Convolve this audio segment with the given impulse", "in decibels. :rtype: float \"\"\" # square root => multiply", "'float64'. Default is 'float32'. :type dtype: str :return: np.ndarray containing", "0.0s. If provided, this function will accrue statistics for the", "dtype='float32') return cls(data, sample_rate) @classmethod def from_sequence_file(cls, filepath): \"\"\"Create audio", "% (type(self), self.num_samples, self.sample_rate, self.duration, self.rms_db)) @classmethod def from_file(cls, file,", "self.duration - subsegment_length) self.subsegment(start_time, start_time + subsegment_length) def convolve(self, impulse_segment,", "+ 1 if startup_sample_idx > 0: cumsum_of_squares[:startup_sample_idx] = \\ cumsum_of_squares[startup_sample_idx]", "it has the same average power as the input signal.", "zero signal. :type max_gain_db: float :param rng: Random number generator", "'float64'. Default is 'float32'. :type dtype: str :return: Byte string", "instead of 20 for dBs mean_square = np.mean(self._samples**2) return 10", "allow_downsampling: bool :param max_gain_db: Maximum amount of gain to apply", "= struct.unpack(\"i\", f.read(4))[0] header_bytes = f.read(bytes_per_header * (num_utterances + 1))", "soundfile.write( filepath, samples, self._sample_rate, format='WAV', subtype=subtype_map[dtype]) def superimpose(self, other): \"\"\"Add", "permissions and # limitations under the License. \"\"\"Contains the audio", "= f.read(4) num_utterances = struct.unpack(\"i\", f.read(4))[0] bytes_per_header = struct.unpack(\"i\", f.read(4))[0]", "dB)\" % (target_db, max_gain_db)) self.gain_db(min(max_gain_db, target_db - self.rms_db)) def normalize_online_bayesian(self,", "the end. :type sides: str :raises ValueError: If sides is", "else start_sec end_sec = self.duration if end_sec is None else", "shift_ms is longer than audio duration. \"\"\" if abs(shift_ms) /", "sample data type is not float or int. \"\"\" def", "\"\"\" if isinstance(other, type(self)): raise TypeError(\"Cannot add segments of different", "sample_rate: Audio sample rate. :type sample_rate: int :raises TypeError: If", "!= other._sample_rate: raise ValueError(\"Sample rates must match to add segments.\")", ":type startup_delay: float \"\"\" # Estimate total RMS online. startup_sample_idx", "samples = np.concatenate([seg.samples for seg in segments]) return cls(samples, sample_rate)", "samples = signal.fftconvolve(self.samples, impulse_segment.samples, \"full\") self._samples = samples def convolve_and_normalize(self,", "with time advance; if negative, shift with time delay. Silence", "the filename of the 5th utterance's audio file in sequence", "because the \" \"the probable gain have exceeds max_gain_db (%f", "end_sec is None else end_sec if start_sec < 0.0: start_sec", "import subfile_from_tar class AudioSegment(): \"\"\"Monaural audio segment abstraction. :param samples:", "= self.duration if end_sec is None else end_sec if start_sec", ".utility import subfile_from_tar class AudioSegment(): \"\"\"Monaural audio segment abstraction. :param", "* prior_samples cumsum_of_squares = np.cumsum(self.samples**2) sample_count = np.arange(self.num_samples) + 1", "\"than audio duration.\") shift_samples = int(shift_ms * self._sample_rate / 1000)", "Note that this is an in-place transformation. :param noise: Noise", "(impulse_segment.sample_rate, self.sample_rate)) samples = signal.fftconvolve(self.samples, impulse_segment.samples, \"full\") self._samples = samples", "downsampled to match the base signal sample rate. :type allow_downsampling:", "headers f = io.open(filename, mode='rb', encoding='utf8') version = f.read(4) num_utterances", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "import io import random import re import struct import numpy", "(noise.sample_rate, self.sample_rate)) if noise.duration < self.duration: raise ValueError(\"Noise signal (%f", "import soundfile from scipy import signal from .utility import convert_samples_from_float32", "subsegment is greater than the origineal segemnt. \"\"\" rng =", "self._samples[start_sample:end_sample] def random_subsegment(self, subsegment_length, rng=None): \"\"\"Cut the specified length of", "integer or float-point. Integers will be scaled to [-1, 1]", "is an in-place transformation. :param subsegment_length: Subsegment length in seconds.", "[-1, 1]. \"\"\" self._samples = self._convert_samples_to_float32(samples) self._sample_rate = sample_rate if", "to normalize segment to %f dB because the \" \"the", "tfm = sox.Transformer() tfm.set_globals(multithread=False) tfm.speed(speed_rate) self._samples = tfm.build_array( input_array=self._samples, sample_rate_in=self._sample_rate).squeeze(-1).astype(", "in-place transformation. :param noise: Noise signal to add. :type noise:", "sample with a period of silence. Note that this is", "License. \"\"\"Contains the audio segment class.\"\"\" import copy import io", "(str|file): Filepath or file object to audio file. infos (TarLocalData,", "audio segment abstraction. :param samples: Audio samples [num_samples x num_channels].", "the head indicating the offsets of each audio byte data", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "return cls.from_file(subfile_from_tar(file, infos)) else: samples, sample_rate = soundfile.read(file, dtype='float32') return", "maximum range supported by the integer type. This is for", "attempting to normalize a signal consisting of all zeros. :type", "convert_samples_to_float32(samples) def _convert_samples_from_float32(self, samples, dtype): \"\"\"Convert sample type from float32", "self.gain_db(gain_db) def resample(self, target_sample_rate, filter='kaiser_best'): \"\"\"Resample the audio to a", "segment from samples. Samples are convert float32 internally, with int", "an in-place transformation. :param duration: Length of silence in seconds", "adds silence in the end; 'both' - adds silence in", "transformation. :param target_db: Target RMS value in decibels. :type target_bd:", "= noise.resample(self.sample_rate) if noise.sample_rate != self.sample_rate: raise ValueError(\"Noise sample rate", ".utility import convert_samples_from_float32 from .utility import convert_samples_to_float32 from .utility import", "one of {'kaiser_best', 'kaiser_fast'}. :type filter: str \"\"\" self._samples =", "rate. Note that this is an in-place transformation. :param target_sample_rate:", "samples = np.zeros(int(duration * sample_rate)) return cls(samples, sample_rate) def to_wav_file(self,", ":type sample_rate: float :return: Silent AudioSegment instance of the given", "state. :type rng: random.Random :raises ValueError: If the length of", "\"\"\"Create a `dtype` audio content. :param dtype: Data type for", "Audio sample type is usually integer or float-point. Integers will", "If end is negative, it wraps around from the end.", "return self._samples.shape[0] / float(self._sample_rate) @property def rms_db(self): \"\"\"Return root mean", "int. \"\"\" def __init__(self, samples, sample_rate): \"\"\"Create audio segment from", "by linear interpolation. Note that this is an in-place transformation.", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "greater than the origineal segemnt. \"\"\" rng = random.Random() if", "- adds silence in both the beginning and the end.", "later than \" \"the slice end position (%f s).\" %", ":type dtype: str :return: np.ndarray containing `dtype` audio content. :rtype:", "delay self._samples[-shift_samples:] = self._samples[:shift_samples] self._samples[:-shift_samples] = 0 def subsegment(self, start_sec=None,", "unequal.\"\"\" return not self.__eq__(other) def __str__(self): \"\"\"Return human-readable representation of", "or float-point. For integer type, float32 will be rescaled from", "+= other._samples def to_bytes(self, dtype='float32'): \"\"\"Create a byte string containing", "= self._convert_samples_from_float32(self._samples, dtype) subtype_map = { 'int16': 'PCM_16', 'int32': 'PCM_32',", ":param rng: Random number generator state. :type rng: None|random.Random :raises", "samples, dtype): \"\"\"Convert sample type from float32 to dtype. Audio", "or file object. :type file: str|file :param start: Start time", ":param start_sec: Beginning of subsegment in seconds. :type start_sec: float", "self._sample_rate / 1000) if shift_samples > 0: # time advance", "Silence are padded to keep the duration unchanged. Note that", "s)\" % (end, duration)) start_frame = int(start * sample_rate) end_frame", "install soxbindings on your system.\" ) tfm = sox.Transformer() tfm.set_globals(multithread=False)", "RMS online. startup_sample_idx = min(self.num_samples - 1, int(self.sample_rate * startup_delay))", "impulse_segment.sample_rate: impulse_segment.resample(self.sample_rate) if self.sample_rate != impulse_segment.sample_rate: raise ValueError(\"Impulse segment's sample", "tar2obj and tar2infos. Defaults to None. Returns: AudioSegment: Audio segment", "int(round(start_sec * self._sample_rate)) end_sample = int(round(end_sec * self._sample_rate)) self._samples =", "other): \"\"\"Add samples from another segment to those of this", "Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # #", "Prior RMS estimate in decibels. :type prior_db: float :param prior_samples:", "sample type to float32. Audio sample type is usually integer", "dtype='float32') return cls(samples, sample_rate) @classmethod def concatenate(cls, *segments): \"\"\"Concatenate an", "def to_bytes(self, dtype='float32'): \"\"\"Create a byte string containing the audio", "End time in seconds. If end is negative, it wraps", "match. :raises TypeError: If any segment is not AudioSegment instance.", "int(self.sample_rate * startup_delay)) prior_mean_squared = 10.**(prior_db / 10.) prior_sum_of_squares =", "\"\"\" if abs(shift_ms) / 1000.0 > self.duration: raise ValueError(\"Absolute value", "\"\"\" if allow_resample and self.sample_rate != impulse_segment.sample_rate: impulse_segment.resample(self.sample_rate) if self.sample_rate", "\"\"\"Save audio segment to disk as wav file. :param filepath:", "type is not float or int. \"\"\" def __init__(self, samples,", "@property def duration(self): \"\"\"Return audio duration. :return: Audio duration in", "- 1, int(self.sample_rate * startup_delay)) prior_mean_squared = 10.**(prior_db / 10.)", "of an audio without having to load the entire file", "later than \" \"the end position (%f s).\" % (start_sec,", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "s) is out of \" \"bounds.\" % start) if end", "seconds to pad. :type duration: float :param sides: Position for", "\"\"\"Create audio segment from audio file. Args: filepath (str|file): Filepath", "when there are very few samples. Note that this is", "prevent attempting to apply infinite gain to a zero signal.", "does not match between the two audio segments when downsampling", "Rights Reserved. # # Licensed under the Apache License, Version", "If the sample rate is not match between two audio", "specific language governing permissions and # limitations under the License.", "to normalize a signal consisting of all zeros. :type max_gain_db:", "= self._samples[:shift_samples] self._samples[:-shift_samples] = 0 def subsegment(self, start_sec=None, end_sec=None): \"\"\"Cut", "transformation. :param start_sec: Beginning of subsegment in seconds. :type start_sec:", "original audio segments. \"\"\" rng = random.Random() if rng is", "when resample is not allowed. \"\"\" if allow_resample and self.sample_rate", "use one of {'kaiser_best', 'kaiser_fast'}. :type filter: str \"\"\" self._samples", "samples. Samples are convert float32 internally, with int scaled to", "limitations under the License. \"\"\"Contains the audio segment class.\"\"\" import", "the default behvaior is to read to the end of", "signal.fftconvolve(self.samples, impulse_segment.samples, \"full\") self._samples = samples def convolve_and_normalize(self, impulse_segment, allow_resample=False):", "0 def subsegment(self, start_sec=None, end_sec=None): \"\"\"Cut the AudioSegment between given", "False return True def __ne__(self, other): \"\"\"Return whether two objects", "/ 1000) if shift_samples > 0: # time advance self._samples[:-shift_samples]", "mean_square = np.mean(self._samples**2) return 10 * np.log10(mean_square) def _convert_samples_to_float32(self, samples):", "bytes per header), [bytes_per_header*(num_utterance+1)] bytes (offsets for each audio), audio_bytes_data_of_1st_utterance,", "{ 'int16': 'PCM_16', 'int32': 'PCM_32', 'float32': 'FLOAT', 'float64': 'DOUBLE' }", "least as long as\" \" base signal (%f sec).\" %", "duration == 0.0: return self cls = type(self) silence =", "ValueError: If the required gain to normalize the segment to", "= np.interp(new_indices, old_indices, self._samples) # sox, slow try: import soxbindings", "end) if start > end: raise ValueError(\"The slice start position", "s).\" % (start_sec, end_sec)) if end_sec > self.duration: raise ValueError(\"The", "noise = noise.resample(self.sample_rate) if noise.sample_rate != self.sample_rate: raise ValueError(\"Noise sample", "\" \"and %s.\" % (type(self), type(other))) if self._sample_rate != other._sample_rate:", "an in-place transformation. :param speed_rate: Rate of speed change: speed_rate", "soxbindings as sox except: raise RuntimeError(\"Can not install soxbindings on", "that this is an in-place transformation. :param impulse_segment: Impulse response", "# you may not use this file except in compliance", "AudioSegment \"\"\" samples = np.zeros(int(duration * sample_rate)) return cls(samples, sample_rate)", "is longer than this segment, a random subsegment of matching", "False if self._sample_rate != other._sample_rate: return False if self._samples.shape !=", "to add segments.\") if len(self._samples) != len(other._samples): raise ValueError(\"Segment lengths", "= \"soxbindings\" dynamic_pip_install.install(package) import soxbindings as sox except: raise RuntimeError(\"Can", "_convert_samples_from_float32(self, samples, dtype): \"\"\"Convert sample type from float32 to dtype.", ":return: np.ndarray containing `dtype` audio content. :rtype: str \"\"\" samples", "unchanged; speed_rate < 1.0, slow down the audio; speed_rate <=", "if end > duration: raise ValueError(\"The slice end position (%f", "Compute required time-varying gain. gain_db = target_db - rms_estimate_db self.gain_db(gain_db)", "= cls.concatenate(silence, self) elif sides == \"end\": padded = cls.concatenate(self,", "segments. \"\"\" rng = random.Random() if rng is None else", "set, e.g. out of bounds in time. \"\"\" sndfile =", "self.sample_rate)) if noise.duration < self.duration: raise ValueError(\"Noise signal (%f sec)", "as e: samples = np.frombuffer(audio_bytes, dtype='int16') return cls(samples=samples, sample_rate=8000) @classmethod", "apply to samples. :type gain: float|1darray \"\"\" self._samples *= 10.**(gain", "/ speed_rate) # old_indices = np.arange(old_length) # new_indices = np.linspace(start=0,", "{'kaiser_best', 'kaiser_fast'}. :type filter: str \"\"\" self._samples = resampy.resample( self.samples,", "Indicates whether resampling is allowed when the impulse_segment has a", "supported. \"\"\" samples = self._convert_samples_from_float32(self._samples, dtype) subtype_map = { 'int16':", "to(self, dtype='int16'): \"\"\"Create a `dtype` audio content. :param dtype: Data", "float :param rng: Random number generator state. :type rng: random.Random", "\"\"\"Return audio samples. :return: Audio samples. :rtype: ndarray \"\"\" return", "Integers will be scaled to [-1, 1] in float32. \"\"\"", "start: Start time in seconds. If start is negative, it", "in time. \"\"\" start_sec = 0.0 if start_sec is None", "to noise signal before adding it in. This is to", "as the input signal. Note that this is an in-place", "with \" \"different sample rates\") if type(seg) is not cls:", "this is an in-place transformation. :param other: Segment containing samples", "float-point. Integers will be scaled to [-1, 1] in float32.", "head indicating the offsets of each audio byte data chunk.", "as concatenating results. :rtype: AudioSegment :raises ValueError: If the number", "seconds before applying online normalization. :type startup_delay: float \"\"\" #", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "representation of segment.\"\"\" return (\"%s: num_samples=%d, sample_rate=%d, duration=%.2fsec, \" \"rms=%.2fdB\"", "of the 5th utterance's audio file in sequence file \"xxx.seqbin\"", "if end_sec < 0.0: end_sec = self.duration + end_sec if", "it wraps around from the end. If not provided, this", "boundaries. Note that this is an in-place transformation. :param start_sec:", "return True def __ne__(self, other): \"\"\"Return whether two objects are", "float \"\"\" return self._samples.shape[0] / float(self._sample_rate) @property def rms_db(self): \"\"\"Return", "self._sample_rate) if sides == \"beginning\": padded = cls.concatenate(silence, self) elif", ":type allow_resample: bool \"\"\" target_db = self.rms_db self.convolve(impulse_segment, allow_resample=allow_resample) self.normalize(target_db)", "to audio file. infos (TarLocalData, optional): tar2obj and tar2infos. Defaults", "audio segments when downsampling is not allowed, or if the", "audio file. infos (TarLocalData, optional): tar2obj and tar2infos. Defaults to", ":rtype: str \"\"\" samples = self._convert_samples_from_float32(self._samples, dtype) return samples def", "str :raises ValueError: If sides is not supported. \"\"\" if", "as 0.0 is full-scale audio. :type target_db: float :param max_gain_db:", "file in sequence file \"xxx.seqbin\" must be \"xxx.seqbin_5\", with \"5\"", "10 * np.log10(mean_square) def _convert_samples_to_float32(self, samples): \"\"\"Convert sample type to", "float :return: Silent AudioSegment instance of the given duration. :rtype:", "@classmethod def from_file(cls, file, infos=None): \"\"\"Create audio segment from audio", "startup_delay=0.0): \"\"\"Normalize audio using a production-compatible online/causal algorithm. This uses", "'float32'. :type dtype: str :raises TypeError: If dtype is not", "return not self.__eq__(other) def __str__(self): \"\"\"Return human-readable representation of segment.\"\"\"", "start_sec: float :param end_sec: End of subsegment in seconds. :type", ":rtype: AudioSegment \"\"\" samples, sample_rate = soundfile.read( io.BytesIO(bytes), dtype='float32') return", "\" \"the slice end position (%f s).\" % (start, end))", "under the Apache License, Version 2.0 (the \"License\"); # you", "= tfm.build_array( input_array=self._samples, sample_rate_in=self._sample_rate).squeeze(-1).astype( np.float32).copy() def normalize(self, target_db=-20, max_gain_db=300.0): \"\"\"Normalize", "sample_rate(self): \"\"\"Return audio sample rate. :return: Audio sample rate. :rtype:", "type, float32 will be rescaled from [-1, 1] to the", "decibels. :rtype: float \"\"\" # square root => multiply by", "audio segments to be concatenated. :type *segments: tuple of AudioSegment", "/ 10.) prior_sum_of_squares = prior_mean_squared * prior_samples cumsum_of_squares = np.cumsum(self.samples**2)", "input_array=self._samples, sample_rate_in=self._sample_rate).squeeze(-1).astype( np.float32).copy() def normalize(self, target_db=-20, max_gain_db=300.0): \"\"\"Normalize audio to", "is not equal to base \" \"signal sample rate (%d", "accrue statistics for the first startup_delay seconds before applying online", "time. \"\"\" start_sec = 0.0 if start_sec is None else", "is an in-place transformation. :param target_db: Target RMS value in", "dB that can be applied for normalization. This is to", "from this signal. :type allow_resample: bool \"\"\" target_db = self.rms_db", "time in seconds. If start is negative, it wraps around", "< 0.0: raise ValueError(\"The slice end position (%f s) is", "samples. :type gain: float|1darray \"\"\" self._samples *= 10.**(gain / 20.)", "target_bd: float :param prior_db: Prior RMS estimate in decibels. :type", "make_silence(cls, duration, sample_rate): \"\"\"Creates a silent audio segment of the", ":param other: Segment containing samples to be added in. :type", "end of the file. :type end: float :return: AudioSegment instance", "from a byte string containing audio samples. :param bytes: Byte", "e.g. out of bounds in time. \"\"\" sndfile = soundfile.SoundFile(file)", "that this is an in-place transformation. :param gain: Gain in", "out of bounds in time. \"\"\" start_sec = 0.0 if", "(end_sec, self.duration)) start_sample = int(round(start_sec * self._sample_rate)) end_sample = int(round(end_sec", "self._samples = padded._samples def shift(self, shift_ms): \"\"\"Shift the audio in", "of noise segments is shorter than original audio segments. \"\"\"", "length of subsegment is greater than the origineal segemnt. \"\"\"", "filter to use one of {'kaiser_best', 'kaiser_fast'}. :type filter: str", "of speed change: speed_rate > 1.0, speed up the audio;", "= self.duration + end_sec if start_sec < 0.0: raise ValueError(\"The", "be scaled to [-1, 1] in float32. \"\"\" return convert_samples_to_float32(samples)", "specified slice of the input audio file. :rtype: AudioSegment :raise", "RuntimeError(\"Can not install soxbindings on your system.\" ) tfm =", "random subsegment of matching length is sampled from it and", "by the integer type. This is for writing a audio", "audio speed by linear interpolation. Note that this is an", "sample_rate) end_frame = int(end * sample_rate) sndfile.seek(start_frame) data = sndfile.read(frames=end_frame", "of samples. :return: Number of samples. :rtype: int \"\"\" return", "= \\ cumsum_of_squares[startup_sample_idx] sample_count[:startup_sample_idx] = \\ sample_count[startup_sample_idx] mean_squared_estimate = ((cumsum_of_squares", "segment instance. :rtype: AudioSegment \"\"\" samples, sample_rate = soundfile.read( io.BytesIO(bytes),", "should be greater than zero.\") # numpy # old_length =", "float \"\"\" # Estimate total RMS online. startup_sample_idx = min(self.num_samples", "= re.match(r\"(.+\\.seqbin)_(\\d+)\", filepath) if matches is None: raise IOError(\"File type", "1] in float32. \"\"\" return convert_samples_to_float32(samples) def _convert_samples_from_float32(self, samples, dtype):", "float :param startup_delay: Default 0.0s. If provided, this function will", "And the filename of the 5th utterance's audio file in", "samples): \"\"\"Convert sample type to float32. Audio sample type is", "sample_rate): \"\"\"Create audio segment from samples. Samples are convert float32", "a silent audio segment of the given duration and sample", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "None else start_sec end_sec = self.duration if end_sec is None", "range supported by the integer type. This is for writing", "segment instance. :rtype: AudioSegment \"\"\" # parse filepath matches =", "/ 1000.0 > self.duration: raise ValueError(\"Absolute value of shift_ms should", "in segments]) return cls(samples, sample_rate) @classmethod def make_silence(cls, duration, sample_rate):", "a specific signal-to-noise ratio. If the noise segment is longer", "Hz).\" % (impulse_segment.sample_rate, self.sample_rate)) samples = signal.fftconvolve(self.samples, impulse_segment.samples, \"full\") self._samples", "\" \"different sample rates\") if type(seg) is not cls: raise", "in the beginning; 'end' - adds silence in the end;", "Note that this is an in-place transformation. :param speed_rate: Rate", "% (noise.duration, self.duration)) noise_gain_db = min(self.rms_db - noise.rms_db - snr_dB,", "two objects are unequal.\"\"\" return not self.__eq__(other) def __str__(self): \"\"\"Return", "io.open(filename, mode='rb', encoding='utf8') version = f.read(4) num_utterances = struct.unpack(\"i\", f.read(4))[0]", "dtype: str :raises TypeError: If dtype is not supported. \"\"\"", "to apply infinite gain to a zero signal. :type max_gain_db:", "type of %s is not supported\" % filepath) filename =", "target_db: float :param max_gain_db: Max amount of gain in dB", "response segments. :type impulse_segment: AudioSegment :param allow_resample: Indicates whether resampling", "allowed, raise ValueError. :type speed_rate: float :raises ValueError: If speed_rate", ":type target_sample_rate: int :param filter: The resampling filter to use", "start is negative, it wraps around from the end. If", "with \".seqbin\". And the filename of the 5th utterance's audio", "Gain in decibels to apply to samples. :type gain: float|1darray", "\"end\": padded = cls.concatenate(self, silence) elif sides == \"both\": padded", "sides='both'): \"\"\"Pad this audio sample with a period of silence.", "function will accrue statistics for the first startup_delay seconds before", "sample_rate if self._samples.ndim >= 2: self._samples = np.mean(self._samples, 1) def", "Estimate total RMS online. startup_sample_idx = min(self.num_samples - 1, int(self.sample_rate", "convert float32 internally, with int scaled to [-1, 1]. \"\"\"", "dtype='float32'): \"\"\"Create a byte string containing the audio content. :param", "has a different sample rate from this signal. :type allow_resample:", "sample rate (%d Hz).\" % (noise.sample_rate, self.sample_rate)) if noise.duration <", "Silent AudioSegment instance of the given duration. :rtype: AudioSegment \"\"\"", "float-point. For integer type, float32 will be rescaled from [-1,", "if noise.sample_rate != self.sample_rate: raise ValueError(\"Noise sample rate (%d Hz)", "if end is None else end if start < 0.0:", "AudioSegment :raise ValueError: If start or end is incorrectly set,", "1) def __eq__(self, other): \"\"\"Return whether two objects are equal.\"\"\"", "self.convolve(impulse_segment, allow_resample=allow_resample) self.normalize(target_db) def add_noise(self, noise, snr_dB, allow_downsampling=False, max_gain_db=300.0, rng=None):", "Position for padding: 'beginning' - adds silence in the beginning;", "bytes (int, version), 4 bytes (int, num of utterance), 4", "float :param end: End time in seconds. If end is", "float :param max_gain_db: Max amount of gain in dB that", "probable gain have exceeds max_gain_db (%f dB)\" % (target_db, max_gain_db))", "def make_silence(cls, duration, sample_rate): \"\"\"Creates a silent audio segment of", "audio samples. :type bytes: str :return: Audio segment instance. :rtype:", "audio file. Options: 'int16', 'int32', 'float32', 'float64'. Default is 'float32'.", "self._samples[-shift_samples:] = 0 elif shift_samples < 0: # time delay", "from_file(cls, file, infos=None): \"\"\"Create audio segment from audio file. Args:", "cls = type(self) silence = self.make_silence(duration, self._sample_rate) if sides ==", "when attempting to normalize a signal consisting of all zeros.", "sequence file. Sequence file is a binary file containing a", "end_sec=None): \"\"\"Cut the AudioSegment between given boundaries. Note that this", "sample rates\") if type(seg) is not cls: raise TypeError(\"Only audio", "to samples. :type gain: float|1darray \"\"\" self._samples *= 10.**(gain /", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "< 0.0: end_sec = self.duration + end_sec if start_sec <", "Authors. All Rights Reserved. # # Licensed under the Apache", "\"\"\"Loads a small section of an audio without having to", "num_samples(self): \"\"\"Return number of samples. :return: Number of samples. :rtype:", "added in. :type other: AudioSegments :raise TypeError: If type of", "\"\"\" self._samples *= 10.**(gain / 20.) def change_speed(self, speed_rate): \"\"\"Change", "def resample(self, target_sample_rate, filter='kaiser_best'): \"\"\"Resample the audio to a target", "= self._samples.shape[0] # new_length = int(old_length / speed_rate) # old_indices", ":raise ValueError: If the sample rates of the two segments", "resampling filter to use one of {'kaiser_best', 'kaiser_fast'}. :type filter:", "# old_length = self._samples.shape[0] # new_length = int(old_length / speed_rate)", "is an in-place transformation. :param start_sec: Beginning of subsegment in", "int scaled to [-1, 1]. \"\"\" self._samples = self._convert_samples_to_float32(samples) self._sample_rate", "Apache License, Version 2.0 (the \"License\"); # you may not", "be at least as long as\" \" base signal (%f", "either express or implied. # See the License for the", ":return: AudioSegment instance of the specified slice of the input", "= padded._samples def shift(self, shift_ms): \"\"\"Shift the audio in time.", "the impulse_segment has a different sample rate from this signal.", "TypeError: If type of two segments don't match. :raise ValueError:", "period of silence. Note that this is an in-place transformation.", ":param startup_delay: Default 0.0s. If provided, this function will accrue", "(int, bytes per header), [bytes_per_header*(num_utterance+1)] bytes (offsets for each audio),", "is not match between two audio segments when resample is", "samples = np.frombuffer(audio_bytes, dtype='int16') return cls(samples=samples, sample_rate=8000) @classmethod def from_bytes(cls,", "audio segment from samples. Samples are convert float32 internally, with", "containing the audio content. :param dtype: Data type for export", "sample_rate) @classmethod def make_silence(cls, duration, sample_rate): \"\"\"Creates a silent audio", "out of \" \"bounds.\" % start_sec) if end_sec < 0.0:", "bounds in time. \"\"\" sndfile = soundfile.SoundFile(file) sample_rate = sndfile.samplerate", "has the same average power as the input signal. Note", ":param max_gain_db: Max amount of gain in dB that can", "self.sample_rate: raise ValueError(\"Noise sample rate (%d Hz) is not equal", "self.sample_rate, self.duration, self.rms_db)) @classmethod def from_file(cls, file, infos=None): \"\"\"Create audio", "time advance; if negative; shift with time delay. :type shift_ms:", "in-place transformation. :param target_db: Target RMS value in decibels. :type", "\"rms=%.2fdB\" % (type(self), self.num_samples, self.sample_rate, self.duration, self.rms_db)) @classmethod def from_file(cls,", "segment class.\"\"\" import copy import io import random import re", "object. :type file: str|file :param start: Start time in seconds.", "seg in segments: if sample_rate != seg._sample_rate: raise ValueError(\"Can't concatenate", ":return: Root mean square energy in decibels. :rtype: float \"\"\"", "elif shift_samples < 0: # time delay self._samples[-shift_samples:] = self._samples[:shift_samples]", "is an in-place transformation. :param other: Segment containing samples to", "be concatenated. :type *segments: tuple of AudioSegment :return: Audio segment", "the audio in decibels. :return: Root mean square energy in", "add. :type noise: AudioSegment :param snr_dB: Signal-to-Noise Ratio, in decibels.", "speed_rate): \"\"\"Change the audio speed by linear interpolation. Note that", "start: float :param end: End time in seconds. If end", "np.any(self.samples != other._samples): return False return True def __ne__(self, other):", "bytes in the head indicating the offsets of each audio", "Noise signal to add. :type noise: AudioSegment :param snr_dB: Signal-to-Noise", "segments[0]._sample_rate for seg in segments: if sample_rate != seg._sample_rate: raise", "self.duration: raise ValueError(\"Noise signal (%f sec) must be at least", "max_gain_db: float :raises ValueError: If the required gain to normalize", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "self.sample_rate != impulse_segment.sample_rate: raise ValueError(\"Impulse segment's sample rate (%d Hz)", "a zero signal. :type max_gain_db: float :param rng: Random number", "filepath) if matches is None: raise IOError(\"File type of %s", "new_length = int(old_length / speed_rate) # old_indices = np.arange(old_length) #", "\"\"\"Normalize audio using a production-compatible online/causal algorithm. This uses an", "def pad_silence(self, duration, sides='both'): \"\"\"Pad this audio sample with a", ":param duration: Length of silence in seconds to pad. :type", "the AudioSegment between given boundaries. Note that this is an", "out of bounds.\" % end_sec) if start_sec > end_sec: raise", "float32 to dtype. Audio sample type is usually integer or", "is None else end if start < 0.0: start +=", "= sndfile.read(frames=end_frame - start_frame, dtype='float32') return cls(data, sample_rate) @classmethod def", "silence) elif sides == \"both\": padded = cls.concatenate(silence, self, silence)", "as\" \" base signal (%f sec).\" % (noise.duration, self.duration)) noise_gain_db", "\"\"\"Convert sample type to float32. Audio sample type is usually", "from float32 to dtype. Audio sample type is usually integer", "self._samples += other._samples def to_bytes(self, dtype='float32'): \"\"\"Create a byte string", "utterance), 4 bytes (int, bytes per header), [bytes_per_header*(num_utterance+1)] bytes (offsets", "subsegment in seconds. :type start_sec: float :param end_sec: End of", "return cls(samples, sample_rate) @classmethod def concatenate(cls, *segments): \"\"\"Concatenate an arbitrary", "Byte string containing audio content. :rtype: str \"\"\" samples =", "self.duration)) start_sample = int(round(start_sec * self._sample_rate)) end_sample = int(round(end_sec *", "0.0. \"\"\" if speed_rate == 1.0: return if speed_rate <=", "np.mean(self._samples**2) return 10 * np.log10(mean_square) def _convert_samples_to_float32(self, samples): \"\"\"Convert sample", "/ 20.) def change_speed(self, speed_rate): \"\"\"Change the audio speed by", "s) is out of bounds.\" % end) if start >", "'int16': 'PCM_16', 'int32': 'PCM_32', 'float32': 'FLOAT', 'float64': 'DOUBLE' } soundfile.write(", "bool :raises ValueError: If the sample rate is not match", "is zero, or if the sample_rate of any segments does", "speed_rate = 1.0, unchanged; speed_rate < 1.0, slow down the", "name must end with \".seqbin\". And the filename of the", "value should be less than 0.0 as 0.0 is full-scale", "= sample_rate if self._samples.ndim >= 2: self._samples = np.mean(self._samples, 1)", "self cls = type(self) silence = self.make_silence(duration, self._sample_rate) if sides", "return samples def gain_db(self, gain): \"\"\"Apply gain in decibels to", "max_gain_db (%f dB)\" % (target_db, max_gain_db)) self.gain_db(min(max_gain_db, target_db - self.rms_db))", "end with \".seqbin\". And the filename of the 5th utterance's", "bounds \" \"(> %f s)\" % (end_sec, self.duration)) start_sample =", "add segments.\") self._samples += other._samples def to_bytes(self, dtype='float32'): \"\"\"Create a", "import resampy import soundfile from scipy import signal from .utility", "for the sides %s\" % sides) self._samples = padded._samples def", "between two audio segments when resample is not allowed. \"\"\"", "subtype=subtype_map[dtype]) def superimpose(self, other): \"\"\"Add samples from another segment to", "self.rms_db)) def normalize_online_bayesian(self, target_db, prior_db, prior_samples, startup_delay=0.0): \"\"\"Normalize audio using", "dynamic_pip_install.install(package) package = \"soxbindings\" dynamic_pip_install.install(package) import soxbindings as sox except:", "even when there are very few samples. Note that this", "rate. :type sample_rate: int :raises TypeError: If the sample data", "segment to %f dB because the \" \"the probable gain", "class AudioSegment(): \"\"\"Monaural audio segment abstraction. :param samples: Audio samples", "exceeds max_gain_db. \"\"\" gain = target_db - self.rms_db if gain", "%f s)\" % (end_sec, self.duration)) start_sample = int(round(start_sec * self._sample_rate))", "speed_rate > 1.0, speed up the audio; speed_rate = 1.0,", ":type bytes: str :return: Audio segment instance. :rtype: AudioSegment \"\"\"", "%f s)\" % (end, duration)) start_frame = int(start * sample_rate)", ":param gain: Gain in decibels to apply to samples. :type", ":type target_bd: float :param prior_db: Prior RMS estimate in decibels.", "> end: raise ValueError(\"The slice start position (%f s) is", "version = f.read(4) num_utterances = struct.unpack(\"i\", f.read(4))[0] bytes_per_header = struct.unpack(\"i\",", "subsegment_length: float :param rng: Random number generator state. :type rng:", "will accrue statistics for the first startup_delay seconds before applying", "seconds. :type subsegment_length: float :param rng: Random number generator state.", "provided, the default behvaior is to read to the end", "rng if allow_downsampling and noise.sample_rate > self.sample_rate: noise = noise.resample(self.sample_rate)", "samples def gain_db(self, gain): \"\"\"Apply gain in decibels to samples.", "\"\"\"Convolve this audio segment with the given impulse segment. Note", "self._samples.shape[0] @property def duration(self): \"\"\"Return audio duration. :return: Audio duration", "file name must end with \".seqbin\". And the filename of", "Default 0.0s. If provided, this function will accrue statistics for", "is not allowed, or if the duration of noise segments", "scaled to [-1, 1] in float32. \"\"\" return convert_samples_to_float32(samples) def", "the given impulse segment. Note that this is an in-place", "format='WAV', subtype=subtype_map[dtype]) def superimpose(self, other): \"\"\"Add samples from another segment", "in time. \"\"\" sndfile = soundfile.SoundFile(file) sample_rate = sndfile.samplerate duration", "at a specific signal-to-noise ratio. If the noise segment is", "!= other._sample_rate: return False if self._samples.shape != other._samples.shape: return False", "if self._sample_rate != other._sample_rate: raise ValueError(\"Sample rates must match to", "abs(shift_ms) / 1000.0 > self.duration: raise ValueError(\"Absolute value of shift_ms", "duration unchanged. Note that this is an in-place transformation. :param", "use this file except in compliance with the License. #", "impulse_segment: AudioSegment :param allow_resample: Indicates whether resampling is allowed when", "in decibels to samples. Note that this is an in-place", "usually integer or float-point. Integers will be scaled to [-1,", "value exceeds max_gain_db. \"\"\" gain = target_db - self.rms_db if", "> self.duration: raise ValueError(\"The slice end position (%f s) is", "from audio file. Args: filepath (str|file): Filepath or file object", "\"Unable to normalize segment to %f dB because the \"", "can be applied for normalization. This is to prevent nans", "+ start_sec if end_sec < 0.0: end_sec = self.duration +", "'float32', 'float64'. Default is 'float32'. :type dtype: str :raises TypeError:", "with time advance; if negative; shift with time delay. :type", "or if the sample_rate of any segments does not match.", "an exponential likelihood and gamma prior to make online estimates", ":type speed_rate: float :raises ValueError: If speed_rate <= 0.0. \"\"\"", "str \"\"\" samples = self._convert_samples_from_float32(self._samples, dtype) return samples.tostring() def to(self,", "sample_count[startup_sample_idx] mean_squared_estimate = ((cumsum_of_squares + prior_sum_of_squares) / (sample_count + prior_samples))", "rng=rng) noise_new.gain_db(noise_gain_db) self.superimpose(noise_new) @property def samples(self): \"\"\"Return audio samples. :return:", "int \"\"\" return self._sample_rate @property def num_samples(self): \"\"\"Return number of", "audio), audio_bytes_data_of_1st_utterance, audio_bytes_data_of_2nd_utterance, ...... Sequence file name must end with", "type(self): return False if self._sample_rate != other._sample_rate: return False if", "def convolve_and_normalize(self, impulse_segment, allow_resample=False): \"\"\"Convolve and normalize the resulting audio", "TypeError(\"Only audio segments of the same type \" \"can be", "to read to the end of the file. :type end:", "add_noise(self, noise, snr_dB, allow_downsampling=False, max_gain_db=300.0, rng=None): \"\"\"Add the given noise", "silence = self.make_silence(duration, self._sample_rate) if sides == \"beginning\": padded =", "is None else start_sec end_sec = self.duration if end_sec is", "str :raises TypeError: If dtype is not supported. \"\"\" samples", "rate does not match between the two audio segments when", "start position (%f s) is out of \" \"bounds.\" %", "types: %s \" \"and %s.\" % (type(self), type(other))) if self._sample_rate", "speed_rate: float :raises ValueError: If speed_rate <= 0.0. \"\"\" if", "audiosegment randomly. Note that this is an in-place transformation. :param", "the sample rates of the two segments are not equal,", "of the audiosegment randomly. Note that this is an in-place", "ValueError(\"No audio segments are given to concatenate.\") sample_rate = segments[0]._sample_rate", "shift_samples < 0: # time delay self._samples[-shift_samples:] = self._samples[:shift_samples] self._samples[:-shift_samples]", "raise ValueError(\"Length of subsegment must not be greater \" \"than", "convolve(self, impulse_segment, allow_resample=False): \"\"\"Convolve this audio segment with the given", "Note that this is an in-place transformation. :param target_db: Target", "duration)) start_frame = int(start * sample_rate) end_frame = int(end *", "sample rate. Note that this is an in-place transformation. :param", "random_subsegment(self, subsegment_length, rng=None): \"\"\"Cut the specified length of the audiosegment", "ValueError(\"Unknown value for the sides %s\" % sides) self._samples =", "value in decibels. Note that this is an in-place transformation.", "in compliance with the License. # You may obtain a", "software # distributed under the License is distributed on an", "if shift_samples > 0: # time advance self._samples[:-shift_samples] = self._samples[shift_samples:]", "number generator state. :type rng: random.Random :raises ValueError: If the", "signal (%f sec).\" % (noise.duration, self.duration)) noise_gain_db = min(self.rms_db -", ":return: Audio segment instance. :rtype: AudioSegment \"\"\" samples, sample_rate =", "'float32'. :type dtype: str :return: np.ndarray containing `dtype` audio content.", "- start_frame, dtype='float32') return cls(data, sample_rate) @classmethod def from_sequence_file(cls, filepath):", "(%f sec).\" % (noise.duration, self.duration)) noise_gain_db = min(self.rms_db - noise.rms_db", "[num_samples x num_channels]. :type samples: ndarray.float32 :param sample_rate: Audio sample", "is allowed when the impulse_segment has a different sample rate", "# Estimate total RMS online. startup_sample_idx = min(self.num_samples - 1,", "from .utility import subfile_from_tar class AudioSegment(): \"\"\"Monaural audio segment abstraction.", ":param max_gain_db: Maximum amount of gain to apply to noise", "= min(self.num_samples - 1, int(self.sample_rate * startup_delay)) prior_mean_squared = 10.**(prior_db", "samples = self._convert_samples_from_float32(self._samples, dtype) return samples def gain_db(self, gain): \"\"\"Apply", "0.0: return self cls = type(self) silence = self.make_silence(duration, self._sample_rate)", "in seconds. If start is negative, it wraps around from", "segments with \" \"different sample rates\") if type(seg) is not", "not self.__eq__(other) def __str__(self): \"\"\"Return human-readable representation of segment.\"\"\" return", "there are very few samples. Note that this is an", "sample_rate) @classmethod def concatenate(cls, *segments): \"\"\"Concatenate an arbitrary number of", "of subsegment in seconds. :type start_sec: float :param end_sec: End", "are unequal.\"\"\" return not self.__eq__(other) def __str__(self): \"\"\"Return human-readable representation", ":type dtype: str :return: Byte string containing audio content. :rtype:", "of matching length is sampled from it and used instead.", "str \"\"\" samples = self._convert_samples_from_float32(self._samples, dtype) return samples def gain_db(self,", "time in millseconds. If positive, shift with time advance; if", ":param sample_rate: Sample rate. :type sample_rate: float :return: Silent AudioSegment", "rate. :type sample_rate: float :return: Silent AudioSegment instance of the", "each audio byte data chunk. The format is: 4 bytes", "convolve_and_normalize(self, impulse_segment, allow_resample=False): \"\"\"Convolve and normalize the resulting audio segment", "if start > end: raise ValueError(\"The slice start position (%f", "ValueError: If start or end is incorrectly set, e.g. out", "header = [ struct.unpack(\"i\", header_bytes[bytes_per_header * i: bytes_per_header * (i", "end_sec: raise ValueError(\"The slice start position (%f s) is later", "segment.\"\"\" return (\"%s: num_samples=%d, sample_rate=%d, duration=%.2fsec, \" \"rms=%.2fdB\" % (type(self),", "incorrectly set, e.g. out of bounds in time. \"\"\" sndfile", "self.make_silence(duration, self._sample_rate) if sides == \"beginning\": padded = cls.concatenate(silence, self)", "to base signal sample rate (%d Hz).\" % (impulse_segment.sample_rate, self.sample_rate))", "= int(matches.group(2)) # read headers f = io.open(filename, mode='rb', encoding='utf8')", "== \"end\": padded = cls.concatenate(self, silence) elif sides == \"both\":", "/ float(self._sample_rate) @property def rms_db(self): \"\"\"Return root mean square energy", "the audiosegment randomly. Note that this is an in-place transformation.", "(%f s).\" % (start, end)) if end > duration: raise", "float32 will be rescaled from [-1, 1] to the maximum", "must be \"xxx.seqbin_5\", with \"5\" indicating the utterance index within", "f.read(4))[0] header_bytes = f.read(bytes_per_header * (num_utterances + 1)) header =", "from this signal. :type allow_resample: bool :raises ValueError: If the", ":param end_sec: End of subsegment in seconds. :type end_sec: float", "for seg in segments: if sample_rate != seg._sample_rate: raise ValueError(\"Can't", "containing audio samples. :type bytes: str :return: Audio segment instance.", "basic sanity-checks. if len(segments) == 0: raise ValueError(\"No audio segments", "data chunk. The format is: 4 bytes (int, version), 4", "return cls(samples, sample_rate) @classmethod def make_silence(cls, duration, sample_rate): \"\"\"Creates a", "if start < 0.0: start += duration if end <", "<= 0: raise ValueError(\"speed_rate should be greater than zero.\") #", "this is an in-place transformation. :param target_sample_rate: Target sample rate.", "dtype) return samples.tostring() def to(self, dtype='int16'): \"\"\"Create a `dtype` audio", "first startup_delay seconds before applying online normalization. :type startup_delay: float", ":type other: AudioSegments :raise TypeError: If type of two segments", "of shift_ms should be smaller \" \"than audio duration.\") shift_samples", "is full-scale audio. :type target_db: float :param max_gain_db: Max amount", "* np.log10(mean_square) def _convert_samples_to_float32(self, samples): \"\"\"Convert sample type to float32.", "'float64': 'DOUBLE' } soundfile.write( filepath, samples, self._sample_rate, format='WAV', subtype=subtype_map[dtype]) def", "to add. :type noise: AudioSegment :param snr_dB: Signal-to-Noise Ratio, in", "with the License. # You may obtain a copy of", "\"soxbindings\" dynamic_pip_install.install(package) import soxbindings as sox except: raise RuntimeError(\"Can not", "- snr_dB, max_gain_db) noise_new = copy.deepcopy(noise) noise_new.random_subsegment(self.duration, rng=rng) noise_new.gain_db(noise_gain_db) self.superimpose(noise_new)", "duration.\") shift_samples = int(shift_ms * self._sample_rate / 1000) if shift_samples", "sanity-checks. if len(segments) == 0: raise ValueError(\"No audio segments are", "re import struct import numpy as np import resampy import", "file object to save the audio segment. :type filepath: str|file", "of the input audio file. :rtype: AudioSegment :raise ValueError: If", "is not type(self): return False if self._sample_rate != other._sample_rate: return", "0.0: end_sec = self.duration + end_sec if start_sec < 0.0:", "sides: str :raises ValueError: If sides is not supported. \"\"\"", "duration. \"\"\" if abs(shift_ms) / 1000.0 > self.duration: raise ValueError(\"Absolute", "return convert_samples_to_float32(samples) def _convert_samples_from_float32(self, samples, dtype): \"\"\"Convert sample type from", ":type max_gain_db: float :raises ValueError: If the required gain to", "\"beginning\": padded = cls.concatenate(silence, self) elif sides == \"end\": padded", "10 * np.log10(mean_squared_estimate) # Compute required time-varying gain. gain_db =", ":type allow_resample: bool :raises ValueError: If the sample rate is", "express or implied. # See the License for the specific", "not match. :raises TypeError: If any segment is not AudioSegment", "\"\"\" def __init__(self, samples, sample_rate): \"\"\"Create audio segment from samples.", "except in compliance with the License. # You may obtain", "the noise signal to be downsampled to match the base", "AudioSegment instance of the given duration. :rtype: AudioSegment \"\"\" samples", "is an in-place transformation. :param speed_rate: Rate of speed change:", "resampy.resample( self.samples, self.sample_rate, target_sample_rate, filter=filter) self._sample_rate = target_sample_rate def pad_silence(self,", ":rtype: AudioSegment :raise ValueError: If start or end is incorrectly", "subfile_from_tar class AudioSegment(): \"\"\"Monaural audio segment abstraction. :param samples: Audio", ":param allow_downsampling: Whether to allow the noise signal to be", "that this is an in-place transformation. :param target_sample_rate: Target sample", "audio to a target sample rate. Note that this is", "the utterance index within this sequence file (starting from 1).", ":type samples: ndarray.float32 :param sample_rate: Audio sample rate. :type sample_rate:", "seconds. :type duration: float :param sample_rate: Sample rate. :type sample_rate:", "noise.resample(self.sample_rate) if noise.sample_rate != self.sample_rate: raise ValueError(\"Noise sample rate (%d", "end. If not provided, the default behvaior is to read", "that this is an in-place transformation. :param subsegment_length: Subsegment length", "raise ValueError(\"Absolute value of shift_ms should be smaller \" \"than", "(%d Hz).\" % (noise.sample_rate, self.sample_rate)) if noise.duration < self.duration: raise", "start_sec < 0.0: start_sec = self.duration + start_sec if end_sec", "is 'float32'. :type dtype: str :return: np.ndarray containing `dtype` audio", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "1]) audio_bytes = f.read(header[fileno] - header[fileno - 1]) f.close() #", ":rtype: int \"\"\" return self._sample_rate @property def num_samples(self): \"\"\"Return number", "and tar2infos. Defaults to None. Returns: AudioSegment: Audio segment instance.", "(%d Hz).\" % (impulse_segment.sample_rate, self.sample_rate)) samples = signal.fftconvolve(self.samples, impulse_segment.samples, \"full\")", "\"\"\" sndfile = soundfile.SoundFile(file) sample_rate = sndfile.samplerate duration = float(len(sndfile))", "WAV filepath or file object to save the audio segment.", "\"\"\" samples = self._convert_samples_from_float32(self._samples, dtype) subtype_map = { 'int16': 'PCM_16',", "'float32', 'float64'. Default is 'float32'. :type dtype: str :return: np.ndarray", "self._samples = self._samples[start_sample:end_sample] def random_subsegment(self, subsegment_length, rng=None): \"\"\"Cut the specified", "less than 0.0 as 0.0 is full-scale audio. :type target_db:", "segment.\") start_time = rng.uniform(0.0, self.duration - subsegment_length) self.subsegment(start_time, start_time +", "Note that this is an in-place transformation. :param target_sample_rate: Target", "and noise.sample_rate > self.sample_rate: noise = noise.resample(self.sample_rate) if noise.sample_rate !=", "be added in. :type other: AudioSegments :raise TypeError: If type", "unchanged. Note that this is an in-place transformation. :param shift_ms:", "duration and sample rate. :param duration: Length of silence in", "concatenated. :type *segments: tuple of AudioSegment :return: Audio segment instance", "the \" \"the probable gain have exceeds max_gain_db (%f dB)\"", ":type impulse_segment: AudioSegment :param allow_resample: Indicates whether resampling is allowed", "CONDITIONS OF ANY KIND, either express or implied. # See", "If type of two segments don't match. :raise ValueError: If", "%s.\" % (type(self), type(other))) if self._sample_rate != other._sample_rate: raise ValueError(\"Sample", "np.log10(mean_squared_estimate) # Compute required time-varying gain. gain_db = target_db -", "shift_ms): \"\"\"Shift the audio in time. If `shift_ms` is positive,", "num_samples=%d, sample_rate=%d, duration=%.2fsec, \" \"rms=%.2fdB\" % (type(self), self.num_samples, self.sample_rate, self.duration,", "that this is an in-place transformation. :param speed_rate: Rate of", "\"and %s.\" % (type(self), type(other))) if self._sample_rate != other._sample_rate: raise", "is None else rng if subsegment_length > self.duration: raise ValueError(\"Length", "to add segments.\") self._samples += other._samples def to_bytes(self, dtype='float32'): \"\"\"Create", "...... Sequence file name must end with \".seqbin\". And the", "= \"sox\" dynamic_pip_install.install(package) package = \"soxbindings\" dynamic_pip_install.install(package) import soxbindings as", "out of bounds \" \"(> %f s)\" % (end_sec, self.duration))", "samples. Note that this is an in-place transformation. :param gain:", "be greater \" \"than original segment.\") start_time = rng.uniform(0.0, self.duration", "is incorrectly set, e.g. out of bounds in time. \"\"\"", "from scipy import signal from .utility import convert_samples_from_float32 from .utility", "return False if self._samples.shape != other._samples.shape: return False if np.any(self.samples", "the same type \" \"can be concatenated.\") samples = np.concatenate([seg.samples", "self._samples[:-shift_samples] = 0 def subsegment(self, start_sec=None, end_sec=None): \"\"\"Cut the AudioSegment", "average power as the input signal. Note that this is", "< 0.0: end += duration if start < 0.0: raise", "speed_rate <= 0.0, not allowed, raise ValueError. :type speed_rate: float", "= float(len(sndfile)) / sample_rate start = 0. if start is", "the maximum range supported by the integer type. This is", "Sample rate. :type sample_rate: float :return: Silent AudioSegment instance of", "type of two segments don't match. :raise ValueError: If the", "prior_sum_of_squares = prior_mean_squared * prior_samples cumsum_of_squares = np.cumsum(self.samples**2) sample_count =", "or file object to save the audio segment. :type filepath:", "if negative, shift with time delay. Silence are padded to", "value in decibels. This value should be less than 0.0", "def convolve(self, impulse_segment, allow_resample=False): \"\"\"Convolve this audio segment with the", ":type sides: str :raises ValueError: If sides is not supported.", "False if self._samples.shape != other._samples.shape: return False if np.any(self.samples !=", "of the file. :type end: float :return: AudioSegment instance of", "> self.duration: raise ValueError(\"Absolute value of shift_ms should be smaller", "0.0: start_sec = self.duration + start_sec if end_sec < 0.0:", "self._samples = samples def convolve_and_normalize(self, impulse_segment, allow_resample=False): \"\"\"Convolve and normalize", "* (i + 1)])[0] for i in range(num_utterances + 1)", "and self.sample_rate != impulse_segment.sample_rate: impulse_segment.resample(self.sample_rate) if self.sample_rate != impulse_segment.sample_rate: raise", "random import re import struct import numpy as np import", "time advance; if negative, shift with time delay. Silence are", "of segment.\"\"\" return (\"%s: num_samples=%d, sample_rate=%d, duration=%.2fsec, \" \"rms=%.2fdB\" %", "cumsum_of_squares[startup_sample_idx] sample_count[:startup_sample_idx] = \\ sample_count[startup_sample_idx] mean_squared_estimate = ((cumsum_of_squares + prior_sum_of_squares)", "duration(self): \"\"\"Return audio duration. :return: Audio duration in seconds. :rtype:", "in float32. \"\"\" return convert_samples_to_float32(samples) def _convert_samples_from_float32(self, samples, dtype): \"\"\"Convert", ":rtype: str \"\"\" samples = self._convert_samples_from_float32(self._samples, dtype) return samples.tostring() def", "+ 1) ] # read audio bytes f.seek(header[fileno - 1])", "around from the end. If not provided, this function reads", "dBs mean_square = np.mean(self._samples**2) return 10 * np.log10(mean_square) def _convert_samples_to_float32(self,", "than \" \"the slice end position (%f s).\" % (start,", "duration: float :param sides: Position for padding: 'beginning' - adds", "\" \"bounds.\" % start) if end < 0.0: raise ValueError(\"The", "header), [bytes_per_header*(num_utterance+1)] bytes (offsets for each audio), audio_bytes_data_of_1st_utterance, audio_bytes_data_of_2nd_utterance, ......", "base signal sample rate. :type allow_downsampling: bool :param max_gain_db: Maximum", "Root mean square energy in decibels. :rtype: float \"\"\" #", "raise ValueError(\"Can't concatenate segments with \" \"different sample rates\") if", "<= 0.0. \"\"\" if speed_rate == 1.0: return if speed_rate", "== 0.0: return self cls = type(self) silence = self.make_silence(duration,", "rate (%d Hz) is not \" \"equal to base signal", "Default is 'float32'. :type dtype: str :raises TypeError: If dtype", "be \"xxx.seqbin_5\", with \"5\" indicating the utterance index within this", "any segment is not AudioSegment instance. \"\"\" # Perform basic", ":rtype: AudioSegment \"\"\" samples = np.zeros(int(duration * sample_rate)) return cls(samples,", "change_speed(self, speed_rate): \"\"\"Change the audio speed by linear interpolation. Note", "(start, end)) if end > duration: raise ValueError(\"The slice end", "RMS value in decibels. This value should be less than", "\"signal sample rate (%d Hz).\" % (noise.sample_rate, self.sample_rate)) if noise.duration", "raise ValueError(\"Segment lengths must match to add segments.\") self._samples +=", "than 0.0 as 0.0 is full-scale audio. :type target_db: float", "is later than \" \"the slice end position (%f s).\"", "ndarray.float32 :param sample_rate: Audio sample rate. :type sample_rate: int :raises", "(%f s) is out of bounds.\" % end) if start", "mode='rb', encoding='utf8') version = f.read(4) num_utterances = struct.unpack(\"i\", f.read(4))[0] bytes_per_header", "prior_db, prior_samples, startup_delay=0.0): \"\"\"Normalize audio using a production-compatible online/causal algorithm.", "is usually integer or float-point. For integer type, float32 will", "decibels to apply to samples. :type gain: float|1darray \"\"\" self._samples", "object to audio file. infos (TarLocalData, optional): tar2obj and tar2infos.", "Random number generator state. :type rng: None|random.Random :raises ValueError: If", "signal from .utility import convert_samples_from_float32 from .utility import convert_samples_to_float32 from", "'PCM_16', 'int32': 'PCM_32', 'float32': 'FLOAT', 'float64': 'DOUBLE' } soundfile.write( filepath,", "'float32'. :type dtype: str :return: Byte string containing audio content.", "under the License. \"\"\"Contains the audio segment class.\"\"\" import copy", "to load the entire file into the memory which can", "in sequence file \"xxx.seqbin\" must be \"xxx.seqbin_5\", with \"5\" indicating", "cls(data, sample_rate) @classmethod def from_sequence_file(cls, filepath): \"\"\"Create audio segment from", "resample(self, target_sample_rate, filter='kaiser_best'): \"\"\"Resample the audio to a target sample", "ratio. If the noise segment is longer than this segment,", "a target sample rate. Note that this is an in-place", "cumsum_of_squares[:startup_sample_idx] = \\ cumsum_of_squares[startup_sample_idx] sample_count[:startup_sample_idx] = \\ sample_count[startup_sample_idx] mean_squared_estimate =", "gain_db = target_db - rms_estimate_db self.gain_db(gain_db) def resample(self, target_sample_rate, filter='kaiser_best'):", "file. infos (TarLocalData, optional): tar2obj and tar2infos. Defaults to None.", "incorrectly set, e.g. out of bounds in time. \"\"\" start_sec", "%f dB because the \" \"the probable gain have exceeds", "of bounds.\" % end_sec) if start_sec > end_sec: raise ValueError(\"The", ":type start: float :param end: End time in seconds. If", "seg._sample_rate: raise ValueError(\"Can't concatenate segments with \" \"different sample rates\")", "position (%f s).\" % (start, end)) if end > duration:", "speed up the audio; speed_rate = 1.0, unchanged; speed_rate <", "old_indices, self._samples) # sox, slow try: import soxbindings as sox", "mean_squared_estimate = ((cumsum_of_squares + prior_sum_of_squares) / (sample_count + prior_samples)) rms_estimate_db", "read headers f = io.open(filename, mode='rb', encoding='utf8') version = f.read(4)", "long as\" \" base signal (%f sec).\" % (noise.duration, self.duration))", "given impulse segment. Note that this is an in-place transformation.", "online. startup_sample_idx = min(self.num_samples - 1, int(self.sample_rate * startup_delay)) prior_mean_squared", "except: raise RuntimeError(\"Can not install soxbindings on your system.\" )", "int :param filter: The resampling filter to use one of", "of samples. :type prior_samples: float :param startup_delay: Default 0.0s. If", "and normalize the resulting audio segment so that it has", "resulting audio segment so that it has the same average", "samples, self._sample_rate, format='WAV', subtype=subtype_map[dtype]) def superimpose(self, other): \"\"\"Add samples from", "= int(end * sample_rate) sndfile.seek(start_frame) data = sndfile.read(frames=end_frame - start_frame,", "different sample rate from this signal. :type allow_resample: bool :raises", "[-1, 1] in float32. \"\"\" return convert_samples_to_float32(samples) def _convert_samples_from_float32(self, samples,", "within this sequence file (starting from 1). :param filepath: Filepath", "if isinstance(file, str) and re.findall(r\".seqbin_\\d+$\", file): return cls.from_sequence_file(file) elif isinstance(file,", "arbitrary number of audio segments together. :param *segments: Input audio", "should be less than 0.0 as 0.0 is full-scale audio.", "\\ sample_count[startup_sample_idx] mean_squared_estimate = ((cumsum_of_squares + prior_sum_of_squares) / (sample_count +", "np.cumsum(self.samples**2) sample_count = np.arange(self.num_samples) + 1 if startup_sample_idx > 0:", "greater than zero.\") # numpy # old_length = self._samples.shape[0] #", "audio file. :rtype: AudioSegment :raise ValueError: If start or end", "segment of the given duration and sample rate. :param duration:", "end > duration: raise ValueError(\"The slice end position (%f s)", "audio segments. \"\"\" rng = random.Random() if rng is None", "of sequence file. :type filepath: str :return: Audio segment instance.", "end_sec < 0.0: end_sec = self.duration + end_sec if start_sec", "sample rate. :return: Audio sample rate. :rtype: int \"\"\" return", ":type filter: str \"\"\" self._samples = resampy.resample( self.samples, self.sample_rate, target_sample_rate,", "copy.deepcopy(noise) noise_new.random_subsegment(self.duration, rng=rng) noise_new.gain_db(noise_gain_db) self.superimpose(noise_new) @property def samples(self): \"\"\"Return audio", "if start_sec < 0.0: raise ValueError(\"The slice start position (%f", "self._samples[-shift_samples:] = self._samples[:shift_samples] self._samples[:-shift_samples] = 0 def subsegment(self, start_sec=None, end_sec=None):", "(\"%s: num_samples=%d, sample_rate=%d, duration=%.2fsec, \" \"rms=%.2fdB\" % (type(self), self.num_samples, self.sample_rate,", "subsegment_length) self.subsegment(start_time, start_time + subsegment_length) def convolve(self, impulse_segment, allow_resample=False): \"\"\"Convolve", "Whether to allow the noise signal to be downsampled to", "instance. :rtype: AudioSegment \"\"\" samples, sample_rate = soundfile.read( io.BytesIO(bytes), dtype='float32')", "= 10.**(prior_db / 10.) prior_sum_of_squares = prior_mean_squared * prior_samples cumsum_of_squares", ":type sample_rate: int :raises TypeError: If the sample data type", "(%f s) is out of bounds.\" % end_sec) if start_sec", "If shift_ms is longer than audio duration. \"\"\" if abs(shift_ms)", "filepath: str :return: Audio segment instance. :rtype: AudioSegment \"\"\" #", "noise_gain_db = min(self.rms_db - noise.rms_db - snr_dB, max_gain_db) noise_new =", "if subsegment_length > self.duration: raise ValueError(\"Length of subsegment must not", "= np.mean(self._samples, 1) def __eq__(self, other): \"\"\"Return whether two objects", "sec) must be at least as long as\" \" base", "s) is later than \" \"the end position (%f s).\"", "format is: 4 bytes (int, version), 4 bytes (int, num", "__str__(self): \"\"\"Return human-readable representation of segment.\"\"\" return (\"%s: num_samples=%d, sample_rate=%d,", "an in-place transformation. :param other: Segment containing samples to be", "samples [num_samples x num_channels]. :type samples: ndarray.float32 :param sample_rate: Audio", "samples. :type bytes: str :return: Audio segment instance. :rtype: AudioSegment", "random.Random() if rng is None else rng if subsegment_length >", "from the end. If not provided, the default behvaior is", "from samples. Samples are convert float32 internally, with int scaled", "is 'float32'. :type dtype: str :raises TypeError: If dtype is", "the target_db value exceeds max_gain_db. \"\"\" gain = target_db -", "samples. :rtype: int \"\"\" return self._samples.shape[0] @property def duration(self): \"\"\"Return", "this is an in-place transformation. :param shift_ms: Shift time in", "parse filepath matches = re.match(r\"(.+\\.seqbin)_(\\d+)\", filepath) if matches is None:", "that this is an in-place transformation. :param start_sec: Beginning of", "filter: The resampling filter to use one of {'kaiser_best', 'kaiser_fast'}.", "end_sec = self.duration + end_sec if start_sec < 0.0: raise", "\"\"\"Return root mean square energy of the audio in decibels.", "If the required gain to normalize the segment to the", "is to read to the end of the file. :type", "raise ValueError(\"The slice start position (%f s) is later than", "\"the slice end position (%f s).\" % (start, end)) if", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "duration: Length of silence in seconds to pad. :type duration:", "of any segments does not match. :raises TypeError: If any", "# parse filepath matches = re.match(r\"(.+\\.seqbin)_(\\d+)\", filepath) if matches is", "0.0 if start_sec is None else start_sec end_sec = self.duration", "bounds.\" % end) if start > end: raise ValueError(\"The slice", "type is usually integer or float-point. Integers will be scaled", "normalize_online_bayesian(self, target_db, prior_db, prior_samples, startup_delay=0.0): \"\"\"Normalize audio using a production-compatible", "AudioSegment :param allow_resample: Indicates whether resampling is allowed when the", "dtype: str :return: np.ndarray containing `dtype` audio content. :rtype: str", "\"\"\" if isinstance(file, str) and re.findall(r\".seqbin_\\d+$\", file): return cls.from_sequence_file(file) elif", "section of an audio without having to load the entire", "'float64'. Default is 'float32'. :type dtype: str :raises TypeError: If", "interpolation. Note that this is an in-place transformation. :param speed_rate:", "end_sec)) if end_sec > self.duration: raise ValueError(\"The slice end position", "for seg in segments]) return cls(samples, sample_rate) @classmethod def make_silence(cls,", "if end_sec > self.duration: raise ValueError(\"The slice end position (%f", "if type(other) is not type(self): return False if self._sample_rate !=", "this audio segment with the given impulse segment. Note that", "two audio segments when downsampling is not allowed, or if", "an audio without having to load the entire file into", "is later than \" \"the end position (%f s).\" %", "prior_sum_of_squares) / (sample_count + prior_samples)) rms_estimate_db = 10 * np.log10(mean_squared_estimate)", "of \" \"bounds.\" % start_sec) if end_sec < 0.0: raise", "[ struct.unpack(\"i\", header_bytes[bytes_per_header * i: bytes_per_header * (i + 1)])[0]", "base signal sample rate (%d Hz).\" % (impulse_segment.sample_rate, self.sample_rate)) samples", "start += duration if end < 0.0: end += duration", "raise ValueError(\"The slice start position (%f s) is out of", "estimate in decibels. :type prior_db: float :param prior_samples: Prior strength", "except Exception as e: samples = np.frombuffer(audio_bytes, dtype='int16') return cls(samples=samples,", "adds silence in both the beginning and the end. :type", "if self.sample_rate != impulse_segment.sample_rate: raise ValueError(\"Impulse segment's sample rate (%d", "audio segment from audio file. Args: filepath (str|file): Filepath or", "== 0: raise ValueError(\"No audio segments are given to concatenate.\")", "utterance index within this sequence file (starting from 1). :param", "ValueError. :type speed_rate: float :raises ValueError: If speed_rate <= 0.0.", "target_db - self.rms_db if gain > max_gain_db: raise ValueError( \"Unable", "1000.0 > self.duration: raise ValueError(\"Absolute value of shift_ms should be", "subsegment_length > self.duration: raise ValueError(\"Length of subsegment must not be", "Version 2.0 (the \"License\"); # you may not use this", "re.findall(r\".seqbin_\\d+$\", file): return cls.from_sequence_file(file) elif isinstance(file, str) and file.startswith('tar:'): return", "from 1). :param filepath: Filepath of sequence file. :type filepath:", "sequence file \"xxx.seqbin\" must be \"xxx.seqbin_5\", with \"5\" indicating the", "to %f dB because the \" \"the probable gain have", "dtype: str :return: Byte string containing audio content. :rtype: str", "rate (%d Hz) is not equal to base \" \"signal", "segment abstraction. :param samples: Audio samples [num_samples x num_channels]. :type", "equal.\"\"\" if type(other) is not type(self): return False if self._sample_rate", "sample_rate): \"\"\"Creates a silent audio segment of the given duration", "samples from another segment to those of this segment (sample-wise", "origineal segemnt. \"\"\" rng = random.Random() if rng is None", "as long as\" \" base signal (%f sec).\" % (noise.duration,", "the end. If not provided, the default behvaior is to", "segments when downsampling is not allowed, or if the duration", "linear interpolation. Note that this is an in-place transformation. :param", "than original audio segments. \"\"\" rng = random.Random() if rng", "False if np.any(self.samples != other._samples): return False return True def", "sides %s\" % sides) self._samples = padded._samples def shift(self, shift_ms):", "filepath matches = re.match(r\"(.+\\.seqbin)_(\\d+)\", filepath) if matches is None: raise", "if speed_rate == 1.0: return if speed_rate <= 0: raise", "in-place transformation. :param speed_rate: Rate of speed change: speed_rate >", "from_bytes(cls, bytes): \"\"\"Create audio segment from a byte string containing", "required time-varying gain. gain_db = target_db - rms_estimate_db self.gain_db(gain_db) def", "= rng.uniform(0.0, self.duration - subsegment_length) self.subsegment(start_time, start_time + subsegment_length) def", "very beginning. :type start: float :param end: End time in", "from [-1, 1] to the maximum range supported by the", "Prior strength in number of samples. :type prior_samples: float :param", "by applicable law or agreed to in writing, software #", "ValueError: If the number of segments is zero, or if", "dtype='float32'): \"\"\"Save audio segment to disk as wav file. :param", "segments are given to concatenate.\") sample_rate = segments[0]._sample_rate for seg", "change: speed_rate > 1.0, speed up the audio; speed_rate =", "a signal consisting of all zeros. :type max_gain_db: float :raises", "* i: bytes_per_header * (i + 1)])[0] for i in", "!= impulse_segment.sample_rate: raise ValueError(\"Impulse segment's sample rate (%d Hz) is", "of multiple audio files, with several header bytes in the", "of samples. :rtype: int \"\"\" return self._samples.shape[0] @property def duration(self):", "the sides %s\" % sides) self._samples = padded._samples def shift(self,", "consisting of all zeros. :type max_gain_db: float :raises ValueError: If", "= int(round(end_sec * self._sample_rate)) self._samples = self._samples[start_sample:end_sample] def random_subsegment(self, subsegment_length,", "dtype: Data type for export samples. Options: 'int16', 'int32', 'float32',", "audio segments together. :param *segments: Input audio segments to be", "start position (%f s) is later than \" \"the end", "same average power as the input signal. Note that this", "add segments.\") if len(self._samples) != len(other._samples): raise ValueError(\"Segment lengths must", "np.ndarray containing `dtype` audio content. :rtype: str \"\"\" samples =", ":raises TypeError: If dtype is not supported. \"\"\" samples =", "data type is not float or int. \"\"\" def __init__(self,", "= self._convert_samples_to_float32(samples) self._sample_rate = sample_rate if self._samples.ndim >= 2: self._samples", "Filepath or file object to audio file. infos (TarLocalData, optional):", "def shift(self, shift_ms): \"\"\"Shift the audio in time. If `shift_ms`", "audio segments when resample is not allowed. \"\"\" if allow_resample", "= ((cumsum_of_squares + prior_sum_of_squares) / (sample_count + prior_samples)) rms_estimate_db =", ":param allow_resample: Indicates whether resampling is allowed when the impulse_segment", "max_gain_db: Max amount of gain in dB that can be", "- subsegment_length) self.subsegment(start_time, start_time + subsegment_length) def convolve(self, impulse_segment, allow_resample=False):", "samples. :rtype: ndarray \"\"\" return self._samples.copy() @property def sample_rate(self): \"\"\"Return", "the origineal segemnt. \"\"\" rng = random.Random() if rng is", "sample type is usually integer or float-point. Integers will be", "+ 1)])[0] for i in range(num_utterances + 1) ] #", "% start) if end < 0.0: raise ValueError(\"The slice end", "prior_samples)) rms_estimate_db = 10 * np.log10(mean_squared_estimate) # Compute required time-varying", "ValueError(\"Can't concatenate segments with \" \"different sample rates\") if type(seg)", "not be greater \" \"than original segment.\") start_time = rng.uniform(0.0,", "header_bytes[bytes_per_header * i: bytes_per_header * (i + 1)])[0] for i", "audio filepath or file object. :type file: str|file :param start:", "for i in range(num_utterances + 1) ] # read audio", "having to load the entire file into the memory which", "bytes f.seek(header[fileno - 1]) audio_bytes = f.read(header[fileno] - header[fileno -", "ValueError: If the sample rate is not match between two", "= min(self.rms_db - noise.rms_db - snr_dB, max_gain_db) noise_new = copy.deepcopy(noise)", "float32. \"\"\" return convert_samples_to_float32(samples) def _convert_samples_from_float32(self, samples, dtype): \"\"\"Convert sample", "to normalize the segment to the target_db value exceeds max_gain_db.", "\"\"\"Return human-readable representation of segment.\"\"\" return (\"%s: num_samples=%d, sample_rate=%d, duration=%.2fsec,", "duration of noise segments is shorter than original audio segments.", "as sox except: try: from paddlespeech.s2t.utils import dynamic_pip_install package =", "end. If not provided, this function reads from the very", "subtype_map = { 'int16': 'PCM_16', 'int32': 'PCM_32', 'float32': 'FLOAT', 'float64':", "snr_dB, max_gain_db) noise_new = copy.deepcopy(noise) noise_new.random_subsegment(self.duration, rng=rng) noise_new.gain_db(noise_gain_db) self.superimpose(noise_new) @property", "audio segments are given to concatenate.\") sample_rate = segments[0]._sample_rate for", "allow_downsampling=False, max_gain_db=300.0, rng=None): \"\"\"Add the given noise segment at a", "should be smaller \" \"than audio duration.\") shift_samples = int(shift_ms", "of %s is not supported\" % filepath) filename = matches.group(1)", "cls.from_bytes(audio_bytes) except Exception as e: samples = np.frombuffer(audio_bytes, dtype='int16') return", "0 elif shift_samples < 0: # time delay self._samples[-shift_samples:] =", "if len(segments) == 0: raise ValueError(\"No audio segments are given", "samples to be added in. :type other: AudioSegments :raise TypeError:", "return self._samples.copy() @property def sample_rate(self): \"\"\"Return audio sample rate. :return:", "in-place transformation. :param duration: Length of silence in seconds to", "4 bytes (int, version), 4 bytes (int, num of utterance),", "padded = cls.concatenate(silence, self, silence) else: raise ValueError(\"Unknown value for", "= int(round(start_sec * self._sample_rate)) end_sample = int(round(end_sec * self._sample_rate)) self._samples", "the given duration. :rtype: AudioSegment \"\"\" samples = np.zeros(int(duration *", "from sequence file. Sequence file is a binary file containing", "padded = cls.concatenate(self, silence) elif sides == \"both\": padded =", "applicable law or agreed to in writing, software # distributed", "is out of bounds.\" % end) if start > end:", "soxbindings as sox except: try: from paddlespeech.s2t.utils import dynamic_pip_install package", "Target RMS value in decibels. :type target_bd: float :param prior_db:", "PaddlePaddle Authors. All Rights Reserved. # # Licensed under the", "this is an in-place transformation. :param target_db: Target RMS value", "Audio sample rate. :rtype: int \"\"\" return self._sample_rate @property def", "sample_rate = sndfile.samplerate duration = float(len(sndfile)) / sample_rate start =", "that can be applied for normalization. This is to prevent", "if allow_downsampling and noise.sample_rate > self.sample_rate: noise = noise.resample(self.sample_rate) if", "of the audio in decibels. :return: Root mean square energy", "np.interp(new_indices, old_indices, self._samples) # sox, slow try: import soxbindings as", "gain have exceeds max_gain_db (%f dB)\" % (target_db, max_gain_db)) self.gain_db(min(max_gain_db,", "attempting to apply infinite gain to a zero signal. :type", "with several header bytes in the head indicating the offsets", "\" \"bounds.\" % start_sec) if end_sec < 0.0: raise ValueError(\"The", "(i + 1)])[0] for i in range(num_utterances + 1) ]", "dtype) return samples def gain_db(self, gain): \"\"\"Apply gain in decibels", "\"\"\"Contains the audio segment class.\"\"\" import copy import io import", "segment from sequence file. Sequence file is a binary file", "given to concatenate.\") sample_rate = segments[0]._sample_rate for seg in segments:", "is not AudioSegment instance. \"\"\" # Perform basic sanity-checks. if", "integer type, float32 will be rescaled from [-1, 1] to", "self._samples.shape[0] # new_length = int(old_length / speed_rate) # old_indices =", "number of audio segments together. :param *segments: Input audio segments", "load the entire file into the memory which can be", "a byte string containing audio samples. :param bytes: Byte string", "self.sample_rate, target_sample_rate, filter=filter) self._sample_rate = target_sample_rate def pad_silence(self, duration, sides='both'):", "self.rms_db if gain > max_gain_db: raise ValueError( \"Unable to normalize", "sample rate (%d Hz).\" % (impulse_segment.sample_rate, self.sample_rate)) samples = signal.fftconvolve(self.samples,", "AudioSegment(): \"\"\"Monaural audio segment abstraction. :param samples: Audio samples [num_samples", "so that it has the same average power as the", "with the given impulse segment. Note that this is an", "* np.log10(mean_squared_estimate) # Compute required time-varying gain. gain_db = target_db", "1.0, speed up the audio; speed_rate = 1.0, unchanged; speed_rate", "two segments are not equal, or if the lengths of", "silence in seconds. :type duration: float :param sample_rate: Sample rate.", "number of samples. :type prior_samples: float :param startup_delay: Default 0.0s.", "% sides) self._samples = padded._samples def shift(self, shift_ms): \"\"\"Shift the", "\"\"\"Return whether two objects are unequal.\"\"\" return not self.__eq__(other) def", "match between two audio segments when resample is not allowed.", "position (%f s) is out of bounds.\" % end_sec) if", "If the sample rates of the two segments are not", "Audio sample type is usually integer or float-point. For integer", "# You may obtain a copy of the License at", "is out of \" \"bounds.\" % start_sec) if end_sec <", "int \"\"\" return self._samples.shape[0] @property def duration(self): \"\"\"Return audio duration.", "transformation. :param target_sample_rate: Target sample rate. :type target_sample_rate: int :param", "(%f s) is out of \" \"bounds.\" % start) if", "for the first startup_delay seconds before applying online normalization. :type", "shift(self, shift_ms): \"\"\"Shift the audio in time. If `shift_ms` is", "the number of segments is zero, or if the sample_rate", "\"full\") self._samples = samples def convolve_and_normalize(self, impulse_segment, allow_resample=False): \"\"\"Convolve and", "be rescaled from [-1, 1] to the maximum range supported", "audio content. :rtype: str \"\"\" samples = self._convert_samples_from_float32(self._samples, dtype) return", "create audio segment try: return cls.from_bytes(audio_bytes) except Exception as e:", "self.duration: raise ValueError(\"Length of subsegment must not be greater \"", "int(round(end_sec * self._sample_rate)) self._samples = self._samples[start_sample:end_sample] def random_subsegment(self, subsegment_length, rng=None):", "The resampling filter to use one of {'kaiser_best', 'kaiser_fast'}. :type", "This is to prevent attempting to apply infinite gain to", "between the two audio segments when downsampling is not allowed,", "greater \" \"than original segment.\") start_time = rng.uniform(0.0, self.duration -", "noise signal before adding it in. This is to prevent", "start_sec = 0.0 if start_sec is None else start_sec end_sec", "if len(self._samples) != len(other._samples): raise ValueError(\"Segment lengths must match to", "segments: if sample_rate != seg._sample_rate: raise ValueError(\"Can't concatenate segments with", "'float32', 'float64'. Default is 'float32'. :type dtype: str :return: Byte", "rate is not match between two audio segments when resample", "AudioSegment :raises ValueError: If the number of segments is zero,", "= [ struct.unpack(\"i\", header_bytes[bytes_per_header * i: bytes_per_header * (i +", "1, int(self.sample_rate * startup_delay)) prior_mean_squared = 10.**(prior_db / 10.) prior_sum_of_squares", "= soundfile.read(file, dtype='float32') return cls(samples, sample_rate) @classmethod def slice_from_file(cls, file,", "Note that this is an in-place transformation. :param subsegment_length: Subsegment", "match. \"\"\" if isinstance(other, type(self)): raise TypeError(\"Cannot add segments of", "an in-place transformation. :param target_db: Target RMS value in decibels.", "chunk. The format is: 4 bytes (int, version), 4 bytes", "end position (%f s).\" % (start_sec, end_sec)) if end_sec >", "self.duration)) noise_gain_db = min(self.rms_db - noise.rms_db - snr_dB, max_gain_db) noise_new", "not allowed, raise ValueError. :type speed_rate: float :raises ValueError: If", "1)) header = [ struct.unpack(\"i\", header_bytes[bytes_per_header * i: bytes_per_header *", "signal (%f sec) must be at least as long as\"", "encoding='utf8') version = f.read(4) num_utterances = struct.unpack(\"i\", f.read(4))[0] bytes_per_header =", "end_sec = self.duration if end_sec is None else end_sec if", "\"(> %f s)\" % (end_sec, self.duration)) start_sample = int(round(start_sec *", "# time delay self._samples[-shift_samples:] = self._samples[:shift_samples] self._samples[:-shift_samples] = 0 def", "results. :rtype: AudioSegment :raises ValueError: If the number of segments", "(type(self), self.num_samples, self.sample_rate, self.duration, self.rms_db)) @classmethod def from_file(cls, file, infos=None):", "of audio segments together. :param *segments: Input audio segments to", "sample_rate) @classmethod def from_sequence_file(cls, filepath): \"\"\"Create audio segment from sequence", "float :raises ValueError: If the required gain to normalize the", "None else rng if subsegment_length > self.duration: raise ValueError(\"Length of", "float :raises ValueError: If speed_rate <= 0.0. \"\"\" if speed_rate", "ValueError(\"The slice start position (%f s) is out of \"", "samples(self): \"\"\"Return audio samples. :return: Audio samples. :rtype: ndarray \"\"\"", "is greater than the origineal segemnt. \"\"\" rng = random.Random()", "apply infinite gain to a zero signal. :type max_gain_db: float", "max_gain_db=300.0, rng=None): \"\"\"Add the given noise segment at a specific", "float :raise ValueError: If start_sec or end_sec is incorrectly set,", "position (%f s) is out of \" \"bounds.\" % start_sec)", "0. if start is None else start end = duration", "This value should be less than 0.0 as 0.0 is", "the beginning; 'end' - adds silence in the end; 'both'", "4 bytes (int, bytes per header), [bytes_per_header*(num_utterance+1)] bytes (offsets for", "duration = float(len(sndfile)) / sample_rate start = 0. if start", "in decibels. :type prior_db: float :param prior_samples: Prior strength in", ":type rng: None|random.Random :raises ValueError: If the sample rate does", "segment from a byte string containing audio samples. :param bytes:", "it in. This is to prevent attempting to apply infinite", "\" \"(> %f s)\" % (end_sec, self.duration)) start_sample = int(round(start_sec", "float :param prior_db: Prior RMS estimate in decibels. :type prior_db:", "given boundaries. Note that this is an in-place transformation. :param", "this segment (sample-wise addition, not segment concatenation). Note that this", "float32. Audio sample type is usually integer or float-point. Integers", "using a production-compatible online/causal algorithm. This uses an exponential likelihood", "ValueError: If sides is not supported. \"\"\" if duration ==", "than the origineal segemnt. \"\"\" rng = random.Random() if rng", "index within this sequence file (starting from 1). :param filepath:", "in. :type other: AudioSegments :raise TypeError: If type of two", "segments are not equal, or if the lengths of segments", "`dtype` audio content. :param dtype: Data type for export samples.", "is: 4 bytes (int, version), 4 bytes (int, num of", "end=None): \"\"\"Loads a small section of an audio without having", "the length of subsegment is greater than the origineal segemnt.", "\"License\"); # you may not use this file except in", "of bounds in time. \"\"\" sndfile = soundfile.SoundFile(file) sample_rate =", "if end_sec is None else end_sec if start_sec < 0.0:", "shift with time advance; if negative, shift with time delay.", "= cls.concatenate(self, silence) elif sides == \"both\": padded = cls.concatenate(silence,", "rate from this signal. :type allow_resample: bool \"\"\" target_db =", "is out of bounds \" \"(> %f s)\" % (end,", ":type max_gain_db: float :param rng: Random number generator state. :type", "x num_channels]. :type samples: ndarray.float32 :param sample_rate: Audio sample rate.", "\"\"\"Convert sample type from float32 to dtype. Audio sample type", "this audio sample with a period of silence. Note that", "return cls.from_sequence_file(file) elif isinstance(file, str) and file.startswith('tar:'): return cls.from_file(subfile_from_tar(file, infos))", "% (type(self), type(other))) if self._sample_rate != other._sample_rate: raise ValueError(\"Sample rates", "behvaior is to read to the end of the file.", "in both the beginning and the end. :type sides: str", ":param filepath: WAV filepath or file object to save the", "f.read(bytes_per_header * (num_utterances + 1)) header = [ struct.unpack(\"i\", header_bytes[bytes_per_header", "concatenate.\") sample_rate = segments[0]._sample_rate for seg in segments: if sample_rate", "samples. Note that this is an in-place transformation. :param target_db:", "import convert_samples_from_float32 from .utility import convert_samples_to_float32 from .utility import subfile_from_tar", "TypeError: If any segment is not AudioSegment instance. \"\"\" #", ":rtype: ndarray \"\"\" return self._samples.copy() @property def sample_rate(self): \"\"\"Return audio", "header[fileno - 1]) f.close() # create audio segment try: return", "float :param end_sec: End of subsegment in seconds. :type end_sec:", "str :return: Byte string containing audio content. :rtype: str \"\"\"", "else rng if allow_downsampling and noise.sample_rate > self.sample_rate: noise =", "allow_resample: Indicates whether resampling is allowed when the impulse_segment has", "segment instance as concatenating results. :rtype: AudioSegment :raises ValueError: If", "= f.read(header[fileno] - header[fileno - 1]) f.close() # create audio", "f.close() # create audio segment try: return cls.from_bytes(audio_bytes) except Exception", "sample_rate_in=self._sample_rate).squeeze(-1).astype( np.float32).copy() def normalize(self, target_db=-20, max_gain_db=300.0): \"\"\"Normalize audio to be", "End of subsegment in seconds. :type end_sec: float :raise ValueError:", "for padding: 'beginning' - adds silence in the beginning; 'end'", "audio; speed_rate <= 0.0, not allowed, raise ValueError. :type speed_rate:", "sox, slow try: import soxbindings as sox except: try: from" ]
[ "= tb.tb_lineno lines = [] try: with open(filename, 'rb') as", "= template.Loader(os.path.dirname(os.path.abspath(__file__))) t = loader.load('debug.html') return t.generate( traceback=traceback, pprint=pprint, handler=self.handler,", "None) implicit = getattr(exc_value, '__context__', None) return explicit or (None", "there's just one exception, take the traceback from self.tb exc_value", "while True: frames.extend(self.get_exception_traceback_frames(exc_value, tb)) try: exc_value = exceptions.pop() except IndexError:", "def get_traceback_frames(self): frames = [] tb = self.exc_tb while tb:", "e: return 'Error in formatting: %s: %s' % (e.__class__.__name__, e)", "value in self.handler.application.settings.items(): if SENSITIVE_SETTINGS_RE.search(arg): value = '*' * 15", "self.tb if not exceptions else exc_value.__traceback__ while True: frames.extend(self.get_exception_traceback_frames(exc_value, tb))", "self.tb exc_value = exceptions.pop() tb = self.tb if not exceptions", "break tb = exc_value.__traceback__ return frames def _get_explicit_or_implicit_cause(self, exc_value): explicit", "settings = {} for arg, value in self.handler.application.settings.items(): if SENSITIVE_SETTINGS_RE.search(arg):", "exception '%s' \" \"encountered again.\" % exc_value, ExceptionCycleWarning, ) #", "= getattr(exc_value, '__suppress_context__', None) implicit = getattr(exc_value, '__context__', None) return", "5, 0), min(lineno + 5, len(_lines)) ): lines.append((_lineno + 1,", "__init__(self, exc_info, handler): self.exc_type = exc_info[0] self.exc_value = exc_info[1] self.exc_tb", "= f.read().splitlines() for _lineno in range( max(lineno - 5, 0),", "detected: exception '%s' \" \"encountered again.\" % exc_value, ExceptionCycleWarning, )", "'%s' \" \"encountered again.\" % exc_value, ExceptionCycleWarning, ) # Avoid", "Avoid infinite loop if there's a cyclic reference (#29393). break", "explicit or (None if suppress_context else implicit) def pprint(value): try:", "f: _lines = f.read().splitlines() for _lineno in range( max(lineno -", "were supplied to ExceptionReporter if not exceptions: return frames #", "exc_value: exceptions.append(exc_value) exc_value = self._get_explicit_or_implicit_cause(exc_value) if exc_value in exceptions: warnings.warn(", "= getattr(exc_value, '__context__', None) return explicit or (None if suppress_context", "return frames # In case there's just one exception, take", "value = '*' * 15 settings[arg] = value return settings", "in the exception chain detected: exception '%s' \" \"encountered again.\"", "else implicit) def pprint(value): try: return pformat(value, width=1) except Exception", "'__cause__', None) suppress_context = getattr(exc_value, '__suppress_context__', None) implicit = getattr(exc_value,", "lines.append((_lineno + 1, _lines[_lineno])) except Exception as e: # could", "frames = [] tb = self.exc_tb while tb: frames.append({ 'lineno':", "exceptions.pop() except IndexError: break tb = exc_value.__traceback__ return frames def", "except Exception as e: return 'Error in formatting: %s: %s'", "take the traceback from self.tb exc_value = exceptions.pop() tb =", "file pass return lines def get_traceback_frames(self): frames = [] tb", "get_traceback_frames(self): frames = [] tb = self.exc_tb while tb: frames.append({", "): lines.append((_lineno + 1, _lines[_lineno])) except Exception as e: #", "tornado_version=tornado.version, sys_version='%d.%d.%d' % sys.version_info[0:3], sys_executable=sys.executable, sys_path=sys.path, ) def get_app_settings(self): settings", "{} for arg, value in self.handler.application.settings.items(): if SENSITIVE_SETTINGS_RE.search(arg): value =", "exceptions: return frames # In case there's just one exception,", "sys_path=sys.path, ) def get_app_settings(self): settings = {} for arg, value", "def _get_explicit_or_implicit_cause(self, exc_value): explicit = getattr(exc_value, '__cause__', None) suppress_context =", "again.\" % exc_value, ExceptionCycleWarning, ) # Avoid infinite loop if", "one exception, take the traceback from self.tb exc_value = exceptions.pop()", "self.get_source_lines(tb), }) tb = tb.tb_next frames.reverse() return frames exceptions =", "= [] # No exceptions were supplied to ExceptionReporter if", "handler): self.exc_type = exc_info[0] self.exc_value = exc_info[1] self.exc_tb = exc_info[2]", "= tb.tb_frame.f_code.co_filename lineno = tb.tb_lineno lines = [] try: with", "traceback from self.tb exc_value = exceptions.pop() tb = self.tb if", "exc_value = exceptions.pop() tb = self.tb if not exceptions else", "sys import traceback from pprint import pformat import tornado from", "min(lineno + 5, len(_lines)) ): lines.append((_lineno + 1, _lines[_lineno])) except", "the exception chain detected: exception '%s' \" \"encountered again.\" %", "= getattr(exc_value, '__cause__', None) suppress_context = getattr(exc_value, '__suppress_context__', None) implicit", "import os.path import re import sys import traceback from pprint", "just one exception, take the traceback from self.tb exc_value =", "No exceptions were supplied to ExceptionReporter if not exceptions: return", "\"encountered again.\" % exc_value, ExceptionCycleWarning, ) # Avoid infinite loop", "or (None if suppress_context else implicit) def pprint(value): try: return", "exc_value in exceptions: warnings.warn( \"Cycle in the exception chain detected:", "t = loader.load('debug.html') return t.generate( traceback=traceback, pprint=pprint, handler=self.handler, app_settings=self.get_app_settings(), exc_type=self.exc_type,", "frames=self.get_traceback_frames(), tornado_version=tornado.version, sys_version='%d.%d.%d' % sys.version_info[0:3], sys_executable=sys.executable, sys_path=sys.path, ) def get_app_settings(self):", "there's a cyclic reference (#29393). break frames = [] #", "return lines def get_traceback_frames(self): frames = [] tb = self.exc_tb", "getattr(exc_value, '__context__', None) return explicit or (None if suppress_context else", "% sys.version_info[0:3], sys_executable=sys.executable, sys_path=sys.path, ) def get_app_settings(self): settings = {}", "loader = template.Loader(os.path.dirname(os.path.abspath(__file__))) t = loader.load('debug.html') return t.generate( traceback=traceback, pprint=pprint,", "= '*' * 15 settings[arg] = value return settings def", "'__suppress_context__', None) implicit = getattr(exc_value, '__context__', None) return explicit or", "'', 'vars': tb.tb_frame.f_locals, 'lines': self.get_source_lines(tb), }) tb = tb.tb_next frames.reverse()", "tb = self.tb if not exceptions else exc_value.__traceback__ while True:", "= value return settings def get_source_lines(self, tb): filename = tb.tb_frame.f_code.co_filename", "exc_value = exceptions.pop() except IndexError: break tb = exc_value.__traceback__ return", "'api|key|pass|salt|secret|signature|token', flags=re.IGNORECASE ) class ExceptionReporter: def __init__(self, exc_info, handler): self.exc_type", "not exceptions else exc_value.__traceback__ while True: frames.extend(self.get_exception_traceback_frames(exc_value, tb)) try: exc_value", "0), min(lineno + 5, len(_lines)) ): lines.append((_lineno + 1, _lines[_lineno]))", ") # Avoid infinite loop if there's a cyclic reference", "return t.generate( traceback=traceback, pprint=pprint, handler=self.handler, app_settings=self.get_app_settings(), exc_type=self.exc_type, exc_value=self.exc_value, exc_tb=self.exc_tb, frames=self.get_traceback_frames(),", "self.handler = handler def get_response(self): loader = template.Loader(os.path.dirname(os.path.abspath(__file__))) t =", "with open(filename, 'rb') as f: _lines = f.read().splitlines() for _lineno", "value return settings def get_source_lines(self, tb): filename = tb.tb_frame.f_code.co_filename lineno", "exc_value = self.exc_value while exc_value: exceptions.append(exc_value) exc_value = self._get_explicit_or_implicit_cause(exc_value) if", "# Avoid infinite loop if there's a cyclic reference (#29393).", "import sys import traceback from pprint import pformat import tornado", "_get_explicit_or_implicit_cause(self, exc_value): explicit = getattr(exc_value, '__cause__', None) suppress_context = getattr(exc_value,", "pformat import tornado from tornado import template SENSITIVE_SETTINGS_RE = re.compile(", "reference (#29393). break frames = [] # No exceptions were", "import pformat import tornado from tornado import template SENSITIVE_SETTINGS_RE =", "SENSITIVE_SETTINGS_RE.search(arg): value = '*' * 15 settings[arg] = value return", "'rb') as f: _lines = f.read().splitlines() for _lineno in range(", "break frames = [] # No exceptions were supplied to", "def get_response(self): loader = template.Loader(os.path.dirname(os.path.abspath(__file__))) t = loader.load('debug.html') return t.generate(", ") class ExceptionReporter: def __init__(self, exc_info, handler): self.exc_type = exc_info[0]", "SENSITIVE_SETTINGS_RE = re.compile( 'api|key|pass|salt|secret|signature|token', flags=re.IGNORECASE ) class ExceptionReporter: def __init__(self,", "- 5, 0), min(lineno + 5, len(_lines)) ): lines.append((_lineno +", "not exceptions: return frames # In case there's just one", "(None if suppress_context else implicit) def pprint(value): try: return pformat(value,", "t.generate( traceback=traceback, pprint=pprint, handler=self.handler, app_settings=self.get_app_settings(), exc_type=self.exc_type, exc_value=self.exc_value, exc_tb=self.exc_tb, frames=self.get_traceback_frames(), tornado_version=tornado.version,", "= self.tb if not exceptions else exc_value.__traceback__ while True: frames.extend(self.get_exception_traceback_frames(exc_value,", "= exc_value.__traceback__ return frames def _get_explicit_or_implicit_cause(self, exc_value): explicit = getattr(exc_value,", "return pformat(value, width=1) except Exception as e: return 'Error in", "tornado import template SENSITIVE_SETTINGS_RE = re.compile( 'api|key|pass|salt|secret|signature|token', flags=re.IGNORECASE ) class", "def get_source_lines(self, tb): filename = tb.tb_frame.f_code.co_filename lineno = tb.tb_lineno lines", "traceback from pprint import pformat import tornado from tornado import", "from tornado import template SENSITIVE_SETTINGS_RE = re.compile( 'api|key|pass|salt|secret|signature|token', flags=re.IGNORECASE )", "= exc_info[1] self.exc_tb = exc_info[2] self.handler = handler def get_response(self):", "tb.tb_next frames.reverse() return frames exceptions = [] exc_value = self.exc_value", "exceptions = [] exc_value = self.exc_value while exc_value: exceptions.append(exc_value) exc_value", "exc_info[1] self.exc_tb = exc_info[2] self.handler = handler def get_response(self): loader", "tb = tb.tb_next frames.reverse() return frames exceptions = [] exc_value", "cyclic reference (#29393). break frames = [] # No exceptions", "self._get_explicit_or_implicit_cause(exc_value) if exc_value in exceptions: warnings.warn( \"Cycle in the exception", "tb.tb_frame.f_locals, 'lines': self.get_source_lines(tb), }) tb = tb.tb_next frames.reverse() return frames", "self.exc_value while exc_value: exceptions.append(exc_value) exc_value = self._get_explicit_or_implicit_cause(exc_value) if exc_value in", "try: with open(filename, 'rb') as f: _lines = f.read().splitlines() for", "frames = [] # No exceptions were supplied to ExceptionReporter", "suppress_context else implicit) def pprint(value): try: return pformat(value, width=1) except", "re.compile( 'api|key|pass|salt|secret|signature|token', flags=re.IGNORECASE ) class ExceptionReporter: def __init__(self, exc_info, handler):", "re import sys import traceback from pprint import pformat import", "exc_info[2] self.handler = handler def get_response(self): loader = template.Loader(os.path.dirname(os.path.abspath(__file__))) t", "= exceptions.pop() except IndexError: break tb = exc_value.__traceback__ return frames", "could not open file pass return lines def get_traceback_frames(self): frames", "= {} for arg, value in self.handler.application.settings.items(): if SENSITIVE_SETTINGS_RE.search(arg): value", "exc_value.__traceback__ return frames def _get_explicit_or_implicit_cause(self, exc_value): explicit = getattr(exc_value, '__cause__',", "}) tb = tb.tb_next frames.reverse() return frames exceptions = []", "try: exc_value = exceptions.pop() except IndexError: break tb = exc_value.__traceback__", "in self.handler.application.settings.items(): if SENSITIVE_SETTINGS_RE.search(arg): value = '*' * 15 settings[arg]", "exc_info, handler): self.exc_type = exc_info[0] self.exc_value = exc_info[1] self.exc_tb =", "'filename': tb.tb_frame.f_code.co_filename, 'function': tb.tb_frame.f_code.co_name, 'module_name': tb.tb_frame.f_globals.get('__name__') or '', 'vars': tb.tb_frame.f_locals,", "True: frames.extend(self.get_exception_traceback_frames(exc_value, tb)) try: exc_value = exceptions.pop() except IndexError: break", "get_source_lines(self, tb): filename = tb.tb_frame.f_code.co_filename lineno = tb.tb_lineno lines =", "'vars': tb.tb_frame.f_locals, 'lines': self.get_source_lines(tb), }) tb = tb.tb_next frames.reverse() return", "handler def get_response(self): loader = template.Loader(os.path.dirname(os.path.abspath(__file__))) t = loader.load('debug.html') return", "sys.version_info[0:3], sys_executable=sys.executable, sys_path=sys.path, ) def get_app_settings(self): settings = {} for", "tb.tb_frame.f_code.co_filename lineno = tb.tb_lineno lines = [] try: with open(filename,", "15 settings[arg] = value return settings def get_source_lines(self, tb): filename", "for _lineno in range( max(lineno - 5, 0), min(lineno +", "a cyclic reference (#29393). break frames = [] # No", "+ 1, _lines[_lineno])) except Exception as e: # could not", "implicit = getattr(exc_value, '__context__', None) return explicit or (None if", "implicit) def pprint(value): try: return pformat(value, width=1) except Exception as", "sys_version='%d.%d.%d' % sys.version_info[0:3], sys_executable=sys.executable, sys_path=sys.path, ) def get_app_settings(self): settings =", "# could not open file pass return lines def get_traceback_frames(self):", "frames.reverse() return frames exceptions = [] exc_value = self.exc_value while", "from self.tb exc_value = exceptions.pop() tb = self.tb if not", "arg, value in self.handler.application.settings.items(): if SENSITIVE_SETTINGS_RE.search(arg): value = '*' *", "open file pass return lines def get_traceback_frames(self): frames = []", "def pprint(value): try: return pformat(value, width=1) except Exception as e:", "ExceptionReporter: def __init__(self, exc_info, handler): self.exc_type = exc_info[0] self.exc_value =", "exc_value=self.exc_value, exc_tb=self.exc_tb, frames=self.get_traceback_frames(), tornado_version=tornado.version, sys_version='%d.%d.%d' % sys.version_info[0:3], sys_executable=sys.executable, sys_path=sys.path, )", "tb.tb_frame.f_code.co_filename, 'function': tb.tb_frame.f_code.co_name, 'module_name': tb.tb_frame.f_globals.get('__name__') or '', 'vars': tb.tb_frame.f_locals, 'lines':", "pprint import pformat import tornado from tornado import template SENSITIVE_SETTINGS_RE", "e: # could not open file pass return lines def", "self.handler.application.settings.items(): if SENSITIVE_SETTINGS_RE.search(arg): value = '*' * 15 settings[arg] =", "open(filename, 'rb') as f: _lines = f.read().splitlines() for _lineno in", "loader.load('debug.html') return t.generate( traceback=traceback, pprint=pprint, handler=self.handler, app_settings=self.get_app_settings(), exc_type=self.exc_type, exc_value=self.exc_value, exc_tb=self.exc_tb,", "_lineno in range( max(lineno - 5, 0), min(lineno + 5,", "import template SENSITIVE_SETTINGS_RE = re.compile( 'api|key|pass|salt|secret|signature|token', flags=re.IGNORECASE ) class ExceptionReporter:", "def get_app_settings(self): settings = {} for arg, value in self.handler.application.settings.items():", "tb = exc_value.__traceback__ return frames def _get_explicit_or_implicit_cause(self, exc_value): explicit =", "explicit = getattr(exc_value, '__cause__', None) suppress_context = getattr(exc_value, '__suppress_context__', None)", "if suppress_context else implicit) def pprint(value): try: return pformat(value, width=1)", "pprint=pprint, handler=self.handler, app_settings=self.get_app_settings(), exc_type=self.exc_type, exc_value=self.exc_value, exc_tb=self.exc_tb, frames=self.get_traceback_frames(), tornado_version=tornado.version, sys_version='%d.%d.%d' %", "# No exceptions were supplied to ExceptionReporter if not exceptions:", "exc_value = self._get_explicit_or_implicit_cause(exc_value) if exc_value in exceptions: warnings.warn( \"Cycle in", "from pprint import pformat import tornado from tornado import template", "warnings.warn( \"Cycle in the exception chain detected: exception '%s' \"", "exception chain detected: exception '%s' \" \"encountered again.\" % exc_value,", "len(_lines)) ): lines.append((_lineno + 1, _lines[_lineno])) except Exception as e:", "get_app_settings(self): settings = {} for arg, value in self.handler.application.settings.items(): if", "5, len(_lines)) ): lines.append((_lineno + 1, _lines[_lineno])) except Exception as", "'*' * 15 settings[arg] = value return settings def get_source_lines(self,", "f.read().splitlines() for _lineno in range( max(lineno - 5, 0), min(lineno", "1, _lines[_lineno])) except Exception as e: # could not open", "[] exc_value = self.exc_value while exc_value: exceptions.append(exc_value) exc_value = self._get_explicit_or_implicit_cause(exc_value)", "else exc_value.__traceback__ while True: frames.extend(self.get_exception_traceback_frames(exc_value, tb)) try: exc_value = exceptions.pop()", ") def get_app_settings(self): settings = {} for arg, value in", "= [] exc_value = self.exc_value while exc_value: exceptions.append(exc_value) exc_value =", "as e: return 'Error in formatting: %s: %s' % (e.__class__.__name__,", "infinite loop if there's a cyclic reference (#29393). break frames", "as f: _lines = f.read().splitlines() for _lineno in range( max(lineno", "exceptions else exc_value.__traceback__ while True: frames.extend(self.get_exception_traceback_frames(exc_value, tb)) try: exc_value =", "chain detected: exception '%s' \" \"encountered again.\" % exc_value, ExceptionCycleWarning,", "\"Cycle in the exception chain detected: exception '%s' \" \"encountered", "= exceptions.pop() tb = self.tb if not exceptions else exc_value.__traceback__", "if exc_value in exceptions: warnings.warn( \"Cycle in the exception chain", "tornado from tornado import template SENSITIVE_SETTINGS_RE = re.compile( 'api|key|pass|salt|secret|signature|token', flags=re.IGNORECASE", "self.exc_value = exc_info[1] self.exc_tb = exc_info[2] self.handler = handler def", "exc_tb=self.exc_tb, frames=self.get_traceback_frames(), tornado_version=tornado.version, sys_version='%d.%d.%d' % sys.version_info[0:3], sys_executable=sys.executable, sys_path=sys.path, ) def", "case there's just one exception, take the traceback from self.tb", "def __init__(self, exc_info, handler): self.exc_type = exc_info[0] self.exc_value = exc_info[1]", "except IndexError: break tb = exc_value.__traceback__ return frames def _get_explicit_or_implicit_cause(self,", "max(lineno - 5, 0), min(lineno + 5, len(_lines)) ): lines.append((_lineno", "return settings def get_source_lines(self, tb): filename = tb.tb_frame.f_code.co_filename lineno =", "ExceptionCycleWarning, ) # Avoid infinite loop if there's a cyclic", "exception, take the traceback from self.tb exc_value = exceptions.pop() tb", "= handler def get_response(self): loader = template.Loader(os.path.dirname(os.path.abspath(__file__))) t = loader.load('debug.html')", "= exc_info[0] self.exc_value = exc_info[1] self.exc_tb = exc_info[2] self.handler =", "app_settings=self.get_app_settings(), exc_type=self.exc_type, exc_value=self.exc_value, exc_tb=self.exc_tb, frames=self.get_traceback_frames(), tornado_version=tornado.version, sys_version='%d.%d.%d' % sys.version_info[0:3], sys_executable=sys.executable,", "self.exc_tb = exc_info[2] self.handler = handler def get_response(self): loader =", "frames.extend(self.get_exception_traceback_frames(exc_value, tb)) try: exc_value = exceptions.pop() except IndexError: break tb", "getattr(exc_value, '__suppress_context__', None) implicit = getattr(exc_value, '__context__', None) return explicit", "return frames def _get_explicit_or_implicit_cause(self, exc_value): explicit = getattr(exc_value, '__cause__', None)", "= self._get_explicit_or_implicit_cause(exc_value) if exc_value in exceptions: warnings.warn( \"Cycle in the", "except Exception as e: # could not open file pass", "import traceback from pprint import pformat import tornado from tornado", "if there's a cyclic reference (#29393). break frames = []", "IndexError: break tb = exc_value.__traceback__ return frames def _get_explicit_or_implicit_cause(self, exc_value):", "[] try: with open(filename, 'rb') as f: _lines = f.read().splitlines()", "if not exceptions: return frames # In case there's just", "not open file pass return lines def get_traceback_frames(self): frames =", "'lines': self.get_source_lines(tb), }) tb = tb.tb_next frames.reverse() return frames exceptions", "'__context__', None) return explicit or (None if suppress_context else implicit)", "sys_executable=sys.executable, sys_path=sys.path, ) def get_app_settings(self): settings = {} for arg,", "or '', 'vars': tb.tb_frame.f_locals, 'lines': self.get_source_lines(tb), }) tb = tb.tb_next", "exceptions were supplied to ExceptionReporter if not exceptions: return frames", "the traceback from self.tb exc_value = exceptions.pop() tb = self.tb", "'module_name': tb.tb_frame.f_globals.get('__name__') or '', 'vars': tb.tb_frame.f_locals, 'lines': self.get_source_lines(tb), }) tb", "tb.tb_frame.f_globals.get('__name__') or '', 'vars': tb.tb_frame.f_locals, 'lines': self.get_source_lines(tb), }) tb =", "as e: # could not open file pass return lines", "template.Loader(os.path.dirname(os.path.abspath(__file__))) t = loader.load('debug.html') return t.generate( traceback=traceback, pprint=pprint, handler=self.handler, app_settings=self.get_app_settings(),", "'lineno': tb.tb_lineno, 'filename': tb.tb_frame.f_code.co_filename, 'function': tb.tb_frame.f_code.co_name, 'module_name': tb.tb_frame.f_globals.get('__name__') or '',", "# In case there's just one exception, take the traceback", "% exc_value, ExceptionCycleWarning, ) # Avoid infinite loop if there's", "lineno = tb.tb_lineno lines = [] try: with open(filename, 'rb')", "return explicit or (None if suppress_context else implicit) def pprint(value):", "* 15 settings[arg] = value return settings def get_source_lines(self, tb):", "[] tb = self.exc_tb while tb: frames.append({ 'lineno': tb.tb_lineno, 'filename':", "= loader.load('debug.html') return t.generate( traceback=traceback, pprint=pprint, handler=self.handler, app_settings=self.get_app_settings(), exc_type=self.exc_type, exc_value=self.exc_value,", "tb = self.exc_tb while tb: frames.append({ 'lineno': tb.tb_lineno, 'filename': tb.tb_frame.f_code.co_filename,", "= [] tb = self.exc_tb while tb: frames.append({ 'lineno': tb.tb_lineno,", "template SENSITIVE_SETTINGS_RE = re.compile( 'api|key|pass|salt|secret|signature|token', flags=re.IGNORECASE ) class ExceptionReporter: def", "pass return lines def get_traceback_frames(self): frames = [] tb =", "loop if there's a cyclic reference (#29393). break frames =", "self.exc_tb while tb: frames.append({ 'lineno': tb.tb_lineno, 'filename': tb.tb_frame.f_code.co_filename, 'function': tb.tb_frame.f_code.co_name,", "[] # No exceptions were supplied to ExceptionReporter if not", "width=1) except Exception as e: return 'Error in formatting: %s:", "'function': tb.tb_frame.f_code.co_name, 'module_name': tb.tb_frame.f_globals.get('__name__') or '', 'vars': tb.tb_frame.f_locals, 'lines': self.get_source_lines(tb),", "return frames exceptions = [] exc_value = self.exc_value while exc_value:", "handler=self.handler, app_settings=self.get_app_settings(), exc_type=self.exc_type, exc_value=self.exc_value, exc_tb=self.exc_tb, frames=self.get_traceback_frames(), tornado_version=tornado.version, sys_version='%d.%d.%d' % sys.version_info[0:3],", "+ 5, len(_lines)) ): lines.append((_lineno + 1, _lines[_lineno])) except Exception", "tb.tb_frame.f_code.co_name, 'module_name': tb.tb_frame.f_globals.get('__name__') or '', 'vars': tb.tb_frame.f_locals, 'lines': self.get_source_lines(tb), })", "= [] try: with open(filename, 'rb') as f: _lines =", "while exc_value: exceptions.append(exc_value) exc_value = self._get_explicit_or_implicit_cause(exc_value) if exc_value in exceptions:", "None) return explicit or (None if suppress_context else implicit) def", "pprint(value): try: return pformat(value, width=1) except Exception as e: return", "tb): filename = tb.tb_frame.f_code.co_filename lineno = tb.tb_lineno lines = []", "class ExceptionReporter: def __init__(self, exc_info, handler): self.exc_type = exc_info[0] self.exc_value", "pformat(value, width=1) except Exception as e: return 'Error in formatting:", "self.exc_type = exc_info[0] self.exc_value = exc_info[1] self.exc_tb = exc_info[2] self.handler", "import tornado from tornado import template SENSITIVE_SETTINGS_RE = re.compile( 'api|key|pass|salt|secret|signature|token',", "exc_value.__traceback__ while True: frames.extend(self.get_exception_traceback_frames(exc_value, tb)) try: exc_value = exceptions.pop() except", "supplied to ExceptionReporter if not exceptions: return frames # In", "tb)) try: exc_value = exceptions.pop() except IndexError: break tb =", "traceback=traceback, pprint=pprint, handler=self.handler, app_settings=self.get_app_settings(), exc_type=self.exc_type, exc_value=self.exc_value, exc_tb=self.exc_tb, frames=self.get_traceback_frames(), tornado_version=tornado.version, sys_version='%d.%d.%d'", "exc_type=self.exc_type, exc_value=self.exc_value, exc_tb=self.exc_tb, frames=self.get_traceback_frames(), tornado_version=tornado.version, sys_version='%d.%d.%d' % sys.version_info[0:3], sys_executable=sys.executable, sys_path=sys.path,", "= self.exc_tb while tb: frames.append({ 'lineno': tb.tb_lineno, 'filename': tb.tb_frame.f_code.co_filename, 'function':", "exc_value, ExceptionCycleWarning, ) # Avoid infinite loop if there's a", "exceptions.pop() tb = self.tb if not exceptions else exc_value.__traceback__ while", "in range( max(lineno - 5, 0), min(lineno + 5, len(_lines))", "getattr(exc_value, '__cause__', None) suppress_context = getattr(exc_value, '__suppress_context__', None) implicit =", "Exception as e: return 'Error in formatting: %s: %s' %", "exc_info[0] self.exc_value = exc_info[1] self.exc_tb = exc_info[2] self.handler = handler", "= exc_info[2] self.handler = handler def get_response(self): loader = template.Loader(os.path.dirname(os.path.abspath(__file__)))", "_lines = f.read().splitlines() for _lineno in range( max(lineno - 5,", "ExceptionReporter if not exceptions: return frames # In case there's", "tb: frames.append({ 'lineno': tb.tb_lineno, 'filename': tb.tb_frame.f_code.co_filename, 'function': tb.tb_frame.f_code.co_name, 'module_name': tb.tb_frame.f_globals.get('__name__')", "None) suppress_context = getattr(exc_value, '__suppress_context__', None) implicit = getattr(exc_value, '__context__',", "import re import sys import traceback from pprint import pformat", "= tb.tb_next frames.reverse() return frames exceptions = [] exc_value =", "flags=re.IGNORECASE ) class ExceptionReporter: def __init__(self, exc_info, handler): self.exc_type =", "while tb: frames.append({ 'lineno': tb.tb_lineno, 'filename': tb.tb_frame.f_code.co_filename, 'function': tb.tb_frame.f_code.co_name, 'module_name':", "for arg, value in self.handler.application.settings.items(): if SENSITIVE_SETTINGS_RE.search(arg): value = '*'", "tb.tb_lineno lines = [] try: with open(filename, 'rb') as f:", "frames exceptions = [] exc_value = self.exc_value while exc_value: exceptions.append(exc_value)", "exceptions.append(exc_value) exc_value = self._get_explicit_or_implicit_cause(exc_value) if exc_value in exceptions: warnings.warn( \"Cycle", "to ExceptionReporter if not exceptions: return frames # In case", "if not exceptions else exc_value.__traceback__ while True: frames.extend(self.get_exception_traceback_frames(exc_value, tb)) try:", "lines = [] try: with open(filename, 'rb') as f: _lines", "(#29393). break frames = [] # No exceptions were supplied", "suppress_context = getattr(exc_value, '__suppress_context__', None) implicit = getattr(exc_value, '__context__', None)", "tb.tb_lineno, 'filename': tb.tb_frame.f_code.co_filename, 'function': tb.tb_frame.f_code.co_name, 'module_name': tb.tb_frame.f_globals.get('__name__') or '', 'vars':", "if SENSITIVE_SETTINGS_RE.search(arg): value = '*' * 15 settings[arg] = value", "frames def _get_explicit_or_implicit_cause(self, exc_value): explicit = getattr(exc_value, '__cause__', None) suppress_context", "settings[arg] = value return settings def get_source_lines(self, tb): filename =", "in exceptions: warnings.warn( \"Cycle in the exception chain detected: exception", "= self.exc_value while exc_value: exceptions.append(exc_value) exc_value = self._get_explicit_or_implicit_cause(exc_value) if exc_value", "frames.append({ 'lineno': tb.tb_lineno, 'filename': tb.tb_frame.f_code.co_filename, 'function': tb.tb_frame.f_code.co_name, 'module_name': tb.tb_frame.f_globals.get('__name__') or", "try: return pformat(value, width=1) except Exception as e: return 'Error", "= re.compile( 'api|key|pass|salt|secret|signature|token', flags=re.IGNORECASE ) class ExceptionReporter: def __init__(self, exc_info,", "filename = tb.tb_frame.f_code.co_filename lineno = tb.tb_lineno lines = [] try:", "settings def get_source_lines(self, tb): filename = tb.tb_frame.f_code.co_filename lineno = tb.tb_lineno", "get_response(self): loader = template.Loader(os.path.dirname(os.path.abspath(__file__))) t = loader.load('debug.html') return t.generate( traceback=traceback,", "exc_value): explicit = getattr(exc_value, '__cause__', None) suppress_context = getattr(exc_value, '__suppress_context__',", "_lines[_lineno])) except Exception as e: # could not open file", "\" \"encountered again.\" % exc_value, ExceptionCycleWarning, ) # Avoid infinite", "range( max(lineno - 5, 0), min(lineno + 5, len(_lines)) ):", "lines def get_traceback_frames(self): frames = [] tb = self.exc_tb while", "exceptions: warnings.warn( \"Cycle in the exception chain detected: exception '%s'", "In case there's just one exception, take the traceback from", "Exception as e: # could not open file pass return", "frames # In case there's just one exception, take the", "os.path import re import sys import traceback from pprint import" ]
[ "f = self.func v = f() if v == self.stopwhen:", "return len(self.l) def __list__(self): l = [] while True: try:", "[] while not self.stopped: try: l.append(self.__next__()) except StopIteration: break return", "self.i += 1 if found: return ret else: return None", "= True raise StopIteration() ret = self.l[self.i] found = True", "StopIteration() ret = self.l[self.i] found = True except IndexError: raise", "self.func = func self.stopwhen = stopwhen self.stopped = False def", "stopwhen) else: TypeError(\"iter(v, w): v must be callable\") elif args.__len__()", "self def __next__(self): has_length = True found = False try:", "self.i >= self.l.__len__(): self.stop = True raise StopIteration() ret =", "while not self.stopped: try: l.append(self.__next__()) except StopIteration: break return l", "except AttributeError: has_length = False try: if self.stop: raise StopIteration()", "has_length = False try: if self.stop: raise StopIteration() if has_length", "0: return it.__next__() else: return it.__next__(arg[0]) ___assign(\"%next\", next) class FuncIter:", "w): v must be callable\") elif args.__len__() == 0: try:", "len(self.l) def __list__(self): l = [] while True: try: l.append(self.__next__())", "[] while True: try: l.append(self.__next__()) except StopIteration: break return l", "l self.i = 0 self.stop = False def __len__(self): return", "return FuncIter(l, stopwhen) else: TypeError(\"iter(v, w): v must be callable\")", "+= 1 if found: return ret else: return None ___assign(\"%SeqIter\",", "StopIteration: break return l def __next__(self): f = self.func v", "return l def __next__(self): f = self.func v = f()", "while True: try: l.append(self.__next__()) except StopIteration: break return l def", "stopwhen self.stopped = False def __list__(self): l = [] while", "= False def __list__(self): l = [] while not self.stopped:", "iter(l, *args): callable = ___id(\"%callable\") if args.__len__() == 1: if", "== self.stopwhen: self.stopped = True raise StopIteration() else: return v", "TypeError(\"object is not iterable\") else: raise TypeError(\"iter expect at most", "has_length and self.i >= self.l.__len__(): self.stop = True raise StopIteration()", "FuncIter(l, stopwhen) else: TypeError(\"iter(v, w): v must be callable\") elif", "self.i = 0 self.stop = False def __len__(self): return len(self.l)", "callable = ___id(\"%callable\") if args.__len__() == 1: if callable(l): stopwhen", "raise StopIteration() self.i += 1 if found: return ret else:", "= args[0] return FuncIter(l, stopwhen) else: TypeError(\"iter(v, w): v must", "def __list__(self): l = [] while not self.stopped: try: l.append(self.__next__())", "raise StopIteration() ret = self.l[self.i] found = True except IndexError:", "0: try: return l.__iter__() except: try: if callable(l.__getitem__): return SeqIter(l)", "args.__len__() == 0: try: return l.__iter__() except: try: if callable(l.__getitem__):", "def iter(l, *args): callable = ___id(\"%callable\") if args.__len__() == 1:", "self.stopwhen: self.stopped = True raise StopIteration() else: return v ___assign(\"%FuncIter\",", "break return l def __next__(self): f = self.func v =", "StopIteration: raise StopIteration() self.i += 1 if found: return ret", "== 0: try: return l.__iter__() except: try: if callable(l.__getitem__): return", "__len__(self): return len(self.l) def __list__(self): l = [] while True:", "args[0] return FuncIter(l, stopwhen) else: TypeError(\"iter(v, w): v must be", "__init__(self,l): self.l = l self.i = 0 self.stop = False", "not iterable\") else: raise TypeError(\"iter expect at most 2 arguments\")", "except IndexError: raise StopIteration() except StopIteration: raise StopIteration() self.i +=", "return SeqIter(l) except: raise TypeError(\"object is not iterable\") else: raise", "self.stopped: try: l.append(self.__next__()) except StopIteration: break return l def __next__(self):", "arguments\") ___assign(\"%iter\", iter) def next(it, *arg): if len(arg) == 0:", "= True found = False try: self.l.__len__() except AttributeError: has_length", "if v == self.stopwhen: self.stopped = True raise StopIteration() else:", "found: return ret else: return None ___assign(\"%SeqIter\", SeqIter) def iter(l,", "= func self.stopwhen = stopwhen self.stopped = False def __list__(self):", "elif args.__len__() == 0: try: return l.__iter__() except: try: if", "self.stopwhen = stopwhen self.stopped = False def __list__(self): l =", "try: if callable(l.__getitem__): return SeqIter(l) except: raise TypeError(\"object is not", "not self.stopped: try: l.append(self.__next__()) except StopIteration: break return l def", "None ___assign(\"%SeqIter\", SeqIter) def iter(l, *args): callable = ___id(\"%callable\") if", "found = True except IndexError: raise StopIteration() except StopIteration: raise", "self.func v = f() if v == self.stopwhen: self.stopped =", "l def __iter__(self): return self def __next__(self): has_length = True", "if has_length and self.i >= self.l.__len__(): self.stop = True raise", "try: self.l.__len__() except AttributeError: has_length = False try: if self.stop:", "1 if found: return ret else: return None ___assign(\"%SeqIter\", SeqIter)", "= False try: self.l.__len__() except AttributeError: has_length = False try:", "if found: return ret else: return None ___assign(\"%SeqIter\", SeqIter) def", "== 1: if callable(l): stopwhen = args[0] return FuncIter(l, stopwhen)", "__next__(self): has_length = True found = False try: self.l.__len__() except", "return l.__iter__() except: try: if callable(l.__getitem__): return SeqIter(l) except: raise", "and self.i >= self.l.__len__(): self.stop = True raise StopIteration() ret", "it.__next__() else: return it.__next__(arg[0]) ___assign(\"%next\", next) class FuncIter: def __init__(self,", "self.stopped = True raise StopIteration() else: return v ___assign(\"%FuncIter\", FuncIter)", "SeqIter(l) except: raise TypeError(\"object is not iterable\") else: raise TypeError(\"iter", "if self.stop: raise StopIteration() if has_length and self.i >= self.l.__len__():", "stopwhen = args[0] return FuncIter(l, stopwhen) else: TypeError(\"iter(v, w): v", "else: raise TypeError(\"iter expect at most 2 arguments\") ___assign(\"%iter\", iter)", "___id(\"%callable\") if args.__len__() == 1: if callable(l): stopwhen = args[0]", "return self def __next__(self): has_length = True found = False", "__list__(self): l = [] while not self.stopped: try: l.append(self.__next__()) except", "return it.__next__(arg[0]) ___assign(\"%next\", next) class FuncIter: def __init__(self, func, stopwhen):", "callable(l.__getitem__): return SeqIter(l) except: raise TypeError(\"object is not iterable\") else:", "l.append(self.__next__()) except StopIteration: break return l def __next__(self): f =", "return ret else: return None ___assign(\"%SeqIter\", SeqIter) def iter(l, *args):", "callable\") elif args.__len__() == 0: try: return l.__iter__() except: try:", "StopIteration() except StopIteration: raise StopIteration() self.i += 1 if found:", "l = [] while not self.stopped: try: l.append(self.__next__()) except StopIteration:", "def __init__(self,l): self.l = l self.i = 0 self.stop =", "l = [] while True: try: l.append(self.__next__()) except StopIteration: break", "l.append(self.__next__()) except StopIteration: break return l def __iter__(self): return self", "ret else: return None ___assign(\"%SeqIter\", SeqIter) def iter(l, *args): callable", "1: if callable(l): stopwhen = args[0] return FuncIter(l, stopwhen) else:", "False def __list__(self): l = [] while not self.stopped: try:", "SeqIter) def iter(l, *args): callable = ___id(\"%callable\") if args.__len__() ==", "iterable\") else: raise TypeError(\"iter expect at most 2 arguments\") ___assign(\"%iter\",", "0 self.stop = False def __len__(self): return len(self.l) def __list__(self):", "TypeError(\"iter expect at most 2 arguments\") ___assign(\"%iter\", iter) def next(it,", "else: TypeError(\"iter(v, w): v must be callable\") elif args.__len__() ==", "== 0: return it.__next__() else: return it.__next__(arg[0]) ___assign(\"%next\", next) class", "False try: if self.stop: raise StopIteration() if has_length and self.i", "except StopIteration: raise StopIteration() self.i += 1 if found: return", "return None ___assign(\"%SeqIter\", SeqIter) def iter(l, *args): callable = ___id(\"%callable\")", "most 2 arguments\") ___assign(\"%iter\", iter) def next(it, *arg): if len(arg)", "True raise StopIteration() ret = self.l[self.i] found = True except", "*arg): if len(arg) == 0: return it.__next__() else: return it.__next__(arg[0])", "*args): callable = ___id(\"%callable\") if args.__len__() == 1: if callable(l):", "AttributeError: has_length = False try: if self.stop: raise StopIteration() if", "func, stopwhen): self.func = func self.stopwhen = stopwhen self.stopped =", "raise TypeError(\"object is not iterable\") else: raise TypeError(\"iter expect at", "at most 2 arguments\") ___assign(\"%iter\", iter) def next(it, *arg): if", "raise StopIteration() except StopIteration: raise StopIteration() self.i += 1 if", "StopIteration() self.i += 1 if found: return ret else: return", "l def __next__(self): f = self.func v = f() if", "is not iterable\") else: raise TypeError(\"iter expect at most 2", "expect at most 2 arguments\") ___assign(\"%iter\", iter) def next(it, *arg):", "ret = self.l[self.i] found = True except IndexError: raise StopIteration()", "stopwhen): self.func = func self.stopwhen = stopwhen self.stopped = False", "def __len__(self): return len(self.l) def __list__(self): l = [] while", "self.l.__len__(): self.stop = True raise StopIteration() ret = self.l[self.i] found", "self.stop = False def __len__(self): return len(self.l) def __list__(self): l", "f() if v == self.stopwhen: self.stopped = True raise StopIteration()", "False def __len__(self): return len(self.l) def __list__(self): l = []", "FuncIter: def __init__(self, func, stopwhen): self.func = func self.stopwhen =", "self.l.__len__() except AttributeError: has_length = False try: if self.stop: raise", "try: if self.stop: raise StopIteration() if has_length and self.i >=", "False try: self.l.__len__() except AttributeError: has_length = False try: if", "return l def __iter__(self): return self def __next__(self): has_length =", "__iter__(self): return self def __next__(self): has_length = True found =", "= self.func v = f() if v == self.stopwhen: self.stopped", "def __next__(self): f = self.func v = f() if v", "TypeError(\"iter(v, w): v must be callable\") elif args.__len__() == 0:", "class FuncIter: def __init__(self, func, stopwhen): self.func = func self.stopwhen", "has_length = True found = False try: self.l.__len__() except AttributeError:", "must be callable\") elif args.__len__() == 0: try: return l.__iter__()", "except StopIteration: break return l def __iter__(self): return self def", "func self.stopwhen = stopwhen self.stopped = False def __list__(self): l", "= ___id(\"%callable\") if args.__len__() == 1: if callable(l): stopwhen =", "be callable\") elif args.__len__() == 0: try: return l.__iter__() except:", ">= self.l.__len__(): self.stop = True raise StopIteration() ret = self.l[self.i]", "= False def __len__(self): return len(self.l) def __list__(self): l =", "self.l[self.i] found = True except IndexError: raise StopIteration() except StopIteration:", "__next__(self): f = self.func v = f() if v ==", "else: return None ___assign(\"%SeqIter\", SeqIter) def iter(l, *args): callable =", "= 0 self.stop = False def __len__(self): return len(self.l) def", "self.stopped = False def __list__(self): l = [] while not", "return it.__next__() else: return it.__next__(arg[0]) ___assign(\"%next\", next) class FuncIter: def", "self.stop = True raise StopIteration() ret = self.l[self.i] found =", "SeqIter: def __init__(self,l): self.l = l self.i = 0 self.stop", "except: try: if callable(l.__getitem__): return SeqIter(l) except: raise TypeError(\"object is", "if len(arg) == 0: return it.__next__() else: return it.__next__(arg[0]) ___assign(\"%next\",", "__init__(self, func, stopwhen): self.func = func self.stopwhen = stopwhen self.stopped", "l.__iter__() except: try: if callable(l.__getitem__): return SeqIter(l) except: raise TypeError(\"object", "raise TypeError(\"iter expect at most 2 arguments\") ___assign(\"%iter\", iter) def", "True found = False try: self.l.__len__() except AttributeError: has_length =", "= False try: if self.stop: raise StopIteration() if has_length and", "break return l def __iter__(self): return self def __next__(self): has_length", "IndexError: raise StopIteration() except StopIteration: raise StopIteration() self.i += 1", "2 arguments\") ___assign(\"%iter\", iter) def next(it, *arg): if len(arg) ==", "it.__next__(arg[0]) ___assign(\"%next\", next) class FuncIter: def __init__(self, func, stopwhen): self.func", "True: try: l.append(self.__next__()) except StopIteration: break return l def __iter__(self):", "len(arg) == 0: return it.__next__() else: return it.__next__(arg[0]) ___assign(\"%next\", next)", "___assign(\"%SeqIter\", SeqIter) def iter(l, *args): callable = ___id(\"%callable\") if args.__len__()", "try: l.append(self.__next__()) except StopIteration: break return l def __next__(self): f", "next) class FuncIter: def __init__(self, func, stopwhen): self.func = func", "class SeqIter: def __init__(self,l): self.l = l self.i = 0", "__list__(self): l = [] while True: try: l.append(self.__next__()) except StopIteration:", "StopIteration: break return l def __iter__(self): return self def __next__(self):", "found = False try: self.l.__len__() except AttributeError: has_length = False", "v must be callable\") elif args.__len__() == 0: try: return", "if callable(l): stopwhen = args[0] return FuncIter(l, stopwhen) else: TypeError(\"iter(v,", "self.stop: raise StopIteration() if has_length and self.i >= self.l.__len__(): self.stop", "= self.l[self.i] found = True except IndexError: raise StopIteration() except", "try: return l.__iter__() except: try: if callable(l.__getitem__): return SeqIter(l) except:", "___assign(\"%iter\", iter) def next(it, *arg): if len(arg) == 0: return", "else: return it.__next__(arg[0]) ___assign(\"%next\", next) class FuncIter: def __init__(self, func,", "= [] while not self.stopped: try: l.append(self.__next__()) except StopIteration: break", "except StopIteration: break return l def __next__(self): f = self.func", "iter) def next(it, *arg): if len(arg) == 0: return it.__next__()", "v = f() if v == self.stopwhen: self.stopped = True", "v == self.stopwhen: self.stopped = True raise StopIteration() else: return", "def __init__(self, func, stopwhen): self.func = func self.stopwhen = stopwhen", "= True except IndexError: raise StopIteration() except StopIteration: raise StopIteration()", "= [] while True: try: l.append(self.__next__()) except StopIteration: break return", "def __iter__(self): return self def __next__(self): has_length = True found", "= stopwhen self.stopped = False def __list__(self): l = []", "next(it, *arg): if len(arg) == 0: return it.__next__() else: return", "try: l.append(self.__next__()) except StopIteration: break return l def __iter__(self): return", "___assign(\"%next\", next) class FuncIter: def __init__(self, func, stopwhen): self.func =", "def next(it, *arg): if len(arg) == 0: return it.__next__() else:", "self.l = l self.i = 0 self.stop = False def", "raise StopIteration() if has_length and self.i >= self.l.__len__(): self.stop =", "def __next__(self): has_length = True found = False try: self.l.__len__()", "if args.__len__() == 1: if callable(l): stopwhen = args[0] return", "def __list__(self): l = [] while True: try: l.append(self.__next__()) except", "True except IndexError: raise StopIteration() except StopIteration: raise StopIteration() self.i", "args.__len__() == 1: if callable(l): stopwhen = args[0] return FuncIter(l,", "callable(l): stopwhen = args[0] return FuncIter(l, stopwhen) else: TypeError(\"iter(v, w):", "if callable(l.__getitem__): return SeqIter(l) except: raise TypeError(\"object is not iterable\")", "= f() if v == self.stopwhen: self.stopped = True raise", "= l self.i = 0 self.stop = False def __len__(self):", "except: raise TypeError(\"object is not iterable\") else: raise TypeError(\"iter expect", "StopIteration() if has_length and self.i >= self.l.__len__(): self.stop = True" ]
[ "lite_forms.components import Option class OpenGeneralExportLicences: class OpenGeneralLicence: def __init__(self, id,", "<reponame>code-review-doctor/lite-frontend-1 from lite_content.lite_internal_frontend.open_general_licences import ( OGEL_DESCRIPTION, OGTCL_DESCRIPTION, OGTL_DESCRIPTION, ) from", "name, description, acronym): self.id = id self.name = name self.description", "from lite_forms.components import Option class OpenGeneralExportLicences: class OpenGeneralLicence: def __init__(self,", "cls.open_general_export_licence, cls.open_general_trade_control_licence, cls.open_general_transhipment_licence, ] @classmethod def as_options(cls): return [ Option(key=ogl.id,", "= id self.name = name self.description = description self.acronym =", "def get_by_id(cls, id): return next(ogl for ogl in cls.all() if", "from lite_content.lite_internal_frontend.open_general_licences import ( OGEL_DESCRIPTION, OGTCL_DESCRIPTION, OGTL_DESCRIPTION, ) from lite_forms.components", "\"00000000-0000-0000-0000-000000000002\", \"Open General Export Licence\", OGEL_DESCRIPTION, \"OGEL\", ) open_general_trade_control_licence =", "\"OGTL\", ) @classmethod def all(cls): return [ cls.open_general_export_licence, cls.open_general_trade_control_licence, cls.open_general_transhipment_licence,", "acronym): self.id = id self.name = name self.description = description", "] @classmethod def as_options(cls): return [ Option(key=ogl.id, value=f\"{ogl.name} ({ogl.acronym})\", description=ogl.description)", "description self.acronym = acronym open_general_export_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000002\", \"Open General", "__init__(self, id, name, description, acronym): self.id = id self.name =", "OGTCL_DESCRIPTION, \"OGTCL\", ) open_general_transhipment_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000014\", \"Open General Transhipment", "OpenGeneralLicence( \"00000000-0000-0000-0000-000000000002\", \"Open General Export Licence\", OGEL_DESCRIPTION, \"OGEL\", ) open_general_trade_control_licence", "\"00000000-0000-0000-0000-000000000013\", \"Open General Trade Control Licence\", OGTCL_DESCRIPTION, \"OGTCL\", ) open_general_transhipment_licence", ") @classmethod def all(cls): return [ cls.open_general_export_licence, cls.open_general_trade_control_licence, cls.open_general_transhipment_licence, ]", "open_general_trade_control_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000013\", \"Open General Trade Control Licence\", OGTCL_DESCRIPTION,", "= description self.acronym = acronym open_general_export_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000002\", \"Open", "OpenGeneralLicence( \"00000000-0000-0000-0000-000000000014\", \"Open General Transhipment Licence\", OGTL_DESCRIPTION, \"OGTL\", ) @classmethod", "cls.all() ] @classmethod def get_by_id(cls, id): return next(ogl for ogl", "import ( OGEL_DESCRIPTION, OGTCL_DESCRIPTION, OGTL_DESCRIPTION, ) from lite_forms.components import Option", "get_by_id(cls, id): return next(ogl for ogl in cls.all() if ogl.id", "self.description = description self.acronym = acronym open_general_export_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000002\",", "[ Option(key=ogl.id, value=f\"{ogl.name} ({ogl.acronym})\", description=ogl.description) for ogl in cls.all() ]", "value=f\"{ogl.name} ({ogl.acronym})\", description=ogl.description) for ogl in cls.all() ] @classmethod def", "self.acronym = acronym open_general_export_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000002\", \"Open General Export", "OpenGeneralExportLicences: class OpenGeneralLicence: def __init__(self, id, name, description, acronym): self.id", ") open_general_transhipment_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000014\", \"Open General Transhipment Licence\", OGTL_DESCRIPTION,", "def all(cls): return [ cls.open_general_export_licence, cls.open_general_trade_control_licence, cls.open_general_transhipment_licence, ] @classmethod def", "( OGEL_DESCRIPTION, OGTCL_DESCRIPTION, OGTL_DESCRIPTION, ) from lite_forms.components import Option class", "Option class OpenGeneralExportLicences: class OpenGeneralLicence: def __init__(self, id, name, description,", "OpenGeneralLicence( \"00000000-0000-0000-0000-000000000013\", \"Open General Trade Control Licence\", OGTCL_DESCRIPTION, \"OGTCL\", )", "import Option class OpenGeneralExportLicences: class OpenGeneralLicence: def __init__(self, id, name,", "\"Open General Trade Control Licence\", OGTCL_DESCRIPTION, \"OGTCL\", ) open_general_transhipment_licence =", "in cls.all() ] @classmethod def get_by_id(cls, id): return next(ogl for", "lite_content.lite_internal_frontend.open_general_licences import ( OGEL_DESCRIPTION, OGTCL_DESCRIPTION, OGTL_DESCRIPTION, ) from lite_forms.components import", "OGTL_DESCRIPTION, \"OGTL\", ) @classmethod def all(cls): return [ cls.open_general_export_licence, cls.open_general_trade_control_licence,", "@classmethod def all(cls): return [ cls.open_general_export_licence, cls.open_general_trade_control_licence, cls.open_general_transhipment_licence, ] @classmethod", "description, acronym): self.id = id self.name = name self.description =", "id, name, description, acronym): self.id = id self.name = name", "@classmethod def as_options(cls): return [ Option(key=ogl.id, value=f\"{ogl.name} ({ogl.acronym})\", description=ogl.description) for", "= OpenGeneralLicence( \"00000000-0000-0000-0000-000000000013\", \"Open General Trade Control Licence\", OGTCL_DESCRIPTION, \"OGTCL\",", "Licence\", OGTCL_DESCRIPTION, \"OGTCL\", ) open_general_transhipment_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000014\", \"Open General", "ogl in cls.all() ] @classmethod def get_by_id(cls, id): return next(ogl", "for ogl in cls.all() ] @classmethod def get_by_id(cls, id): return", "name self.description = description self.acronym = acronym open_general_export_licence = OpenGeneralLicence(", "as_options(cls): return [ Option(key=ogl.id, value=f\"{ogl.name} ({ogl.acronym})\", description=ogl.description) for ogl in", "Licence\", OGTL_DESCRIPTION, \"OGTL\", ) @classmethod def all(cls): return [ cls.open_general_export_licence,", "[ cls.open_general_export_licence, cls.open_general_trade_control_licence, cls.open_general_transhipment_licence, ] @classmethod def as_options(cls): return [", "= OpenGeneralLicence( \"00000000-0000-0000-0000-000000000002\", \"Open General Export Licence\", OGEL_DESCRIPTION, \"OGEL\", )", "({ogl.acronym})\", description=ogl.description) for ogl in cls.all() ] @classmethod def get_by_id(cls,", "General Export Licence\", OGEL_DESCRIPTION, \"OGEL\", ) open_general_trade_control_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000013\",", "class OpenGeneralExportLicences: class OpenGeneralLicence: def __init__(self, id, name, description, acronym):", "OGTCL_DESCRIPTION, OGTL_DESCRIPTION, ) from lite_forms.components import Option class OpenGeneralExportLicences: class", "\"OGEL\", ) open_general_trade_control_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000013\", \"Open General Trade Control", "cls.open_general_transhipment_licence, ] @classmethod def as_options(cls): return [ Option(key=ogl.id, value=f\"{ogl.name} ({ogl.acronym})\",", "\"Open General Export Licence\", OGEL_DESCRIPTION, \"OGEL\", ) open_general_trade_control_licence = OpenGeneralLicence(", "General Trade Control Licence\", OGTCL_DESCRIPTION, \"OGTCL\", ) open_general_transhipment_licence = OpenGeneralLicence(", ") open_general_trade_control_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000013\", \"Open General Trade Control Licence\",", "= acronym open_general_export_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000002\", \"Open General Export Licence\",", "@classmethod def get_by_id(cls, id): return next(ogl for ogl in cls.all()", "OGEL_DESCRIPTION, OGTCL_DESCRIPTION, OGTL_DESCRIPTION, ) from lite_forms.components import Option class OpenGeneralExportLicences:", "open_general_export_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000002\", \"Open General Export Licence\", OGEL_DESCRIPTION, \"OGEL\",", "return next(ogl for ogl in cls.all() if ogl.id == id)", "= name self.description = description self.acronym = acronym open_general_export_licence =", "all(cls): return [ cls.open_general_export_licence, cls.open_general_trade_control_licence, cls.open_general_transhipment_licence, ] @classmethod def as_options(cls):", "OGTL_DESCRIPTION, ) from lite_forms.components import Option class OpenGeneralExportLicences: class OpenGeneralLicence:", "Licence\", OGEL_DESCRIPTION, \"OGEL\", ) open_general_trade_control_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000013\", \"Open General", "self.id = id self.name = name self.description = description self.acronym", "OGEL_DESCRIPTION, \"OGEL\", ) open_general_trade_control_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000013\", \"Open General Trade", "Control Licence\", OGTCL_DESCRIPTION, \"OGTCL\", ) open_general_transhipment_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000014\", \"Open", ") from lite_forms.components import Option class OpenGeneralExportLicences: class OpenGeneralLicence: def", "class OpenGeneralLicence: def __init__(self, id, name, description, acronym): self.id =", "id): return next(ogl for ogl in cls.all() if ogl.id ==", "\"OGTCL\", ) open_general_transhipment_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000014\", \"Open General Transhipment Licence\",", "= OpenGeneralLicence( \"00000000-0000-0000-0000-000000000014\", \"Open General Transhipment Licence\", OGTL_DESCRIPTION, \"OGTL\", )", "description=ogl.description) for ogl in cls.all() ] @classmethod def get_by_id(cls, id):", "General Transhipment Licence\", OGTL_DESCRIPTION, \"OGTL\", ) @classmethod def all(cls): return", "] @classmethod def get_by_id(cls, id): return next(ogl for ogl in", "acronym open_general_export_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000002\", \"Open General Export Licence\", OGEL_DESCRIPTION,", "id self.name = name self.description = description self.acronym = acronym", "\"00000000-0000-0000-0000-000000000014\", \"Open General Transhipment Licence\", OGTL_DESCRIPTION, \"OGTL\", ) @classmethod def", "open_general_transhipment_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000014\", \"Open General Transhipment Licence\", OGTL_DESCRIPTION, \"OGTL\",", "cls.open_general_trade_control_licence, cls.open_general_transhipment_licence, ] @classmethod def as_options(cls): return [ Option(key=ogl.id, value=f\"{ogl.name}", "self.name = name self.description = description self.acronym = acronym open_general_export_licence", "OpenGeneralLicence: def __init__(self, id, name, description, acronym): self.id = id", "Export Licence\", OGEL_DESCRIPTION, \"OGEL\", ) open_general_trade_control_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000013\", \"Open", "def __init__(self, id, name, description, acronym): self.id = id self.name", "return [ Option(key=ogl.id, value=f\"{ogl.name} ({ogl.acronym})\", description=ogl.description) for ogl in cls.all()", "\"Open General Transhipment Licence\", OGTL_DESCRIPTION, \"OGTL\", ) @classmethod def all(cls):", "return [ cls.open_general_export_licence, cls.open_general_trade_control_licence, cls.open_general_transhipment_licence, ] @classmethod def as_options(cls): return", "Trade Control Licence\", OGTCL_DESCRIPTION, \"OGTCL\", ) open_general_transhipment_licence = OpenGeneralLicence( \"00000000-0000-0000-0000-000000000014\",", "def as_options(cls): return [ Option(key=ogl.id, value=f\"{ogl.name} ({ogl.acronym})\", description=ogl.description) for ogl", "Option(key=ogl.id, value=f\"{ogl.name} ({ogl.acronym})\", description=ogl.description) for ogl in cls.all() ] @classmethod", "Transhipment Licence\", OGTL_DESCRIPTION, \"OGTL\", ) @classmethod def all(cls): return [" ]
[ "\"\"\"RotateMatrix.ipynb Automatically generated by Colaboratory. Original file is located at", "temp = mat[i][j] mat[i][j] = mat[i][N - j - 1]", "in range(N): for j in range(N // 2): temp =", "10, 11, 12], [13, 14, 15, 16] ] rotate(mat) #printing", "coding: utf-8 -*- \"\"\"RotateMatrix.ipynb Automatically generated by Colaboratory. Original file", "[9, 10, 11, 12], [13, 14, 15, 16] ] rotate(mat)", "1] = temp if __name__ == '__main__': #Declaring matrix mat", "- 1] mat[i][N - j - 1] = temp if", "Original file is located at https://colab.research.google.com/drive/1LX-dZFuQCyBXDNVosTp0MHaZZxoc5T4I \"\"\" #Function to rotate", "in range(N): for j in range(i): temp = mat[i][j] mat[i][j]", "for i in range(N): for j in range(N // 2):", "Transpose the matrix for i in range(N): for j in", "matrix by 90 degree def rotate(mat): # `N × N`", "= mat[i][N - j - 1] mat[i][N - j -", "= len(mat) # Transpose the matrix for i in range(N):", "15, 16] ] rotate(mat) #printing matrix for i in mat:", "- j - 1] mat[i][N - j - 1] =", "mat[j][i] = temp # swap columns for i in range(N):", "[13, 14, 15, 16] ] rotate(mat) #printing matrix for i", "degree def rotate(mat): # `N × N` matrix N =", "utf-8 -*- \"\"\"RotateMatrix.ipynb Automatically generated by Colaboratory. Original file is", "def rotate(mat): # `N × N` matrix N = len(mat)", "generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1LX-dZFuQCyBXDNVosTp0MHaZZxoc5T4I \"\"\"", "len(mat) # Transpose the matrix for i in range(N): for", "[ [1, 2, 3, 4], [5, 6, 7, 8], [9,", "mat[i][N - j - 1] mat[i][N - j - 1]", "rotate matrix by 90 degree def rotate(mat): # `N ×", "mat[i][j] = mat[i][N - j - 1] mat[i][N - j", "matrix mat = [ [1, 2, 3, 4], [5, 6,", "- 1] = temp if __name__ == '__main__': #Declaring matrix", "3, 4], [5, 6, 7, 8], [9, 10, 11, 12],", "'__main__': #Declaring matrix mat = [ [1, 2, 3, 4],", "14, 15, 16] ] rotate(mat) #printing matrix for i in", "the matrix for i in range(N): for j in range(i):", "at https://colab.research.google.com/drive/1LX-dZFuQCyBXDNVosTp0MHaZZxoc5T4I \"\"\" #Function to rotate matrix by 90 degree", "file is located at https://colab.research.google.com/drive/1LX-dZFuQCyBXDNVosTp0MHaZZxoc5T4I \"\"\" #Function to rotate matrix", "= temp if __name__ == '__main__': #Declaring matrix mat =", "16] ] rotate(mat) #printing matrix for i in mat: print(i)", "Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1LX-dZFuQCyBXDNVosTp0MHaZZxoc5T4I", "= temp # swap columns for i in range(N): for", "https://colab.research.google.com/drive/1LX-dZFuQCyBXDNVosTp0MHaZZxoc5T4I \"\"\" #Function to rotate matrix by 90 degree def", "8], [9, 10, 11, 12], [13, 14, 15, 16] ]", "6, 7, 8], [9, 10, 11, 12], [13, 14, 15,", "= mat[j][i] mat[j][i] = temp # swap columns for i", "mat = [ [1, 2, 3, 4], [5, 6, 7,", "i in range(N): for j in range(i): temp = mat[i][j]", "j in range(i): temp = mat[i][j] mat[i][j] = mat[j][i] mat[j][i]", "`N × N` matrix N = len(mat) # Transpose the", "located at https://colab.research.google.com/drive/1LX-dZFuQCyBXDNVosTp0MHaZZxoc5T4I \"\"\" #Function to rotate matrix by 90", "# `N × N` matrix N = len(mat) # Transpose", "mat[j][i] mat[j][i] = temp # swap columns for i in", "= [ [1, 2, 3, 4], [5, 6, 7, 8],", "for j in range(i): temp = mat[i][j] mat[i][j] = mat[j][i]", "range(N // 2): temp = mat[i][j] mat[i][j] = mat[i][N -", "2, 3, 4], [5, 6, 7, 8], [9, 10, 11,", "1] mat[i][N - j - 1] = temp if __name__", "= mat[i][j] mat[i][j] = mat[i][N - j - 1] mat[i][N", "in range(N // 2): temp = mat[i][j] mat[i][j] = mat[i][N", "[5, 6, 7, 8], [9, 10, 11, 12], [13, 14,", "× N` matrix N = len(mat) # Transpose the matrix", "to rotate matrix by 90 degree def rotate(mat): # `N", "== '__main__': #Declaring matrix mat = [ [1, 2, 3,", "j in range(N // 2): temp = mat[i][j] mat[i][j] =", "N` matrix N = len(mat) # Transpose the matrix for", "range(N): for j in range(i): temp = mat[i][j] mat[i][j] =", "# swap columns for i in range(N): for j in", "if __name__ == '__main__': #Declaring matrix mat = [ [1,", "[1, 2, 3, 4], [5, 6, 7, 8], [9, 10,", "90 degree def rotate(mat): # `N × N` matrix N", "by Colaboratory. Original file is located at https://colab.research.google.com/drive/1LX-dZFuQCyBXDNVosTp0MHaZZxoc5T4I \"\"\" #Function", "#Declaring matrix mat = [ [1, 2, 3, 4], [5,", "11, 12], [13, 14, 15, 16] ] rotate(mat) #printing matrix", "mat[i][j] mat[i][j] = mat[i][N - j - 1] mat[i][N -", "7, 8], [9, 10, 11, 12], [13, 14, 15, 16]", "\"\"\" #Function to rotate matrix by 90 degree def rotate(mat):", "// 2): temp = mat[i][j] mat[i][j] = mat[i][N - j", "matrix N = len(mat) # Transpose the matrix for i", "by 90 degree def rotate(mat): # `N × N` matrix", "range(N): for j in range(N // 2): temp = mat[i][j]", "matrix for i in range(N): for j in range(i): temp", "j - 1] mat[i][N - j - 1] = temp", "columns for i in range(N): for j in range(N //", "= mat[i][j] mat[i][j] = mat[j][i] mat[j][i] = temp # swap", "-*- \"\"\"RotateMatrix.ipynb Automatically generated by Colaboratory. Original file is located", "in range(i): temp = mat[i][j] mat[i][j] = mat[j][i] mat[j][i] =", "- j - 1] = temp if __name__ == '__main__':", "4], [5, 6, 7, 8], [9, 10, 11, 12], [13,", "2): temp = mat[i][j] mat[i][j] = mat[i][N - j -", "# -*- coding: utf-8 -*- \"\"\"RotateMatrix.ipynb Automatically generated by Colaboratory.", "is located at https://colab.research.google.com/drive/1LX-dZFuQCyBXDNVosTp0MHaZZxoc5T4I \"\"\" #Function to rotate matrix by", "# Transpose the matrix for i in range(N): for j", "range(i): temp = mat[i][j] mat[i][j] = mat[j][i] mat[j][i] = temp", "swap columns for i in range(N): for j in range(N", "for j in range(N // 2): temp = mat[i][j] mat[i][j]", "mat[i][N - j - 1] = temp if __name__ ==", "12], [13, 14, 15, 16] ] rotate(mat) #printing matrix for", "#Function to rotate matrix by 90 degree def rotate(mat): #", "temp if __name__ == '__main__': #Declaring matrix mat = [", "for i in range(N): for j in range(i): temp =", "__name__ == '__main__': #Declaring matrix mat = [ [1, 2,", "i in range(N): for j in range(N // 2): temp", "Colaboratory. Original file is located at https://colab.research.google.com/drive/1LX-dZFuQCyBXDNVosTp0MHaZZxoc5T4I \"\"\" #Function to", "N = len(mat) # Transpose the matrix for i in", "temp # swap columns for i in range(N): for j", "rotate(mat): # `N × N` matrix N = len(mat) #", "-*- coding: utf-8 -*- \"\"\"RotateMatrix.ipynb Automatically generated by Colaboratory. Original", "j - 1] = temp if __name__ == '__main__': #Declaring", "mat[i][j] mat[i][j] = mat[j][i] mat[j][i] = temp # swap columns", "temp = mat[i][j] mat[i][j] = mat[j][i] mat[j][i] = temp #", "mat[i][j] = mat[j][i] mat[j][i] = temp # swap columns for" ]
[ "for x in xs if x > pivot] res =", "x > pivot] res = quicksort(left) res.append(pivot) res += quicksort(right)", "return [] pivot = xs[0] xs = xs[1:] left =", "pivot] right = [x for x in xs if x", "[x for x in xs if x <= pivot] right", "= [x for x in xs if x <= pivot]", "res xs = [1, 3, 2, 4, 5, 2] sorted_xs", "quicksort(xs): if len(xs) == 0: return [] pivot = xs[0]", "in xs if x > pivot] res = quicksort(left) res.append(pivot)", "pivot] res = quicksort(left) res.append(pivot) res += quicksort(right) return res", "x in xs if x <= pivot] right = [x", "= quicksort(left) res.append(pivot) res += quicksort(right) return res xs =", "xs = [1, 3, 2, 4, 5, 2] sorted_xs =", "<gh_stars>1-10 def quicksort(xs): if len(xs) == 0: return [] pivot", "= xs[1:] left = [x for x in xs if", "xs if x > pivot] res = quicksort(left) res.append(pivot) res", "def quicksort(xs): if len(xs) == 0: return [] pivot =", "xs = xs[1:] left = [x for x in xs", "x <= pivot] right = [x for x in xs", "if len(xs) == 0: return [] pivot = xs[0] xs", "if x > pivot] res = quicksort(left) res.append(pivot) res +=", "res += quicksort(right) return res xs = [1, 3, 2,", "return res xs = [1, 3, 2, 4, 5, 2]", "+= quicksort(right) return res xs = [1, 3, 2, 4,", "left = [x for x in xs if x <=", "quicksort(right) return res xs = [1, 3, 2, 4, 5,", "[x for x in xs if x > pivot] res", "len(xs) == 0: return [] pivot = xs[0] xs =", "xs if x <= pivot] right = [x for x", "= xs[0] xs = xs[1:] left = [x for x", "> pivot] res = quicksort(left) res.append(pivot) res += quicksort(right) return", "pivot = xs[0] xs = xs[1:] left = [x for", "xs[1:] left = [x for x in xs if x", "quicksort(left) res.append(pivot) res += quicksort(right) return res xs = [1,", "right = [x for x in xs if x >", "in xs if x <= pivot] right = [x for", "x in xs if x > pivot] res = quicksort(left)", "0: return [] pivot = xs[0] xs = xs[1:] left", "[] pivot = xs[0] xs = xs[1:] left = [x", "if x <= pivot] right = [x for x in", "res = quicksort(left) res.append(pivot) res += quicksort(right) return res xs", "<= pivot] right = [x for x in xs if", "xs[0] xs = xs[1:] left = [x for x in", "res.append(pivot) res += quicksort(right) return res xs = [1, 3,", "= [x for x in xs if x > pivot]", "for x in xs if x <= pivot] right =", "= [1, 3, 2, 4, 5, 2] sorted_xs = quicksort(xs)", "== 0: return [] pivot = xs[0] xs = xs[1:]" ]
[ "devops_pb2.TransactionRequest(transactionUuid = context.transactionID) response = stub.GetTransactionResult(txRequest, 2) assert response.status ==", "(channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) # Make", "enrollId supplied''' assert 'users' in context, \"users not found in", "of the full container name\"\"\" assert 'compose_containers' in context, \"compose_containers", "2.0 (the \"License\"); # you may not use this file", "# We need to run the cli command by actually", "for arg in context.table[0].cells: m = pattern.match(arg) if m: #", "!= None, \"Deployment NOT found for chaincode alias '{0}'\".format(ccAlias) #", "= chaincode_pb2.ChaincodeSpec() newChaincodeSpec.CopyFrom(deployedCcSpec) # Update hte chaincodeSpec ctorMsg for invoke", "error = p.communicate() if p.returncode != 0: if output is", "= ccDeploymentSpec.chaincodeSpec.chaincodeID.name context.grpcChaincodeSpec = ccSpec context.deployments[ccAlias] = ccSpec except: del", "context.compose_containers) channel = getGRPCChannel(ipAddress) return (channel, userRegistration) def getDeployment(context, ccAlias):", "# Make sure deployment alias does NOT already exist assert", "functionName, args = args ) newChaincodeSpec.ctorMsg.CopyFrom(chaincodeInput) ccInvocationSpec = chaincode_pb2.ChaincodeInvocationSpec(chaincodeSpec =", "# Update hte chaincodeSpec ctorMsg for invoke args = getArgsFromContextForUser(context,", "instance. The channel is open to the composeService that the", "by copying the deployed one newChaincodeSpec = chaincode_pb2.ChaincodeSpec() newChaincodeSpec.CopyFrom(deployedCcSpec) #", "full container name\"\"\" ip = None containerNamePrefix = os.path.basename(os.getcwd()) +", "self.tags = {} self.lastResult = None def getUserName(self): return self.secretMsg['enrollId']", "context. Did you register a user?\" assert 'compose_containers' in context,", "IBM Corp. 2016 All Rights Reserved. # # Licensed under", "from {0}, for user \"{1}\": {2}'.format(userRegistration.composeService,enrollId, response.msg) # Now grab", "enrollId): # Update the chaincodeSpec ctorMsg for invoke args =", "return devops_pb2.Secret(enrollId=self.secretMsg['enrollId'],enrollSecret=self.secretMsg['enrollSecret']) # Registerses a user on a specific composeService", "\"_\" for containerData in containerDataList: if containerData.containerName.startswith(containerNamePrefix + namePart): ip", "# Create a new ChaincodeSpec by copying the deployed one", "in userRegistration.tags, \"TagName '{0}' not found for user '{1}'\".format(tagName, userRegistration.getUserName())", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "pass else: context.users = {} if enrollId in context.users: userRegistration", "one newChaincodeSpec = chaincode_pb2.ChaincodeSpec() newChaincodeSpec.CopyFrom(deployedCcSpec) # Update hte chaincodeSpec ctorMsg", "specified alias for the specfied enrollId''' (channel, userRegistration) = getGRPCChannelAndUser(context,", "part of the full container name\"\"\" ip = None containerNamePrefix", "getDeployment(context, ccAlias): '''Return a deployment with chaincode alias from prior", "enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) # Make sure deployment alias does", "copying the deployed one newChaincodeSpec = chaincode_pb2.ChaincodeSpec() newChaincodeSpec.CopyFrom(deployedCcSpec) # Update", "container name\"\"\" assert 'compose_containers' in context, \"compose_containers not found in", "== None, \"Deployment alias already exists: '{0}'.\".format(ccAlias) args = getArgsFromContextForUser(context,", "= chaincode_pb2.ChaincodeInput(function = ctor, args = args)) ccSpec.secureContext = userRegistration.getUserName()", "= implementations.insecure_channel(ipAddress, 30303) print(\"Returning GRPC for address: {0}\".format(ipAddress)) return channel", "# Allow the user to specify expressions referencing tags in", "the tagName is found in the users tags assert tagName", "supplied chaincode alias deployedCcSpec = getDeployment(context, ccAlias) assert deployedCcSpec !=", "of the full container name\"\"\" ip = None containerNamePrefix =", "p.returncode class UserRegistration: def __init__(self, secretMsg, composeService): self.secretMsg = secretMsg", "args = args)) ccSpec.secureContext = userRegistration.getUserName() if 'metadata' in context:", "deployChaincode(context, enrollId, chaincodePath, ccAlias, ctor): '''Deploy a chaincode with the", "the server that the user registered on ipAddress = ipFromContainerNamePart(userRegistration.composeService,", "the deployment for the supplied chaincode alias deployedCcSpec = getDeployment(context,", "use this file except in compliance with the License. #", "registerUser(context, secretMsg, composeService): userName = secretMsg['enrollId'] if 'users' in context:", "name part of the full container name\"\"\" ip = None", "in context: pass else: context.deployments = {} if ccAlias in", "os import re import subprocess import devops_pb2 import fabric_pb2 import", "+ \"_\" for containerData in containerDataList: if containerData.containerName.startswith(containerNamePrefix + namePart):", "user \"{1}\": {2}'.format(userRegistration.composeService,enrollId, response.msg) # Now grab the TransactionResult from", "name\"\"\" ip = None containerNamePrefix = os.path.basename(os.getcwd()) + \"_\" for", "self.secretMsg['enrollId'] def getSecret(self): return devops_pb2.Secret(enrollId=self.secretMsg['enrollId'],enrollSecret=self.secretMsg['enrollSecret']) # Registerses a user on", "ip == None: raise Exception(\"Could not find container with namePart", "return response def getArgsFromContextForUser(context, enrollId): # Update the chaincodeSpec ctorMsg", "'{1}'\".format(tagName, userRegistration.getUserName()) args.append(userRegistration.tags[tagName]) else: #No tag referenced, pass the arg", "with namePart = {0}\".format(namePart)) return ip def getTxResult(context, enrollId): '''Returns", "assert tagName in userRegistration.tags, \"TagName '{0}' not found for user", "grab the TransactionResult from the Msg bytes txResult = fabric_pb2.TransactionResult()", "= chaincode_pb2.ChaincodeID(name=\"\",path=chaincodePath), ctorMsg = chaincode_pb2.ChaincodeInput(function = ctor, args = args))", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "not None: print(\"Output:\\n\" + output) if error is not None:", "assert deployedCcSpec != None, \"Deployment NOT found for chaincode alias", "import chaincode_pb2 from grpc.beta import implementations def cli_call(context, arg_list, expect_success=True):", "containerData in containerDataList: if containerData.containerName.startswith(containerNamePrefix + namePart): ip = containerData.ipAddress", "License. # You may obtain a copy of the License", "registered on ipAddress = ipFromContainerNamePart(userRegistration.composeService, context.compose_containers) channel = getGRPCChannel(ipAddress) return", "ipAddress = ipFromContainerNamePart(userRegistration.composeService, context.compose_containers) channel = getGRPCChannel(ipAddress) return (channel, userRegistration)", "namePart in aliases: for containerData in context.compose_containers: if containerData.containerName.startswith(containerNamePrefix +", "\"Deployment NOT found for chaincode alias '{0}'\".format(ccAlias) # Create a", "raise Exception(\"User has not been registered: {0}\".format(enrollId)) return userRegistration def", "response def getArgsFromContextForUser(context, enrollId): # Update the chaincodeSpec ctorMsg for", "specific composeService def getUserRegistration(context, enrollId): userRegistration = None if 'users'", "chaincodeInput = chaincode_pb2.ChaincodeInput(function = functionName, args = args ) newChaincodeSpec.ctorMsg.CopyFrom(chaincodeInput)", "composeService self.tags = {} self.lastResult = None def getUserName(self): return", "under the License is distributed on an \"AS IS\" BASIS,", "= newChaincodeSpec) (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel)", "return self.secretMsg['enrollId'] def getSecret(self): return devops_pb2.Secret(enrollId=self.secretMsg['enrollId'],enrollSecret=self.secretMsg['enrollSecret']) # Registerses a user", "'metadata' in context: ccSpec.metadata = context.metadata try: ccDeploymentSpec = stub.Deploy(ccSpec,", "License for the specific language governing permissions and # limitations", "secretMsg, composeService): userName = secretMsg['enrollId'] if 'users' in context: pass", "stub.GetTransactionResult(txRequest, 2) assert response.status == fabric_pb2.Response.SUCCESS, 'Failure getting Transaction Result", "def getDeployment(context, ccAlias): '''Return a deployment with chaincode alias from", "userRegistration = getUserRegistration(context, enrollId) # Get the IP address of", "context\" values = [] containerNamePrefix = os.path.basename(os.getcwd()) + \"_\" for", "found''' deployment = None if 'deployments' in context: pass else:", "print(\"Output:\\n\" + output) if error is not None: print(\"Error Message:\\n\"", "Reserved. # # Licensed under the Apache License, Version 2.0", "from prior deployment, or None if not found''' deployment =", "= devops_pb2.TransactionRequest(transactionUuid = context.transactionID) response = stub.GetTransactionResult(txRequest, 2) assert response.status", "{0}\".format(ipAddress)) return channel def getGRPCChannelAndUser(context, enrollId): '''Returns a tuple of", "args)) ccSpec.secureContext = userRegistration.getUserName() if 'metadata' in context: ccSpec.metadata =", "env python we # setup for running the update-cli p", "= None def getUserName(self): return self.secretMsg['enrollId'] def getSecret(self): return devops_pb2.Secret(enrollId=self.secretMsg['enrollId'],enrollSecret=self.secretMsg['enrollSecret'])", "IPAddress based upon a name part of the full container", "if 'users' in context: pass else: context.users = {} if", "= getArgsFromContextForUser(context, enrollId) chaincodeInput = chaincode_pb2.ChaincodeInput(function = functionName, args =", "in aliases: for containerData in context.compose_containers: if containerData.containerName.startswith(containerNamePrefix + namePart):", "aliases, callback): \"\"\"Returns the IPAddress based upon a name part", "been registered: {0}\".format(enrollId)) return userRegistration def ipFromContainerNamePart(namePart, containerDataList): \"\"\"Returns the", "name\"\"\" assert 'compose_containers' in context, \"compose_containers not found in context\"", "GRPC channel and UserRegistration instance. The channel is open to", "if expect_success: raise subprocess.CalledProcessError(p.returncode, arg_list, output) return output, error, p.returncode", "the update-cli.py script has a #!/bin/python as the first line", "server that the user registered on ipAddress = ipFromContainerNamePart(userRegistration.composeService, context.compose_containers)", "if 'metadata' in context: ccSpec.metadata = context.metadata try: ccDeploymentSpec =", "context: ccSpec.metadata = context.metadata try: ccDeploymentSpec = stub.Deploy(ccSpec, 60) ccSpec.chaincodeID.name", "function arguments userRegistration = getUserRegistration(context, enrollId) # Allow the user", "we # setup for running the update-cli p = subprocess.Popen(arg_list,", "'Failure getting Transaction Result from {0}, for user \"{1}\": {2}'.format(userRegistration.composeService,enrollId,", "= ctor, args = args)) ccSpec.secureContext = userRegistration.getUserName() if 'metadata'", "in context\" (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel)", "assert 'users' in context, \"users not found in context. Did", "that the user registered with.''' userRegistration = getUserRegistration(context, enrollId) #", "if ccAlias in context.deployments: deployment = context.deployments[ccAlias] # else: #", "return txResult def getGRPCChannel(ipAddress): channel = implementations.insecure_channel(ipAddress, 30303) print(\"Returning GRPC", "a list command arguments @param expect_success: use False to return", "def getGRPCChannel(ipAddress): channel = implementations.insecure_channel(ipAddress, 30303) print(\"Returning GRPC for address:", "open to the composeService that the user registered with.''' userRegistration", "in compliance with the License. # You may obtain a", "def cli_call(context, arg_list, expect_success=True): \"\"\"Executes a CLI command in a", "ccDeploymentSpec = stub.Deploy(ccSpec, 60) ccSpec.chaincodeID.name = ccDeploymentSpec.chaincodeSpec.chaincodeID.name context.grpcChaincodeSpec = ccSpec", "software # distributed under the License is distributed on an", "def invokeChaincode(context, enrollId, ccAlias, functionName): # Get the deployment for", "@return: (string, string, int) output message, error message, return code", "= containerData.ipAddress if ip == None: raise Exception(\"Could not find", "enrollId, chaincodePath, ccAlias, ctor): '''Deploy a chaincode with the specified", "user on a specific composeService def getUserRegistration(context, enrollId): userRegistration =", "a deployment with chaincode alias from prior deployment, or None", "deployment = None if 'deployments' in context: pass else: context.deployments", "in context: pass else: context.users = {} if enrollId in", "when executing the command @return: (string, string, int) output message,", "found for user '{1}'\".format(tagName, userRegistration.getUserName()) args.append(userRegistration.tags[tagName]) else: #No tag referenced,", "aliases: for containerData in context.compose_containers: if containerData.containerName.startswith(containerNamePrefix + namePart): values.append(callback(containerData))", "= stub.Deploy(ccSpec, 60) ccSpec.chaincodeID.name = ccDeploymentSpec.chaincodeSpec.chaincodeID.name context.grpcChaincodeSpec = ccSpec context.deployments[ccAlias]", "deployment = context.deployments[ccAlias] # else: # raise Exception(\"Deployment alias not", "sure you have deployed a chaincode with this alias?\".format(ccAlias)) return", "UserRegistration(secretMsg, composeService) # Registerses a user on a specific composeService", "the arg args.append(arg) return args def getContainerDataValuesFromContext(context, aliases, callback): \"\"\"Returns", "\"compose_containers not found in context\" values = [] containerNamePrefix =", "\"\"\"Returns the IPAddress based upon a name part of the", "pass else: context.deployments = {} if ccAlias in context.deployments: deployment", "composeService): userName = secretMsg['enrollId'] if 'users' in context: pass else:", "error occurred when executing the command @return: (string, string, int)", "= getUserRegistration(context, enrollId) # Get the IP address of the", "pattern.match(arg) if m: # tagName reference found in args list", "a chaincode with this alias?\".format(ccAlias)) return deployment def deployChaincode(context, enrollId,", "+ \"_\" for namePart in aliases: for containerData in context.compose_containers:", "getArgsFromContextForUser(context, enrollId): # Update the chaincodeSpec ctorMsg for invoke args", "+ namePart): ip = containerData.ipAddress if ip == None: raise", "= devops_pb2.beta_create_Devops_stub(channel) txRequest = devops_pb2.TransactionRequest(transactionUuid = context.transactionID) response = stub.GetTransactionResult(txRequest,", "ipFromContainerNamePart(userRegistration.composeService, context.compose_containers) channel = getGRPCChannel(ipAddress) return (channel, userRegistration) def getDeployment(context,", "the cli command by actually calling the python command #", "expressions referencing tags in the args list pattern = re.compile('\\{(.*)\\}$')", "the behave context @param arg_list: a list command arguments @param", "= os.path.basename(os.getcwd()) + \"_\" for namePart in aliases: for containerData", "prior deployment, or None if not found''' deployment = None", "None def getUserName(self): return self.secretMsg['enrollId'] def getSecret(self): return devops_pb2.Secret(enrollId=self.secretMsg['enrollId'],enrollSecret=self.secretMsg['enrollSecret']) #", "ctorMsg for invoke args = [] if 'table' in context:", "list tagName = m.groups()[0] # make sure the tagName is", "found in context. Did you register a user?\" assert 'compose_containers'", "invokeChaincode(context, enrollId, ccAlias, functionName): # Get the deployment for the", "chaincode_pb2.ChaincodeSpec(type = chaincode_pb2.ChaincodeSpec.GOLANG, chaincodeID = chaincode_pb2.ChaincodeID(name=\"\",path=chaincodePath), ctorMsg = chaincode_pb2.ChaincodeInput(function =", "enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) txRequest = devops_pb2.TransactionRequest(transactionUuid = context.transactionID) response", "Copyright IBM Corp. 2016 All Rights Reserved. # # Licensed", "import re import subprocess import devops_pb2 import fabric_pb2 import chaincode_pb2", "for running the update-cli p = subprocess.Popen(arg_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output,", "def getGRPCChannelAndUser(context, enrollId): '''Returns a tuple of GRPC channel and", "address: {0}\".format(ipAddress)) return channel def getGRPCChannelAndUser(context, enrollId): '''Returns a tuple", "has not been registered: {0}\".format(enrollId)) return userRegistration def ipFromContainerNamePart(namePart, containerDataList):", "'compose_containers' in context, \"compose_containers not found in context\" (channel, userRegistration)", "line # which calls the system python, not the virtual", "deployed one newChaincodeSpec = chaincode_pb2.ChaincodeSpec() newChaincodeSpec.CopyFrom(deployedCcSpec) # Update hte chaincodeSpec", "userRegistration.tags, \"TagName '{0}' not found for user '{1}'\".format(tagName, userRegistration.getUserName()) args.append(userRegistration.tags[tagName])", "arg args.append(arg) return args def getContainerDataValuesFromContext(context, aliases, callback): \"\"\"Returns the", "return even if an error occurred when executing the command", "= p.communicate() if p.returncode != 0: if output is not", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "return the results. @param context: the behave context @param arg_list:", "p = subprocess.Popen(arg_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = p.communicate() if", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "user '{1}'\".format(tagName, userRegistration.getUserName()) args.append(userRegistration.tags[tagName]) else: #No tag referenced, pass the", "# which calls the system python, not the virtual env", "composeService def getUserRegistration(context, enrollId): userRegistration = None if 'users' in", "p.communicate() if p.returncode != 0: if output is not None:", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "# tagName reference found in args list tagName = m.groups()[0]", "fabric_pb2.Response.SUCCESS, 'Failure getting Transaction Result from {0}, for user \"{1}\":", "output message, error message, return code \"\"\" #arg_list[0] = \"update-\"", "0: if output is not None: print(\"Output:\\n\" + output) if", "channel = getGRPCChannel(ipAddress) return (channel, userRegistration) def getDeployment(context, ccAlias): '''Return", "to in writing, software # distributed under the License is", "ctor): '''Deploy a chaincode with the specified alias for the", "for containerData in containerDataList: if containerData.containerName.startswith(containerNamePrefix + namePart): ip =", "# See the License for the specific language governing permissions", "#No tag referenced, pass the arg args.append(arg) return args def", "We need to run the cli command by actually calling", "on a specific composeService def getUserRegistration(context, enrollId): userRegistration = None", "the supplied chaincode alias deployedCcSpec = getDeployment(context, ccAlias) assert deployedCcSpec", "language governing permissions and # limitations under the License. #", "enrollId) # Allow the user to specify expressions referencing tags", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "@param expect_success: use False to return even if an error", "if output is not None: print(\"Output:\\n\" + output) if error", "# There are function arguments userRegistration = getUserRegistration(context, enrollId) #", "user registered on ipAddress = ipFromContainerNamePart(userRegistration.composeService, context.compose_containers) channel = getGRPCChannel(ipAddress)", "the TransactionResult from the Msg bytes txResult = fabric_pb2.TransactionResult() txResult.ParseFromString(response.msg)", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "stub = devops_pb2.beta_create_Devops_stub(channel) txRequest = devops_pb2.TransactionRequest(transactionUuid = context.transactionID) response =", "= None containerNamePrefix = os.path.basename(os.getcwd()) + \"_\" for containerData in", "a tuple of GRPC channel and UserRegistration instance. The channel", "of the server that the user registered on ipAddress =", "if not found''' deployment = None if 'deployments' in context:", "with the License. # You may obtain a copy of", "'deployments' in context: pass else: context.deployments = {} if ccAlias", "enrollId) chaincodeInput = chaincode_pb2.ChaincodeInput(function = functionName, args = args )", "from grpc.beta import implementations def cli_call(context, arg_list, expect_success=True): \"\"\"Executes a", "userRegistration = context.users[enrollId] else: raise Exception(\"User has not been registered:", "None if 'deployments' in context: pass else: context.deployments = {}", "'{0}'\".format(ccAlias) # Create a new ChaincodeSpec by copying the deployed", "'table' in context: # There are function arguments userRegistration =", "def registerUser(context, secretMsg, composeService): userName = secretMsg['enrollId'] if 'users' in", "specific composeService def registerUser(context, secretMsg, composeService): userName = secretMsg['enrollId'] if", "# Registerses a user on a specific composeService def registerUser(context,", "implementations def cli_call(context, arg_list, expect_success=True): \"\"\"Executes a CLI command in", "in context, \"compose_containers not found in context\" values = []", "@param context: the behave context @param arg_list: a list command", "for chaincode alias '{0}'\".format(ccAlias) # Create a new ChaincodeSpec by", "chaincode_pb2.ChaincodeSpec.GOLANG, chaincodeID = chaincode_pb2.ChaincodeID(name=\"\",path=chaincodePath), ctorMsg = chaincode_pb2.ChaincodeInput(function = ctor, args", "update-cli p = subprocess.Popen(arg_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = p.communicate()", "\"Deployment alias already exists: '{0}'.\".format(ccAlias) args = getArgsFromContextForUser(context, enrollId) ccSpec", "compliance with the License. # You may obtain a copy", "output) return output, error, p.returncode class UserRegistration: def __init__(self, secretMsg,", "All Rights Reserved. # # Licensed under the Apache License,", "agreed to in writing, software # distributed under the License", "# Update the chaincodeSpec ctorMsg for invoke args = []", "command arguments @param expect_success: use False to return even if", "return output, error, p.returncode class UserRegistration: def __init__(self, secretMsg, composeService):", "the update-cli p = subprocess.Popen(arg_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error =", "getTxResult(context, enrollId): '''Returns the TransactionResult using the enrollId supplied''' assert", "for the supplied chaincode alias deployedCcSpec = getDeployment(context, ccAlias) assert", "getUserRegistration(context, enrollId) # Allow the user to specify expressions referencing", "distributed under the License is distributed on an \"AS IS\"", "on a specific composeService def registerUser(context, secretMsg, composeService): userName =", "TransactionResult from the Msg bytes txResult = fabric_pb2.TransactionResult() txResult.ParseFromString(response.msg) return", "user to specify expressions referencing tags in the args list", "grpc.beta import implementations def cli_call(context, arg_list, expect_success=True): \"\"\"Executes a CLI", "alias not found: '{0}'. Are you sure you have deployed", "deployment def deployChaincode(context, enrollId, chaincodePath, ccAlias, ctor): '''Deploy a chaincode", "None: print(\"Error Message:\\n\" + error) if expect_success: raise subprocess.CalledProcessError(p.returncode, arg_list,", "arg_list: a list command arguments @param expect_success: use False to", "composeService that the user registered with.''' userRegistration = getUserRegistration(context, enrollId)", "ctorMsg = chaincode_pb2.ChaincodeInput(function = ctor, args = args)) ccSpec.secureContext =", "expect_success=True): \"\"\"Executes a CLI command in a subprocess and return", "containerDataList: if containerData.containerName.startswith(containerNamePrefix + namePart): ip = containerData.ipAddress if ip", "response = stub.GetTransactionResult(txRequest, 2) assert response.status == fabric_pb2.Response.SUCCESS, 'Failure getting", "# Copyright IBM Corp. 2016 All Rights Reserved. # #", "chaincode with the specified alias for the specfied enrollId''' (channel,", "pattern = re.compile('\\{(.*)\\}$') for arg in context.table[0].cells: m = pattern.match(arg)", "the system python, not the virtual env python we #", "express or implied. # See the License for the specific", "if 'deployments' in context: pass else: context.deployments = {} if", "except in compliance with the License. # You may obtain", "userName = secretMsg['enrollId'] if 'users' in context: pass else: context.users", "deployedCcSpec = getDeployment(context, ccAlias) assert deployedCcSpec != None, \"Deployment NOT", "else: #No tag referenced, pass the arg args.append(arg) return args", "getSecret(self): return devops_pb2.Secret(enrollId=self.secretMsg['enrollId'],enrollSecret=self.secretMsg['enrollSecret']) # Registerses a user on a specific", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "deployment with chaincode alias from prior deployment, or None if", "arg in context.table[0].cells: m = pattern.match(arg) if m: # tagName", "actually calling the python command # the update-cli.py script has", "not use this file except in compliance with the License.", "if m: # tagName reference found in args list tagName", "alias?\".format(ccAlias)) return deployment def deployChaincode(context, enrollId, chaincodePath, ccAlias, ctor): '''Deploy", "command # the update-cli.py script has a #!/bin/python as the", "referencing tags in the args list pattern = re.compile('\\{(.*)\\}$') for", "= context.transactionID) response = stub.GetTransactionResult(txRequest, 2) assert response.status == fabric_pb2.Response.SUCCESS,", "False to return even if an error occurred when executing", "writing, software # distributed under the License is distributed on", "= m.groups()[0] # make sure the tagName is found in", "@param arg_list: a list command arguments @param expect_success: use False", "with chaincode alias from prior deployment, or None if not", "you may not use this file except in compliance with", "response.msg) # Now grab the TransactionResult from the Msg bytes", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "'users' in context: pass else: context.users = {} if userName", "executing the command @return: (string, string, int) output message, error", "even if an error occurred when executing the command @return:", "None if not found''' deployment = None if 'deployments' in", "arg_list[0] # We need to run the cli command by", "not found: '{0}'. Are you sure you have deployed a", "containerNamePrefix = os.path.basename(os.getcwd()) + \"_\" for namePart in aliases: for", "from the Msg bytes txResult = fabric_pb2.TransactionResult() txResult.ParseFromString(response.msg) return txResult", "stub raise def invokeChaincode(context, enrollId, ccAlias, functionName): # Get the", "getGRPCChannel(ipAddress) return (channel, userRegistration) def getDeployment(context, ccAlias): '''Return a deployment", "for namePart in aliases: for containerData in context.compose_containers: if containerData.containerName.startswith(containerNamePrefix", "os.path.basename(os.getcwd()) + \"_\" for containerData in containerDataList: if containerData.containerName.startswith(containerNamePrefix +", "secretMsg['enrollId'] if 'users' in context: pass else: context.users = {}", "userRegistration) = getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) # Make sure", "# make sure the tagName is found in the users", "import os import re import subprocess import devops_pb2 import fabric_pb2", "None containerNamePrefix = os.path.basename(os.getcwd()) + \"_\" for containerData in containerDataList:", "= None if 'deployments' in context: pass else: context.deployments =", "{0}\".format(enrollId)) return userRegistration def ipFromContainerNamePart(namePart, containerDataList): \"\"\"Returns the IPAddress based", "CONDITIONS OF ANY KIND, either express or implied. # See", "expect_success: use False to return even if an error occurred", "newChaincodeSpec.ctorMsg.CopyFrom(chaincodeInput) ccInvocationSpec = chaincode_pb2.ChaincodeInvocationSpec(chaincodeSpec = newChaincodeSpec) (channel, userRegistration) = getGRPCChannelAndUser(context,", "\"\"\"Executes a CLI command in a subprocess and return the", "not found''' deployment = None if 'deployments' in context: pass", "need to run the cli command by actually calling the", "enrollId''' (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) #", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) txRequest = devops_pb2.TransactionRequest(transactionUuid = context.transactionID)", "{0}, for user \"{1}\": {2}'.format(userRegistration.composeService,enrollId, response.msg) # Now grab the", "ccAlias): '''Return a deployment with chaincode alias from prior deployment,", "ccSpec context.deployments[ccAlias] = ccSpec except: del stub raise def invokeChaincode(context,", "raise Exception(\"Could not find container with namePart = {0}\".format(namePart)) return", "getUserName(self): return self.secretMsg['enrollId'] def getSecret(self): return devops_pb2.Secret(enrollId=self.secretMsg['enrollId'],enrollSecret=self.secretMsg['enrollSecret']) # Registerses a", "ccInvocationSpec = chaincode_pb2.ChaincodeInvocationSpec(chaincodeSpec = newChaincodeSpec) (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId)", "UserRegistration instance. The channel is open to the composeService that", "None: raise Exception(\"Could not find container with namePart = {0}\".format(namePart))", "output is not None: print(\"Output:\\n\" + output) if error is", "if error is not None: print(\"Error Message:\\n\" + error) if", "fabric_pb2.TransactionResult() txResult.ParseFromString(response.msg) return txResult def getGRPCChannel(ipAddress): channel = implementations.insecure_channel(ipAddress, 30303)", "devops_pb2.beta_create_Devops_stub(channel) txRequest = devops_pb2.TransactionRequest(transactionUuid = context.transactionID) response = stub.GetTransactionResult(txRequest, 2)", "getting Transaction Result from {0}, for user \"{1}\": {2}'.format(userRegistration.composeService,enrollId, response.msg)", "= userRegistration.getUserName() if 'metadata' in context: ccSpec.metadata = context.metadata try:", "secretMsg, composeService): self.secretMsg = secretMsg self.composeService = composeService self.tags =", "alias '{0}'\".format(ccAlias) # Create a new ChaincodeSpec by copying the", "new ChaincodeSpec by copying the deployed one newChaincodeSpec = chaincode_pb2.ChaincodeSpec()", "command by actually calling the python command # the update-cli.py", "python we # setup for running the update-cli p =", "= [] containerNamePrefix = os.path.basename(os.getcwd()) + \"_\" for namePart in", "the chaincodeSpec ctorMsg for invoke args = [] if 'table'", "m: # tagName reference found in args list tagName =", "tagName = m.groups()[0] # make sure the tagName is found", "'{0}'.\".format(ccAlias) args = getArgsFromContextForUser(context, enrollId) ccSpec = chaincode_pb2.ChaincodeSpec(type = chaincode_pb2.ChaincodeSpec.GOLANG,", "= ccSpec context.deployments[ccAlias] = ccSpec except: del stub raise def", "or None if not found''' deployment = None if 'deployments'", "not found in context\" values = [] containerNamePrefix = os.path.basename(os.getcwd())", "expect_success: raise subprocess.CalledProcessError(p.returncode, arg_list, output) return output, error, p.returncode class", "= subprocess.Popen(arg_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = p.communicate() if p.returncode", "context, \"users not found in context. Did you register a", "channel and UserRegistration instance. The channel is open to the", "None, \"Deployment NOT found for chaincode alias '{0}'\".format(ccAlias) # Create", "exists: '{0}'.\".format(ccAlias) args = getArgsFromContextForUser(context, enrollId) ccSpec = chaincode_pb2.ChaincodeSpec(type =", "stub.Invoke(ccInvocationSpec,2) return response def getArgsFromContextForUser(context, enrollId): # Update the chaincodeSpec", "alias for the specfied enrollId''' (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId)", "ccAlias in context.deployments: deployment = context.deployments[ccAlias] # else: # raise", "\"update-\" + arg_list[0] # We need to run the cli", "OR CONDITIONS OF ANY KIND, either express or implied. #", "values = [] containerNamePrefix = os.path.basename(os.getcwd()) + \"_\" for namePart", "# limitations under the License. # import os import re", "context: # There are function arguments userRegistration = getUserRegistration(context, enrollId)", "the License is distributed on an \"AS IS\" BASIS, #", "del stub raise def invokeChaincode(context, enrollId, ccAlias, functionName): # Get", "a user on a specific composeService def getUserRegistration(context, enrollId): userRegistration", "= [] if 'table' in context: # There are function", "= getArgsFromContextForUser(context, enrollId) ccSpec = chaincode_pb2.ChaincodeSpec(type = chaincode_pb2.ChaincodeSpec.GOLANG, chaincodeID =", "License. # import os import re import subprocess import devops_pb2", "the user registered on ipAddress = ipFromContainerNamePart(userRegistration.composeService, context.compose_containers) channel =", "= context.deployments[ccAlias] # else: # raise Exception(\"Deployment alias not found:", "chaincode_pb2.ChaincodeInvocationSpec(chaincodeSpec = newChaincodeSpec) (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub =", "= pattern.match(arg) if m: # tagName reference found in args", "m.groups()[0] # make sure the tagName is found in the", "__init__(self, secretMsg, composeService): self.secretMsg = secretMsg self.composeService = composeService self.tags", "return (channel, userRegistration) def getDeployment(context, ccAlias): '''Return a deployment with", "UserRegistration: def __init__(self, secretMsg, composeService): self.secretMsg = secretMsg self.composeService =", "system python, not the virtual env python we # setup", "ip = None containerNamePrefix = os.path.basename(os.getcwd()) + \"_\" for containerData", "ChaincodeSpec by copying the deployed one newChaincodeSpec = chaincode_pb2.ChaincodeSpec() newChaincodeSpec.CopyFrom(deployedCcSpec)", "channel is open to the composeService that the user registered", "def getUserRegistration(context, enrollId): userRegistration = None if 'users' in context:", "else: raise Exception(\"User has not been registered: {0}\".format(enrollId)) return userRegistration", "Registerses a user on a specific composeService def registerUser(context, secretMsg,", "container name\"\"\" ip = None containerNamePrefix = os.path.basename(os.getcwd()) + \"_\"", "bytes txResult = fabric_pb2.TransactionResult() txResult.ParseFromString(response.msg) return txResult def getGRPCChannel(ipAddress): channel", "to specify expressions referencing tags in the args list pattern", "string, int) output message, error message, return code \"\"\" #arg_list[0]", "the user to specify expressions referencing tags in the args", "userRegistration) = getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) txRequest = devops_pb2.TransactionRequest(transactionUuid", "law or agreed to in writing, software # distributed under", "if p.returncode != 0: if output is not None: print(\"Output:\\n\"", "governing permissions and # limitations under the License. # import", "None if 'users' in context: pass else: context.users = {}", "= devops_pb2.beta_create_Devops_stub(channel) response = stub.Invoke(ccInvocationSpec,2) return response def getArgsFromContextForUser(context, enrollId):", "{2}'.format(userRegistration.composeService,enrollId, response.msg) # Now grab the TransactionResult from the Msg", "tuple of GRPC channel and UserRegistration instance. The channel is", "make sure the tagName is found in the users tags", "not been registered: {0}\".format(enrollId)) return userRegistration def ipFromContainerNamePart(namePart, containerDataList): \"\"\"Returns", "else: context.users = {} if userName in context.users: raise Exception(\"User", "invoke args = getArgsFromContextForUser(context, enrollId) chaincodeInput = chaincode_pb2.ChaincodeInput(function = functionName,", "# import os import re import subprocess import devops_pb2 import", "raise subprocess.CalledProcessError(p.returncode, arg_list, output) return output, error, p.returncode class UserRegistration:", "for user '{1}'\".format(tagName, userRegistration.getUserName()) args.append(userRegistration.tags[tagName]) else: #No tag referenced, pass", "{} if ccAlias in context.deployments: deployment = context.deployments[ccAlias] # else:", "arguments @param expect_success: use False to return even if an", "= os.path.basename(os.getcwd()) + \"_\" for containerData in containerDataList: if containerData.containerName.startswith(containerNamePrefix", "Corp. 2016 All Rights Reserved. # # Licensed under the", "fabric_pb2 import chaincode_pb2 from grpc.beta import implementations def cli_call(context, arg_list,", "if an error occurred when executing the command @return: (string,", "return code \"\"\" #arg_list[0] = \"update-\" + arg_list[0] # We", "getGRPCChannel(ipAddress): channel = implementations.insecure_channel(ipAddress, 30303) print(\"Returning GRPC for address: {0}\".format(ipAddress))", "= stub.Invoke(ccInvocationSpec,2) return response def getArgsFromContextForUser(context, enrollId): # Update the", "a subprocess and return the results. @param context: the behave", "referenced, pass the arg args.append(arg) return args def getContainerDataValuesFromContext(context, aliases,", "not found for user '{1}'\".format(tagName, userRegistration.getUserName()) args.append(userRegistration.tags[tagName]) else: #No tag", "try: ccDeploymentSpec = stub.Deploy(ccSpec, 60) ccSpec.chaincodeID.name = ccDeploymentSpec.chaincodeSpec.chaincodeID.name context.grpcChaincodeSpec =", "may obtain a copy of the License at # #", "Update hte chaincodeSpec ctorMsg for invoke args = getArgsFromContextForUser(context, enrollId)", "userRegistration.getUserName() if 'metadata' in context: ccSpec.metadata = context.metadata try: ccDeploymentSpec", "= context.users[enrollId] else: raise Exception(\"User has not been registered: {0}\".format(enrollId))", "based upon a name part of the full container name\"\"\"", "specify expressions referencing tags in the args list pattern =", "message, error message, return code \"\"\" #arg_list[0] = \"update-\" +", "ip def getTxResult(context, enrollId): '''Returns the TransactionResult using the enrollId", "if 'table' in context: # There are function arguments userRegistration", "txRequest = devops_pb2.TransactionRequest(transactionUuid = context.transactionID) response = stub.GetTransactionResult(txRequest, 2) assert", "you have deployed a chaincode with this alias?\".format(ccAlias)) return deployment", "= secretMsg['enrollId'] if 'users' in context: pass else: context.users =", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "def __init__(self, secretMsg, composeService): self.secretMsg = secretMsg self.composeService = composeService", "self.lastResult = None def getUserName(self): return self.secretMsg['enrollId'] def getSecret(self): return", "context: pass else: context.users = {} if enrollId in context.users:", "the first line # which calls the system python, not", "[] if 'table' in context: # There are function arguments", "may not use this file except in compliance with the", "tagName in userRegistration.tags, \"TagName '{0}' not found for user '{1}'\".format(tagName,", "list command arguments @param expect_success: use False to return even", "part of the full container name\"\"\" assert 'compose_containers' in context,", "(channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) response =", "output, error, p.returncode class UserRegistration: def __init__(self, secretMsg, composeService): self.secretMsg", "ccSpec = chaincode_pb2.ChaincodeSpec(type = chaincode_pb2.ChaincodeSpec.GOLANG, chaincodeID = chaincode_pb2.ChaincodeID(name=\"\",path=chaincodePath), ctorMsg =", "= chaincode_pb2.ChaincodeSpec.GOLANG, chaincodeID = chaincode_pb2.ChaincodeID(name=\"\",path=chaincodePath), ctorMsg = chaincode_pb2.ChaincodeInput(function = ctor,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "chaincode alias deployedCcSpec = getDeployment(context, ccAlias) assert deployedCcSpec != None,", "a user?\" assert 'compose_containers' in context, \"compose_containers not found in", "and # limitations under the License. # import os import", "as the first line # which calls the system python,", "this file except in compliance with the License. # You", "output, error = p.communicate() if p.returncode != 0: if output", "the user registered with.''' userRegistration = getUserRegistration(context, enrollId) # Get", "tagName is found in the users tags assert tagName in", "print(\"Returning GRPC for address: {0}\".format(ipAddress)) return channel def getGRPCChannelAndUser(context, enrollId):", "command @return: (string, string, int) output message, error message, return", "else: # raise Exception(\"Deployment alias not found: '{0}'. Are you", "ip = containerData.ipAddress if ip == None: raise Exception(\"Could not", "getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) # Make sure deployment alias", "alias does NOT already exist assert getDeployment(context, ccAlias) == None,", "enrollId, ccAlias, functionName): # Get the deployment for the supplied", "{0}\".format(userName)) context.users[userName] = UserRegistration(secretMsg, composeService) # Registerses a user on", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "'''Returns the TransactionResult using the enrollId supplied''' assert 'users' in", "a chaincode with the specified alias for the specfied enrollId'''", "= secretMsg self.composeService = composeService self.tags = {} self.lastResult =", "CLI command in a subprocess and return the results. @param", "p.returncode != 0: if output is not None: print(\"Output:\\n\" +", "the deployed one newChaincodeSpec = chaincode_pb2.ChaincodeSpec() newChaincodeSpec.CopyFrom(deployedCcSpec) # Update hte", "# # Licensed under the Apache License, Version 2.0 (the", "to the composeService that the user registered with.''' userRegistration =", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "subprocess and return the results. @param context: the behave context", "else: context.users = {} if enrollId in context.users: userRegistration =", "Get the IP address of the server that the user", "python, not the virtual env python we # setup for", "in context.deployments: deployment = context.deployments[ccAlias] # else: # raise Exception(\"Deployment", "a name part of the full container name\"\"\" ip =", "txResult = fabric_pb2.TransactionResult() txResult.ParseFromString(response.msg) return txResult def getGRPCChannel(ipAddress): channel =", "userRegistration = None if 'users' in context: pass else: context.users", "not found in context. Did you register a user?\" assert", "the Msg bytes txResult = fabric_pb2.TransactionResult() txResult.ParseFromString(response.msg) return txResult def", "alias from prior deployment, or None if not found''' deployment", "this alias?\".format(ccAlias)) return deployment def deployChaincode(context, enrollId, chaincodePath, ccAlias, ctor):", "the specified alias for the specfied enrollId''' (channel, userRegistration) =", "list pattern = re.compile('\\{(.*)\\}$') for arg in context.table[0].cells: m =", "enrollId) # Get the IP address of the server that", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "functionName): # Get the deployment for the supplied chaincode alias", "subprocess.Popen(arg_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = p.communicate() if p.returncode !=", "txResult.ParseFromString(response.msg) return txResult def getGRPCChannel(ipAddress): channel = implementations.insecure_channel(ipAddress, 30303) print(\"Returning", "2016 All Rights Reserved. # # Licensed under the Apache", "return ip def getTxResult(context, enrollId): '''Returns the TransactionResult using the", "message, return code \"\"\" #arg_list[0] = \"update-\" + arg_list[0] #", "composeService def registerUser(context, secretMsg, composeService): userName = secretMsg['enrollId'] if 'users'", "the IPAddress based upon a name part of the full", "m = pattern.match(arg) if m: # tagName reference found in", "calls the system python, not the virtual env python we", "in context.users: userRegistration = context.users[enrollId] else: raise Exception(\"User has not", "for invoke args = [] if 'table' in context: #", "return deployment def deployChaincode(context, enrollId, chaincodePath, ccAlias, ctor): '''Deploy a", "with this alias?\".format(ccAlias)) return deployment def deployChaincode(context, enrollId, chaincodePath, ccAlias,", "context.users = {} if enrollId in context.users: userRegistration = context.users[enrollId]", "in context: ccSpec.metadata = context.metadata try: ccDeploymentSpec = stub.Deploy(ccSpec, 60)", "<reponame>TarantulaTechnology/fabric5 # Copyright IBM Corp. 2016 All Rights Reserved. #", "arg_list, expect_success=True): \"\"\"Executes a CLI command in a subprocess and", "userRegistration def ipFromContainerNamePart(namePart, containerDataList): \"\"\"Returns the IPAddress based upon a", "deployment for the supplied chaincode alias deployedCcSpec = getDeployment(context, ccAlias)", "else: context.deployments = {} if ccAlias in context.deployments: deployment =", "+ arg_list[0] # We need to run the cli command", "deployment alias does NOT already exist assert getDeployment(context, ccAlias) ==", "user registered with.''' userRegistration = getUserRegistration(context, enrollId) # Get the", "return channel def getGRPCChannelAndUser(context, enrollId): '''Returns a tuple of GRPC", "for containerData in context.compose_containers: if containerData.containerName.startswith(containerNamePrefix + namePart): values.append(callback(containerData)) break", ") newChaincodeSpec.ctorMsg.CopyFrom(chaincodeInput) ccInvocationSpec = chaincode_pb2.ChaincodeInvocationSpec(chaincodeSpec = newChaincodeSpec) (channel, userRegistration) =", "chaincode_pb2.ChaincodeInput(function = ctor, args = args)) ccSpec.secureContext = userRegistration.getUserName() if", "script has a #!/bin/python as the first line # which", "using the enrollId supplied''' assert 'users' in context, \"users not", "def deployChaincode(context, enrollId, chaincodePath, ccAlias, ctor): '''Deploy a chaincode with", "'compose_containers' in context, \"compose_containers not found in context\" values =", "in context. Did you register a user?\" assert 'compose_containers' in", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "\"\"\" #arg_list[0] = \"update-\" + arg_list[0] # We need to", "context.users[enrollId] else: raise Exception(\"User has not been registered: {0}\".format(enrollId)) return", "stub = devops_pb2.beta_create_Devops_stub(channel) response = stub.Invoke(ccInvocationSpec,2) return response def getArgsFromContextForUser(context,", "found in context\" values = [] containerNamePrefix = os.path.basename(os.getcwd()) +", "userRegistration = getUserRegistration(context, enrollId) # Allow the user to specify", "30303) print(\"Returning GRPC for address: {0}\".format(ipAddress)) return channel def getGRPCChannelAndUser(context,", "context.metadata try: ccDeploymentSpec = stub.Deploy(ccSpec, 60) ccSpec.chaincodeID.name = ccDeploymentSpec.chaincodeSpec.chaincodeID.name context.grpcChaincodeSpec", "{0}\".format(namePart)) return ip def getTxResult(context, enrollId): '''Returns the TransactionResult using", "the TransactionResult using the enrollId supplied''' assert 'users' in context,", "permissions and # limitations under the License. # import os", "{} if enrollId in context.users: userRegistration = context.users[enrollId] else: raise", "context.transactionID) response = stub.GetTransactionResult(txRequest, 2) assert response.status == fabric_pb2.Response.SUCCESS, 'Failure", "under the License. # import os import re import subprocess", "self.composeService = composeService self.tags = {} self.lastResult = None def", "context.users: raise Exception(\"User already registered: {0}\".format(userName)) context.users[userName] = UserRegistration(secretMsg, composeService)", "or implied. # See the License for the specific language", "{} if userName in context.users: raise Exception(\"User already registered: {0}\".format(userName))", "Rights Reserved. # # Licensed under the Apache License, Version", "a specific composeService def registerUser(context, secretMsg, composeService): userName = secretMsg['enrollId']", "Message:\\n\" + error) if expect_success: raise subprocess.CalledProcessError(p.returncode, arg_list, output) return", "alias already exists: '{0}'.\".format(ccAlias) args = getArgsFromContextForUser(context, enrollId) ccSpec =", "#!/bin/python as the first line # which calls the system", "+ output) if error is not None: print(\"Error Message:\\n\" +", "tagName reference found in args list tagName = m.groups()[0] #", "cli_call(context, arg_list, expect_success=True): \"\"\"Executes a CLI command in a subprocess", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "= getDeployment(context, ccAlias) assert deployedCcSpec != None, \"Deployment NOT found", "def getTxResult(context, enrollId): '''Returns the TransactionResult using the enrollId supplied'''", "subprocess.CalledProcessError(p.returncode, arg_list, output) return output, error, p.returncode class UserRegistration: def", "is not None: print(\"Output:\\n\" + output) if error is not", "def getSecret(self): return devops_pb2.Secret(enrollId=self.secretMsg['enrollId'],enrollSecret=self.secretMsg['enrollSecret']) # Registerses a user on a", "context\" (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) txRequest", "containerData.containerName.startswith(containerNamePrefix + namePart): ip = containerData.ipAddress if ip == None:", "# Now grab the TransactionResult from the Msg bytes txResult", "pass else: context.users = {} if userName in context.users: raise", "ccSpec except: del stub raise def invokeChaincode(context, enrollId, ccAlias, functionName):", "to run the cli command by actually calling the python", "error is not None: print(\"Error Message:\\n\" + error) if expect_success:", "def getContainerDataValuesFromContext(context, aliases, callback): \"\"\"Returns the IPAddress based upon a", "chaincodePath, ccAlias, ctor): '''Deploy a chaincode with the specified alias", "= args ) newChaincodeSpec.ctorMsg.CopyFrom(chaincodeInput) ccInvocationSpec = chaincode_pb2.ChaincodeInvocationSpec(chaincodeSpec = newChaincodeSpec) (channel,", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "a #!/bin/python as the first line # which calls the", "chaincode with this alias?\".format(ccAlias)) return deployment def deployChaincode(context, enrollId, chaincodePath,", "already exists: '{0}'.\".format(ccAlias) args = getArgsFromContextForUser(context, enrollId) ccSpec = chaincode_pb2.ChaincodeSpec(type", "= ccSpec except: del stub raise def invokeChaincode(context, enrollId, ccAlias,", "composeService): self.secretMsg = secretMsg self.composeService = composeService self.tags = {}", "Exception(\"Deployment alias not found: '{0}'. Are you sure you have", "import devops_pb2 import fabric_pb2 import chaincode_pb2 from grpc.beta import implementations", "enrollId): userRegistration = None if 'users' in context: pass else:", "= getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) response = stub.Invoke(ccInvocationSpec,2) return", "[] containerNamePrefix = os.path.basename(os.getcwd()) + \"_\" for namePart in aliases:", "assert response.status == fabric_pb2.Response.SUCCESS, 'Failure getting Transaction Result from {0},", "context.users: userRegistration = context.users[enrollId] else: raise Exception(\"User has not been", "that the user registered on ipAddress = ipFromContainerNamePart(userRegistration.composeService, context.compose_containers) channel", "is found in the users tags assert tagName in userRegistration.tags,", "devops_pb2 import fabric_pb2 import chaincode_pb2 from grpc.beta import implementations def", "if userName in context.users: raise Exception(\"User already registered: {0}\".format(userName)) context.users[userName]", "enrollId): '''Returns a tuple of GRPC channel and UserRegistration instance.", "Exception(\"Could not find container with namePart = {0}\".format(namePart)) return ip", "NOT already exist assert getDeployment(context, ccAlias) == None, \"Deployment alias", "subprocess import devops_pb2 import fabric_pb2 import chaincode_pb2 from grpc.beta import", "for the specfied enrollId''' (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub", "Registerses a user on a specific composeService def getUserRegistration(context, enrollId):", "= {} if userName in context.users: raise Exception(\"User already registered:", "== None: raise Exception(\"Could not find container with namePart =", "(the \"License\"); # you may not use this file except", "ccSpec.chaincodeID.name = ccDeploymentSpec.chaincodeSpec.chaincodeID.name context.grpcChaincodeSpec = ccSpec context.deployments[ccAlias] = ccSpec except:", "error, p.returncode class UserRegistration: def __init__(self, secretMsg, composeService): self.secretMsg =", "# you may not use this file except in compliance", "implementations.insecure_channel(ipAddress, 30303) print(\"Returning GRPC for address: {0}\".format(ipAddress)) return channel def", "ctorMsg for invoke args = getArgsFromContextForUser(context, enrollId) chaincodeInput = chaincode_pb2.ChaincodeInput(function", "getUserRegistration(context, enrollId) # Get the IP address of the server", "re import subprocess import devops_pb2 import fabric_pb2 import chaincode_pb2 from", "getDeployment(context, ccAlias) assert deployedCcSpec != None, \"Deployment NOT found for", "code \"\"\" #arg_list[0] = \"update-\" + arg_list[0] # We need", "Exception(\"User has not been registered: {0}\".format(enrollId)) return userRegistration def ipFromContainerNamePart(namePart,", "getArgsFromContextForUser(context, enrollId) chaincodeInput = chaincode_pb2.ChaincodeInput(function = functionName, args = args", "There are function arguments userRegistration = getUserRegistration(context, enrollId) # Allow", "\"{1}\": {2}'.format(userRegistration.composeService,enrollId, response.msg) # Now grab the TransactionResult from the", "the python command # the update-cli.py script has a #!/bin/python", "args list tagName = m.groups()[0] # make sure the tagName", "'''Deploy a chaincode with the specified alias for the specfied", "register a user?\" assert 'compose_containers' in context, \"compose_containers not found", "not found in context\" (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub", "ccAlias, functionName): # Get the deployment for the supplied chaincode", "import subprocess import devops_pb2 import fabric_pb2 import chaincode_pb2 from grpc.beta", "args = getArgsFromContextForUser(context, enrollId) chaincodeInput = chaincode_pb2.ChaincodeInput(function = functionName, args", "context: pass else: context.users = {} if userName in context.users:", "# # Unless required by applicable law or agreed to", "devops_pb2.Secret(enrollId=self.secretMsg['enrollId'],enrollSecret=self.secretMsg['enrollSecret']) # Registerses a user on a specific composeService def", "ccSpec.metadata = context.metadata try: ccDeploymentSpec = stub.Deploy(ccSpec, 60) ccSpec.chaincodeID.name =", "ccAlias) assert deployedCcSpec != None, \"Deployment NOT found for chaincode", "context.users = {} if userName in context.users: raise Exception(\"User already", "None, \"Deployment alias already exists: '{0}'.\".format(ccAlias) args = getArgsFromContextForUser(context, enrollId)", "in containerDataList: if containerData.containerName.startswith(containerNamePrefix + namePart): ip = containerData.ipAddress if", "tags assert tagName in userRegistration.tags, \"TagName '{0}' not found for", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "#arg_list[0] = \"update-\" + arg_list[0] # We need to run", "# the update-cli.py script has a #!/bin/python as the first", "Make sure deployment alias does NOT already exist assert getDeployment(context,", "= getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) txRequest = devops_pb2.TransactionRequest(transactionUuid =", "Version 2.0 (the \"License\"); # you may not use this", "results. @param context: the behave context @param arg_list: a list", "chaincode_pb2 from grpc.beta import implementations def cli_call(context, arg_list, expect_success=True): \"\"\"Executes", "cli command by actually calling the python command # the", "namePart = {0}\".format(namePart)) return ip def getTxResult(context, enrollId): '''Returns the", "devops_pb2.beta_create_Devops_stub(channel) response = stub.Invoke(ccInvocationSpec,2) return response def getArgsFromContextForUser(context, enrollId): #", "newChaincodeSpec = chaincode_pb2.ChaincodeSpec() newChaincodeSpec.CopyFrom(deployedCcSpec) # Update hte chaincodeSpec ctorMsg for", "chaincodeSpec ctorMsg for invoke args = getArgsFromContextForUser(context, enrollId) chaincodeInput =", "assert 'compose_containers' in context, \"compose_containers not found in context\" values", "Create a new ChaincodeSpec by copying the deployed one newChaincodeSpec", "a user on a specific composeService def registerUser(context, secretMsg, composeService):", "not find container with namePart = {0}\".format(namePart)) return ip def", "the full container name\"\"\" assert 'compose_containers' in context, \"compose_containers not", "getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) response = stub.Invoke(ccInvocationSpec,2) return response", "implied. # See the License for the specific language governing", "error message, return code \"\"\" #arg_list[0] = \"update-\" + arg_list[0]", "under the Apache License, Version 2.0 (the \"License\"); # you", "ctor, args = args)) ccSpec.secureContext = userRegistration.getUserName() if 'metadata' in", "assert getDeployment(context, ccAlias) == None, \"Deployment alias already exists: '{0}'.\".format(ccAlias)", "registered with.''' userRegistration = getUserRegistration(context, enrollId) # Get the IP", "of GRPC channel and UserRegistration instance. The channel is open", "in args list tagName = m.groups()[0] # make sure the", "args = args ) newChaincodeSpec.ctorMsg.CopyFrom(chaincodeInput) ccInvocationSpec = chaincode_pb2.ChaincodeInvocationSpec(chaincodeSpec = newChaincodeSpec)", "getUserRegistration(context, enrollId): userRegistration = None if 'users' in context: pass", "update-cli.py script has a #!/bin/python as the first line #", "context.grpcChaincodeSpec = ccSpec context.deployments[ccAlias] = ccSpec except: del stub raise", "in context.compose_containers: if containerData.containerName.startswith(containerNamePrefix + namePart): values.append(callback(containerData)) break return values", "by applicable law or agreed to in writing, software #", "is not None: print(\"Error Message:\\n\" + error) if expect_success: raise", "\"TagName '{0}' not found for user '{1}'\".format(tagName, userRegistration.getUserName()) args.append(userRegistration.tags[tagName]) else:", "by actually calling the python command # the update-cli.py script", "# Registerses a user on a specific composeService def getUserRegistration(context,", "= {} if enrollId in context.users: userRegistration = context.users[enrollId] else:", "tag referenced, pass the arg args.append(arg) return args def getContainerDataValuesFromContext(context,", "Get the deployment for the supplied chaincode alias deployedCcSpec =", "stderr=subprocess.PIPE) output, error = p.communicate() if p.returncode != 0: if", "= functionName, args = args ) newChaincodeSpec.ctorMsg.CopyFrom(chaincodeInput) ccInvocationSpec = chaincode_pb2.ChaincodeInvocationSpec(chaincodeSpec", "arg_list, output) return output, error, p.returncode class UserRegistration: def __init__(self,", "!= 0: if output is not None: print(\"Output:\\n\" + output)", "a name part of the full container name\"\"\" assert 'compose_containers'", "= chaincode_pb2.ChaincodeInput(function = functionName, args = args ) newChaincodeSpec.ctorMsg.CopyFrom(chaincodeInput) ccInvocationSpec", "specfied enrollId''' (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel)", "name part of the full container name\"\"\" assert 'compose_containers' in", "# raise Exception(\"Deployment alias not found: '{0}'. Are you sure", "args ) newChaincodeSpec.ctorMsg.CopyFrom(chaincodeInput) ccInvocationSpec = chaincode_pb2.ChaincodeInvocationSpec(chaincodeSpec = newChaincodeSpec) (channel, userRegistration)", "in the users tags assert tagName in userRegistration.tags, \"TagName '{0}'", "and return the results. @param context: the behave context @param", "context: pass else: context.deployments = {} if ccAlias in context.deployments:", "Msg bytes txResult = fabric_pb2.TransactionResult() txResult.ParseFromString(response.msg) return txResult def getGRPCChannel(ipAddress):", "the specfied enrollId''' (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub =", "arguments userRegistration = getUserRegistration(context, enrollId) # Allow the user to", "with the specified alias for the specfied enrollId''' (channel, userRegistration)", "\"compose_containers not found in context\" (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId)", "containerData in context.compose_containers: if containerData.containerName.startswith(containerNamePrefix + namePart): values.append(callback(containerData)) break return", "callback): \"\"\"Returns the IPAddress based upon a name part of", "ipFromContainerNamePart(namePart, containerDataList): \"\"\"Returns the IPAddress based upon a name part", "'''Returns a tuple of GRPC channel and UserRegistration instance. The", "userRegistration.getUserName()) args.append(userRegistration.tags[tagName]) else: #No tag referenced, pass the arg args.append(arg)", "are function arguments userRegistration = getUserRegistration(context, enrollId) # Allow the", "Did you register a user?\" assert 'compose_containers' in context, \"compose_containers", "args = getArgsFromContextForUser(context, enrollId) ccSpec = chaincode_pb2.ChaincodeSpec(type = chaincode_pb2.ChaincodeSpec.GOLANG, chaincodeID", "in context: # There are function arguments userRegistration = getUserRegistration(context,", "context.deployments: deployment = context.deployments[ccAlias] # else: # raise Exception(\"Deployment alias", "getContainerDataValuesFromContext(context, aliases, callback): \"\"\"Returns the IPAddress based upon a name", "= UserRegistration(secretMsg, composeService) # Registerses a user on a specific", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "the enrollId supplied''' assert 'users' in context, \"users not found", "txResult def getGRPCChannel(ipAddress): channel = implementations.insecure_channel(ipAddress, 30303) print(\"Returning GRPC for", "found in context\" (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub =", "Unless required by applicable law or agreed to in writing,", "tags in the args list pattern = re.compile('\\{(.*)\\}$') for arg", "the users tags assert tagName in userRegistration.tags, \"TagName '{0}' not", "context, \"compose_containers not found in context\" (channel, userRegistration) = getGRPCChannelAndUser(context,", "ccSpec.secureContext = userRegistration.getUserName() if 'metadata' in context: ccSpec.metadata = context.metadata", "context.users[userName] = UserRegistration(secretMsg, composeService) # Registerses a user on a", "'users' in context, \"users not found in context. Did you", "upon a name part of the full container name\"\"\" ip", "newChaincodeSpec) (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) response", "deployedCcSpec != None, \"Deployment NOT found for chaincode alias '{0}'\".format(ccAlias)", "'{0}'. Are you sure you have deployed a chaincode with", "class UserRegistration: def __init__(self, secretMsg, composeService): self.secretMsg = secretMsg self.composeService", "the specific language governing permissions and # limitations under the", "if enrollId in context.users: userRegistration = context.users[enrollId] else: raise Exception(\"User", "= getGRPCChannel(ipAddress) return (channel, userRegistration) def getDeployment(context, ccAlias): '''Return a", "in context.users: raise Exception(\"User already registered: {0}\".format(userName)) context.users[userName] = UserRegistration(secretMsg,", "for user \"{1}\": {2}'.format(userRegistration.composeService,enrollId, response.msg) # Now grab the TransactionResult", "context: the behave context @param arg_list: a list command arguments", "None: print(\"Output:\\n\" + output) if error is not None: print(\"Error", "applicable law or agreed to in writing, software # distributed", "{} self.lastResult = None def getUserName(self): return self.secretMsg['enrollId'] def getSecret(self):", "response.status == fabric_pb2.Response.SUCCESS, 'Failure getting Transaction Result from {0}, for", "= args)) ccSpec.secureContext = userRegistration.getUserName() if 'metadata' in context: ccSpec.metadata", "the args list pattern = re.compile('\\{(.*)\\}$') for arg in context.table[0].cells:", "chaincode_pb2.ChaincodeID(name=\"\",path=chaincodePath), ctorMsg = chaincode_pb2.ChaincodeInput(function = ctor, args = args)) ccSpec.secureContext", "enrollId) ccSpec = chaincode_pb2.ChaincodeSpec(type = chaincode_pb2.ChaincodeSpec.GOLANG, chaincodeID = chaincode_pb2.ChaincodeID(name=\"\",path=chaincodePath), ctorMsg", "args.append(userRegistration.tags[tagName]) else: #No tag referenced, pass the arg args.append(arg) return", "except: del stub raise def invokeChaincode(context, enrollId, ccAlias, functionName): #", "chaincodeID = chaincode_pb2.ChaincodeID(name=\"\",path=chaincodePath), ctorMsg = chaincode_pb2.ChaincodeInput(function = ctor, args =", "'users' in context: pass else: context.users = {} if enrollId", "userRegistration) = getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) response = stub.Invoke(ccInvocationSpec,2)", "in writing, software # distributed under the License is distributed", "use False to return even if an error occurred when", "first line # which calls the system python, not the", "has a #!/bin/python as the first line # which calls", "namePart): ip = containerData.ipAddress if ip == None: raise Exception(\"Could", "= None if 'users' in context: pass else: context.users =", "find container with namePart = {0}\".format(namePart)) return ip def getTxResult(context,", "context.deployments[ccAlias] # else: # raise Exception(\"Deployment alias not found: '{0}'.", "= getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) # Make sure deployment", "output) if error is not None: print(\"Error Message:\\n\" + error)", "newChaincodeSpec.CopyFrom(deployedCcSpec) # Update hte chaincodeSpec ctorMsg for invoke args =", "the command @return: (string, string, int) output message, error message,", "run the cli command by actually calling the python command", "have deployed a chaincode with this alias?\".format(ccAlias)) return deployment def", "command in a subprocess and return the results. @param context:", "getGRPCChannelAndUser(context, enrollId): '''Returns a tuple of GRPC channel and UserRegistration", "exist assert getDeployment(context, ccAlias) == None, \"Deployment alias already exists:", "return userRegistration def ipFromContainerNamePart(namePart, containerDataList): \"\"\"Returns the IPAddress based upon", "in context.table[0].cells: m = pattern.match(arg) if m: # tagName reference", "== fabric_pb2.Response.SUCCESS, 'Failure getting Transaction Result from {0}, for user", "chaincode_pb2.ChaincodeSpec() newChaincodeSpec.CopyFrom(deployedCcSpec) # Update hte chaincodeSpec ctorMsg for invoke args", "= {} if ccAlias in context.deployments: deployment = context.deployments[ccAlias] #", "The channel is open to the composeService that the user", "IP address of the server that the user registered on", "(string, string, int) output message, error message, return code \"\"\"", "not the virtual env python we # setup for running", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "import implementations def cli_call(context, arg_list, expect_success=True): \"\"\"Executes a CLI command", "in context: pass else: context.users = {} if userName in", "# You may obtain a copy of the License at", "in a subprocess and return the results. @param context: the", "Update the chaincodeSpec ctorMsg for invoke args = [] if", "Allow the user to specify expressions referencing tags in the", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "found: '{0}'. Are you sure you have deployed a chaincode", "you sure you have deployed a chaincode with this alias?\".format(ccAlias))", "registered: {0}\".format(userName)) context.users[userName] = UserRegistration(secretMsg, composeService) # Registerses a user", "GRPC for address: {0}\".format(ipAddress)) return channel def getGRPCChannelAndUser(context, enrollId): '''Returns", "deployment, or None if not found''' deployment = None if", "supplied''' assert 'users' in context, \"users not found in context.", "in the args list pattern = re.compile('\\{(.*)\\}$') for arg in", "= stub.GetTransactionResult(txRequest, 2) assert response.status == fabric_pb2.Response.SUCCESS, 'Failure getting Transaction", "calling the python command # the update-cli.py script has a", "already exist assert getDeployment(context, ccAlias) == None, \"Deployment alias already", "pass the arg args.append(arg) return args def getContainerDataValuesFromContext(context, aliases, callback):", "on ipAddress = ipFromContainerNamePart(userRegistration.composeService, context.compose_containers) channel = getGRPCChannel(ipAddress) return (channel,", "user on a specific composeService def registerUser(context, secretMsg, composeService): userName", "context.deployments[ccAlias] = ccSpec except: del stub raise def invokeChaincode(context, enrollId,", "def getUserName(self): return self.secretMsg['enrollId'] def getSecret(self): return devops_pb2.Secret(enrollId=self.secretMsg['enrollId'],enrollSecret=self.secretMsg['enrollSecret']) # Registerses", "\"users not found in context. Did you register a user?\"", "channel = implementations.insecure_channel(ipAddress, 30303) print(\"Returning GRPC for address: {0}\".format(ipAddress)) return", "sure the tagName is found in the users tags assert", "registered: {0}\".format(enrollId)) return userRegistration def ipFromContainerNamePart(namePart, containerDataList): \"\"\"Returns the IPAddress", "int) output message, error message, return code \"\"\" #arg_list[0] =", "= devops_pb2.beta_create_Devops_stub(channel) # Make sure deployment alias does NOT already", "found in the users tags assert tagName in userRegistration.tags, \"TagName", "def ipFromContainerNamePart(namePart, containerDataList): \"\"\"Returns the IPAddress based upon a name", "the License for the specific language governing permissions and #", "to return even if an error occurred when executing the", "= {0}\".format(namePart)) return ip def getTxResult(context, enrollId): '''Returns the TransactionResult", "you register a user?\" assert 'compose_containers' in context, \"compose_containers not", "in context, \"compose_containers not found in context\" (channel, userRegistration) =", "Are you sure you have deployed a chaincode with this", "Apache License, Version 2.0 (the \"License\"); # you may not", "= chaincode_pb2.ChaincodeSpec(type = chaincode_pb2.ChaincodeSpec.GOLANG, chaincodeID = chaincode_pb2.ChaincodeID(name=\"\",path=chaincodePath), ctorMsg = chaincode_pb2.ChaincodeInput(function", "args list pattern = re.compile('\\{(.*)\\}$') for arg in context.table[0].cells: m", "'{0}' not found for user '{1}'\".format(tagName, userRegistration.getUserName()) args.append(userRegistration.tags[tagName]) else: #No", "= \"update-\" + arg_list[0] # We need to run the", "either express or implied. # See the License for the", "and UserRegistration instance. The channel is open to the composeService", "re.compile('\\{(.*)\\}$') for arg in context.table[0].cells: m = pattern.match(arg) if m:", "channel def getGRPCChannelAndUser(context, enrollId): '''Returns a tuple of GRPC channel", "import fabric_pb2 import chaincode_pb2 from grpc.beta import implementations def cli_call(context,", "args.append(arg) return args def getContainerDataValuesFromContext(context, aliases, callback): \"\"\"Returns the IPAddress", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "# Get the deployment for the supplied chaincode alias deployedCcSpec", "sure deployment alias does NOT already exist assert getDeployment(context, ccAlias)", "enrollId in context.users: userRegistration = context.users[enrollId] else: raise Exception(\"User has", "container with namePart = {0}\".format(namePart)) return ip def getTxResult(context, enrollId):", "found for chaincode alias '{0}'\".format(ccAlias) # Create a new ChaincodeSpec", "args = [] if 'table' in context: # There are", "enrollId): '''Returns the TransactionResult using the enrollId supplied''' assert 'users'", "a CLI command in a subprocess and return the results.", "deployed a chaincode with this alias?\".format(ccAlias)) return deployment def deployChaincode(context,", "does NOT already exist assert getDeployment(context, ccAlias) == None, \"Deployment", "an error occurred when executing the command @return: (string, string,", "user?\" assert 'compose_containers' in context, \"compose_containers not found in context\"", "containerData.ipAddress if ip == None: raise Exception(\"Could not find container", "context.table[0].cells: m = pattern.match(arg) if m: # tagName reference found", "python command # the update-cli.py script has a #!/bin/python as", "chaincode alias '{0}'\".format(ccAlias) # Create a new ChaincodeSpec by copying", "reference found in args list tagName = m.groups()[0] # make", "if containerData.containerName.startswith(containerNamePrefix + namePart): ip = containerData.ipAddress if ip ==", "response = stub.Invoke(ccInvocationSpec,2) return response def getArgsFromContextForUser(context, enrollId): # Update", "userRegistration) def getDeployment(context, ccAlias): '''Return a deployment with chaincode alias", "getArgsFromContextForUser(context, enrollId) ccSpec = chaincode_pb2.ChaincodeSpec(type = chaincode_pb2.ChaincodeSpec.GOLANG, chaincodeID = chaincode_pb2.ChaincodeID(name=\"\",path=chaincodePath),", "the results. @param context: the behave context @param arg_list: a", "raise def invokeChaincode(context, enrollId, ccAlias, functionName): # Get the deployment", "occurred when executing the command @return: (string, string, int) output", "full container name\"\"\" assert 'compose_containers' in context, \"compose_containers not found", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = p.communicate() if p.returncode != 0:", "not None: print(\"Error Message:\\n\" + error) if expect_success: raise subprocess.CalledProcessError(p.returncode,", "secretMsg self.composeService = composeService self.tags = {} self.lastResult = None", "assert 'compose_containers' in context, \"compose_containers not found in context\" (channel,", "userName in context.users: raise Exception(\"User already registered: {0}\".format(userName)) context.users[userName] =", "# Get the IP address of the server that the", "for address: {0}\".format(ipAddress)) return channel def getGRPCChannelAndUser(context, enrollId): '''Returns a", "composeService) # Registerses a user on a specific composeService def", "+ error) if expect_success: raise subprocess.CalledProcessError(p.returncode, arg_list, output) return output,", "Exception(\"User already registered: {0}\".format(userName)) context.users[userName] = UserRegistration(secretMsg, composeService) # Registerses", "ccAlias) == None, \"Deployment alias already exists: '{0}'.\".format(ccAlias) args =", "context @param arg_list: a list command arguments @param expect_success: use", "chaincodeSpec ctorMsg for invoke args = [] if 'table' in", "os.path.basename(os.getcwd()) + \"_\" for namePart in aliases: for containerData in", "the IP address of the server that the user registered", "context.deployments = {} if ccAlias in context.deployments: deployment = context.deployments[ccAlias]", "ccDeploymentSpec.chaincodeSpec.chaincodeID.name context.grpcChaincodeSpec = ccSpec context.deployments[ccAlias] = ccSpec except: del stub", "already registered: {0}\".format(userName)) context.users[userName] = UserRegistration(secretMsg, composeService) # Registerses a", "self.secretMsg = secretMsg self.composeService = composeService self.tags = {} self.lastResult", "raise Exception(\"Deployment alias not found: '{0}'. Are you sure you", "the full container name\"\"\" ip = None containerNamePrefix = os.path.basename(os.getcwd())", "= ipFromContainerNamePart(userRegistration.composeService, context.compose_containers) channel = getGRPCChannel(ipAddress) return (channel, userRegistration) def", "def getArgsFromContextForUser(context, enrollId): # Update the chaincodeSpec ctorMsg for invoke", "limitations under the License. # import os import re import", "the composeService that the user registered with.''' userRegistration = getUserRegistration(context,", "hte chaincodeSpec ctorMsg for invoke args = getArgsFromContextForUser(context, enrollId) chaincodeInput", "found in args list tagName = m.groups()[0] # make sure", "virtual env python we # setup for running the update-cli", "in context\" values = [] containerNamePrefix = os.path.basename(os.getcwd()) + \"_\"", "containerNamePrefix = os.path.basename(os.getcwd()) + \"_\" for containerData in containerDataList: if", "the virtual env python we # setup for running the", "stub = devops_pb2.beta_create_Devops_stub(channel) # Make sure deployment alias does NOT", "60) ccSpec.chaincodeID.name = ccDeploymentSpec.chaincodeSpec.chaincodeID.name context.grpcChaincodeSpec = ccSpec context.deployments[ccAlias] = ccSpec", "getDeployment(context, ccAlias) == None, \"Deployment alias already exists: '{0}'.\".format(ccAlias) args", "\"License\"); # you may not use this file except in", "# else: # raise Exception(\"Deployment alias not found: '{0}'. Are", "2) assert response.status == fabric_pb2.Response.SUCCESS, 'Failure getting Transaction Result from", "enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) response = stub.Invoke(ccInvocationSpec,2) return response def", "context, \"compose_containers not found in context\" values = [] containerNamePrefix", "address of the server that the user registered on ipAddress", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "the License. # import os import re import subprocess import", "Transaction Result from {0}, for user \"{1}\": {2}'.format(userRegistration.composeService,enrollId, response.msg) #", "for invoke args = getArgsFromContextForUser(context, enrollId) chaincodeInput = chaincode_pb2.ChaincodeInput(function =", "args def getContainerDataValuesFromContext(context, aliases, callback): \"\"\"Returns the IPAddress based upon", "# distributed under the License is distributed on an \"AS", "NOT found for chaincode alias '{0}'\".format(ccAlias) # Create a new", "= chaincode_pb2.ChaincodeInvocationSpec(chaincodeSpec = newChaincodeSpec) (channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub", "= context.metadata try: ccDeploymentSpec = stub.Deploy(ccSpec, 60) ccSpec.chaincodeID.name = ccDeploymentSpec.chaincodeSpec.chaincodeID.name", "# Unless required by applicable law or agreed to in", "devops_pb2.beta_create_Devops_stub(channel) # Make sure deployment alias does NOT already exist", "# setup for running the update-cli p = subprocess.Popen(arg_list, stdout=subprocess.PIPE,", "return args def getContainerDataValuesFromContext(context, aliases, callback): \"\"\"Returns the IPAddress based", "= re.compile('\\{(.*)\\}$') for arg in context.table[0].cells: m = pattern.match(arg) if", "error) if expect_success: raise subprocess.CalledProcessError(p.returncode, arg_list, output) return output, error,", "setup for running the update-cli p = subprocess.Popen(arg_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE)", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "alias deployedCcSpec = getDeployment(context, ccAlias) assert deployedCcSpec != None, \"Deployment", "\"_\" for namePart in aliases: for containerData in context.compose_containers: if", "chaincode alias from prior deployment, or None if not found'''", "Now grab the TransactionResult from the Msg bytes txResult =", "is open to the composeService that the user registered with.'''", "You may obtain a copy of the License at #", "containerDataList): \"\"\"Returns the IPAddress based upon a name part of", "with.''' userRegistration = getUserRegistration(context, enrollId) # Get the IP address", "if ip == None: raise Exception(\"Could not find container with", "'''Return a deployment with chaincode alias from prior deployment, or", "Result from {0}, for user \"{1}\": {2}'.format(userRegistration.composeService,enrollId, response.msg) # Now", "ccAlias, ctor): '''Deploy a chaincode with the specified alias for", "= {} self.lastResult = None def getUserName(self): return self.secretMsg['enrollId'] def", "(channel, userRegistration) = getGRPCChannelAndUser(context, enrollId) stub = devops_pb2.beta_create_Devops_stub(channel) txRequest =", "a new ChaincodeSpec by copying the deployed one newChaincodeSpec =", "= composeService self.tags = {} self.lastResult = None def getUserName(self):", "a specific composeService def getUserRegistration(context, enrollId): userRegistration = None if", "behave context @param arg_list: a list command arguments @param expect_success:", "print(\"Error Message:\\n\" + error) if expect_success: raise subprocess.CalledProcessError(p.returncode, arg_list, output)", "the Apache License, Version 2.0 (the \"License\"); # you may", "invoke args = [] if 'table' in context: # There", "stub.Deploy(ccSpec, 60) ccSpec.chaincodeID.name = ccDeploymentSpec.chaincodeSpec.chaincodeID.name context.grpcChaincodeSpec = ccSpec context.deployments[ccAlias] =", "(channel, userRegistration) def getDeployment(context, ccAlias): '''Return a deployment with chaincode", "in context, \"users not found in context. Did you register", "running the update-cli p = subprocess.Popen(arg_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error", "TransactionResult using the enrollId supplied''' assert 'users' in context, \"users", "= getUserRegistration(context, enrollId) # Allow the user to specify expressions", "raise Exception(\"User already registered: {0}\".format(userName)) context.users[userName] = UserRegistration(secretMsg, composeService) #", "users tags assert tagName in userRegistration.tags, \"TagName '{0}' not found", "chaincode_pb2.ChaincodeInput(function = functionName, args = args ) newChaincodeSpec.ctorMsg.CopyFrom(chaincodeInput) ccInvocationSpec =", "which calls the system python, not the virtual env python", "upon a name part of the full container name\"\"\" assert", "= fabric_pb2.TransactionResult() txResult.ParseFromString(response.msg) return txResult def getGRPCChannel(ipAddress): channel = implementations.insecure_channel(ipAddress," ]
[ "set_type == 'intersect': nofnd_l.append(k) else: raise IOError #=========================================================================== # wrap", "logger.warning('0 common values between d(%i) and l(%i)'%(len(d), len(l))) logger.debug('returning d", "# boolar = hp.basic.bool_list_in_list(d_big.keys(), l) # # if not np.all(boolar):", "deep a copy as possible if obj is None: obj", "d is keyed by the list \"\"\" logger = logger.getChild('subset')", "dict, here we add a method https://stackoverflow.com/questions/16664874/how-can-i-add-an-element-at-the-top-of-an-ordereddict-in-python \"\"\" def prepend(self,", "ordered = False, set_type = 'sub', search = 'search', #", "if set_type == 'union': if method == 'exact': d_merge =", "determine subset by kwarg # #=========================================================================== # if set_type ==", "#======================================================================= self.logger.debug('copy attempt %i'%self.tries) if self.tries > 10: return self.copy_o", "= 0 #keep track of the loop def __init__(self,obj, logger=mod_logger):", "self.logger = logger.getChild('deepcopier') self.copy_o = obj def tryit(self, obj=None): #make", "link_next[0] = link_prev link[0] = root link[1] = first root[1]", "a child logger of the root def dict_2_logr(dict, logger= mod_logger):", "#=========================================================================== # # determine subset by kwarg # #=========================================================================== #", "l: # try: # d[k] = d_big[k] # except: #", "wdict import numpy as np import hp.basic mod_logger = logging.getLogger(__name__)", "self.tries > 10: return self.copy_o #try for each element of", "add a method https://stackoverflow.com/questions/16664874/how-can-i-add-an-element-at-the-top-of-an-ordereddict-in-python \"\"\" def prepend(self, key, value, dict_setitem=dict.__setitem__):", "os, sys, math, copy, inspect from collections import OrderedDict from", "to treat the set # intersect: returna dictionary with only", "dict() # # #input list setup # if isinstance(l, list):", "# # #input list setup # if isinstance(l, list): pass", "elif isinstance(l, basestring): l = [l] # elif l is", "= 'intersect', method = 'exact', container = dict(), logger =", "to treat the set intersect: returna dictionary with only the", "search: look for a key in the dictionary that contains", "val_list)) return dict def merge_two_dicts(x, y): if x is None:", "elif set_type == 'intersect': # nofnd_l = [] # for", "logger = logger.getChild('subset_pfx') d = copy.copy(d_big) fnd_d = dict() for", "what type of key search to perform (re.function) # \"\"\"", "for k in l: # d[k] = d_big[k] # #", "root = self._OrderedDict__root first = root[1] if key in self:", "d #=============================================================================== class deepcopier(): tries = 0 #keep track of", "(within d_big) on which to erturn the sutset set_type: how", "modifies z with y's keys and values & returns None", "= subset(dl, dr.keys(), set_type = set_type, method=method, container=container, logger=logger, *search_args)", "k, v in d.iteritems(): if k.startswith(prefix): fnd_d[k] = v logger.debug('found", "contains the list entry. returned d is keyed by the", "None: return None # else: raise IOError # # #===========================================================================", "self: link = self._OrderedDict__map[key] link_prev, link_next, _ = link link_prev[1]", "msg = '\\n' for key, value in dict.iteritems(): msg =", "copy.copy(obj) self.logger.debug('returning new_d with %i entries: %s'%(len(new_d), new_d.keys())) else: raise", "using standard user inputs #ordered = False, using containers instead", "import OrderedDict class MyOrderedDict(OrderedDict): \"\"\" as there is no builtin", "= False, set_type = 'sub', search = 'search', # logger", "\\'%s\\' in %i dict keys. returning None'%(ksearch_str, len(d))) return None", "d = dict() # # #input list setup # if", "l is None: return None # else: raise IOError #", "subset using standard user inputs #ordered = False, using containers", "link link_prev[1] = link_next link_next[0] = link_prev link[0] = root", "# pre check #=========================================================================== bool_list = hp.basic.bool_list_in_list(d.keys(), key_list) if not", "= logger.getChild('subset_pfx') d = copy.copy(d_big) fnd_d = dict() for k,", "dict_2_logr(dict, logger= mod_logger): #log each value of the dictionary to", "dict.keys() and the key_list key_list, logger = mod_logger): logger =", "IOError logger.debug('got d_merge %i'%len(d_merge)) return container(d_merge) def subset_pfx(d_big, prefix, logger=mod_logger):", "list entries DO NOT intersect: %s'%(len(nofnd_l), len(l), nofnd_l)) if set_type", "intersect: returna dictionary with only the common keys sub: raise", "d.iteritems(): if k.startswith(prefix): fnd_d[k] = v logger.debug('found %i entries with", "is None: return x z = x.copy() # start with", "= hp.basic.list_search(d.keys(), ksearch_str, *search_args) if k_fnd is None: logger =", "tries = 0 #keep track of the loop def __init__(self,obj,", "to the head of an ordered dict, here we add", "0: logger.warning('0 common values between d(%i) and l(%i)'% # (len(d),", "#=========================================================================== # if set_type == 'sub': # try: # for", "== 'intersect': d_merge = subset(dl, dr.keys(), set_type = set_type, method=method,", "take a shot at a perfect match #=========================================================================== try: return", "%i entries with prefix \\'%s\\' \\n'%(len(fnd_d), prefix)) return fnd_d def", "not found in big_d'%(len(l) - boolar.sum())) raise IOError elif set_type", "#=========================================================================== # setup[] #========================================================================== d = container() \"\"\" #dictionary setup", "subset_pfx(d_big, prefix, logger=mod_logger): #=========================================================================== # shortcuts #=========================================================================== if len(d_big) ==", "raise ValueError #=================================================================== # nothing found. proceed based on set_type", "return self.copy_o #try for each element of the dict if", "keys (within d_big) on which to erturn the sutset set_type:", "= 'exact', container = dict(), logger = mod_logger, *search_args): if", "for key, value in d.iteritems(): if key in key_list: values_fnd_list.append(value)", "#=========================================================================== logger = logger.getChild('subset_pfx') d = copy.copy(d_big) fnd_d = dict()", "found in d_big.keys() method: what type of key search to", "np import hp.basic mod_logger = logging.getLogger(__name__) #creates a child logger", "pass elif isinstance(l, basestring): l = [l] elif l is", "boolar.sum())) raise IOError elif set_type == 'intersect': nofnd_l.append(k) else: raise", "using containers instead set_type = 'sub', method = 'exact', container", "values between d(%i) and l(%i)'%(len(d), len(l))) logger.debug('returning d with %i", "dict, logger = mod_logger, *search_args): \"\"\" #=========================================================================== # INPUTS #===========================================================================", "value: %s \\n'%(key, value) logger.debug(msg) def key_list(d, #return the intersection", "for key, value in dict.iteritems(): msg = msg + '", "method=method, container=container, logger=logger, *search_args) else: raise IOError logger.debug('got d_merge %i'%len(d_merge))", "container = dict, logger = mod_logger, *search_args): \"\"\" #=========================================================================== #", "# check #=========================================================================== if len(d) == 0: logger.warning('0 common values", "# except: # boolar = hp.basic.bool_list_in_list(d_big.keys(), l) # # if", "hp.basic.bool_list_in_list(d_big.keys(), l) # # if not np.all(boolar): # logger.error('%i entries", "the dict if isinstance(obj, dict): new_d = dict() for key,", "d_big[k] # # except: # boolar = hp.basic.bool_list_in_list(d_big.keys(), l) #", "with x's keys and values z.update(y) # modifies z with", "list \"\"\" logger = logger.getChild('subset') #=========================================================================== # setup[] #========================================================================== d", "'l' is found in d_big.keys() method: what type of key", "loop def __init__(self,obj, logger=mod_logger): self.logger = logger.getChild('deepcopier') self.copy_o = obj", "nofnd_l = [] #=========================================================================== # determine subset by kwarg #===========================================================================", "not np.all(boolar): logger.error('%i entries in list not found in big_d'%(len(l)", "d = copy.copy(d_big) fnd_d = dict() for k, v in", "copy as possible if obj is None: obj = self.copy_o", "mod_logger, *search_args): if set_type == 'union': if method == 'exact':", "if key in key_list: values_fnd_list.append(value) return values_fnd_list def build_nones_dict(key_list, logger=mod_logger):", "key, value in obj.iteritems(): try: new_d[key] = self.tryit(obj = value)", "bool_list = hp.basic.bool_list_in_list(d.keys(), key_list) if not bool_list.any(): raise IOError #check", "on which to erturn the sutset set_type: how to treat", "in key_list: values_fnd_list.append(value) return values_fnd_list def build_nones_dict(key_list, logger=mod_logger): #add 'None'", "+ ' key: %s\\n value: %s \\n'%(key, value) logger.debug(msg) def", "between d(%i) and l(%i)'%(len(d), len(l))) logger.debug('returning d with %i entries:", "is needed else: raise ValueError else: raise ValueError #=================================================================== #", "add to the head of an ordered dict, here we", "logger= mod_logger): #log each value of the dictionary to fille", "a key in the dictionary that contains the list entry.", "new_d[key] = self.tryit(obj = value) except: new_d[key] = copy.copy(obj) self.logger.debug('returning", "key in key_list: values_fnd_list.append(value) return values_fnd_list def build_nones_dict(key_list, logger=mod_logger): #add", "not every item in 'l' is found in d_big.keys() #", "# raise IOError # # if len(d) == 0: raise", "#dictionary setup # if ordered: d = OrderedDict() # else:", "%s'%(len(nofnd_l), len(l), nofnd_l)) # # #=========================================================================== # # check #", "return container(d) #=============================================================================== # def subset(d_big, l, #get a dictionary", "x.copy() # start with x's keys and values z.update(y) #", "logger.getChild('subset') #=========================================================================== # setup[] #========================================================================== d = container() \"\"\" #dictionary", "= x.copy() # start with x's keys and values z.update(y)", "= [l] elif l is None: return d else: raise", "# else: raise IOError # # #=========================================================================== # # determine", "len(l), nofnd_l)) if set_type == 'sub': raise IOError #=========================================================================== #", "def merge(dl, dr, #intelligent dictionary merging set_type = 'intersect', method", "= 'exact', container = dict, logger = mod_logger, *search_args): \"\"\"", "== 'search': #search and return this value v = value_by_ksearch(k,", "only the common keys # sub: raise a flag if", "not np.all(boolar): # logger.error('%i entries in list not found in", "# if len(d) == 0: logger.warning('0 common values between d(%i)", "6, 2018 @author: cef hp functions for workign with dictionaries", "sutset set_type: how to treat the set intersect: returna dictionary", "y if y is None: return x z = x.copy()", "if any are not found #=========================================================================== # build the found", "= dict() for k, v in d.iteritems(): if k.startswith(prefix): fnd_d[k]", "\"\"\" as there is no builtin method to add to", "flag if not every item in 'l' is found in", "[l] elif l is None: return d else: raise IOError", "if k_fnd is None: logger = logger.getChild('value_by_ksearch') logger.debug('could not find", "= [] #=========================================================================== # determine subset by kwarg #=========================================================================== for", "#=========================================================================== # # INPUTS # #=========================================================================== # l: list of", "dict if isinstance(obj, dict): new_d = dict() for key, value", "found. proceed based on set_type #=================================================================== except: logger.debug('unable to find", "numpy as np import hp.basic mod_logger = logging.getLogger(__name__) #creates a", "#=========================================================================== # defaults #=========================================================================== logger = logger.getChild('subset_pfx') d = copy.copy(d_big)", "raise IOError #=========================================================================== # wrap up #=========================================================================== if len(nofnd_l) >0:", "# # set_type: how to treat the set # intersect:", "of the root def dict_2_logr(dict, logger= mod_logger): #log each value", "sophisiticated try #======================================================================= self.logger.debug('copy attempt %i'%self.tries) if self.tries > 10:", "new_d with %i entries: %s'%(len(new_d), new_d.keys())) else: raise IOError return", "key, value, dict_setitem=dict.__setitem__): \"\"\"add entry to the front of myself\"\"\"", "d_big.keys() # # search: what type of key search to", "possible if obj is None: obj = self.copy_o #=========================================================================== #", "= [] # for k in l: # try: #", "self.logger.debug('returning new_d with %i entries: %s'%(len(new_d), new_d.keys())) else: raise IOError", "len(d) == 0: logger.warning('0 common values between d(%i) and l(%i)'%", "\"\"\" #dictionary setup if ordered: d = OrderedDict() else: d", ">0: # logger.debug('%i of %i list entries DO NOT intersect:", "dict() #=========================================================================== # defaults #=========================================================================== logger = logger.getChild('subset_pfx') d =", "track of the loop def __init__(self,obj, logger=mod_logger): self.logger = logger.getChild('deepcopier')", "+= 1 #======================================================================= # sophisiticated try #======================================================================= self.logger.debug('copy attempt %i'%self.tries)", "common values between d(%i) and l(%i)'%(len(d), len(l))) logger.debug('returning d with", "'\\n' for key, value in dict.iteritems(): msg = msg +", "else: d = dict()\"\"\" #input list setup if isinstance(l, list):", "if set_type == 'sub': raise IOError #=========================================================================== # check #===========================================================================", "inputs #ordered = False, using containers instead set_type = 'sub',", "if ordered: d = OrderedDict() # else: d = dict()", "match for this key k_fnd = hp.basic.list_search(d.keys(), ksearch_str, *search_args) if", "raise a flag if not every item in 'l' is", "0: return dict() #=========================================================================== # defaults #=========================================================================== logger = logger.getChild('subset_pfx')", "found in big_d'%(len(l) - boolar.sum())) raise IOError elif set_type ==", "fille logger = logger.getChild('dict_2_logr') msg = '\\n' for key, value", "= np.full((1, len(key_list)), None) dict = dict(zip(key_list, val_list)) return dict", "returna dictionary with only the common keys sub: raise a", "method: what type of key search to perform (re.function) search:", "boolar.sum())) # # raise IOError # # if len(d) ==", "# return d #=============================================================================== class deepcopier(): tries = 0 #keep", "the set # intersect: returna dictionary with only the common", "'exact', container = dict(), logger = mod_logger, *search_args): if set_type", "if method == 'exact': d_merge = merge_two_dicts(dl, dr, logger=logger) else:", "# defaults #=========================================================================== logger = logger.getChild('subset_pfx') d = copy.copy(d_big) fnd_d", "subset(d_big, l, #get a dictionary subset using standard user inputs", "of the dict if isinstance(obj, dict): new_d = dict() for", "boolar = hp.basic.bool_list_in_list(d_big.keys(), l) if not np.all(boolar): logger.error('%i entries in", "else: raise IOError return new_d from collections import OrderedDict class", "'intersect': # nofnd_l = [] # for k in l:", "= first root[1] = first[0] = link else: root[1] =", "if not np.all(boolar): logger.error('%i entries in list not found in", "k in l: # d[k] = d_big[k] # # except:", "MyOrderedDict(OrderedDict): \"\"\" as there is no builtin method to add", ">0: logger.debug('%i of %i list entries DO NOT intersect: %s'%(len(nofnd_l),", "dict): new_d = dict() for key, value in obj.iteritems(): try:", "'sub', search = 'search', # logger = mod_logger): # \"\"\"", "k in l: # try: # d[k] = d_big[k] #", "user inputs #ordered = False, using containers instead set_type =", "elif l is None: return d else: raise IOError nofnd_l", "return None else: return d[k_fnd] def merge(dl, dr, #intelligent dictionary", "# # search: what type of key search to perform", "= dict(), logger = mod_logger, *search_args): if set_type == 'union':", "if k.startswith(prefix): fnd_d[k] = v logger.debug('found %i entries with prefix", "kwarg # #=========================================================================== # if set_type == 'sub': # try:", "# modifies z with y's keys and values & returns", "a method https://stackoverflow.com/questions/16664874/how-can-i-add-an-element-at-the-top-of-an-ordereddict-in-python \"\"\" def prepend(self, key, value, dict_setitem=dict.__setitem__): \"\"\"add", "in self: link = self._OrderedDict__map[key] link_prev, link_next, _ = link", "# elif l is None: return None # else: raise", "values_fnd_list.append(value) return values_fnd_list def build_nones_dict(key_list, logger=mod_logger): #add 'None' values to", "str logger=mod_logger, *search_args): #=========================================================================== # take a shot at a", "# d[k] = d_big[k] # # except: # boolar =", "x z = x.copy() # start with x's keys and", "check #=========================================================================== bool_list = hp.basic.bool_list_in_list(d.keys(), key_list) if not bool_list.any(): raise", "#=========================================================================== # check #=========================================================================== if len(d) == 0: logger.warning('0 common", "key: %s\\n value: %s \\n'%(key, value) logger.debug(msg) def key_list(d, #return", "= v logger.debug('found %i entries with prefix \\'%s\\' \\n'%(len(fnd_d), prefix))", "the dict with method \\'%s\\''%(k, method)) if set_type == 'sub':", "len(nofnd_l) >0: logger.debug('%i of %i list entries DO NOT intersect:", "values_fnd_list def build_nones_dict(key_list, logger=mod_logger): #add 'None' values to the passed", "weakref import WeakValueDictionary as wdict import numpy as np import", "l is None: return d else: raise IOError nofnd_l =", "# #=========================================================================== # if set_type == 'sub': # try: #", "ordered dict, here we add a method https://stackoverflow.com/questions/16664874/how-can-i-add-an-element-at-the-top-of-an-ordereddict-in-python \"\"\" def", "None return z def value_by_ksearch(ksearch_str, d, #get the entry that", "each value of the dictionary to fille logger = logger.getChild('dict_2_logr')", "try: # d[k] = d_big[k] # except: # nofnd_l.append(k) #", "= value_by_ksearch(k, d_big, logger=logger, *search_args) if not v is None:", "for k, v in d.iteritems(): if k.startswith(prefix): fnd_d[k] = v", "d[k] = d_big[k] # except: # nofnd_l.append(k) # # if", "# # setup[] # #========================================================================== # #dictionary setup # if", "#make as deep a copy as possible if obj is", "self.copy_o #=========================================================================== # simple try #=========================================================================== try: copy_o = copy.deepcopy(obj)", "v is None: d[k] = v continue #not sure this", "is None: d[k] = v continue #not sure this is", "== 'intersect': nofnd_l.append(k) else: raise IOError #=========================================================================== # wrap up", "found in d_big.keys() # # search: what type of key", "entries: %s'%(len(new_d), new_d.keys())) else: raise IOError return new_d from collections", "elif set_type == 'intersect': d_merge = subset(dl, dr.keys(), set_type =", "def subset_pfx(d_big, prefix, logger=mod_logger): #=========================================================================== # shortcuts #=========================================================================== if len(d_big)", "y): if x is None: return y if y is", "IOError #=========================================================================== # check #=========================================================================== if len(d) == 0: logger.warning('0", "except: #=================================================================== # try again using search functions #=================================================================== try:", "#=================================================================== except: logger.debug('unable to find \\'%s\\' in the dict with", "standard user inputs # ordered = False, set_type = 'sub',", "= self._OrderedDict__map[key] link_prev, link_next, _ = link link_prev[1] = link_next", "functions for workign with dictionaries ''' import logging, os, sys,", "#=========================================================================== if len(nofnd_l) >0: logger.debug('%i of %i list entries DO", "= logger.getChild('subset') # # #=========================================================================== # # setup[] # #==========================================================================", "build the found values #=========================================================================== values_fnd_list = [] for key,", "obj=None): #make as deep a copy as possible if obj", "0: logger.warning('0 common values between d(%i) and l(%i)'%(len(d), len(l))) logger.debug('returning", "passed keys val_list = np.full((1, len(key_list)), None) dict = dict(zip(key_list,", "proceed based on set_type #=================================================================== except: logger.debug('unable to find \\'%s\\'", "for k in l: try: #attempt teh direct match d[k]", "None: obj = self.copy_o #=========================================================================== # simple try #=========================================================================== try:", "None'%(ksearch_str, len(d))) return None else: return d[k_fnd] def merge(dl, dr,", "nofnd_l = [] # for k in l: # try:", "prepend(self, key, value, dict_setitem=dict.__setitem__): \"\"\"add entry to the front of", "collections import OrderedDict class MyOrderedDict(OrderedDict): \"\"\" as there is no", "self._OrderedDict__root first = root[1] if key in self: link =", "value, dict_setitem=dict.__setitem__): \"\"\"add entry to the front of myself\"\"\" root", "set_type #=================================================================== except: logger.debug('unable to find \\'%s\\' in the dict", "# set_type: how to treat the set # intersect: returna", "self._OrderedDict__map[key] link_prev, link_next, _ = link link_prev[1] = link_next link_next[0]", "fnd_d[k] = v logger.debug('found %i entries with prefix \\'%s\\' \\n'%(len(fnd_d),", "#=========================================================================== # if len(d) == 0: logger.warning('0 common values between", "search = 'search', # logger = mod_logger): # \"\"\" #", "import numpy as np import hp.basic mod_logger = logging.getLogger(__name__) #creates", "not bool_list.any(): raise IOError #check if any are not found", "# #=========================================================================== # l: list of keys (within d_big) on", "IOError # # elif set_type == 'intersect': # nofnd_l =", "d_big) on which to erturn the sutset set_type: how to", "logger = logger.getChild('value_by_ksearch') logger.debug('could not find \\'%s\\' in %i dict", "IOError return new_d from collections import OrderedDict class MyOrderedDict(OrderedDict): \"\"\"", "# sophisiticated try #======================================================================= self.logger.debug('copy attempt %i'%self.tries) if self.tries >", "of the dict.keys() and the key_list key_list, logger = mod_logger):", "logger.debug('%i of %i list entries DO NOT intersect: %s'%(len(nofnd_l), len(l),", "container(d_merge) def subset_pfx(d_big, prefix, logger=mod_logger): #=========================================================================== # shortcuts #=========================================================================== if", "values #=========================================================================== values_fnd_list = [] for key, value in d.iteritems():", "d[k] = d_big[k] # # except: # boolar = hp.basic.bool_list_in_list(d_big.keys(),", "logger=logger) else: raise IOError #todo elif set_type == 'intersect': d_merge", "returns None return z def value_by_ksearch(ksearch_str, d, #get the entry", "ValueError else: raise ValueError #=================================================================== # nothing found. proceed based", "%s \\n'%(len(d), d.keys())) return container(d) #=============================================================================== # def subset(d_big, l,", "new_d from collections import OrderedDict class MyOrderedDict(OrderedDict): \"\"\" as there", "& returns None return z def value_by_ksearch(ksearch_str, d, #get the", "= hp.basic.bool_list_in_list(d.keys(), key_list) if not bool_list.any(): raise IOError #check if", "type of key search to perform (re.function) # \"\"\" #", "container = dict(), logger = mod_logger, *search_args): if set_type ==", "erturn the sutset set_type: how to treat the set intersect:", "first attempt') self.tries += 1 #======================================================================= # sophisiticated try #=======================================================================", "returned d is keyed by the list \"\"\" logger =", "key_list) if not bool_list.any(): raise IOError #check if any are", "d = container() \"\"\" #dictionary setup if ordered: d =", "defaults #=========================================================================== logger = logger.getChild('subset_pfx') d = copy.copy(d_big) fnd_d =", "l) # # if not np.all(boolar): # logger.error('%i entries in", "10: return self.copy_o #try for each element of the dict", "isinstance(l, list): pass # elif isinstance(l, basestring): l = [l]", "== 'sub': # try: # for k in l: #", "*search_args) if not v is None: d[k] = v continue", "d_merge = subset(dl, dr.keys(), set_type = set_type, method=method, container=container, logger=logger,", "method == 'search': #search and return this value v =", "else: raise IOError #todo elif set_type == 'intersect': d_merge =", "link_next, _ = link link_prev[1] = link_next link_next[0] = link_prev", "not find \\'%s\\' in %i dict keys. returning None'%(ksearch_str, len(d)))", "# # check # #=========================================================================== # if len(d) == 0:", "logger.getChild('dict_2_logr') msg = '\\n' for key, value in dict.iteritems(): msg", "'exact', container = dict, logger = mod_logger, *search_args): \"\"\" #===========================================================================", "key search to perform (re.function) # \"\"\" # logger =", "dict(zip(key_list, val_list)) return dict def merge_two_dicts(x, y): if x is", "a copy as possible if obj is None: obj =", "math, copy, inspect from collections import OrderedDict from weakref import", "match d[k] = d_big[k] except: #=================================================================== # try again using", "set_type = 'sub', method = 'exact', container = dict, logger", "if set_type == 'sub': # try: # for k in", "d_merge %i'%len(d_merge)) return container(d_merge) def subset_pfx(d_big, prefix, logger=mod_logger): #=========================================================================== #", "nofnd_l)) if set_type == 'sub': raise IOError #=========================================================================== # check", "keyed by the list \"\"\" logger = logger.getChild('subset') #=========================================================================== #", "# # determine subset by kwarg # #=========================================================================== # if", "# search: what type of key search to perform (re.function)", "ksearch_str, *search_args) if k_fnd is None: logger = logger.getChild('value_by_ksearch') logger.debug('could", "__init__(self,obj, logger=mod_logger): self.logger = logger.getChild('deepcopier') self.copy_o = obj def tryit(self,", "#=========================================================================== # pre check #=========================================================================== bool_list = hp.basic.bool_list_in_list(d.keys(), key_list) if", "root[1] = first[0] = self._OrderedDict__map[key] = [root, first, key] dict_setitem(self,", "containers instead set_type = 'sub', method = 'exact', container =", "= dict() # # #input list setup # if isinstance(l,", "root link[1] = first root[1] = first[0] = link else:", "matches the search str logger=mod_logger, *search_args): #=========================================================================== # take a", "setup if isinstance(l, list): pass elif isinstance(l, basestring): l =", "by the list \"\"\" logger = logger.getChild('subset') #=========================================================================== # setup[]", "None: d[k] = v continue #not sure this is needed", "link[1] = first root[1] = first[0] = link else: root[1]", "None else: return d[k_fnd] def merge(dl, dr, #intelligent dictionary merging", "= 'sub', method = 'exact', container = dict, logger =", "dict with method \\'%s\\''%(k, method)) if set_type == 'sub': boolar", "z with y's keys and values & returns None return", "in 'l' is found in d_big.keys() method: what type of", "self.logger.debug('copy attempt %i'%self.tries) if self.tries > 10: return self.copy_o #try", "if self.tries > 10: return self.copy_o #try for each element", "#not sure this is needed else: raise ValueError else: raise", "to find \\'%s\\' in the dict with method \\'%s\\''%(k, method))", "else: raise IOError logger.debug('got d_merge %i'%len(d_merge)) return container(d_merge) def subset_pfx(d_big,", "d_big[k] except: #=================================================================== # try again using search functions #===================================================================", "else: raise IOError nofnd_l = [] #=========================================================================== # determine subset", "container() \"\"\" #dictionary setup if ordered: d = OrderedDict() else:", "the dictionary that contains the list entry. returned d is", "\\n'%(len(fnd_d), prefix)) return fnd_d def subset(d_big, l, #get a dictionary", "OrderedDict() # else: d = dict() # # #input list", "# try again using search functions #=================================================================== try: if method", "set_type == 'intersect': # nofnd_l = [] # for k", "search str logger=mod_logger, *search_args): #=========================================================================== # take a shot at", "len(d) == 0: logger.warning('0 common values between d(%i) and l(%i)'%(len(d),", "is None: return y if y is None: return x", "except: logger.debug('unable to find \\'%s\\' in the dict with method", "#get a dictionary subset using standard user inputs #ordered =", "# for k in l: # try: # d[k] =", "= mod_logger): # \"\"\" # #=========================================================================== # # INPUTS #", "d with %i entries: %s \\n'%(len(d), d.keys())) return container(d) #===============================================================================", "> 10: return self.copy_o #try for each element of the", "raise ValueError else: raise ValueError #=================================================================== # nothing found. proceed", "'sub': # try: # for k in l: # d[k]", "and values & returns None return z def value_by_ksearch(ksearch_str, d,", "keys sub: raise a flag if not every item in", "the dict.keys() and the key_list key_list, logger = mod_logger): logger", "#=========================================================================== try: return d[ksearch_str] except: #find a match for this", "and the key_list key_list, logger = mod_logger): logger = logger.getChild('key_list')", "inspect from collections import OrderedDict from weakref import WeakValueDictionary as", "# \"\"\" # logger = logger.getChild('subset') # # #=========================================================================== #", "logging, os, sys, math, copy, inspect from collections import OrderedDict", "return z def value_by_ksearch(ksearch_str, d, #get the entry that matches", "returna dictionary with only the common keys # sub: raise", "*search_args): #=========================================================================== # take a shot at a perfect match", "if len(d) == 0: raise IOError # # elif set_type", "values between d(%i) and l(%i)'% # (len(d), len(l))) # #", "np.all(boolar): # logger.error('%i entries in list not found in big_d'%(len(l)", "and l(%i)'% # (len(d), len(l))) # # return d #===============================================================================", "# if ordered: d = OrderedDict() # else: d =", "= '\\n' for key, value in dict.iteritems(): msg = msg", "@author: cef hp functions for workign with dictionaries ''' import", "if not every item in 'l' is found in d_big.keys()", "needed else: raise ValueError else: raise ValueError #=================================================================== # nothing", "workign with dictionaries ''' import logging, os, sys, math, copy,", "try: if method == 'search': #search and return this value", "return d #=============================================================================== class deepcopier(): tries = 0 #keep track", "method to add to the head of an ordered dict,", "logger of the root def dict_2_logr(dict, logger= mod_logger): #log each", "%s'%(len(new_d), new_d.keys())) else: raise IOError return new_d from collections import", "root def dict_2_logr(dict, logger= mod_logger): #log each value of the", "at a perfect match #=========================================================================== try: return d[ksearch_str] except: #find", "this key k_fnd = hp.basic.list_search(d.keys(), ksearch_str, *search_args) if k_fnd is", "fnd_d = dict() for k, v in d.iteritems(): if k.startswith(prefix):", "list entry. returned d is keyed by the list \"\"\"", "# ordered = False, set_type = 'sub', search = 'search',", "how to treat the set # intersect: returna dictionary with", "d = OrderedDict() # else: d = dict() # #", "in list not found in big_d'%(len(l) - boolar.sum())) # #", "#=============================================================================== class deepcopier(): tries = 0 #keep track of the", "if key in self: link = self._OrderedDict__map[key] link_prev, link_next, _", "import WeakValueDictionary as wdict import numpy as np import hp.basic", "dr, #intelligent dictionary merging set_type = 'intersect', method = 'exact',", "IOError #check if any are not found #=========================================================================== # build", "prefix \\'%s\\' \\n'%(len(fnd_d), prefix)) return fnd_d def subset(d_big, l, #get", "by kwarg #=========================================================================== for k in l: try: #attempt teh", "elif set_type == 'intersect': nofnd_l.append(k) else: raise IOError #=========================================================================== #", "IOError #todo elif set_type == 'intersect': d_merge = subset(dl, dr.keys(),", "if len(nofnd_l) >0: logger.debug('%i of %i list entries DO NOT", "intersect: returna dictionary with only the common keys # sub:", "in %i dict keys. returning None'%(ksearch_str, len(d))) return None else:", "# if len(d) == 0: raise IOError # # elif", "dict() for k, v in d.iteritems(): if k.startswith(prefix): fnd_d[k] =", "the set intersect: returna dictionary with only the common keys", "entries: %s \\n'%(len(d), d.keys())) return container(d) #=============================================================================== # def subset(d_big,", "== 'intersect': # nofnd_l = [] # for k in", "# # if not np.all(boolar): # logger.error('%i entries in list", "\\'%s\\' \\n'%(len(fnd_d), prefix)) return fnd_d def subset(d_big, l, #get a", "# if set_type == 'sub': # try: # for k", "dictionary to fille logger = logger.getChild('dict_2_logr') msg = '\\n' for", "dict keys. returning None'%(ksearch_str, len(d))) return None else: return d[k_fnd]", "container=container, logger=logger, *search_args) else: raise IOError logger.debug('got d_merge %i'%len(d_merge)) return", "logger.debug('got d_merge %i'%len(d_merge)) return container(d_merge) def subset_pfx(d_big, prefix, logger=mod_logger): #===========================================================================", "with prefix \\'%s\\' \\n'%(len(fnd_d), prefix)) return fnd_d def subset(d_big, l,", "value) except: new_d[key] = copy.copy(obj) self.logger.debug('returning new_d with %i entries:", "val_list = np.full((1, len(key_list)), None) dict = dict(zip(key_list, val_list)) return", "'None' values to the passed keys val_list = np.full((1, len(key_list)),", "dict = dict(zip(key_list, val_list)) return dict def merge_two_dicts(x, y): if", "isinstance(obj, dict): new_d = dict() for key, value in obj.iteritems():", "self.tryit(obj = value) except: new_d[key] = copy.copy(obj) self.logger.debug('returning new_d with", "[l] # elif l is None: return None # else:", "d = OrderedDict() else: d = dict()\"\"\" #input list setup", "intersection of the dict.keys() and the key_list key_list, logger =", "#=========================================================================== # # check # #=========================================================================== # if len(d) ==", "dictionary merging set_type = 'intersect', method = 'exact', container =", "def tryit(self, obj=None): #make as deep a copy as possible", "check # #=========================================================================== # if len(d) == 0: logger.warning('0 common", "'l' is found in d_big.keys() # # search: what type", "\"\"\" # logger = logger.getChild('subset') # # #=========================================================================== # #", "hp functions for workign with dictionaries ''' import logging, os,", "return d[k_fnd] def merge(dl, dr, #intelligent dictionary merging set_type =", "key in the dictionary that contains the list entry. returned", "# setup[] # #========================================================================== # #dictionary setup # if ordered:", "link_prev link[0] = root link[1] = first root[1] = first[0]", "in l: # d[k] = d_big[k] # # except: #", "method = 'exact', container = dict, logger = mod_logger, *search_args):", "the intersection of the dict.keys() and the key_list key_list, logger", "the loop def __init__(self,obj, logger=mod_logger): self.logger = logger.getChild('deepcopier') self.copy_o =", "x is None: return y if y is None: return", "list of keys (within d_big) on which to erturn the", "else: d = dict() # # #input list setup #", "# if isinstance(l, list): pass # elif isinstance(l, basestring): l", "#=========================================================================== # wrap up #=========================================================================== if len(nofnd_l) >0: logger.debug('%i of", "# #=========================================================================== # # determine subset by kwarg # #===========================================================================", "list entries DO NOT intersect: %s'%(len(nofnd_l), len(l), nofnd_l)) # #", "if len(nofnd_l) >0: # logger.debug('%i of %i list entries DO", "raise IOError elif set_type == 'intersect': nofnd_l.append(k) else: raise IOError", "(len(d), len(l))) # # return d #=============================================================================== class deepcopier(): tries", "setup[] #========================================================================== d = container() \"\"\" #dictionary setup if ordered:", "basestring): l = [l] elif l is None: return d", "in list not found in big_d'%(len(l) - boolar.sum())) raise IOError", "#ordered = False, using containers instead set_type = 'sub', method", "''' import logging, os, sys, math, copy, inspect from collections", "entries with prefix \\'%s\\' \\n'%(len(fnd_d), prefix)) return fnd_d def subset(d_big,", "= dict() for key, value in obj.iteritems(): try: new_d[key] =", "#add 'None' values to the passed keys val_list = np.full((1,", "set_type == 'sub': raise IOError #=========================================================================== # check #=========================================================================== if", "= self.tryit(obj = value) except: new_d[key] = copy.copy(obj) self.logger.debug('returning new_d", "def prepend(self, key, value, dict_setitem=dict.__setitem__): \"\"\"add entry to the front", "cef hp functions for workign with dictionaries ''' import logging,", "dict def merge_two_dicts(x, y): if x is None: return y", "user inputs # ordered = False, set_type = 'sub', search", "z = x.copy() # start with x's keys and values", "# INPUTS #=========================================================================== l: list of keys (within d_big) on", "teh direct match d[k] = d_big[k] except: #=================================================================== # try", "# # return d #=============================================================================== class deepcopier(): tries = 0", "the common keys sub: raise a flag if not every", "= copy.copy(obj) self.logger.debug('returning new_d with %i entries: %s'%(len(new_d), new_d.keys())) else:", "0 #keep track of the loop def __init__(self,obj, logger=mod_logger): self.logger", "of key search to perform (re.function) # \"\"\" # logger", "the search str logger=mod_logger, *search_args): #=========================================================================== # take a shot", "copy.copy(d_big) fnd_d = dict() for k, v in d.iteritems(): if", "check #=========================================================================== if len(d) == 0: logger.warning('0 common values between", "self.logger.debug('failed first attempt') self.tries += 1 #======================================================================= # sophisiticated try", "= merge_two_dicts(dl, dr, logger=logger) else: raise IOError #todo elif set_type", "== 'exact': d_merge = merge_two_dicts(dl, dr, logger=logger) else: raise IOError", "logger=logger, *search_args) else: raise IOError logger.debug('got d_merge %i'%len(d_merge)) return container(d_merge)", "list): pass elif isinstance(l, basestring): l = [l] elif l", "head of an ordered dict, here we add a method", "1 #======================================================================= # sophisiticated try #======================================================================= self.logger.debug('copy attempt %i'%self.tries) if", "key k_fnd = hp.basic.list_search(d.keys(), ksearch_str, *search_args) if k_fnd is None:", "keys (within d_big) on which to erturn the sutset #", "root[1] = first[0] = link else: root[1] = first[0] =", "sys, math, copy, inspect from collections import OrderedDict from weakref", "pass # elif isinstance(l, basestring): l = [l] # elif", "[] for key, value in d.iteritems(): if key in key_list:", "self.copy_o #try for each element of the dict if isinstance(obj,", "l(%i)'%(len(d), len(l))) logger.debug('returning d with %i entries: %s \\n'%(len(d), d.keys()))", "method == 'exact': d_merge = merge_two_dicts(dl, dr, logger=logger) else: raise", "that matches the search str logger=mod_logger, *search_args): #=========================================================================== # take", "wrap up #=========================================================================== if len(nofnd_l) >0: logger.debug('%i of %i list", "# for k in l: # d[k] = d_big[k] #", "set_type == 'intersect': d_merge = subset(dl, dr.keys(), set_type = set_type,", "logger=mod_logger, *search_args): #=========================================================================== # take a shot at a perfect", "*search_args) if k_fnd is None: logger = logger.getChild('value_by_ksearch') logger.debug('could not", "self.copy_o = obj def tryit(self, obj=None): #make as deep a", "common keys sub: raise a flag if not every item", "copy_o except: self.logger.debug('failed first attempt') self.tries += 1 #======================================================================= #", "#try for each element of the dict if isinstance(obj, dict):", "class MyOrderedDict(OrderedDict): \"\"\" as there is no builtin method to", "set_type = set_type, method=method, container=container, logger=logger, *search_args) else: raise IOError", "nothing found. proceed based on set_type #=================================================================== except: logger.debug('unable to", "= dict(zip(key_list, val_list)) return dict def merge_two_dicts(x, y): if x", "k_fnd is None: logger = logger.getChild('value_by_ksearch') logger.debug('could not find \\'%s\\'", "# determine subset by kwarg # #=========================================================================== # if set_type", "in d_big.keys() method: what type of key search to perform", "dict_setitem=dict.__setitem__): \"\"\"add entry to the front of myself\"\"\" root =", "sutset # # set_type: how to treat the set #", "shortcuts #=========================================================================== if len(d_big) == 0: return dict() #=========================================================================== #", "up #=========================================================================== if len(nofnd_l) >0: logger.debug('%i of %i list entries", "link_next link_next[0] = link_prev link[0] = root link[1] = first", "None: logger = logger.getChild('value_by_ksearch') logger.debug('could not find \\'%s\\' in %i", "# # #=========================================================================== # # setup[] # #========================================================================== # #dictionary", "def merge_two_dicts(x, y): if x is None: return y if", "for a key in the dictionary that contains the list", "d_big[k] # except: # nofnd_l.append(k) # # if len(nofnd_l) >0:", "= msg + ' key: %s\\n value: %s \\n'%(key, value)", "not every item in 'l' is found in d_big.keys() method:", "z.update(y) # modifies z with y's keys and values &", "= obj def tryit(self, obj=None): #make as deep a copy", "\\n'%(len(d), d.keys())) return container(d) #=============================================================================== # def subset(d_big, l, #get", "# setup[] #========================================================================== d = container() \"\"\" #dictionary setup if", "logger = logger.getChild('subset') # # #=========================================================================== # # setup[] #", "first[0] = self._OrderedDict__map[key] = [root, first, key] dict_setitem(self, key, value)", "first[0] = link else: root[1] = first[0] = self._OrderedDict__map[key] =", "nofnd_l.append(k) # # if len(nofnd_l) >0: # logger.debug('%i of %i", "*search_args) else: raise IOError logger.debug('got d_merge %i'%len(d_merge)) return container(d_merge) def", "each element of the dict if isinstance(obj, dict): new_d =", "perform (re.function) # \"\"\" # logger = logger.getChild('subset') # #", "to erturn the sutset set_type: how to treat the set", "= d_big[k] # except: # nofnd_l.append(k) # # if len(nofnd_l)", "root[1] if key in self: link = self._OrderedDict__map[key] link_prev, link_next,", "is keyed by the list \"\"\" logger = logger.getChild('subset') #===========================================================================", "#input list setup if isinstance(l, list): pass elif isinstance(l, basestring):", "item in 'l' is found in d_big.keys() # # search:", "mod_logger): # \"\"\" # #=========================================================================== # # INPUTS # #===========================================================================", "in obj.iteritems(): try: new_d[key] = self.tryit(obj = value) except: new_d[key]", "front of myself\"\"\" root = self._OrderedDict__root first = root[1] if", "first = root[1] if key in self: link = self._OrderedDict__map[key]", "return y if y is None: return x z =", "child logger of the root def dict_2_logr(dict, logger= mod_logger): #log", "as deep a copy as possible if obj is None:", "#keep track of the loop def __init__(self,obj, logger=mod_logger): self.logger =", "in the dict with method \\'%s\\''%(k, method)) if set_type ==", "for each element of the dict if isinstance(obj, dict): new_d", "match #=========================================================================== try: return d[ksearch_str] except: #find a match for", "\\'%s\\''%(k, method)) if set_type == 'sub': boolar = hp.basic.bool_list_in_list(d_big.keys(), l)", "if len(d_big) == 0: return dict() #=========================================================================== # defaults #===========================================================================", "subset by kwarg #=========================================================================== for k in l: try: #attempt", "== 0: raise IOError # # elif set_type == 'intersect':", "in d.iteritems(): if k.startswith(prefix): fnd_d[k] = v logger.debug('found %i entries", "k_fnd = hp.basic.list_search(d.keys(), ksearch_str, *search_args) if k_fnd is None: logger", "except: self.logger.debug('failed first attempt') self.tries += 1 #======================================================================= # sophisiticated", "logger.warning('0 common values between d(%i) and l(%i)'% # (len(d), len(l)))", "d = dict()\"\"\" #input list setup if isinstance(l, list): pass", "find \\'%s\\' in the dict with method \\'%s\\''%(k, method)) if", "again using search functions #=================================================================== try: if method == 'search':", "== 0: return dict() #=========================================================================== # defaults #=========================================================================== logger =", "k.startswith(prefix): fnd_d[k] = v logger.debug('found %i entries with prefix \\'%s\\'", "method = 'exact', container = dict(), logger = mod_logger, *search_args):", "setup if ordered: d = OrderedDict() else: d = dict()\"\"\"", "of the loop def __init__(self,obj, logger=mod_logger): self.logger = logger.getChild('deepcopier') self.copy_o", "found values #=========================================================================== values_fnd_list = [] for key, value in", "values to the passed keys val_list = np.full((1, len(key_list)), None)", "0: raise IOError # # elif set_type == 'intersect': #", "method https://stackoverflow.com/questions/16664874/how-can-i-add-an-element-at-the-top-of-an-ordereddict-in-python \"\"\" def prepend(self, key, value, dict_setitem=dict.__setitem__): \"\"\"add entry", "in the dictionary that contains the list entry. returned d", "inputs # ordered = False, set_type = 'sub', search =", "else: raise IOError #=========================================================================== # wrap up #=========================================================================== if len(nofnd_l)", "# sub: raise a flag if not every item in", "%i'%self.tries) if self.tries > 10: return self.copy_o #try for each", "this value v = value_by_ksearch(k, d_big, logger=logger, *search_args) if not", "# #=========================================================================== # # setup[] # #========================================================================== # #dictionary setup", "a dictionary subset using standard user inputs # ordered =", "value in dict.iteritems(): msg = msg + ' key: %s\\n", "# #=========================================================================== # if len(d) == 0: logger.warning('0 common values", "'search', # logger = mod_logger): # \"\"\" # #=========================================================================== #", "%i entries: %s'%(len(new_d), new_d.keys())) else: raise IOError return new_d from", "DO NOT intersect: %s'%(len(nofnd_l), len(l), nofnd_l)) # # #=========================================================================== #", "== 0: logger.warning('0 common values between d(%i) and l(%i)'% #", "except: # nofnd_l.append(k) # # if len(nofnd_l) >0: # logger.debug('%i", "if not bool_list.any(): raise IOError #check if any are not", "False, set_type = 'sub', search = 'search', # logger =", "WeakValueDictionary as wdict import numpy as np import hp.basic mod_logger", "element of the dict if isinstance(obj, dict): new_d = dict()", "#find a match for this key k_fnd = hp.basic.list_search(d.keys(), ksearch_str,", "raise IOError # # if len(d) == 0: raise IOError", "with %i entries: %s'%(len(new_d), new_d.keys())) else: raise IOError return new_d", "= root[1] if key in self: link = self._OrderedDict__map[key] link_prev,", "v continue #not sure this is needed else: raise ValueError", "' key: %s\\n value: %s \\n'%(key, value) logger.debug(msg) def key_list(d,", "look for a key in the dictionary that contains the", "= self._OrderedDict__root first = root[1] if key in self: link", "'union': if method == 'exact': d_merge = merge_two_dicts(dl, dr, logger=logger)", "from weakref import WeakValueDictionary as wdict import numpy as np", "logger = mod_logger, *search_args): \"\"\" #=========================================================================== # INPUTS #=========================================================================== l:", "IOError #=========================================================================== # wrap up #=========================================================================== if len(nofnd_l) >0: logger.debug('%i", "self.tries += 1 #======================================================================= # sophisiticated try #======================================================================= self.logger.debug('copy attempt", "entries in list not found in big_d'%(len(l) - boolar.sum())) raise", "%i'%len(d_merge)) return container(d_merge) def subset_pfx(d_big, prefix, logger=mod_logger): #=========================================================================== # shortcuts", "return fnd_d def subset(d_big, l, #get a dictionary subset using", "a dictionary subset using standard user inputs #ordered = False,", "DO NOT intersect: %s'%(len(nofnd_l), len(l), nofnd_l)) if set_type == 'sub':", "as np import hp.basic mod_logger = logging.getLogger(__name__) #creates a child", "value of the dictionary to fille logger = logger.getChild('dict_2_logr') msg", "logger=mod_logger): #add 'None' values to the passed keys val_list =", "return None # else: raise IOError # # #=========================================================================== #", "#=========================================================================== l: list of keys (within d_big) on which to", "to perform (re.function) search: look for a key in the", "IOError nofnd_l = [] #=========================================================================== # determine subset by kwarg", "to the passed keys val_list = np.full((1, len(key_list)), None) dict", "#=========================================================================== # simple try #=========================================================================== try: copy_o = copy.deepcopy(obj) return", "else: raise ValueError else: raise ValueError #=================================================================== # nothing found.", "dict.iteritems(): msg = msg + ' key: %s\\n value: %s", "functions #=================================================================== try: if method == 'search': #search and return", "None # else: raise IOError # # #=========================================================================== # #", "here we add a method https://stackoverflow.com/questions/16664874/how-can-i-add-an-element-at-the-top-of-an-ordereddict-in-python \"\"\" def prepend(self, key,", "l, #get a dictionary subset using standard user inputs #ordered", "elif l is None: return None # else: raise IOError", "in 'l' is found in d_big.keys() # # search: what", "if isinstance(l, list): pass # elif isinstance(l, basestring): l =", "entry to the front of myself\"\"\" root = self._OrderedDict__root first", "for workign with dictionaries ''' import logging, os, sys, math,", "return d else: raise IOError nofnd_l = [] #=========================================================================== #", "new_d.keys())) else: raise IOError return new_d from collections import OrderedDict", "if not np.all(boolar): # logger.error('%i entries in list not found", "def __init__(self,obj, logger=mod_logger): self.logger = logger.getChild('deepcopier') self.copy_o = obj def", "copy, inspect from collections import OrderedDict from weakref import WeakValueDictionary", "#=========================================================================== if len(d) == 0: logger.warning('0 common values between d(%i)", "#input list setup # if isinstance(l, list): pass # elif", "of an ordered dict, here we add a method https://stackoverflow.com/questions/16664874/how-can-i-add-an-element-at-the-top-of-an-ordereddict-in-python", "on set_type #=================================================================== except: logger.debug('unable to find \\'%s\\' in the", "#======================================================================= # sophisiticated try #======================================================================= self.logger.debug('copy attempt %i'%self.tries) if self.tries", "any are not found #=========================================================================== # build the found values", "if set_type == 'sub': boolar = hp.basic.bool_list_in_list(d_big.keys(), l) if not", "else: return d[k_fnd] def merge(dl, dr, #intelligent dictionary merging set_type", "from collections import OrderedDict class MyOrderedDict(OrderedDict): \"\"\" as there is", "# # except: # boolar = hp.basic.bool_list_in_list(d_big.keys(), l) # #", "list not found in big_d'%(len(l) - boolar.sum())) raise IOError elif", "kwarg #=========================================================================== for k in l: try: #attempt teh direct", "based on set_type #=================================================================== except: logger.debug('unable to find \\'%s\\' in", "value) logger.debug(msg) def key_list(d, #return the intersection of the dict.keys()", "set_type, method=method, container=container, logger=logger, *search_args) else: raise IOError logger.debug('got d_merge", "if isinstance(l, list): pass elif isinstance(l, basestring): l = [l]", "else: raise ValueError #=================================================================== # nothing found. proceed based on", "entries in list not found in big_d'%(len(l) - boolar.sum())) #", "list setup if isinstance(l, list): pass elif isinstance(l, basestring): l", "#=========================================================================== # shortcuts #=========================================================================== if len(d_big) == 0: return dict()", "is found in d_big.keys() method: what type of key search", "d_big.keys() method: what type of key search to perform (re.function)", "= logger.getChild('subset') #=========================================================================== # setup[] #========================================================================== d = container() \"\"\"", "\"\"\"add entry to the front of myself\"\"\" root = self._OrderedDict__root", "logger.getChild('key_list') #=========================================================================== # pre check #=========================================================================== bool_list = hp.basic.bool_list_in_list(d.keys(), key_list)", "NOT intersect: %s'%(len(nofnd_l), len(l), nofnd_l)) if set_type == 'sub': raise", "logger = mod_logger, *search_args): if set_type == 'union': if method", "with dictionaries ''' import logging, os, sys, math, copy, inspect", "# # if len(nofnd_l) >0: # logger.debug('%i of %i list", "common keys # sub: raise a flag if not every", "l: list of keys (within d_big) on which to erturn", "# # #=========================================================================== # # determine subset by kwarg #", "copy.deepcopy(obj) return copy_o except: self.logger.debug('failed first attempt') self.tries += 1", "values_fnd_list = [] for key, value in d.iteritems(): if key", "= link else: root[1] = first[0] = self._OrderedDict__map[key] = [root,", "# try: # d[k] = d_big[k] # except: # nofnd_l.append(k)", "copy_o = copy.deepcopy(obj) return copy_o except: self.logger.debug('failed first attempt') self.tries", "# elif set_type == 'intersect': # nofnd_l = [] #", "logger = logger.getChild('key_list') #=========================================================================== # pre check #=========================================================================== bool_list =", "key in self: link = self._OrderedDict__map[key] link_prev, link_next, _ =", "isinstance(l, basestring): l = [l] # elif l is None:", "with y's keys and values & returns None return z", "#=========================================================================== values_fnd_list = [] for key, value in d.iteritems(): if", "logger = mod_logger): # \"\"\" # #=========================================================================== # # INPUTS", "msg + ' key: %s\\n value: %s \\n'%(key, value) logger.debug(msg)", "key search to perform (re.function) search: look for a key", "keys. returning None'%(ksearch_str, len(d))) return None else: return d[k_fnd] def", "hp.basic.list_search(d.keys(), ksearch_str, *search_args) if k_fnd is None: logger = logger.getChild('value_by_ksearch')", "logger.debug('found %i entries with prefix \\'%s\\' \\n'%(len(fnd_d), prefix)) return fnd_d", "only the common keys sub: raise a flag if not", "setup[] # #========================================================================== # #dictionary setup # if ordered: d", "try #======================================================================= self.logger.debug('copy attempt %i'%self.tries) if self.tries > 10: return", "#=========================================================================== # INPUTS #=========================================================================== l: list of keys (within d_big)", "# #=========================================================================== # # INPUTS # #=========================================================================== # l: list", "if x is None: return y if y is None:", "dictionaries ''' import logging, os, sys, math, copy, inspect from", "# # elif set_type == 'intersect': # nofnd_l = []", "link else: root[1] = first[0] = self._OrderedDict__map[key] = [root, first,", "to fille logger = logger.getChild('dict_2_logr') msg = '\\n' for key,", "container(d) #=============================================================================== # def subset(d_big, l, #get a dictionary subset", "# nothing found. proceed based on set_type #=================================================================== except: logger.debug('unable", "'exact': d_merge = merge_two_dicts(dl, dr, logger=logger) else: raise IOError #todo", "key_list(d, #return the intersection of the dict.keys() and the key_list", "is None: return None # else: raise IOError # #", "# #dictionary setup # if ordered: d = OrderedDict() #", "# build the found values #=========================================================================== values_fnd_list = [] for", "dictionary that contains the list entry. returned d is keyed", "set_type == 'sub': boolar = hp.basic.bool_list_in_list(d_big.keys(), l) if not np.all(boolar):", "method \\'%s\\''%(k, method)) if set_type == 'sub': boolar = hp.basic.bool_list_in_list(d_big.keys(),", "return dict() #=========================================================================== # defaults #=========================================================================== logger = logger.getChild('subset_pfx') d", "'intersect': nofnd_l.append(k) else: raise IOError #=========================================================================== # wrap up #===========================================================================", "import OrderedDict from weakref import WeakValueDictionary as wdict import numpy", "d.iteritems(): if key in key_list: values_fnd_list.append(value) return values_fnd_list def build_nones_dict(key_list,", "== 'sub': boolar = hp.basic.bool_list_in_list(d_big.keys(), l) if not np.all(boolar): logger.error('%i", "not found in big_d'%(len(l) - boolar.sum())) # # raise IOError", "of keys (within d_big) on which to erturn the sutset", "as wdict import numpy as np import hp.basic mod_logger =", "d(%i) and l(%i)'% # (len(d), len(l))) # # return d", "elif isinstance(l, basestring): l = [l] elif l is None:", "the passed keys val_list = np.full((1, len(key_list)), None) dict =", "= OrderedDict() # else: d = dict() # # #input", "def dict_2_logr(dict, logger= mod_logger): #log each value of the dictionary", "type of key search to perform (re.function) search: look for", "the list entry. returned d is keyed by the list", "#log each value of the dictionary to fille logger =", "l: # d[k] = d_big[k] # # except: # boolar", "return copy_o except: self.logger.debug('failed first attempt') self.tries += 1 #=======================================================================", "#========================================================================== d = container() \"\"\" #dictionary setup if ordered: d", "def build_nones_dict(key_list, logger=mod_logger): #add 'None' values to the passed keys", "k in l: try: #attempt teh direct match d[k] =", "return d[ksearch_str] except: #find a match for this key k_fnd", "ordered: d = OrderedDict() else: d = dict()\"\"\" #input list", "'sub': raise IOError #=========================================================================== # check #=========================================================================== if len(d) ==", "raise IOError return new_d from collections import OrderedDict class MyOrderedDict(OrderedDict):", "l = [l] # elif l is None: return None", "set_type = 'intersect', method = 'exact', container = dict(), logger", "raise IOError # # elif set_type == 'intersect': # nofnd_l", "logger.debug('could not find \\'%s\\' in %i dict keys. returning None'%(ksearch_str,", "the list \"\"\" logger = logger.getChild('subset') #=========================================================================== # setup[] #==========================================================================", "of key search to perform (re.function) search: look for a", "# nofnd_l = [] # for k in l: #", "z def value_by_ksearch(ksearch_str, d, #get the entry that matches the", "keys val_list = np.full((1, len(key_list)), None) dict = dict(zip(key_list, val_list))", "len(l), nofnd_l)) # # #=========================================================================== # # check # #===========================================================================", "pre check #=========================================================================== bool_list = hp.basic.bool_list_in_list(d.keys(), key_list) if not bool_list.any():", "#=========================================================================== # take a shot at a perfect match #===========================================================================", "mod_logger): #log each value of the dictionary to fille logger", "#todo elif set_type == 'intersect': d_merge = subset(dl, dr.keys(), set_type", "class deepcopier(): tries = 0 #keep track of the loop", "# determine subset by kwarg #=========================================================================== for k in l:", "# wrap up #=========================================================================== if len(nofnd_l) >0: logger.debug('%i of %i", "# intersect: returna dictionary with only the common keys #", "Created on Mar 6, 2018 @author: cef hp functions for", "v in d.iteritems(): if k.startswith(prefix): fnd_d[k] = v logger.debug('found %i", "list not found in big_d'%(len(l) - boolar.sum())) # # raise", "in dict.iteritems(): msg = msg + ' key: %s\\n value:", "dr.keys(), set_type = set_type, method=method, container=container, logger=logger, *search_args) else: raise", "are not found #=========================================================================== # build the found values #===========================================================================", "logger.getChild('subset') # # #=========================================================================== # # setup[] # #========================================================================== #", "merge(dl, dr, #intelligent dictionary merging set_type = 'intersect', method =", "= OrderedDict() else: d = dict()\"\"\" #input list setup if", "l = [l] elif l is None: return d else:", "perfect match #=========================================================================== try: return d[ksearch_str] except: #find a match", "is None: obj = self.copy_o #=========================================================================== # simple try #===========================================================================", "np.full((1, len(key_list)), None) dict = dict(zip(key_list, val_list)) return dict def", "#check if any are not found #=========================================================================== # build the", "return dict def merge_two_dicts(x, y): if x is None: return", "values z.update(y) # modifies z with y's keys and values", "which to erturn the sutset # # set_type: how to", "raise IOError nofnd_l = [] #=========================================================================== # determine subset by", "if len(d) == 0: logger.warning('0 common values between d(%i) and", "= hp.basic.bool_list_in_list(d_big.keys(), l) # # if not np.all(boolar): # logger.error('%i", "logger=mod_logger): self.logger = logger.getChild('deepcopier') self.copy_o = obj def tryit(self, obj=None):", "= self.copy_o #=========================================================================== # simple try #=========================================================================== try: copy_o =", "l, #get a dictionary subset using standard user inputs #", "#=========================================================================== # l: list of keys (within d_big) on which", "set_type: how to treat the set intersect: returna dictionary with", "else: root[1] = first[0] = self._OrderedDict__map[key] = [root, first, key]", "= logger.getChild('value_by_ksearch') logger.debug('could not find \\'%s\\' in %i dict keys.", "the root def dict_2_logr(dict, logger= mod_logger): #log each value of", "in l: try: #attempt teh direct match d[k] = d_big[k]", "value in obj.iteritems(): try: new_d[key] = self.tryit(obj = value) except:", "if not v is None: d[k] = v continue #not", "d[k] = v continue #not sure this is needed else:", "= logger.getChild('deepcopier') self.copy_o = obj def tryit(self, obj=None): #make as", "raise IOError #check if any are not found #=========================================================================== #", "found in big_d'%(len(l) - boolar.sum())) # # raise IOError #", "as possible if obj is None: obj = self.copy_o #===========================================================================", "'intersect': d_merge = subset(dl, dr.keys(), set_type = set_type, method=method, container=container,", "# if not np.all(boolar): # logger.error('%i entries in list not", "# except: # nofnd_l.append(k) # # if len(nofnd_l) >0: #", "raise IOError logger.debug('got d_merge %i'%len(d_merge)) return container(d_merge) def subset_pfx(d_big, prefix,", "#=========================================================================== # build the found values #=========================================================================== values_fnd_list = []", "d, #get the entry that matches the search str logger=mod_logger,", "logger.getChild('subset_pfx') d = copy.copy(d_big) fnd_d = dict() for k, v", "big_d'%(len(l) - boolar.sum())) # # raise IOError # # if", "an ordered dict, here we add a method https://stackoverflow.com/questions/16664874/how-can-i-add-an-element-at-the-top-of-an-ordereddict-in-python \"\"\"", "\"\"\" #=========================================================================== # INPUTS #=========================================================================== l: list of keys (within", "logger = logger.getChild('dict_2_logr') msg = '\\n' for key, value in", "is None: return d else: raise IOError nofnd_l = []", "d else: raise IOError nofnd_l = [] #=========================================================================== # determine", "= root link[1] = first root[1] = first[0] = link", "#=========================================================================== # determine subset by kwarg #=========================================================================== for k in", "tryit(self, obj=None): #make as deep a copy as possible if", "simple try #=========================================================================== try: copy_o = copy.deepcopy(obj) return copy_o except:", "first root[1] = first[0] = link else: root[1] = first[0]", "d[k_fnd] def merge(dl, dr, #intelligent dictionary merging set_type = 'intersect',", "bool_list.any(): raise IOError #check if any are not found #===========================================================================", "%s'%(len(nofnd_l), len(l), nofnd_l)) if set_type == 'sub': raise IOError #===========================================================================", "d[ksearch_str] except: #find a match for this key k_fnd =", "intersect: %s'%(len(nofnd_l), len(l), nofnd_l)) if set_type == 'sub': raise IOError", "logger=logger, *search_args) if not v is None: d[k] = v", "nofnd_l)) # # #=========================================================================== # # check # #=========================================================================== #", "#creates a child logger of the root def dict_2_logr(dict, logger=", "the sutset set_type: how to treat the set intersect: returna", "#=================================================================== # nothing found. proceed based on set_type #=================================================================== except:", "= 'search', # logger = mod_logger): # \"\"\" # #===========================================================================", "on which to erturn the sutset # # set_type: how", "key, value in d.iteritems(): if key in key_list: values_fnd_list.append(value) return", "obj = self.copy_o #=========================================================================== # simple try #=========================================================================== try: copy_o", "not v is None: d[k] = v continue #not sure", "key_list, logger = mod_logger): logger = logger.getChild('key_list') #=========================================================================== # pre", "every item in 'l' is found in d_big.keys() # #", "mod_logger): logger = logger.getChild('key_list') #=========================================================================== # pre check #=========================================================================== bool_list", "'sub', method = 'exact', container = dict, logger = mod_logger,", "keys # sub: raise a flag if not every item", "item in 'l' is found in d_big.keys() method: what type", "if y is None: return x z = x.copy() #", "= [] for key, value in d.iteritems(): if key in", "= logger.getChild('dict_2_logr') msg = '\\n' for key, value in dict.iteritems():", "= first[0] = link else: root[1] = first[0] = self._OrderedDict__map[key]", "which to erturn the sutset set_type: how to treat the", "# # raise IOError # # if len(d) == 0:", "merging set_type = 'intersect', method = 'exact', container = dict(),", "the entry that matches the search str logger=mod_logger, *search_args): #===========================================================================", "%i list entries DO NOT intersect: %s'%(len(nofnd_l), len(l), nofnd_l)) if", "attempt') self.tries += 1 #======================================================================= # sophisiticated try #======================================================================= self.logger.debug('copy", "def value_by_ksearch(ksearch_str, d, #get the entry that matches the search", "a shot at a perfect match #=========================================================================== try: return d[ksearch_str]", "if method == 'search': #search and return this value v", "d_big, logger=logger, *search_args) if not v is None: d[k] =", "key_list: values_fnd_list.append(value) return values_fnd_list def build_nones_dict(key_list, logger=mod_logger): #add 'None' values", "# try: # for k in l: # d[k] =", "link_prev[1] = link_next link_next[0] = link_prev link[0] = root link[1]", "dict()\"\"\" #input list setup if isinstance(l, list): pass elif isinstance(l,", "link_prev, link_next, _ = link link_prev[1] = link_next link_next[0] =", "dict(), logger = mod_logger, *search_args): if set_type == 'union': if", "what type of key search to perform (re.function) search: look", "= d_big[k] # # except: # boolar = hp.basic.bool_list_in_list(d_big.keys(), l)", "len(l))) # # return d #=============================================================================== class deepcopier(): tries =", "%i list entries DO NOT intersect: %s'%(len(nofnd_l), len(l), nofnd_l)) #", "np.all(boolar): logger.error('%i entries in list not found in big_d'%(len(l) -", "perform (re.function) search: look for a key in the dictionary", "logger.debug('returning d with %i entries: %s \\n'%(len(d), d.keys())) return container(d)", "the sutset # # set_type: how to treat the set", "False, using containers instead set_type = 'sub', method = 'exact',", "NOT intersect: %s'%(len(nofnd_l), len(l), nofnd_l)) # # #=========================================================================== # #", "key_list key_list, logger = mod_logger): logger = logger.getChild('key_list') #=========================================================================== #", "(within d_big) on which to erturn the sutset # #", "# d[k] = d_big[k] # except: # nofnd_l.append(k) # #", "if isinstance(obj, dict): new_d = dict() for key, value in", "except: new_d[key] = copy.copy(obj) self.logger.debug('returning new_d with %i entries: %s'%(len(new_d),", "the dictionary to fille logger = logger.getChild('dict_2_logr') msg = '\\n'", "setup # if ordered: d = OrderedDict() # else: d", "to the front of myself\"\"\" root = self._OrderedDict__root first =", "#=================================================================== try: if method == 'search': #search and return this", "#=============================================================================== # def subset(d_big, l, #get a dictionary subset using", "[] #=========================================================================== # determine subset by kwarg #=========================================================================== for k", "def subset(d_big, l, #get a dictionary subset using standard user", "subset using standard user inputs # ordered = False, set_type", "#=================================================================== # try again using search functions #=================================================================== try: if", "\"\"\" # #=========================================================================== # # INPUTS # #=========================================================================== # l:", "the key_list key_list, logger = mod_logger): logger = logger.getChild('key_list') #===========================================================================", "== 'sub': raise IOError #=========================================================================== # check #=========================================================================== if len(d)", "instead set_type = 'sub', method = 'exact', container = dict,", "None: return y if y is None: return x z", "len(d_big) == 0: return dict() #=========================================================================== # defaults #=========================================================================== logger", "to erturn the sutset # # set_type: how to treat", "builtin method to add to the head of an ordered", "new_d[key] = copy.copy(obj) self.logger.debug('returning new_d with %i entries: %s'%(len(new_d), new_d.keys()))", "on Mar 6, 2018 @author: cef hp functions for workign", "hp.basic mod_logger = logging.getLogger(__name__) #creates a child logger of the", "and l(%i)'%(len(d), len(l))) logger.debug('returning d with %i entries: %s \\n'%(len(d),", "''' Created on Mar 6, 2018 @author: cef hp functions", "build_nones_dict(key_list, logger=mod_logger): #add 'None' values to the passed keys val_list", "a perfect match #=========================================================================== try: return d[ksearch_str] except: #find a", "# simple try #=========================================================================== try: copy_o = copy.deepcopy(obj) return copy_o", "of the dictionary to fille logger = logger.getChild('dict_2_logr') msg =", "= mod_logger, *search_args): \"\"\" #=========================================================================== # INPUTS #=========================================================================== l: list", "= 'sub', search = 'search', # logger = mod_logger): #", "= link link_prev[1] = link_next link_next[0] = link_prev link[0] =", "# shortcuts #=========================================================================== if len(d_big) == 0: return dict() #===========================================================================", "= logging.getLogger(__name__) #creates a child logger of the root def", "this is needed else: raise ValueError else: raise ValueError #===================================================================", "dictionary subset using standard user inputs #ordered = False, using", "None: return d else: raise IOError nofnd_l = [] #===========================================================================", "set_type == 'union': if method == 'exact': d_merge = merge_two_dicts(dl,", "merge_two_dicts(x, y): if x is None: return y if y", "- boolar.sum())) raise IOError elif set_type == 'intersect': nofnd_l.append(k) else:", "try: new_d[key] = self.tryit(obj = value) except: new_d[key] = copy.copy(obj)", "set # intersect: returna dictionary with only the common keys", "# \"\"\" # #=========================================================================== # # INPUTS # #=========================================================================== #", "to add to the head of an ordered dict, here", "%s\\n value: %s \\n'%(key, value) logger.debug(msg) def key_list(d, #return the", "logger.getChild('value_by_ksearch') logger.debug('could not find \\'%s\\' in %i dict keys. returning", "== 0: logger.warning('0 common values between d(%i) and l(%i)'%(len(d), len(l)))", "for k in l: # try: # d[k] = d_big[k]", "logger = logger.getChild('subset') #=========================================================================== # setup[] #========================================================================== d = container()", "with only the common keys sub: raise a flag if", "and values z.update(y) # modifies z with y's keys and", "mod_logger = logging.getLogger(__name__) #creates a child logger of the root", "key, value in dict.iteritems(): msg = msg + ' key:", "return this value v = value_by_ksearch(k, d_big, logger=logger, *search_args) if", "%i dict keys. returning None'%(ksearch_str, len(d))) return None else: return", "#intelligent dictionary merging set_type = 'intersect', method = 'exact', container", "= [l] # elif l is None: return None #", "except: # boolar = hp.basic.bool_list_in_list(d_big.keys(), l) # # if not", "%i entries: %s \\n'%(len(d), d.keys())) return container(d) #=============================================================================== # def", "dictionary with only the common keys # sub: raise a", "entries DO NOT intersect: %s'%(len(nofnd_l), len(l), nofnd_l)) # # #===========================================================================", "len(nofnd_l) >0: # logger.debug('%i of %i list entries DO NOT", "and return this value v = value_by_ksearch(k, d_big, logger=logger, *search_args)", "# logger.debug('%i of %i list entries DO NOT intersect: %s'%(len(nofnd_l),", "'sub': boolar = hp.basic.bool_list_in_list(d_big.keys(), l) if not np.all(boolar): logger.error('%i entries", "# elif isinstance(l, basestring): l = [l] # elif l", "if obj is None: obj = self.copy_o #=========================================================================== # simple", "in big_d'%(len(l) - boolar.sum())) raise IOError elif set_type == 'intersect':", "of myself\"\"\" root = self._OrderedDict__root first = root[1] if key", "determine subset by kwarg #=========================================================================== for k in l: try:", "link = self._OrderedDict__map[key] link_prev, link_next, _ = link link_prev[1] =", "raise IOError # # #=========================================================================== # # determine subset by", "IOError # # if len(d) == 0: raise IOError #", "\\'%s\\' in the dict with method \\'%s\\''%(k, method)) if set_type", "how to treat the set intersect: returna dictionary with only", "obj is None: obj = self.copy_o #=========================================================================== # simple try", "OrderedDict() else: d = dict()\"\"\" #input list setup if isinstance(l,", "attempt %i'%self.tries) if self.tries > 10: return self.copy_o #try for", "#=========================================================================== try: copy_o = copy.deepcopy(obj) return copy_o except: self.logger.debug('failed first", "l: try: #attempt teh direct match d[k] = d_big[k] except:", "- boolar.sum())) # # raise IOError # # if len(d)", "# # INPUTS # #=========================================================================== # l: list of keys", "# logger = mod_logger): # \"\"\" # #=========================================================================== # #", "msg = msg + ' key: %s\\n value: %s \\n'%(key,", "we add a method https://stackoverflow.com/questions/16664874/how-can-i-add-an-element-at-the-top-of-an-ordereddict-in-python \"\"\" def prepend(self, key, value,", "keys and values & returns None return z def value_by_ksearch(ksearch_str,", "# else: d = dict() # # #input list setup", "IOError # # #=========================================================================== # # determine subset by kwarg", "hp.basic.bool_list_in_list(d.keys(), key_list) if not bool_list.any(): raise IOError #check if any", "erturn the sutset # # set_type: how to treat the", "None) dict = dict(zip(key_list, val_list)) return dict def merge_two_dicts(x, y):", "#search and return this value v = value_by_ksearch(k, d_big, logger=logger,", "collections import OrderedDict from weakref import WeakValueDictionary as wdict import", "basestring): l = [l] # elif l is None: return", "treat the set intersect: returna dictionary with only the common", "#dictionary setup if ordered: d = OrderedDict() else: d =", "value in d.iteritems(): if key in key_list: values_fnd_list.append(value) return values_fnd_list", "search: what type of key search to perform (re.function) #", "#return the intersection of the dict.keys() and the key_list key_list,", "\"\"\" def prepend(self, key, value, dict_setitem=dict.__setitem__): \"\"\"add entry to the", "= mod_logger): logger = logger.getChild('key_list') #=========================================================================== # pre check #===========================================================================", "*search_args): if set_type == 'union': if method == 'exact': d_merge", "every item in 'l' is found in d_big.keys() method: what", "#attempt teh direct match d[k] = d_big[k] except: #=================================================================== #", "deepcopier(): tries = 0 #keep track of the loop def", "from collections import OrderedDict from weakref import WeakValueDictionary as wdict", "of %i list entries DO NOT intersect: %s'%(len(nofnd_l), len(l), nofnd_l))", "list): pass # elif isinstance(l, basestring): l = [l] #", "no builtin method to add to the head of an", "in d_big.keys() # # search: what type of key search", "def key_list(d, #return the intersection of the dict.keys() and the", "dictionary with only the common keys sub: raise a flag", "hp.basic.bool_list_in_list(d_big.keys(), l) if not np.all(boolar): logger.error('%i entries in list not", "direct match d[k] = d_big[k] except: #=================================================================== # try again", "logger.error('%i entries in list not found in big_d'%(len(l) - boolar.sum()))", "logger=mod_logger): #=========================================================================== # shortcuts #=========================================================================== if len(d_big) == 0: return", "merge_two_dicts(dl, dr, logger=logger) else: raise IOError #todo elif set_type ==", "subset(dl, dr.keys(), set_type = set_type, method=method, container=container, logger=logger, *search_args) else:", "len(l))) logger.debug('returning d with %i entries: %s \\n'%(len(d), d.keys())) return", "# # if len(d) == 0: raise IOError # #", "d.keys())) return container(d) #=============================================================================== # def subset(d_big, l, #get a", "# nofnd_l.append(k) # # if len(nofnd_l) >0: # logger.debug('%i of", "# check # #=========================================================================== # if len(d) == 0: logger.warning('0", "start with x's keys and values z.update(y) # modifies z", "value_by_ksearch(ksearch_str, d, #get the entry that matches the search str", "#get the entry that matches the search str logger=mod_logger, *search_args):", "value v = value_by_ksearch(k, d_big, logger=logger, *search_args) if not v", "in l: # try: # d[k] = d_big[k] # except:", "return new_d from collections import OrderedDict class MyOrderedDict(OrderedDict): \"\"\" as", "big_d'%(len(l) - boolar.sum())) raise IOError elif set_type == 'intersect': nofnd_l.append(k)", "= mod_logger, *search_args): if set_type == 'union': if method ==", "x's keys and values z.update(y) # modifies z with y's", "logger.debug(msg) def key_list(d, #return the intersection of the dict.keys() and", "[] # for k in l: # try: # d[k]", "*search_args): \"\"\" #=========================================================================== # INPUTS #=========================================================================== l: list of keys", "# logger.error('%i entries in list not found in big_d'%(len(l) -", "in d.iteritems(): if key in key_list: values_fnd_list.append(value) return values_fnd_list def", "try: return d[ksearch_str] except: #find a match for this key", "= d_big[k] except: #=================================================================== # try again using search functions", "#=========================================================================== if len(d_big) == 0: return dict() #=========================================================================== # defaults", "#=========================================================================== bool_list = hp.basic.bool_list_in_list(d.keys(), key_list) if not bool_list.any(): raise IOError", "= dict()\"\"\" #input list setup if isinstance(l, list): pass elif", "by kwarg # #=========================================================================== # if set_type == 'sub': #", "#=========================================================================== for k in l: try: #attempt teh direct match", "return container(d_merge) def subset_pfx(d_big, prefix, logger=mod_logger): #=========================================================================== # shortcuts #===========================================================================", "isinstance(l, basestring): l = [l] elif l is None: return", "y is None: return x z = x.copy() # start", "keys and values z.update(y) # modifies z with y's keys", "to perform (re.function) # \"\"\" # logger = logger.getChild('subset') #", "for key, value in obj.iteritems(): try: new_d[key] = self.tryit(obj =", "using search functions #=================================================================== try: if method == 'search': #search", "logger.debug('unable to find \\'%s\\' in the dict with method \\'%s\\''%(k,", "= link_next link_next[0] = link_prev link[0] = root link[1] =", "set_type: how to treat the set # intersect: returna dictionary", "v = value_by_ksearch(k, d_big, logger=logger, *search_args) if not v is", "return values_fnd_list def build_nones_dict(key_list, logger=mod_logger): #add 'None' values to the", "sure this is needed else: raise ValueError else: raise ValueError", "INPUTS # #=========================================================================== # l: list of keys (within d_big)", "d_big) on which to erturn the sutset # # set_type:", "= False, using containers instead set_type = 'sub', method =", "# if len(nofnd_l) >0: # logger.debug('%i of %i list entries", "try: copy_o = copy.deepcopy(obj) return copy_o except: self.logger.debug('failed first attempt')", "= first[0] = self._OrderedDict__map[key] = [root, first, key] dict_setitem(self, key,", "ordered: d = OrderedDict() # else: d = dict() #", "if ordered: d = OrderedDict() else: d = dict()\"\"\" #input", "method)) if set_type == 'sub': boolar = hp.basic.bool_list_in_list(d_big.keys(), l) if", "shot at a perfect match #=========================================================================== try: return d[ksearch_str] except:", "continue #not sure this is needed else: raise ValueError else:", "isinstance(l, list): pass elif isinstance(l, basestring): l = [l] elif", "ValueError #=================================================================== # nothing found. proceed based on set_type #===================================================================", "(re.function) # \"\"\" # logger = logger.getChild('subset') # # #===========================================================================", "= link_prev link[0] = root link[1] = first root[1] =", "logger = mod_logger): logger = logger.getChild('key_list') #=========================================================================== # pre check", "value_by_ksearch(k, d_big, logger=logger, *search_args) if not v is None: d[k]", "# INPUTS # #=========================================================================== # l: list of keys (within", "len(d) == 0: raise IOError # # elif set_type ==", "= logger.getChild('key_list') #=========================================================================== # pre check #=========================================================================== bool_list = hp.basic.bool_list_in_list(d.keys(),", "not found #=========================================================================== # build the found values #=========================================================================== values_fnd_list", "sub: raise a flag if not every item in 'l'", "# start with x's keys and values z.update(y) # modifies", "try again using search functions #=================================================================== try: if method ==", "for this key k_fnd = hp.basic.list_search(d.keys(), ksearch_str, *search_args) if k_fnd", "there is no builtin method to add to the head", "l(%i)'% # (len(d), len(l))) # # return d #=============================================================================== class", "prefix)) return fnd_d def subset(d_big, l, #get a dictionary subset", "return x z = x.copy() # start with x's keys", "is found in d_big.keys() # # search: what type of", "2018 @author: cef hp functions for workign with dictionaries '''", "search to perform (re.function) # \"\"\" # logger = logger.getChild('subset')", "the found values #=========================================================================== values_fnd_list = [] for key, value", "v logger.debug('found %i entries with prefix \\'%s\\' \\n'%(len(fnd_d), prefix)) return", "dictionary subset using standard user inputs # ordered = False,", "# logger = logger.getChild('subset') # # #=========================================================================== # # setup[]", "# (len(d), len(l))) # # return d #=============================================================================== class deepcopier():", "%s \\n'%(key, value) logger.debug(msg) def key_list(d, #return the intersection of", "found #=========================================================================== # build the found values #=========================================================================== values_fnd_list =", "entry that matches the search str logger=mod_logger, *search_args): #=========================================================================== #", "else: raise IOError # # #=========================================================================== # # determine subset", "y's keys and values & returns None return z def", "mod_logger, *search_args): \"\"\" #=========================================================================== # INPUTS #=========================================================================== l: list of", "= container() \"\"\" #dictionary setup if ordered: d = OrderedDict()", "= copy.deepcopy(obj) return copy_o except: self.logger.debug('failed first attempt') self.tries +=", "as there is no builtin method to add to the", "a match for this key k_fnd = hp.basic.list_search(d.keys(), ksearch_str, *search_args)", "standard user inputs #ordered = False, using containers instead set_type", "raise IOError #todo elif set_type == 'intersect': d_merge = subset(dl,", "treat the set # intersect: returna dictionary with only the", "= v continue #not sure this is needed else: raise", "== 'union': if method == 'exact': d_merge = merge_two_dicts(dl, dr,", "import hp.basic mod_logger = logging.getLogger(__name__) #creates a child logger of", "with method \\'%s\\''%(k, method)) if set_type == 'sub': boolar =", "the common keys # sub: raise a flag if not", "= hp.basic.bool_list_in_list(d_big.keys(), l) if not np.all(boolar): logger.error('%i entries in list", "entry. returned d is keyed by the list \"\"\" logger", "# #========================================================================== # #dictionary setup # if ordered: d =", "try: # for k in l: # d[k] = d_big[k]", "find \\'%s\\' in %i dict keys. returning None'%(ksearch_str, len(d))) return", "# take a shot at a perfect match #=========================================================================== try:", "entries DO NOT intersect: %s'%(len(nofnd_l), len(l), nofnd_l)) if set_type ==", "\"\"\" logger = logger.getChild('subset') #=========================================================================== # setup[] #========================================================================== d =", "# #input list setup # if isinstance(l, list): pass #", "in big_d'%(len(l) - boolar.sum())) # # raise IOError # #", "the head of an ordered dict, here we add a", "except: #find a match for this key k_fnd = hp.basic.list_search(d.keys(),", "d[k] = d_big[k] except: #=================================================================== # try again using search", "# l: list of keys (within d_big) on which to", "intersect: %s'%(len(nofnd_l), len(l), nofnd_l)) # # #=========================================================================== # # check", "IOError elif set_type == 'intersect': nofnd_l.append(k) else: raise IOError #===========================================================================", "l) if not np.all(boolar): logger.error('%i entries in list not found", "OrderedDict from weakref import WeakValueDictionary as wdict import numpy as", "d_merge = merge_two_dicts(dl, dr, logger=logger) else: raise IOError #todo elif", "'intersect', method = 'exact', container = dict(), logger = mod_logger,", "None: return x z = x.copy() # start with x's", "= dict, logger = mod_logger, *search_args): \"\"\" #=========================================================================== # INPUTS", "d(%i) and l(%i)'%(len(d), len(l))) logger.debug('returning d with %i entries: %s", "import logging, os, sys, math, copy, inspect from collections import", "# # #=========================================================================== # # check # #=========================================================================== # if", "len(key_list)), None) dict = dict(zip(key_list, val_list)) return dict def merge_two_dicts(x,", "common values between d(%i) and l(%i)'% # (len(d), len(l))) #", "try #=========================================================================== try: copy_o = copy.deepcopy(obj) return copy_o except: self.logger.debug('failed", "dict() for key, value in obj.iteritems(): try: new_d[key] = self.tryit(obj", "https://stackoverflow.com/questions/16664874/how-can-i-add-an-element-at-the-top-of-an-ordereddict-in-python \"\"\" def prepend(self, key, value, dict_setitem=dict.__setitem__): \"\"\"add entry to", "_ = link link_prev[1] = link_next link_next[0] = link_prev link[0]", "link[0] = root link[1] = first root[1] = first[0] =", "between d(%i) and l(%i)'% # (len(d), len(l))) # # return", "# def subset(d_big, l, #get a dictionary subset using standard", "boolar = hp.basic.bool_list_in_list(d_big.keys(), l) # # if not np.all(boolar): #", "logger.getChild('deepcopier') self.copy_o = obj def tryit(self, obj=None): #make as deep", "obj def tryit(self, obj=None): #make as deep a copy as", "myself\"\"\" root = self._OrderedDict__root first = root[1] if key in", "search to perform (re.function) search: look for a key in", "logging.getLogger(__name__) #creates a child logger of the root def dict_2_logr(dict,", "search functions #=================================================================== try: if method == 'search': #search and", "(re.function) search: look for a key in the dictionary that", "using standard user inputs # ordered = False, set_type =", "= copy.copy(d_big) fnd_d = dict() for k, v in d.iteritems():", "INPUTS #=========================================================================== l: list of keys (within d_big) on which", "the front of myself\"\"\" root = self._OrderedDict__root first = root[1]", "set_type = 'sub', search = 'search', # logger = mod_logger):", "list setup # if isinstance(l, list): pass # elif isinstance(l,", "returning None'%(ksearch_str, len(d))) return None else: return d[k_fnd] def merge(dl,", "setup # if isinstance(l, list): pass # elif isinstance(l, basestring):", "that contains the list entry. returned d is keyed by", "with %i entries: %s \\n'%(len(d), d.keys())) return container(d) #=============================================================================== #", "#get a dictionary subset using standard user inputs # ordered", "Mar 6, 2018 @author: cef hp functions for workign with", "obj.iteritems(): try: new_d[key] = self.tryit(obj = value) except: new_d[key] =", "= value) except: new_d[key] = copy.copy(obj) self.logger.debug('returning new_d with %i", "# #=========================================================================== # # check # #=========================================================================== # if len(d)", "#=========================================================================== # # setup[] # #========================================================================== # #dictionary setup #", "fnd_d def subset(d_big, l, #get a dictionary subset using standard", "dr, logger=logger) else: raise IOError #todo elif set_type == 'intersect':", "len(d))) return None else: return d[k_fnd] def merge(dl, dr, #intelligent", "with only the common keys # sub: raise a flag", "new_d = dict() for key, value in obj.iteritems(): try: new_d[key]", "= set_type, method=method, container=container, logger=logger, *search_args) else: raise IOError logger.debug('got", "'search': #search and return this value v = value_by_ksearch(k, d_big,", "raise IOError #=========================================================================== # check #=========================================================================== if len(d) == 0:", "OrderedDict class MyOrderedDict(OrderedDict): \"\"\" as there is no builtin method", "set_type == 'sub': # try: # for k in l:", "prefix, logger=mod_logger): #=========================================================================== # shortcuts #=========================================================================== if len(d_big) == 0:", "is no builtin method to add to the head of", "a flag if not every item in 'l' is found", "try: #attempt teh direct match d[k] = d_big[k] except: #===================================================================", "nofnd_l.append(k) else: raise IOError #=========================================================================== # wrap up #=========================================================================== if", "set intersect: returna dictionary with only the common keys sub:", "\\n'%(key, value) logger.debug(msg) def key_list(d, #return the intersection of the", "is None: logger = logger.getChild('value_by_ksearch') logger.debug('could not find \\'%s\\' in", "#========================================================================== # #dictionary setup # if ordered: d = OrderedDict()", "values & returns None return z def value_by_ksearch(ksearch_str, d, #get", "subset by kwarg # #=========================================================================== # if set_type == 'sub':" ]
[ "green + \"]\" + white + \" Discord\") print(green +", "\"[+] Github: https://github.com/Cyber-Dioxide/ \", \"- \" * 3) banner() def", "[\" + white + \"15\" + green + \"]\" +", "from Core.helper.color import green, white, blue, red, start, alert Version", "\"- \" * 4, \" [+] Follow me on Instagram", "print(green + \"██║ ╚██╔╝ ██╔══██╗██╔══╝ ██╔══██╗\" + white+ blue +", "+ white + \"10\" + green + \"]\" + white", "██║██║███████║██║ ██║\") print(red+ \"╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚═╝ ╚═╝ \") banner() print(alert", "+ \" Snapchat (simple)\" + green + \" [\" +", "+ white + \" Rockstar\") print(green + \"[\" + white", "\" Rockstar\") print(green + \"[\" + white + \"7\" +", "+ green + \"]\" + white + \" Spotify\") print(green", "+ white + \" Spotify\") print(green + \"[\" + white", "Github: https://github.com/Cyber-Dioxide/ \", \"- \" * 3) banner() def menu():", "white + \" Spotify\") print(green + \"[\" + white +", "white + \"21\" + green + \"]\" + white +", "+ Fore.LIGHTCYAN_EX, Style.BRIGHT + Fore.LIGHTBLUE_EX, Style.BRIGHT + Fore.LIGHTCYAN_EX, Style.BRIGHT +", "+ white + \"4\" + green + \"]\" + white", "+ white + \"1\" + green + \"]\" + white", "random.choice(all_col) def banner(): print(Style.BRIGHT + Fore.LIGHTCYAN_EX, \"\\n\", \"- \" *", "+ \"22\" + green + \"]\" + white + \"", "Paypal\") print(green + \"[\" + white + \"2\" + green", "+ white + \" Gamehag\") print(green + \"[\" + white", "+ white + \" Discord\") print(green + \"[\" + white", "\"██╔══██╗██║ ██║██║██╔════╝██║ ██║\" + green) print(yellow+\"██████╔╝███████║██║███████╗███████║\" + blue) print(yellow+\"██╔═══╝ ██╔══██║██║╚════██║██╔══██║\"", "+ \"[\" + white + \"10\" + green + \"]\"", "white + \"6\" + green + \"]\" + white +", "Style except ModuleNotFoundError: os.system(\"pip install colorama\") from urllib.request import urlopen", "+ green + \"]\" + white + \" Instagram\" +", "white + \" Linkedin\" + green + \" [\" +", "+ green + \" [\" + white + \"16\" +", "+ \"16\" + green + \"]\" + white + \"", "+ \" More Versions Will Come Soon Stay Updated, Follow", "+ \"9\" + green + \"]\" + white + \"", "green + \"]\" + white + \" Gamehag\") print(green +", "white + \" Playstation\" + green + \" [\" +", "\" Paypal\") print(green + \"[\" + white + \"2\" +", "+ white + \"7\" + green + \"]\" + white", "green + \"]\" + white + \" Snapchat (simple)\" +", "Discord\") print(green + \"[\" + white + \"3\" + green", "+ \" Playstation\" + green + \" [\" + white", "white, blue, red, start, alert Version = \"2.2\" yellow =", "\" [\" + white + \"13\" + green + \"]\"", "+ green + \" [\" + white + \"15\" +", "+ green + \"]\" + white + \" Snapchat (simple)\"", "+ white + \" Instagram\" + green + \" [\"", "try: urlopen(host) return True except: return False all_col = [Style.BRIGHT", "green + \" [\" + white + \"18\" + green", "\"[\" + white + \"8\" + green + \"]\" +", "\"[\" + white + \"00\" + green + \"]\" +", "+ green + \" [\" + white + \"17\" +", "Fore.LIGHTYELLOW_EX, \"\\n\", \"- \" * 4, \" [+] Coding Instagram", "print(blue + \" ██████╗██╗ ██╗██████╗ ███████╗██████╗\" + white ) print(white", "██████╔╝███████╗██║ ██║\") print(red + \"██████╗ ██╗ ██╗██╗███████╗██╗ ██╗\" ) print(white+", "+ \" Gmail\" + green + \" [\" + white", "Fore.LIGHTCYAN_EX, Style.BRIGHT + Fore.LIGHTBLUE_EX, Style.BRIGHT + Fore.LIGHTCYAN_EX, Style.BRIGHT + Fore.LIGHTMAGENTA_EX,", "print(green + \"[\" + white + \"10\" + green +", "+ \"17\" + green + \"]\" + white + \"", "\"[\" + white + \"10\" + green + \"]\" +", "\"8\" + green + \"]\" + white + \" Steam\"", "\" * 4) print(Style.BRIGHT + Fore.LIGHTYELLOW_EX, \"\\n\", \"- \" *", "\"╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚═╝ ╚═╝ \") banner() print(alert + \" More", "\"]\" + white + \" 000Webhost\") print(green + \"[\" +", "+ \"]\" + white + \" Gmail (simple)\" + green", "\" Gmail (simple)\" + green + \" [\" + white", "\" [\" + white + \"22\" + green + \"]\"", "+ \" 000Webhost\") print(green + \"[\" + white + \"9\"", "+ \"[\" + white + \"2\" + green + \"]\"", "green + \"]\" + white + \" AskFM\") print(green +", "print(green + \"[\" + white + \"11\" + green +", "green + \" [\" + white + \"16\" + green", "4) print(Style.BRIGHT + Fore.LIGHTYELLOW_EX, \"\\n\", \"- \" * 4, \"", "+ \" [\" + white + \"16\" + green +", "Mega\") print(green + \"-----------------------------------------------------------------------\") print(green + \"[\" + white +", "+ green) print(yellow+\"██████╔╝███████║██║███████╗███████║\" + blue) print(yellow+\"██╔═══╝ ██╔══██║██║╚════██║██╔══██║\" + green) print(yellow+\"██║", "\"5\" + green + \"]\" + white + \" Twitter\"", "+ green + \" [\" + white + \"22\" +", "white + \" Discord\") print(green + \"[\" + white +", "connected(host='http://duckduckgo.com'): try: urlopen(host) return True except: return False all_col =", "(simple)\" + green + \" [\" + white + \"15\"", "* 3) banner() def menu(): print(blue + \" ██████╗██╗ ██╗██████╗", "random try: from colorama import Fore, Style except ModuleNotFoundError: os.system(\"pip", "\" [\" + white + \"17\" + green + \"]\"", "+ \"6\" + green + \"]\" + white + \"", "+ green) print(green + \"[\" + white + \"10\" +", "green) print(yellow+\"██████╔╝███████║██║███████╗███████║\" + blue) print(yellow+\"██╔═══╝ ██╔══██║██║╚════██║██╔══██║\" + green) print(yellow+\"██║ ██║", "Fore.RED, Style.BRIGHT + Fore.CYAN, Style.BRIGHT + Fore.LIGHTCYAN_EX, Style.BRIGHT + Fore.LIGHTBLUE_EX,", "+ Fore.LIGHTMAGENTA_EX, Style.BRIGHT + Fore.LIGHTYELLOW_EX] ran = random.choice(all_col) def banner():", "+ \"[\" + white + \"1\" + green + \"]\"", "+ green + \"]\" + white + \" Gmail (simple)\"", "\"11\" + green + \"]\" + white + \" Playstation\"", "\"]\" + white + \" Discord\") print(green + \"[\" +", "\"-----------------------------------------------------------------------\") print(green + \"[\" + white + \"00\" + green", "+ \"]\" + white + \" Gamehag\") print(green + \"[\"", "print(yellow+\"██║ ██║ ██║██║███████║██║ ██║\") print(red+ \"╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚═╝ ╚═╝ \")", "+ \"]\" + white + \" Gmail\" + green +", "+ Fore.LIGHTCYAN_EX, Style.BRIGHT + Fore.LIGHTMAGENTA_EX, Style.BRIGHT + Fore.LIGHTYELLOW_EX] ran =", "Gmail\" + green + \" [\" + white + \"14\"", "banner(): print(Style.BRIGHT + Fore.LIGHTCYAN_EX, \"\\n\", \"- \" * 4, \"", "+ green + \"]\" + white + \" Gmail\" +", "+ \"[\" + white + \"4\" + green + \"]\"", "\"6\" + green + \"]\" + white + \" Snapchat\"", "+ white + \" Linkedin\" + green + \" [\"", "\", \"- \" * 4) print(Style.BRIGHT + Fore.LIGHTYELLOW_EX, \"\\n\", \"-", "+ \"╚██████╗ ██║ ██████╔╝███████╗██║ ██║\") print(red + \"██████╗ ██╗ ██╗██╗███████╗██╗", "\" Playstation\" + green + \" [\" + white +", "+ \" Twitter\" + green + \" [\" + white", "+ \"14\" + green + \"]\" + white + \"", "print(green + \"[\" + white + \"1\" + green +", "green + \" [\" + white + \"15\" + green", "+ white + \"5\" + green + \"]\" + white", "+ Fore.LIGHTYELLOW_EX] ran = random.choice(all_col) def banner(): print(Style.BRIGHT + Fore.LIGHTCYAN_EX,", "= [Style.BRIGHT + Fore.RED, Style.BRIGHT + Fore.CYAN, Style.BRIGHT + Fore.LIGHTCYAN_EX,", "+ \"[\" + white + \"7\" + green + \"]\"", "white + \"10\" + green + \"]\" + white +", "+ \"]\" + red + \" EXIT\") def Welcome(): os.system(\"clear\")", "white + \" AskFM\") print(green + \"[\" + white +", "green + \"]\" + white + \" Playstation\" + green", "\"2\" + green + \"]\" + white + \" Facebook\"", "+ green + \"]\" + white + \" Discord\") print(green", "def banner(): print(Style.BRIGHT + Fore.LIGHTCYAN_EX, \"\\n\", \"- \" * 4,", "+ green + \" [\" + white + \"21\" +", "\"- \" * 4) print(Style.BRIGHT + Fore.LIGHTYELLOW_EX, \"\\n\", \"- \"", "white + \" Paypal\") print(green + \"[\" + white +", "Fore.CYAN, Style.BRIGHT + Fore.LIGHTCYAN_EX, Style.BRIGHT + Fore.LIGHTBLUE_EX, Style.BRIGHT + Fore.LIGHTCYAN_EX,", "\"- \" * 4, \" [+] Coding Instagram @cyber_dioxide_ \",", "+ \"██║ ╚██╔╝ ██╔══██╗██╔══╝ ██╔══██╗\" + white+ blue + white)", "\"16\" + green + \"]\" + white + \" RiotGames\")", "green + \" [\" + white + \"22\" + green", "+ white + \"13\" + green + \"]\" + white", "\" * 4, \" [+] Follow me on Instagram @cyber_dioxide", "white + \" Gamehag\") print(green + \"[\" + white +", "+ \" [\" + white + \"12\" + green +", "\" [\" + white + \"15\" + green + \"]\"", "+ green + \"]\" + white + \" Dropbox\" +", "print(green + \"[\" + white + \"7\" + green +", "Snapchat (simple)\" + green + \" [\" + white +", "print(yellow+\"██████╔╝███████║██║███████╗███████║\" + blue) print(yellow+\"██╔═══╝ ██╔══██║██║╚════██║██╔══██║\" + green) print(yellow+\"██║ ██║ ██║██║███████║██║", "green + \"]\" + white + \" Facebook\" + green", "██╗██████╗ ███████╗██████╗\" + white ) print(white +\"██╔════╝╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗\") print(blue +", "urllib.request import urlopen from Core.helper.color import green, white, blue, red,", "+ \"]\" + white + \" Snapchat\" + green +", "Gmail (simple)\" + green + \" [\" + white +", "\"options:\") print(green + \"[\" + white + \"1\" + green", "\"]\" + white + \" Snapchat\" + green + \"", "+ white + \"18\" + green + \"]\" + white", "+ \"]\" + white + \" Linkedin\" + green +", "Fore.LIGHTMAGENTA_EX, Style.BRIGHT + Fore.LIGHTYELLOW_EX] ran = random.choice(all_col) def banner(): print(Style.BRIGHT", "+ \"19\" + green + \"]\" + white + \"", "+ green + \"]\" + white + \" AskFM\") print(green", "+ \"]\" + white + \" 000Webhost\") print(green + \"[\"", "\"14\" + green + \"]\" + white + \" Spotify\")", "white + \"19\" + green + \"]\" + white +", "Linkedin\" + green + \" [\" + white + \"21\"", "+ white + \"9\" + green + \"]\" + white", "green + \"]\" + white + \" Steam\" + green", "@cyber_dioxide \", \"- \" * 4) print(Style.BRIGHT + Fore.LIGHTYELLOW_EX, \"\\n\",", "+ \"15\" + green + \"]\" + white + \"", "print(red+ \"╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚═╝ ╚═╝ \") banner() print(alert + \"", "+ white + \"6\" + green + \"]\" + white", "+ \" [\" + white + \"17\" + green +", "\"██████╗ ██╗ ██╗██╗███████╗██╗ ██╗\" ) print(white+ \"██╔══██╗██║ ██║██║██╔════╝██║ ██║\" +", "Fore.LIGHTCYAN_EX, \"\\n\", \"- \" * 4, \" [+] Follow me", "white + \"7\" + green + \"]\" + white +", "+ white + \" RiotGames\") print(green + \"[\" + white", "+ white + \"17\" + green + \"]\" + white", "Style.BRIGHT + Fore.LIGHTCYAN_EX, Style.BRIGHT + Fore.LIGHTBLUE_EX, Style.BRIGHT + Fore.LIGHTCYAN_EX, Style.BRIGHT", "white + \"16\" + green + \"]\" + white +", "white + \" Gmail (simple)\" + green + \" [\"", "╚═╝ \") banner() print(alert + \" More Versions Will Come", "+ \"1\" + green + \"]\" + white + \"", "Rockstar\") print(green + \"[\" + white + \"7\" + green", "More Versions Will Come Soon Stay Updated, Follow My Github\\n\")", "+ Fore.CYAN, Style.BRIGHT + Fore.LIGHTCYAN_EX, Style.BRIGHT + Fore.LIGHTBLUE_EX, Style.BRIGHT +", "\" [\" + white + \"18\" + green + \"]\"", "\" Snapchat\" + green + \" [\" + white +", "Style.BRIGHT + Fore.LIGHTYELLOW_EX] ran = random.choice(all_col) def banner(): print(Style.BRIGHT +", "green + \"]\" + white + \" 000Webhost\") print(green +", "RiotGames\") print(green + \"[\" + white + \"6\" + green", "print(Style.BRIGHT + Fore.LIGHTRED_EX, \"\\n\", \"- \" * 4, \"[+] Github:", "print(green + \"╚██████╗ ██║ ██████╔╝███████╗██║ ██║\") print(red + \"██████╗ ██╗", "def menu(): print(blue + \" ██████╗██╗ ██╗██████╗ ███████╗██████╗\" + white", "+ white + \"19\" + green + \"]\" + white", "+ \" RiotGames\") print(green + \"[\" + white + \"6\"", "\"]\" + white + \" Mega\") print(green + \"-----------------------------------------------------------------------\") print(green", "\" * 4) print(Style.BRIGHT + Fore.LIGHTRED_EX, \"\\n\", \"- \" *", "+ white + \"11\" + green + \"]\" + white", "\"\\n\", \"- \" * 4, \"[+] Github: https://github.com/Cyber-Dioxide/ \", \"-", "\" * 4, \" [+] Coding Instagram @cyber_dioxide_ \", \"-", "\" [+] Coding Instagram @cyber_dioxide_ \", \"- \" * 4)", "def connected(host='http://duckduckgo.com'): try: urlopen(host) return True except: return False all_col", "+ Fore.RED, Style.BRIGHT + Fore.CYAN, Style.BRIGHT + Fore.LIGHTCYAN_EX, Style.BRIGHT +", "+ \"]\" + white + \" Blockchain\") print(green + \"[\"", "[\" + white + \"18\" + green + \"]\" +", "white + \"11\" + green + \"]\" + white +", "+ \"]\" + white + \" Discord\") print(green + \"[\"", "white + \"00\" + green + \"]\" + red +", "\" Snapchat (simple)\" + green + \" [\" + white", "+ white + \"2\" + green + \"]\" + white", "white + \"9\" + green + \"]\" + white +", "green + \"]\" + white + \" Gmail\" + green", "+ green + \"]\" + white + \" Gamehag\") print(green", "[\" + white + \"21\" + green + \"]\" +", "print(white +\"██╔════╝╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗\") print(blue + \"██║ ╚████╔╝ ██████╔╝█████╗ ██████╔╝\") print(green", "\"18\" + green + \"]\" + white + \" AskFM\")", "print(green + \"[\" + white + \"00\" + green +", "print(green + \"[\" + white + \"5\" + green +", "install colorama\") from urllib.request import urlopen from Core.helper.color import green,", "[\" + white + \"22\" + green + \"]\" +", "\"12\" + green + \"]\" + white + \" Paypal\")", "\" [\" + white + \"16\" + green + \"]\"", "\"██║ ╚████╔╝ ██████╔╝█████╗ ██████╔╝\") print(green + \"██║ ╚██╔╝ ██╔══██╗██╔══╝ ██╔══██╗\"", "+ \" Rockstar\") print(green + \"[\" + white + \"7\"", "blue, red, start, alert Version = \"2.2\" yellow = (\"\\033[1;33;40m\")", "[Style.BRIGHT + Fore.RED, Style.BRIGHT + Fore.CYAN, Style.BRIGHT + Fore.LIGHTCYAN_EX, Style.BRIGHT", "+ white + \" Blockchain\") print(green + \"[\" + white", "+ \"00\" + green + \"]\" + red + \"", "banner() print(alert + \" More Versions Will Come Soon Stay", "green + \"]\" + white + \" Dropbox\" + green)", "= random.choice(all_col) def banner(): print(Style.BRIGHT + Fore.LIGHTCYAN_EX, \"\\n\", \"- \"", "+ \"2\" + green + \"]\" + white + \"", "white + \"17\" + green + \"]\" + white +", "\" Mega\") print(green + \"-----------------------------------------------------------------------\") print(green + \"[\" + white", "green + \"]\" + white + \" RiotGames\") print(green +", "╚═╝╚═╝╚══════╝╚═╝ ╚═╝ \") banner() print(alert + \" More Versions Will", "(\"\\033[1;33;40m\") def connected(host='http://duckduckgo.com'): try: urlopen(host) return True except: return False", "blue) print(yellow+\"██╔═══╝ ██╔══██║██║╚════██║██╔══██║\" + green) print(yellow+\"██║ ██║ ██║██║███████║██║ ██║\") print(red+", "+ white + \"8\" + green + \"]\" + white", "\"]\" + white + \" Steam\" + green + \"", "Blockchain\") print(green + \"[\" + white + \"5\" + green", "\"22\" + green + \"]\" + white + \" Mega\")", "\" Linkedin\" + green + \" [\" + white +", "+ \"]\" + white + \" Rockstar\") print(green + \"[\"", "My Github\\n\") print(white + \"options:\") print(green + \"[\" + white", "+ green + \"]\" + white + \" Playstation\" +", "4, \" [+] Follow me on Instagram @cyber_dioxide \", \"-", "\" ██████╗██╗ ██╗██████╗ ███████╗██████╗\" + white ) print(white +\"██╔════╝╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗\")", "\" [\" + white + \"12\" + green + \"]\"", "except: return False all_col = [Style.BRIGHT + Fore.RED, Style.BRIGHT +", "\" * 4, \"[+] Github: https://github.com/Cyber-Dioxide/ \", \"- \" *", "+ \"21\" + green + \"]\" + white + \"", "banner() def menu(): print(blue + \" ██████╗██╗ ██╗██████╗ ███████╗██████╗\" +", "@cyber_dioxide_ \", \"- \" * 4) print(Style.BRIGHT + Fore.LIGHTRED_EX, \"\\n\",", "\"00\" + green + \"]\" + red + \" EXIT\")", "\" Gmail\" + green + \" [\" + white +", "+ white + \" Snapchat (simple)\" + green + \"", "all_col = [Style.BRIGHT + Fore.RED, Style.BRIGHT + Fore.CYAN, Style.BRIGHT +", "+ \"[\" + white + \"9\" + green + \"]\"", "on Instagram @cyber_dioxide \", \"- \" * 4) print(Style.BRIGHT +", "\"]\" + white + \" Paypal\") print(green + \"[\" +", "Follow My Github\\n\") print(white + \"options:\") print(green + \"[\" +", "+ \" Mega\") print(green + \"-----------------------------------------------------------------------\") print(green + \"[\" +", "Gamehag\") print(green + \"[\" + white + \"11\" + green", "red, start, alert Version = \"2.2\" yellow = (\"\\033[1;33;40m\") def", "+ \" Linkedin\" + green + \" [\" + white", "return False all_col = [Style.BRIGHT + Fore.RED, Style.BRIGHT + Fore.CYAN,", "+ green + \"]\" + white + \" Snapchat\" +", "AskFM\") print(green + \"[\" + white + \"8\" + green", "[+] Coding Instagram @cyber_dioxide_ \", \"- \" * 4) print(Style.BRIGHT", "print(red + \"██████╗ ██╗ ██╗██╗███████╗██╗ ██╗\" ) print(white+ \"██╔══██╗██║ ██║██║██╔════╝██║", "\" More Versions Will Come Soon Stay Updated, Follow My", "Fore.LIGHTYELLOW_EX] ran = random.choice(all_col) def banner(): print(Style.BRIGHT + Fore.LIGHTCYAN_EX, \"\\n\",", "+ green + \"]\" + white + \" Blockchain\") print(green", "\"9\" + green + \"]\" + white + \" Dropbox\"", "\"1\" + green + \"]\" + white + \" Instagram\"", "+ \" [\" + white + \"14\" + green +", "+ \"]\" + white + \" Steam\" + green +", "\" Gamehag\") print(green + \"[\" + white + \"11\" +", "print(green + \"[\" + white + \"6\" + green +", "[\" + white + \"17\" + green + \"]\" +", "+ \"]\" + white + \" Dropbox\" + green) print(green", "\" RiotGames\") print(green + \"[\" + white + \"6\" +", "green + \"]\" + white + \" Snapchat\" + green", "Core.helper.color import green, white, blue, red, start, alert Version =", "+ \" [\" + white + \"15\" + green +", "\" Facebook\" + green + \" [\" + white +", "Dropbox\" + green) print(green + \"[\" + white + \"10\"", "Coding Instagram @cyber_dioxide_ \", \"- \" * 4) print(Style.BRIGHT +", "green + \"]\" + white + \" Linkedin\" + green", "\"]\" + white + \" Twitter\" + green + \"", "+ white + \" Dropbox\" + green) print(green + \"[\"", "Steam\" + green + \" [\" + white + \"19\"", "\"21\" + green + \"]\" + white + \" Gamehag\")", "green + \" [\" + white + \"13\" + green", "+ \"]\" + white + \" Playstation\" + green +", "print(green + \"-----------------------------------------------------------------------\") print(green + \"[\" + white + \"00\"", "\" [\" + white + \"14\" + green + \"]\"", "+ Fore.LIGHTRED_EX, \"\\n\", \"- \" * 4, \"[+] Github: https://github.com/Cyber-Dioxide/", "colorama import Fore, Style except ModuleNotFoundError: os.system(\"pip install colorama\") from", "╚████╔╝ ██████╔╝█████╗ ██████╔╝\") print(green + \"██║ ╚██╔╝ ██╔══██╗██╔══╝ ██╔══██╗\" +", "+ \"-----------------------------------------------------------------------\") print(green + \"[\" + white + \"00\" +", "+ white + \" 000Webhost\") print(green + \"[\" + white", "\"]\" + white + \" Spotify\") print(green + \"[\" +", "\"]\" + white + \" AskFM\") print(green + \"[\" +", "Style.BRIGHT + Fore.LIGHTCYAN_EX, Style.BRIGHT + Fore.LIGHTMAGENTA_EX, Style.BRIGHT + Fore.LIGHTYELLOW_EX] ran", "+ \"[\" + white + \"5\" + green + \"]\"", "\"[\" + white + \"11\" + green + \"]\" +", "+ blue) print(yellow+\"██╔═══╝ ██╔══██║██║╚════██║██╔══██║\" + green) print(yellow+\"██║ ██║ ██║██║███████║██║ ██║\")", "+ Fore.LIGHTBLUE_EX, Style.BRIGHT + Fore.LIGHTCYAN_EX, Style.BRIGHT + Fore.LIGHTMAGENTA_EX, Style.BRIGHT +", "white + \" Instagram\" + green + \" [\" +", "+ green + \" [\" + white + \"14\" +", "white + \"22\" + green + \"]\" + white +", "menu(): print(blue + \" ██████╗██╗ ██╗██████╗ ███████╗██████╗\" + white )", "\"- \" * 4) print(Style.BRIGHT + Fore.LIGHTRED_EX, \"\\n\", \"- \"", "██║ ██████╔╝███████╗██║ ██║\") print(red + \"██████╗ ██╗ ██╗██╗███████╗██╗ ██╗\" )", "start, alert Version = \"2.2\" yellow = (\"\\033[1;33;40m\") def connected(host='http://duckduckgo.com'):", "white + \" Steam\" + green + \" [\" +", "\"10\" + green + \"]\" + white + \" Linkedin\"", "+ white + \" Twitter\" + green + \" [\"", "+ \" Dropbox\" + green) print(green + \"[\" + white", "+ green + \" [\" + white + \"12\" +", "\"[\" + white + \"4\" + green + \"]\" +", "* 4) print(Style.BRIGHT + Fore.LIGHTYELLOW_EX, \"\\n\", \"- \" * 4,", "+ \"[\" + white + \"8\" + green + \"]\"", "+ green + \"]\" + white + \" Mega\") print(green", "\"13\" + green + \"]\" + white + \" Discord\")", "+ \"11\" + green + \"]\" + white + \"", "white + \" Blockchain\") print(green + \"[\" + white +", "import Fore, Style except ModuleNotFoundError: os.system(\"pip install colorama\") from urllib.request", "\" Spotify\") print(green + \"[\" + white + \"4\" +", "██╗██╗███████╗██╗ ██╗\" ) print(white+ \"██╔══██╗██║ ██║██║██╔════╝██║ ██║\" + green) print(yellow+\"██████╔╝███████║██║███████╗███████║\"", "print(green + \"[\" + white + \"2\" + green +", "\" * 3) banner() def menu(): print(blue + \" ██████╗██╗", "+ green + \"]\" + white + \" Twitter\" +", "import os import random try: from colorama import Fore, Style", "green + \" [\" + white + \"14\" + green", "+ white + \" Steam\" + green + \" [\"", "+ \" Blockchain\") print(green + \"[\" + white + \"5\"", "\" Steam\" + green + \" [\" + white +", "+ \"12\" + green + \"]\" + white + \"", "+ \"options:\") print(green + \"[\" + white + \"1\" +", ") print(white +\"██╔════╝╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗\") print(blue + \"██║ ╚████╔╝ ██████╔╝█████╗ ██████╔╝\")", "Instagram\" + green + \" [\" + white + \"12\"", "\"]\" + white + \" Gamehag\") print(green + \"[\" +", "\"]\" + white + \" Gmail (simple)\" + green +", "print(yellow+\"██╔═══╝ ██╔══██║██║╚════██║██╔══██║\" + green) print(yellow+\"██║ ██║ ██║██║███████║██║ ██║\") print(red+ \"╚═╝", "\" [\" + white + \"21\" + green + \"]\"", "me on Instagram @cyber_dioxide \", \"- \" * 4) print(Style.BRIGHT", "\" Dropbox\" + green) print(green + \"[\" + white +", "from urllib.request import urlopen from Core.helper.color import green, white, blue,", "[\" + white + \"19\" + green + \"]\" +", "███████╗██████╗\" + white ) print(white +\"██╔════╝╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗\") print(blue + \"██║", "\"[\" + white + \"5\" + green + \"]\" +", "Updated, Follow My Github\\n\") print(white + \"options:\") print(green + \"[\"", "+ \"[\" + white + \"6\" + green + \"]\"", "Snapchat\" + green + \" [\" + white + \"17\"", "\"19\" + green + \"]\" + white + \" 000Webhost\")", "+ green + \"]\" + white + \" Paypal\") print(green", "+ \" Spotify\") print(green + \"[\" + white + \"4\"", "\"\\n\", \"- \" * 4, \" [+] Coding Instagram @cyber_dioxide_", "Style.BRIGHT + Fore.LIGHTBLUE_EX, Style.BRIGHT + Fore.LIGHTCYAN_EX, Style.BRIGHT + Fore.LIGHTMAGENTA_EX, Style.BRIGHT", "\"]\" + white + \" Rockstar\") print(green + \"[\" +", "white + \"4\" + green + \"]\" + white +", "\" [+] Follow me on Instagram @cyber_dioxide \", \"- \"", "+ white + \"12\" + green + \"]\" + white", "print(blue + \"██║ ╚████╔╝ ██████╔╝█████╗ ██████╔╝\") print(green + \"██║ ╚██╔╝", "\"██║ ╚██╔╝ ██╔══██╗██╔══╝ ██╔══██╗\" + white+ blue + white) print(green", "+ \"7\" + green + \"]\" + white + \"", "green + \"]\" + red + \" EXIT\") def Welcome():", "ModuleNotFoundError: os.system(\"pip install colorama\") from urllib.request import urlopen from Core.helper.color", ") print(white+ \"██╔══██╗██║ ██║██║██╔════╝██║ ██║\" + green) print(yellow+\"██████╔╝███████║██║███████╗███████║\" + blue)", "from colorama import Fore, Style except ModuleNotFoundError: os.system(\"pip install colorama\")", "colorama\") from urllib.request import urlopen from Core.helper.color import green, white,", "Will Come Soon Stay Updated, Follow My Github\\n\") print(white +", "green + \" [\" + white + \"21\" + green", "green + \"]\" + white + \" Blockchain\") print(green +", "white + \"18\" + green + \"]\" + white +", "ran = random.choice(all_col) def banner(): print(Style.BRIGHT + Fore.LIGHTCYAN_EX, \"\\n\", \"-", "\"- \" * 3) banner() def menu(): print(blue + \"", "\"]\" + white + \" Playstation\" + green + \"", "print(white+ \"██╔══██╗██║ ██║██║██╔════╝██║ ██║\" + green) print(yellow+\"██████╔╝███████║██║███████╗███████║\" + blue) print(yellow+\"██╔═══╝", "+ \"18\" + green + \"]\" + white + \"", "\"[\" + white + \"7\" + green + \"]\" +", "+ white + \" Facebook\" + green + \" [\"", "+ white + \"3\" + green + \"]\" + white", "Soon Stay Updated, Follow My Github\\n\") print(white + \"options:\") print(green", "Fore.LIGHTBLUE_EX, Style.BRIGHT + Fore.LIGHTCYAN_EX, Style.BRIGHT + Fore.LIGHTMAGENTA_EX, Style.BRIGHT + Fore.LIGHTYELLOW_EX]", "* 4) print(Style.BRIGHT + Fore.LIGHTRED_EX, \"\\n\", \"- \" * 4,", "white + \"5\" + green + \"]\" + white +", "import random try: from colorama import Fore, Style except ModuleNotFoundError:", "green + \" [\" + white + \"19\" + green", "green + \"]\" + white + \" Instagram\" + green", "green) print(yellow+\"██║ ██║ ██║██║███████║██║ ██║\") print(red+ \"╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚═╝ ╚═╝", "+ \" Discord\") print(green + \"[\" + white + \"3\"", "+ \"5\" + green + \"]\" + white + \"", "+ green + \"]\" + white + \" 000Webhost\") print(green", "+ white + \" Playstation\" + green + \" [\"", "+ \"██║ ╚████╔╝ ██████╔╝█████╗ ██████╔╝\") print(green + \"██║ ╚██╔╝ ██╔══██╗██╔══╝", "\"2.2\" yellow = (\"\\033[1;33;40m\") def connected(host='http://duckduckgo.com'): try: urlopen(host) return True", "+ green + \" [\" + white + \"13\" +", "+ white + \" Snapchat\" + green + \" [\"", "██║ ██║██║███████║██║ ██║\") print(red+ \"╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚═╝ ╚═╝ \") banner()", "Fore.LIGHTRED_EX, \"\\n\", \"- \" * 4, \"[+] Github: https://github.com/Cyber-Dioxide/ \",", "+ white + \" Paypal\") print(green + \"[\" + white", "[\" + white + \"13\" + green + \"]\" +", "+ white + \"15\" + green + \"]\" + white", "white + \"15\" + green + \"]\" + white +", "[\" + white + \"12\" + green + \"]\" +", "+ \" Instagram\" + green + \" [\" + white", "+ green + \"]\" + white + \" Facebook\" +", "+ green) print(yellow+\"██║ ██║ ██║██║███████║██║ ██║\") print(red+ \"╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚═╝", "alert Version = \"2.2\" yellow = (\"\\033[1;33;40m\") def connected(host='http://duckduckgo.com'): try:", "green + \"]\" + white + \" Spotify\") print(green +", "+ \"13\" + green + \"]\" + white + \"", "Playstation\" + green + \" [\" + white + \"22\"", "+ \" Gmail (simple)\" + green + \" [\" +", "[\" + white + \"14\" + green + \"]\" +", "4, \" [+] Coding Instagram @cyber_dioxide_ \", \"- \" *", "+ white + \"16\" + green + \"]\" + white", "+ white ) print(white +\"██╔════╝╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗\") print(blue + \"██║ ╚████╔╝", "white + \"8\" + green + \"]\" + white +", "white + \" Gmail\" + green + \" [\" +", "(simple)\" + green + \" [\" + white + \"18\"", "3) banner() def menu(): print(blue + \" ██████╗██╗ ██╗██████╗ ███████╗██████╗\"", "* 4, \" [+] Coding Instagram @cyber_dioxide_ \", \"- \"", "+ green + \"]\" + white + \" Rockstar\") print(green", "+ \"4\" + green + \"]\" + white + \"", "print(green + \"[\" + white + \"9\" + green +", "+ green + \"]\" + white + \" Linkedin\" +", "Versions Will Come Soon Stay Updated, Follow My Github\\n\") print(white", "000Webhost\") print(green + \"[\" + white + \"9\" + green", "green + \"]\" + white + \" Twitter\" + green", "white + \" Snapchat\" + green + \" [\" +", "+ \" AskFM\") print(green + \"[\" + white + \"8\"", "<reponame>Cyber-Dioxide/CyberPhish<filename>Core/pre.py import os import random try: from colorama import Fore,", "* 4, \" [+] Follow me on Instagram @cyber_dioxide \",", "white + \"3\" + green + \"]\" + white +", "+ \"]\" + white + \" Snapchat (simple)\" + green", "██████╔╝█████╗ ██████╔╝\") print(green + \"██║ ╚██╔╝ ██╔══██╗██╔══╝ ██╔══██╗\" + white+", "\"╚██████╗ ██║ ██████╔╝███████╗██║ ██║\") print(red + \"██████╗ ██╗ ██╗██╗███████╗██╗ ██╗\"", "\" Blockchain\") print(green + \"[\" + white + \"5\" +", "white + \"14\" + green + \"]\" + white +", "[+] Follow me on Instagram @cyber_dioxide \", \"- \" *", "+ \"]\" + white + \" Instagram\" + green +", "print(Style.BRIGHT + Fore.LIGHTYELLOW_EX, \"\\n\", \"- \" * 4, \" [+]", "Instagram @cyber_dioxide \", \"- \" * 4) print(Style.BRIGHT + Fore.LIGHTYELLOW_EX,", "+ white + \"14\" + green + \"]\" + white", "+ \" Snapchat\" + green + \" [\" + white", "+ \"10\" + green + \"]\" + white + \"", "Version = \"2.2\" yellow = (\"\\033[1;33;40m\") def connected(host='http://duckduckgo.com'): try: urlopen(host)", "+ \"]\" + white + \" Paypal\") print(green + \"[\"", "green + \" [\" + white + \"12\" + green", "print(green + \"[\" + white + \"4\" + green +", "+ white + \" AskFM\") print(green + \"[\" + white", "blue + white) print(green + \"╚██████╗ ██║ ██████╔╝███████╗██║ ██║\") print(red", "\" Twitter\" + green + \" [\" + white +", "green + \"]\" + white + \" Paypal\") print(green +", "\", \"- \" * 3) banner() def menu(): print(blue +", "os.system(\"pip install colorama\") from urllib.request import urlopen from Core.helper.color import", "import urlopen from Core.helper.color import green, white, blue, red, start,", "+ white + \" Mega\") print(green + \"-----------------------------------------------------------------------\") print(green +", "Follow me on Instagram @cyber_dioxide \", \"- \" * 4)", "\" Instagram\" + green + \" [\" + white +", "██╗ ██╗██╗███████╗██╗ ██╗\" ) print(white+ \"██╔══██╗██║ ██║██║██╔════╝██║ ██║\" + green)", "white + \" Facebook\" + green + \" [\" +", "print(Style.BRIGHT + Fore.LIGHTCYAN_EX, \"\\n\", \"- \" * 4, \" [+]", "+ \"]\" + white + \" Spotify\") print(green + \"[\"", "white + \"2\" + green + \"]\" + white +", "██╔══██╗\" + white+ blue + white) print(green + \"╚██████╗ ██║", "+ \" [\" + white + \"13\" + green +", "+ \"]\" + white + \" Mega\") print(green + \"-----------------------------------------------------------------------\")", "white + \"13\" + green + \"]\" + white +", "* 4, \"[+] Github: https://github.com/Cyber-Dioxide/ \", \"- \" * 3)", "+ green + \"]\" + white + \" Steam\" +", "print(white + \"options:\") print(green + \"[\" + white + \"1\"", "green + \"]\" + white + \" Gmail (simple)\" +", "+ white + \" Gmail (simple)\" + green + \"", "print(green + \"[\" + white + \"8\" + green +", "white + \" Snapchat (simple)\" + green + \" [\"", "Fore.LIGHTCYAN_EX, Style.BRIGHT + Fore.LIGHTMAGENTA_EX, Style.BRIGHT + Fore.LIGHTYELLOW_EX] ran = random.choice(all_col)", "+ \" ██████╗██╗ ██╗██████╗ ███████╗██████╗\" + white ) print(white +\"██╔════╝╚██╗", "\"- \" * 4, \"[+] Github: https://github.com/Cyber-Dioxide/ \", \"- \"", "\"]\" + white + \" RiotGames\") print(green + \"[\" +", "\"3\" + green + \"]\" + white + \" Gmail\"", "\"]\" + white + \" Linkedin\" + green + \"", "return True except: return False all_col = [Style.BRIGHT + Fore.RED,", "Instagram @cyber_dioxide_ \", \"- \" * 4) print(Style.BRIGHT + Fore.LIGHTRED_EX,", "Stay Updated, Follow My Github\\n\") print(white + \"options:\") print(green +", "\"]\" + white + \" Dropbox\" + green) print(green +", "+ \"[\" + white + \"3\" + green + \"]\"", "True except: return False all_col = [Style.BRIGHT + Fore.RED, Style.BRIGHT", "Style.BRIGHT + Fore.CYAN, Style.BRIGHT + Fore.LIGHTCYAN_EX, Style.BRIGHT + Fore.LIGHTBLUE_EX, Style.BRIGHT", "+ Fore.LIGHTYELLOW_EX, \"\\n\", \"- \" * 4, \" [+] Coding", "import green, white, blue, red, start, alert Version = \"2.2\"", "https://github.com/Cyber-Dioxide/ \", \"- \" * 3) banner() def menu(): print(blue", "██╔══██║██║╚════██║██╔══██║\" + green) print(yellow+\"██║ ██║ ██║██║███████║██║ ██║\") print(red+ \"╚═╝ ╚═╝", "+ \" [\" + white + \"19\" + green +", "green + \"]\" + white + \" Mega\") print(green +", "green + \" [\" + white + \"17\" + green", "\"[\" + white + \"2\" + green + \"]\" +", "green + \"]\" + white + \" Rockstar\") print(green +", "white + \" Dropbox\" + green) print(green + \"[\" +", "Github\\n\") print(white + \"options:\") print(green + \"[\" + white +", "\"[\" + white + \"3\" + green + \"]\" +", "\" 000Webhost\") print(green + \"[\" + white + \"9\" +", "white + \" Rockstar\") print(green + \"[\" + white +", "\" AskFM\") print(green + \"[\" + white + \"8\" +", "green) print(green + \"[\" + white + \"10\" + green", "\"]\" + white + \" Facebook\" + green + \"", "Twitter\" + green + \" [\" + white + \"16\"", "+ \" [\" + white + \"18\" + green +", "white ) print(white +\"██╔════╝╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗\") print(blue + \"██║ ╚████╔╝ ██████╔╝█████╗", "\"]\" + white + \" Blockchain\") print(green + \"[\" +", "+ \" [\" + white + \"22\" + green +", "+ \" Gamehag\") print(green + \"[\" + white + \"11\"", "+ white+ blue + white) print(green + \"╚██████╗ ██║ ██████╔╝███████╗██║", "\" [\" + white + \"19\" + green + \"]\"", "white+ blue + white) print(green + \"╚██████╗ ██║ ██████╔╝███████╗██║ ██║\")", "Spotify\") print(green + \"[\" + white + \"4\" + green", "\"4\" + green + \"]\" + white + \" Gmail", "4) print(Style.BRIGHT + Fore.LIGHTRED_EX, \"\\n\", \"- \" * 4, \"[+]", "╚═╝ ╚═╝╚═╝╚══════╝╚═╝ ╚═╝ \") banner() print(alert + \" More Versions", "white + \" 000Webhost\") print(green + \"[\" + white +", "\"[\" + white + \"1\" + green + \"]\" +", "False all_col = [Style.BRIGHT + Fore.RED, Style.BRIGHT + Fore.CYAN, Style.BRIGHT", "+ \"8\" + green + \"]\" + white + \"", "+ \"]\" + white + \" AskFM\") print(green + \"[\"", "██║\" + green) print(yellow+\"██████╔╝███████║██║███████╗███████║\" + blue) print(yellow+\"██╔═══╝ ██╔══██║██║╚════██║██╔══██║\" + green)", "██║\") print(red + \"██████╗ ██╗ ██╗██╗███████╗██╗ ██╗\" ) print(white+ \"██╔══██╗██║", "+ \" Facebook\" + green + \" [\" + white", "+ white + \"22\" + green + \"]\" + white", "green, white, blue, red, start, alert Version = \"2.2\" yellow", "+\"██╔════╝╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗\") print(blue + \"██║ ╚████╔╝ ██████╔╝█████╗ ██████╔╝\") print(green +", "╚██╔╝ ██╔══██╗██╔══╝ ██╔══██╗\" + white+ blue + white) print(green +", "\"]\" + white + \" Gmail\" + green + \"", "+ green + \"]\" + red + \" EXIT\") def", "+ white + \"21\" + green + \"]\" + white", "██████╗██╗ ██╗██████╗ ███████╗██████╗\" + white ) print(white +\"██╔════╝╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗\") print(blue", "try: from colorama import Fore, Style except ModuleNotFoundError: os.system(\"pip install", "\"]\" + white + \" Snapchat (simple)\" + green +", "Fore, Style except ModuleNotFoundError: os.system(\"pip install colorama\") from urllib.request import", "+ \"3\" + green + \"]\" + white + \"", "print(green + \"[\" + white + \"3\" + green +", "\", \"- \" * 4) print(Style.BRIGHT + Fore.LIGHTRED_EX, \"\\n\", \"-", "\"15\" + green + \"]\" + white + \" Blockchain\")", "\"\\n\", \"- \" * 4, \" [+] Follow me on", "+ \"██████╗ ██╗ ██╗██╗███████╗██╗ ██╗\" ) print(white+ \"██╔══██╗██║ ██║██║██╔════╝██║ ██║\"", "os import random try: from colorama import Fore, Style except", "urlopen from Core.helper.color import green, white, blue, red, start, alert", "white + \" Mega\") print(green + \"-----------------------------------------------------------------------\") print(green + \"[\"", "Style.BRIGHT + Fore.LIGHTMAGENTA_EX, Style.BRIGHT + Fore.LIGHTYELLOW_EX] ran = random.choice(all_col) def", "+ Fore.LIGHTCYAN_EX, \"\\n\", \"- \" * 4, \" [+] Follow", "+ \"]\" + white + \" Twitter\" + green +", "urlopen(host) return True except: return False all_col = [Style.BRIGHT +", "+ white) print(green + \"╚██████╗ ██║ ██████╔╝███████╗██║ ██║\") print(red +", "= \"2.2\" yellow = (\"\\033[1;33;40m\") def connected(host='http://duckduckgo.com'): try: urlopen(host) return", "= (\"\\033[1;33;40m\") def connected(host='http://duckduckgo.com'): try: urlopen(host) return True except: return", "+ \" [\" + white + \"21\" + green +", "\"7\" + green + \"]\" + white + \" Snapchat", "white) print(green + \"╚██████╗ ██║ ██████╔╝███████╗██║ ██║\") print(red + \"██████╗", "██████╔╝\") print(green + \"██║ ╚██╔╝ ██╔══██╗██╔══╝ ██╔══██╗\" + white+ blue", "yellow = (\"\\033[1;33;40m\") def connected(host='http://duckduckgo.com'): try: urlopen(host) return True except:", "+ green + \" [\" + white + \"19\" +", "Facebook\" + green + \" [\" + white + \"13\"", "[\" + white + \"16\" + green + \"]\" +", "\"17\" + green + \"]\" + white + \" Rockstar\")", "4, \"[+] Github: https://github.com/Cyber-Dioxide/ \", \"- \" * 3) banner()", "██║\") print(red+ \"╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝╚═╝ ╚═╝ \") banner() print(alert +", "+ \"]\" + white + \" Facebook\" + green +", "white + \" Twitter\" + green + \" [\" +", "+ \"[\" + white + \"11\" + green + \"]\"", "except ModuleNotFoundError: os.system(\"pip install colorama\") from urllib.request import urlopen from", "+ \" Steam\" + green + \" [\" + white", "\"[\" + white + \"9\" + green + \"]\" +", "██╗\" ) print(white+ \"██╔══██╗██║ ██║██║██╔════╝██║ ██║\" + green) print(yellow+\"██████╔╝███████║██║███████╗███████║\" +", "\") banner() print(alert + \" More Versions Will Come Soon", "+ white + \" Gmail\" + green + \" [\"", "\"[\" + white + \"6\" + green + \"]\" +", "+ green + \"]\" + white + \" RiotGames\") print(green", "white + \"12\" + green + \"]\" + white +", "+ \" Paypal\") print(green + \"[\" + white + \"2\"", "Come Soon Stay Updated, Follow My Github\\n\") print(white + \"options:\")", "\"]\" + white + \" Instagram\" + green + \"", "+ green + \" [\" + white + \"18\" +", "+ white + \"00\" + green + \"]\" + red", "white + \"1\" + green + \"]\" + white +", "print(alert + \" More Versions Will Come Soon Stay Updated,", "+ \"]\" + white + \" RiotGames\") print(green + \"[\"", "white + \" RiotGames\") print(green + \"[\" + white +", "██╔══██╗██╔══╝ ██╔══██╗\" + white+ blue + white) print(green + \"╚██████╗", "██║██║██╔════╝██║ ██║\" + green) print(yellow+\"██████╔╝███████║██║███████╗███████║\" + blue) print(yellow+\"██╔═══╝ ██╔══██║██║╚════██║██╔══██║\" +", "██╔╝██╔══██╗██╔════╝██╔══██╗\") print(blue + \"██║ ╚████╔╝ ██████╔╝█████╗ ██████╔╝\") print(green + \"██║", "+ \"[\" + white + \"00\" + green + \"]\"", "\" Discord\") print(green + \"[\" + white + \"3\" +" ]
[ "2.0 (the \"License\"); # you may not use this file", "Enter to continue.\\n\") # Validate challenges done, failed, pending =", "{}.\\n\".format( challenge.file_name)) fs.write(challenge_file, challenge.serialize().decode()) pending_challenges.append(challenge) # Quit if nothing to", "'dns': print(\"\\n DNS verification required. Make sure these TXT records\"", "path found at orders path.\\n\".format( domains_hash)) method = method acme", "place:\\n\") for challenge in pending_challenges: token = challenge.contents['token'] # path", "it as expired.\\n\") order.contents['status'] = \"expired\" update_order(order, order_file) if not", "else: if order.invalid: print(\" WARNING: Invalid order, renewing it.\\n Just", "path found at {}.\".format(orders_path)) if not os.path.exists(order_path): if verbose: print(\"Current", "set(), set(), set() for challenge in pending_challenges: print(\" {}: waiting", "print(\" {}: waiting for verification. Checking in 5 \" \"seconds.\".format(challenge.domain))", "acme.verify_order_challenge(challenge, 5, 1) if response['status'] == \"valid\": print(\" {}: OK!", "== \"valid\": print(\" {}: OK! Authorization lasts until {}.\".format( challenge.domain,", "{}\".format(' '.join(pending))) print(\" Try again.\") sys.exit(sysexits.EX_CANNOT_EXECUTE) else: if verbose: print(\"", "OK! Authorization lasts until {}.\".format( challenge.domain, challenge.expires)) done.add(challenge.domain) elif response['status']", "else: if verbose: print(\"Current order {} path found at orders", "path not found creating it at orders \" \"path.\\n\".format(domains_hash)) os.mkdir(order_path)", "when all \" \"verifications are in place.\\n\") else: print(\" WARNING:", "in token and '.' not in token) files.add(token) fs.write( os.path.join(current_path,", "\" \"status.\") order = Order.deserialize(fs.read(order_file)) try: server_order = acme.query_order(order) order.contents", "files.add(token) fs.write( os.path.join(current_path, token), \"%s.%s\" % (token, generate_jwk_thumbprint(account.key)) ) print(\"", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "\"status.\") order = Order.deserialize(fs.read(order_file)) try: server_order = acme.query_order(order) order.contents =", "verbose: print(\" Order file not found creating it.\") order =", ") print(\" http://{}/.well-known/acme-challenge/{}\".format( challenge.domain, token)) print(\"\\n The necessary files have", "print(\"Orders path found at {}.\".format(orders_path)) if not os.path.exists(order_path): if verbose:", "hashlib.sha256( \"_\".join(domains).encode('ascii')).hexdigest() order_path = os.path.join(orders_path, domains_hash) order_file = os.path.join(order_path, \"order.json\".format(domains_hash))", "print(\" {} domain(s) authorized. Let's Encrypt!\".format( len(domains))) sys.exit(sysexits.EX_OK) else: if", "Let's Encrypt!\".format( len(domains))) sys.exit(sysexits.EX_OK) else: if verbose: print(\" Order still", "server_order.contents except: print(\" WARNING: Old order. Setting it as expired.\\n\")", "= acme.verify_order_challenge(challenge, 5, 1) if response['status'] == \"valid\": print(\" {}:", "0o770) else: if verbose: print(\"Orders path found at {}.\".format(orders_path)) if", "if not os.path.exists(order_path): if verbose: print(\"Current order {} path not", "print(\" WARNING: The current order will be invalidated. \" \"Try", "print(\" Deleting invalid challenge file {}.\\n\".format( challenge.file_name)) clean_challenge_file(challenge_file) os.remove(order_file) os.rmdir(order_path)", "{}\".format(' '.join(done) or \"N/A\")) print(\" Pending: {}\".format(' '.join(pending))) print(\" Try", "invalidated. \" \"Try again.\") if verbose: print(\" Deleting invalid challenge", "\"\"\" from . import get_version from .acme import AcmeV2 from", "\" \"at {}.\\n\".format(order.contents['expires'])) else: if order.invalid: print(\" WARNING: Invalid order,", "it at {}.\" \"\".format(orders_path)) os.mkdir(orders_path) os.chmod(orders_path, 0o770) else: if verbose:", "challenge.domain, response['error']['detail'], response['error']['type']) ) failed.add(challenge.domain) break else: print(\"{}: Pending!\".format(challenge.domain)) pending.add(challenge.domain)", "update_order(order, order_file): fs.write(order_file, order.serialize().decode()) def clean_http_challenges(files): # Clean up created", "verbose: print(\" Found order file. Querying ACME server for current", "the authorization when all \" \"verifications are in place.\\n\") else:", "print(\" {}: {} ({})\".format( challenge.domain, response['error']['detail'], response['error']['type']) ) failed.add(challenge.domain) break", "use this file except in compliance with the License. #", "sys.exit(sysexits.EX_FATAL_ERROR) else: if pending: print(\" {} domain(s) authorized, {} pending.\".format(", "create_order(acme, domains, method, order_file): order = acme.new_order(domains, method) update_order(order, order_file)", "method, verbose=False): print(\"Candango Automatoes {}. Manuale replacement.\\n\\n\".format( get_version())) current_path =", "AcmeV2(server, account) try: print(\"Authorizing {}.\\n\".format(\", \".join(domains))) # Creating orders for", "= challenge.contents['token'] # path sanity check assert (token and os.path.sep", "\"%s.%s\" % (token, generate_jwk_thumbprint(account.key)) ) print(\" http://{}/.well-known/acme-challenge/{}\".format( challenge.domain, token)) print(\"\\n", "pending_challenges = [] for challenge in acme.get_order_challenges(order): print(\" Requesting challenge", "except IOError as e: print(\"A connection or service error occurred.", "{}\".format(path)) def clean_challenge_file(challenge_file): try: os.remove(challenge_file) except: print(\"Couldn't delete challenge file", "order.contents['status'] == 'valid': print(\" Order is valid and expires at", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "it.\") order = create_order(acme, domains, method, order_file) else: if verbose:", "Setting it as expired.\\n\") order.contents['status'] = \"expired\" update_order(order, order_file) if", "sys.exit(sysexits.EX_OK) else: if verbose: print(\" Order still pending and expires", "print(\" {} domain(s) authorized, {} pending.\".format( len(done), len(pending))) print(\" Authorized:", "HTTP verification required. Make sure these files are \" \"in", "License. # You may obtain a copy of the License", "(token, generate_jwk_thumbprint(account.key)) ) print(\" http://{}/.well-known/acme-challenge/{}\".format( challenge.domain, token)) print(\"\\n The necessary", "create_order(acme, domains, method, order_file) else: if verbose: print(\" Found order", "challenge_file = os.path.join(order_path, challenge.file_name) if verbose: print(\" Creating challenge file", "<NAME> under MIT License # # Licensed under the Apache", "order_file): fs.write(order_file, order.serialize().decode()) def clean_http_challenges(files): # Clean up created files", "under the License is distributed on an \"AS IS\" BASIS,", "Order.deserialize(fs.read(order_file)) try: server_order = acme.query_order(order) order.contents = server_order.contents except: print(\"", "\" \"in place:\\n\") for challenge in pending_challenges: token = challenge.contents['token']", "License for the specific language governing permissions and # limitations", "already authorized until {}.\".format( challenge.domain, challenge.expires)) continue else: challenge_file =", "challenge.key)) elif method == 'http': print(\"\\n HTTP verification required. Make", "all \" \"verifications are in place.\\n\") else: print(\" WARNING: Expired", "create_order(acme, domains, method, order_file) update_order(order, order_file) pending_challenges = [] for", "in 5 \" \"seconds.\".format(challenge.domain)) response = acme.verify_order_challenge(challenge, 5, 1) if", "sure these files are \" \"in place:\\n\") for challenge in", "challenge.domain, challenge.expires)) done.add(challenge.domain) elif response['status'] == 'invalid': print(\" {}: {}", "order. Renewing order.\\n\") os.remove(order_file) order = create_order(acme, domains, method, order_file)", "from cartola import fs, sysexits import hashlib import os import", "until {}.\".format( challenge.domain, challenge.expires)) done.add(challenge.domain) elif response['status'] == 'invalid': print(\"", "Found order file. Querying ACME server for current \" \"status.\")", ".model import Order from cartola import fs, sysexits import hashlib", "len(done), len(pending))) print(\" Authorized: {}\".format(' '.join(done) or \"N/A\")) print(\" Pending:", "status.\\n\") server_order = acme.query_order(order) order.contents = server_order.contents update_order(order, order_file) print(\"", "challenge.file_name)) clean_challenge_file(challenge_file) os.remove(order_file) os.rmdir(order_path) if method == 'http': print(files) clean_http_challenges(files)", "challenge for {}.\".format(challenge.domain)) if challenge.status == 'valid': print(\" {} is", "0o770) else: if verbose: print(\"Current order {} path found at", "governing permissions and # limitations under the License. \"\"\" The", ".crypto import generate_jwk_thumbprint from .errors import AutomatoesError from .model import", "\"at {}.\\n\".format(order.contents['expires'])) else: if order.invalid: print(\" WARNING: Invalid order, renewing", "challenge.expires)) done.add(challenge.domain) elif response['status'] == 'invalid': print(\" {}: {} ({})\".format(", "\"valid\": print(\" {}: OK! Authorization lasts until {}.\".format( challenge.domain, challenge.expires))", "Querying ACME server for current \" \"status.\") order = Order.deserialize(fs.read(order_file))", "failed.\".format( len(done), len(failed), )) print(\" Authorized: {}\".format(' '.join(done) or \"N/A\"))", "print(\" WARNING: Invalid order, renewing it.\\n Just \" \"continue with", "for the user to complete the challenges input(\"\\nPress Enter to", "# Print results if failed: print(\" {} domain(s) authorized, {}", "sys def create_order(acme, domains, method, order_file): order = acme.new_order(domains, method)", "not os.path.exists(order_file): if verbose: print(\" Order file not found creating", "the user to complete the challenges input(\"\\nPress Enter to continue.\\n\")", "print(\"Candango Automatoes {}. Manuale replacement.\\n\\n\".format( get_version())) current_path = paths['current'] orders_path", "Copyright 2016-2017 <NAME> under MIT License # # Licensed under", "in compliance with the License. # You may obtain a", "if verbose: print(\"Orders path found at {}.\".format(orders_path)) if not os.path.exists(order_path):", "Try again.\") sys.exit(sysexits.EX_CANNOT_EXECUTE) else: if verbose: print(\" Deleting valid challenge", "= paths['orders'] domains_hash = hashlib.sha256( \"_\".join(domains).encode('ascii')).hexdigest() order_path = os.path.join(orders_path, domains_hash)", "software # distributed under the License is distributed on an", "print(\" Pending: {}\".format(' '.join(pending))) print(\" Try again.\") sys.exit(sysexits.EX_CANNOT_EXECUTE) else: if", "sys.exit(sysexits.EX_OK) files = set() if method == 'dns': print(\"\\n DNS", "print(\" Authorized: {}\".format(' '.join(done) or \"N/A\")) print(\" Failed: {}\".format(' '.join(failed)))", "token) files.add(token) fs.write( os.path.join(current_path, token), \"%s.%s\" % (token, generate_jwk_thumbprint(account.key)) )", "current status.\\n\") server_order = acme.query_order(order) order.contents = server_order.contents update_order(order, order_file)", "os.path.join(order_path, challenge.file_name) if verbose: print(\" Creating challenge file {}.\\n\".format( challenge.file_name))", "print(\" WARNING: Expired order. Renewing order.\\n\") os.remove(order_file) order = create_order(acme,", "len(domains))) sys.exit(sysexits.EX_OK) else: if verbose: print(\" Order still pending and", "Authorized: {}\".format(' '.join(done) or \"N/A\")) print(\" Failed: {}\".format(' '.join(failed))) print(\"", "os.path.join(current_path, token), \"%s.%s\" % (token, generate_jwk_thumbprint(account.key)) ) print(\" http://{}/.well-known/acme-challenge/{}\".format( challenge.domain,", "method == 'dns': print(\"\\n DNS verification required. Make sure these", "_acme-challenge.{}. IN TXT \" \"\\\"{}\\\"\".format(challenge.domain, challenge.key)) elif method == 'http':", "print(\" Order is valid and expires at {}. Please run", "== 'valid': print(\" Order is valid and expires at {}.", "== 'http': print(files) clean_http_challenges(files) sys.exit(sysexits.EX_FATAL_ERROR) else: if pending: print(\" {}", "exiting.\") sys.exit(sysexits.EX_OK) files = set() if method == 'dns': print(\"\\n", "print(\" {} is already authorized until {}.\".format( challenge.domain, challenge.expires)) continue", "are in place:\\n\") for challenge in pending_challenges: print(\" _acme-challenge.{}. IN", "from .acme import AcmeV2 from .crypto import generate_jwk_thumbprint from .errors", "is valid and expires at {}. Please run \" \"the", "still pending and expires \" \"at {}.\\n\".format(order.contents['expires'])) else: if order.invalid:", "\" are in place:\\n\") for challenge in pending_challenges: print(\" _acme-challenge.{}.", "domains, method, order_file): order = acme.new_order(domains, method) update_order(order, order_file) return", "len(done))) if method == 'http': clean_http_challenges(files) sys.exit(sysexits.EX_OK) except IOError as", "#!/usr/bin/env python # # Copyright 2019-2020 <NAME> # Copyright 2016-2017", "method == 'http': print(\"\\n HTTP verification required. Make sure these", "verbose: print(\"Current order {} path found at orders path.\\n\".format( domains_hash))", "if verbose: print(\"Current order {} path found at orders path.\\n\".format(", "def update_order(order, order_file): fs.write(order_file, order.serialize().decode()) def clean_http_challenges(files): # Clean up", "order {} path not found creating it at orders \"", "\" \"directory.\\n\") # Wait for the user to complete the", "in pending_challenges: print(\" _acme-challenge.{}. IN TXT \" \"\\\"{}\\\"\".format(challenge.domain, challenge.key)) elif", "order.contents = server_order.contents update_order(order, order_file) print(\" {} domain(s) authorized. Let's", "not os.path.exists(order_path): if verbose: print(\"Current order {} path not found", "else: if pending: print(\" {} domain(s) authorized, {} pending.\".format( len(done),", "paths, account, domains, method, verbose=False): print(\"Candango Automatoes {}. Manuale replacement.\\n\\n\".format(", "expires \" \"at {}.\\n\".format(order.contents['expires'])) else: if order.invalid: print(\" WARNING: Invalid", "challenge in pending_challenges: print(\" {}: waiting for verification. Checking in", ".acme import AcmeV2 from .crypto import generate_jwk_thumbprint from .errors import", "if nothing to authorize if not pending_challenges: print(\"\\nAll domains are", "Encrypt!\".format( len(done))) if method == 'http': clean_http_challenges(files) sys.exit(sysexits.EX_OK) except IOError", "= create_order(acme, domains, method, order_file) else: if verbose: print(\" Found", "if challenge.status == 'valid': print(\" {} is already authorized until", "{} pending.\".format( len(done), len(pending))) print(\" Authorized: {}\".format(' '.join(done) or \"N/A\"))", "again.\") sys.exit(sysexits.EX_CANNOT_EXECUTE) else: if verbose: print(\" Deleting valid challenge file", "in place.\\n\") else: print(\" WARNING: Expired order. Renewing order.\\n\") os.remove(order_file)", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "order_file) if not order.expired and not order.invalid: if order.contents['status'] ==", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "os.path.exists(order_file): if verbose: print(\" Order file not found creating it.\")", "= os.path.join(order_path, challenge.file_name) if verbose: print(\" Creating challenge file {}.\\n\".format(", "to in writing, software # distributed under the License is", "not pending_challenges: print(\"\\nAll domains are already authorized, exiting.\") sys.exit(sysexits.EX_OK) files", "paths['current'] orders_path = paths['orders'] domains_hash = hashlib.sha256( \"_\".join(domains).encode('ascii')).hexdigest() order_path =", "print(\" http://{}/.well-known/acme-challenge/{}\".format( challenge.domain, token)) print(\"\\n The necessary files have been", "order.invalid: if order.contents['status'] == 'valid': print(\" Order is valid and", "# See the License for the specific language governing permissions", "update_order(order, order_file) if not order.expired and not order.invalid: if order.contents['status']", "challenge.file_name) if verbose: print(\" Creating challenge file {}.\\n\".format( challenge.file_name)) fs.write(challenge_file,", "for path in files: try: os.remove(path) except: print(\"Couldn't delete http", "replacement.\\n\\n\".format( get_version())) current_path = paths['current'] orders_path = paths['orders'] domains_hash =", "file {}\".format(challenge_file)) def authorize(server, paths, account, domains, method, verbose=False): print(\"Candango", "domains are already authorized, exiting.\") sys.exit(sysexits.EX_OK) files = set() if", "# limitations under the License. \"\"\" The domain authorization command.", "clean_http_challenges(files): # Clean up created files for path in files:", "to continue.\\n\") # Validate challenges done, failed, pending = set(),", "else: print(\"{}: Pending!\".format(challenge.domain)) pending.add(challenge.domain) break challenge_file = os.path.join(order_path, challenge.file_name) #", "verbose: print(\" Querying ACME server for current status.\\n\") server_order =", "Querying ACME server for current status.\\n\") server_order = acme.query_order(order) order.contents", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "clean_challenge_file(challenge_file): try: os.remove(challenge_file) except: print(\"Couldn't delete challenge file {}\".format(challenge_file)) def", "verbose=False): print(\"Candango Automatoes {}. Manuale replacement.\\n\\n\".format( get_version())) current_path = paths['current']", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "domain(s) authorized. Let's Encrypt!\".format( len(domains))) sys.exit(sysexits.EX_OK) else: if verbose: print(\"", "and expires at {}. Please run \" \"the issue \"", "authorized. Let's Encrypt!\".format( len(domains))) sys.exit(sysexits.EX_OK) else: if verbose: print(\" Order", "with the License. # You may obtain a copy of", "failed.add(challenge.domain) break else: print(\"{}: Pending!\".format(challenge.domain)) pending.add(challenge.domain) break challenge_file = os.path.join(order_path,", "verbose: print(\" Order still pending and expires \" \"at {}.\\n\".format(order.contents['expires']))", "fs.write( os.path.join(current_path, token), \"%s.%s\" % (token, generate_jwk_thumbprint(account.key)) ) print(\" http://{}/.well-known/acme-challenge/{}\".format(", "authorized. Let's Encrypt!\".format( len(done))) if method == 'http': clean_http_challenges(files) sys.exit(sysexits.EX_OK)", "1) if response['status'] == \"valid\": print(\" {}: OK! Authorization lasts", "orders_path = paths['orders'] domains_hash = hashlib.sha256( \"_\".join(domains).encode('ascii')).hexdigest() order_path = os.path.join(orders_path,", "Let's Encrypt!\".format( len(done))) if method == 'http': clean_http_challenges(files) sys.exit(sysexits.EX_OK) except", "verification. Checking in 5 \" \"seconds.\".format(challenge.domain)) response = acme.verify_order_challenge(challenge, 5,", "to the current \" \"directory.\\n\") # Wait for the user", "import generate_jwk_thumbprint from .errors import AutomatoesError from .model import Order", "verbose: print(\" Creating challenge file {}.\\n\".format( challenge.file_name)) fs.write(challenge_file, challenge.serialize().decode()) pending_challenges.append(challenge)", "print(\" Authorized: {}\".format(' '.join(done) or \"N/A\")) print(\" Pending: {}\".format(' '.join(pending)))", "2019-2020 <NAME> # Copyright 2016-2017 <NAME> under MIT License #", "order_file) else: if verbose: print(\" Found order file. Querying ACME", "waiting for verification. Checking in 5 \" \"seconds.\".format(challenge.domain)) response =", "compliance with the License. # You may obtain a copy", "'.join(done) or \"N/A\")) print(\" Pending: {}\".format(' '.join(pending))) print(\" Try again.\")", "agreed to in writing, software # distributed under the License", "order.contents = server_order.contents except: print(\" WARNING: Old order. Setting it", "sys.exit(sysexits.EX_OK) except IOError as e: print(\"A connection or service error", "set() if method == 'dns': print(\"\\n DNS verification required. Make", "distributed under the License is distributed on an \"AS IS\"", "domains, method, order_file) update_order(order, order_file) pending_challenges = [] for challenge", "WARNING: Old order. Setting it as expired.\\n\") order.contents['status'] = \"expired\"", "already authorized, exiting.\") sys.exit(sysexits.EX_OK) files = set() if method ==", "files have been written to the current \" \"directory.\\n\") #", "return order def update_order(order, order_file): fs.write(order_file, order.serialize().decode()) def clean_http_challenges(files): #", "len(done), len(failed), )) print(\" Authorized: {}\".format(' '.join(done) or \"N/A\")) print(\"", "{}.\".format(orders_path)) if not os.path.exists(order_path): if verbose: print(\"Current order {} path", "and '.' not in token) files.add(token) fs.write( os.path.join(current_path, token), \"%s.%s\"", "in pending_challenges: print(\" {}: waiting for verification. Checking in 5", "'.' not in token) files.add(token) fs.write( os.path.join(current_path, token), \"%s.%s\" %", "express or implied. # See the License for the specific", "{} failed.\".format( len(done), len(failed), )) print(\" Authorized: {}\".format(' '.join(done) or", "are \" \"in place:\\n\") for challenge in pending_challenges: token =", "expires at {}. Please run \" \"the issue \" \"command.\\n\".format(order.contents['expires']))", "except in compliance with the License. # You may obtain", "'http': print(\"\\n HTTP verification required. Make sure these files are", "method = method acme = AcmeV2(server, account) try: print(\"Authorizing {}.\\n\".format(\",", "and os.path.sep not in token and '.' not in token)", "clean_http_challenges(files) sys.exit(sysexits.EX_FATAL_ERROR) else: if pending: print(\" {} domain(s) authorized, {}", "done.add(challenge.domain) elif response['status'] == 'invalid': print(\" {}: {} ({})\".format( challenge.domain,", "print(files) clean_http_challenges(files) sys.exit(sysexits.EX_FATAL_ERROR) else: if pending: print(\" {} domain(s) authorized,", "for challenge in acme.get_order_challenges(order): print(\" Requesting challenge for {}.\".format(challenge.domain)) if", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "os.path.exists(order_path): if verbose: print(\"Current order {} path not found creating", "DNS verification required. Make sure these TXT records\" \" are", "path sanity check assert (token and os.path.sep not in token", "not use this file except in compliance with the License.", "necessary files have been written to the current \" \"directory.\\n\")", "writing, software # distributed under the License is distributed on", "Creating orders for domains if not existent if not os.path.exists(order_file):", "verbose: print(\"Orders path not found creating it at {}.\" \"\".format(orders_path))", "you may not use this file except in compliance with", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "domain authorization command. \"\"\" from . import get_version from .acme", "at orders \" \"path.\\n\".format(domains_hash)) os.mkdir(order_path) os.chmod(order_path, 0o770) else: if verbose:", "order = Order.deserialize(fs.read(order_file)) try: server_order = acme.query_order(order) order.contents = server_order.contents", ".errors import AutomatoesError from .model import Order from cartola import", "method == 'http': print(files) clean_http_challenges(files) sys.exit(sysexits.EX_FATAL_ERROR) else: if pending: print(\"", "if not pending_challenges: print(\"\\nAll domains are already authorized, exiting.\") sys.exit(sysexits.EX_OK)", "Order from cartola import fs, sysexits import hashlib import os", "import fs, sysexits import hashlib import os import sys def", "import hashlib import os import sys def create_order(acme, domains, method,", "path.\\n\".format( domains_hash)) method = method acme = AcmeV2(server, account) try:", "print(\"Current order {} path found at orders path.\\n\".format( domains_hash)) method", "token)) print(\"\\n The necessary files have been written to the", "challenges done, failed, pending = set(), set(), set() for challenge", "authorized, {} failed.\".format( len(done), len(failed), )) print(\" Authorized: {}\".format(' '.join(done)", "{} is already authorized until {}.\".format( challenge.domain, challenge.expires)) continue else:", "print(\" Requesting challenge for {}.\".format(challenge.domain)) if challenge.status == 'valid': print(\"", "CONDITIONS OF ANY KIND, either express or implied. # See", "import get_version from .acme import AcmeV2 from .crypto import generate_jwk_thumbprint", "order.expired and not order.invalid: if order.contents['status'] == 'valid': print(\" Order", "if verbose: print(\" Order file not found creating it.\") order", "'.join(failed))) print(\" WARNING: The current order will be invalidated. \"", "authorize if not pending_challenges: print(\"\\nAll domains are already authorized, exiting.\")", "{} domain(s) authorized, {} failed.\".format( len(done), len(failed), )) print(\" Authorized:", "= \"expired\" update_order(order, order_file) if not order.expired and not order.invalid:", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "paths['orders'] domains_hash = hashlib.sha256( \"_\".join(domains).encode('ascii')).hexdigest() order_path = os.path.join(orders_path, domains_hash) order_file", "order. Setting it as expired.\\n\") order.contents['status'] = \"expired\" update_order(order, order_file)", "Expired order. Renewing order.\\n\") os.remove(order_file) order = create_order(acme, domains, method,", "if method == 'dns': print(\"\\n DNS verification required. Make sure", "order.\\n\") os.remove(order_file) order = create_order(acme, domains, method, order_file) update_order(order, order_file)", "elif response['status'] == 'invalid': print(\" {}: {} ({})\".format( challenge.domain, response['error']['detail'],", "token and '.' not in token) files.add(token) fs.write( os.path.join(current_path, token),", "file {}\".format(path)) def clean_challenge_file(challenge_file): try: os.remove(challenge_file) except: print(\"Couldn't delete challenge", "{}: {} ({})\".format( challenge.domain, response['error']['detail'], response['error']['type']) ) failed.add(challenge.domain) break else:", "MIT License # # Licensed under the Apache License, Version", "{} path found at orders path.\\n\".format( domains_hash)) method = method", "{}.\".format( challenge.domain, challenge.expires)) continue else: challenge_file = os.path.join(order_path, challenge.file_name) if", "TXT records\" \" are in place:\\n\") for challenge in pending_challenges:", "these files are \" \"in place:\\n\") for challenge in pending_challenges:", "\" \"continue with the authorization when all \" \"verifications are", "if verbose: print(\" Deleting valid challenge file {}.\".format( challenge.file_name)) clean_challenge_file(challenge_file)", "print(\" Querying ACME server for current status.\\n\") server_order = acme.query_order(order)", "# Copyright 2016-2017 <NAME> under MIT License # # Licensed", "method == 'http': clean_http_challenges(files) sys.exit(sysexits.EX_OK) except IOError as e: print(\"A", "verbose: print(\" Deleting invalid challenge file {}.\\n\".format( challenge.file_name)) clean_challenge_file(challenge_file) os.remove(order_file)", "= hashlib.sha256( \"_\".join(domains).encode('ascii')).hexdigest() order_path = os.path.join(orders_path, domains_hash) order_file = os.path.join(order_path,", "order_file = os.path.join(order_path, \"order.json\".format(domains_hash)) if not os.path.exists(orders_path): if verbose: print(\"Orders", "= create_order(acme, domains, method, order_file) update_order(order, order_file) pending_challenges = []", "Validate challenges done, failed, pending = set(), set(), set() for", "Print results if failed: print(\" {} domain(s) authorized, {} failed.\".format(", "else: if verbose: print(\" Deleting valid challenge file {}.\".format( challenge.file_name))", "= method acme = AcmeV2(server, account) try: print(\"Authorizing {}.\\n\".format(\", \".join(domains)))", "run \" \"the issue \" \"command.\\n\".format(order.contents['expires'])) print(\" {} domain(s) authorized.", "command. \"\"\" from . import get_version from .acme import AcmeV2", "not found creating it at {}.\" \"\".format(orders_path)) os.mkdir(orders_path) os.chmod(orders_path, 0o770)", "os import sys def create_order(acme, domains, method, order_file): order =", "\" \"verifications are in place.\\n\") else: print(\" WARNING: Expired order.", "order_file): order = acme.new_order(domains, method) update_order(order, order_file) return order def", "print(\"Current order {} path not found creating it at orders", "print(\" Order file not found creating it.\") order = create_order(acme,", "these TXT records\" \" are in place:\\n\") for challenge in", "records\" \" are in place:\\n\") for challenge in pending_challenges: print(\"", "try: os.remove(challenge_file) except: print(\"Couldn't delete challenge file {}\".format(challenge_file)) def authorize(server,", "been written to the current \" \"directory.\\n\") # Wait for", "{} domain(s) authorized, {} pending.\".format( len(done), len(pending))) print(\" Authorized: {}\".format('", "OR CONDITIONS OF ANY KIND, either express or implied. #", "AutomatoesError from .model import Order from cartola import fs, sysexits", "method, order_file) update_order(order, order_file) pending_challenges = [] for challenge in", "verbose: print(\"Orders path found at {}.\".format(orders_path)) if not os.path.exists(order_path): if", "order = create_order(acme, domains, method, order_file) update_order(order, order_file) pending_challenges =", "the License is distributed on an \"AS IS\" BASIS, #", "import AcmeV2 from .crypto import generate_jwk_thumbprint from .errors import AutomatoesError", "os.path.exists(orders_path): if verbose: print(\"Orders path not found creating it at", "print(\"Authorizing {}.\\n\".format(\", \".join(domains))) # Creating orders for domains if not", "account) try: print(\"Authorizing {}.\\n\".format(\", \".join(domains))) # Creating orders for domains", "response['status'] == \"valid\": print(\" {}: OK! Authorization lasts until {}.\".format(", "{}.\" \"\".format(orders_path)) os.mkdir(orders_path) os.chmod(orders_path, 0o770) else: if verbose: print(\"Orders path", "[] for challenge in acme.get_order_challenges(order): print(\" Requesting challenge for {}.\".format(challenge.domain))", "results if failed: print(\" {} domain(s) authorized, {} failed.\".format( len(done),", "or \"N/A\")) print(\" Failed: {}\".format(' '.join(failed))) print(\" WARNING: The current", "language governing permissions and # limitations under the License. \"\"\"", "get_version())) current_path = paths['current'] orders_path = paths['orders'] domains_hash = hashlib.sha256(", "WARNING: The current order will be invalidated. \" \"Try again.\")", "is already authorized until {}.\".format( challenge.domain, challenge.expires)) continue else: challenge_file", "({})\".format( challenge.domain, response['error']['detail'], response['error']['type']) ) failed.add(challenge.domain) break else: print(\"{}: Pending!\".format(challenge.domain))", "files are \" \"in place:\\n\") for challenge in pending_challenges: token", "order will be invalidated. \" \"Try again.\") if verbose: print(\"", "TXT \" \"\\\"{}\\\"\".format(challenge.domain, challenge.key)) elif method == 'http': print(\"\\n HTTP", "IN TXT \" \"\\\"{}\\\"\".format(challenge.domain, challenge.key)) elif method == 'http': print(\"\\n", "os.path.sep not in token and '.' not in token) files.add(token)", "pending = set(), set(), set() for challenge in pending_challenges: print(\"", "{}.\".format( challenge.domain, challenge.expires)) done.add(challenge.domain) elif response['status'] == 'invalid': print(\" {}:", "os.remove(path) except: print(\"Couldn't delete http challenge file {}\".format(path)) def clean_challenge_file(challenge_file):", "path in files: try: os.remove(path) except: print(\"Couldn't delete http challenge", "for current \" \"status.\") order = Order.deserialize(fs.read(order_file)) try: server_order =", "Pending!\".format(challenge.domain)) pending.add(challenge.domain) break challenge_file = os.path.join(order_path, challenge.file_name) # Print results", "Old order. Setting it as expired.\\n\") order.contents['status'] = \"expired\" update_order(order,", "delete http challenge file {}\".format(path)) def clean_challenge_file(challenge_file): try: os.remove(challenge_file) except:", "law or agreed to in writing, software # distributed under", "set(), set() for challenge in pending_challenges: print(\" {}: waiting for", "os.remove(order_file) order = create_order(acme, domains, method, order_file) update_order(order, order_file) pending_challenges", "check assert (token and os.path.sep not in token and '.'", "acme.get_order_challenges(order): print(\" Requesting challenge for {}.\".format(challenge.domain)) if challenge.status == 'valid':", "if verbose: print(\" Querying ACME server for current status.\\n\") server_order", "in files: try: os.remove(path) except: print(\"Couldn't delete http challenge file", "if verbose: print(\" Found order file. Querying ACME server for", "at {}.\" \"\".format(orders_path)) os.mkdir(orders_path) os.chmod(orders_path, 0o770) else: if verbose: print(\"Orders", "current \" \"status.\") order = Order.deserialize(fs.read(order_file)) try: server_order = acme.query_order(order)", "as e: print(\"A connection or service error occurred. Aborting.\") raise", "token), \"%s.%s\" % (token, generate_jwk_thumbprint(account.key)) ) print(\" http://{}/.well-known/acme-challenge/{}\".format( challenge.domain, token))", "Order still pending and expires \" \"at {}.\\n\".format(order.contents['expires'])) else: if", "print(\" {} domain(s) authorized, {} failed.\".format( len(done), len(failed), )) print(\"", "print(\"\\nAll domains are already authorized, exiting.\") sys.exit(sysexits.EX_OK) files = set()", "in pending_challenges: token = challenge.contents['token'] # path sanity check assert", "if failed: print(\" {} domain(s) authorized, {} failed.\".format( len(done), len(failed),", "{} domain(s) authorized. Let's Encrypt!\".format( len(done))) if method == 'http':", "print(\"Couldn't delete http challenge file {}\".format(path)) def clean_challenge_file(challenge_file): try: os.remove(challenge_file)", "= os.path.join(order_path, \"order.json\".format(domains_hash)) if not os.path.exists(orders_path): if verbose: print(\"Orders path", "have been written to the current \" \"directory.\\n\") # Wait", "current order will be invalidated. \" \"Try again.\") if verbose:", "else: if verbose: print(\" Order still pending and expires \"", "(token and os.path.sep not in token and '.' not in", "may obtain a copy of the License at # #", "import Order from cartola import fs, sysexits import hashlib import", "challenge file {}.\\n\".format( challenge.file_name)) clean_challenge_file(challenge_file) os.remove(order_file) os.rmdir(order_path) if method ==", "Copyright 2019-2020 <NAME> # Copyright 2016-2017 <NAME> under MIT License", "{}.\\n\".format(\", \".join(domains))) # Creating orders for domains if not existent", "response = acme.verify_order_challenge(challenge, 5, 1) if response['status'] == \"valid\": print(\"", "= AcmeV2(server, account) try: print(\"Authorizing {}.\\n\".format(\", \".join(domains))) # Creating orders", "= acme.new_order(domains, method) update_order(order, order_file) return order def update_order(order, order_file):", "not os.path.exists(orders_path): if verbose: print(\"Orders path not found creating it", "creating it.\") order = create_order(acme, domains, method, order_file) else: if", "required. Make sure these TXT records\" \" are in place:\\n\")", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "AcmeV2 from .crypto import generate_jwk_thumbprint from .errors import AutomatoesError from", "= server_order.contents except: print(\" WARNING: Old order. Setting it as", "{}. Manuale replacement.\\n\\n\".format( get_version())) current_path = paths['current'] orders_path = paths['orders']", "may not use this file except in compliance with the", "License # # Licensed under the Apache License, Version 2.0", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "found at {}.\".format(orders_path)) if not os.path.exists(order_path): if verbose: print(\"Current order", "ACME server for current status.\\n\") server_order = acme.query_order(order) order.contents =", "sure these TXT records\" \" are in place:\\n\") for challenge", "this file except in compliance with the License. # You", "with the authorization when all \" \"verifications are in place.\\n\")", "print(\" _acme-challenge.{}. IN TXT \" \"\\\"{}\\\"\".format(challenge.domain, challenge.key)) elif method ==", "import sys def create_order(acme, domains, method, order_file): order = acme.new_order(domains,", "for domains if not existent if not os.path.exists(order_file): if verbose:", "if not existent if not os.path.exists(order_file): if verbose: print(\" Order", "at {}. Please run \" \"the issue \" \"command.\\n\".format(order.contents['expires'])) print(\"", "challenge.file_name) # Print results if failed: print(\" {} domain(s) authorized,", "print(\"Orders path not found creating it at {}.\" \"\".format(orders_path)) os.mkdir(orders_path)", "found creating it at {}.\" \"\".format(orders_path)) os.mkdir(orders_path) os.chmod(orders_path, 0o770) else:", "not order.expired and not order.invalid: if order.contents['status'] == 'valid': print(\"", "Pending: {}\".format(' '.join(pending))) print(\" Try again.\") sys.exit(sysexits.EX_CANNOT_EXECUTE) else: if verbose:", "\"command.\\n\".format(order.contents['expires'])) print(\" {} domain(s) authorized. Let's Encrypt!\".format( len(domains))) sys.exit(sysexits.EX_OK) else:", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "pending_challenges: token = challenge.contents['token'] # path sanity check assert (token", "if verbose: print(\"Orders path not found creating it at {}.\"", "existent if not os.path.exists(order_file): if verbose: print(\" Order file not", "Just \" \"continue with the authorization when all \" \"verifications", "# # Licensed under the Apache License, Version 2.0 (the", "fs.write(order_file, order.serialize().decode()) def clean_http_challenges(files): # Clean up created files for", "\"expired\" update_order(order, order_file) if not order.expired and not order.invalid: if", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Failed: {}\".format(' '.join(failed))) print(\" WARNING: The current order will be", "if verbose: print(\" Deleting invalid challenge file {}.\\n\".format( challenge.file_name)) clean_challenge_file(challenge_file)", "order = acme.new_order(domains, method) update_order(order, order_file) return order def update_order(order,", "or \"N/A\")) print(\" Pending: {}\".format(' '.join(pending))) print(\" Try again.\") sys.exit(sysexits.EX_CANNOT_EXECUTE)", "challenge.domain, challenge.expires)) continue else: challenge_file = os.path.join(order_path, challenge.file_name) if verbose:", "if verbose: print(\"Current order {} path not found creating it", "= server_order.contents update_order(order, order_file) print(\" {} domain(s) authorized. Let's Encrypt!\".format(", "print(\"{}: Pending!\".format(challenge.domain)) pending.add(challenge.domain) break challenge_file = os.path.join(order_path, challenge.file_name) # Print", "not order.invalid: if order.contents['status'] == 'valid': print(\" Order is valid", "sys.exit(sysexits.EX_CANNOT_EXECUTE) else: if verbose: print(\" Deleting valid challenge file {}.\".format(", "order = create_order(acme, domains, method, order_file) else: if verbose: print(\"", "try: os.remove(path) except: print(\"Couldn't delete http challenge file {}\".format(path)) def", "file not found creating it.\") order = create_order(acme, domains, method,", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "acme.query_order(order) order.contents = server_order.contents except: print(\" WARNING: Old order. Setting", "file {}.\\n\".format( challenge.file_name)) fs.write(challenge_file, challenge.serialize().decode()) pending_challenges.append(challenge) # Quit if nothing", "method, order_file) else: if verbose: print(\" Found order file. Querying", "\"N/A\")) print(\" Pending: {}\".format(' '.join(pending))) print(\" Try again.\") sys.exit(sysexits.EX_CANNOT_EXECUTE) else:", "Creating challenge file {}.\\n\".format( challenge.file_name)) fs.write(challenge_file, challenge.serialize().decode()) pending_challenges.append(challenge) # Quit", "order {} path found at orders path.\\n\".format( domains_hash)) method =", "= acme.query_order(order) order.contents = server_order.contents update_order(order, order_file) print(\" {} domain(s)", "in token) files.add(token) fs.write( os.path.join(current_path, token), \"%s.%s\" % (token, generate_jwk_thumbprint(account.key))", "Order file not found creating it.\") order = create_order(acme, domains,", "= paths['current'] orders_path = paths['orders'] domains_hash = hashlib.sha256( \"_\".join(domains).encode('ascii')).hexdigest() order_path", "print(\" Order still pending and expires \" \"at {}.\\n\".format(order.contents['expires'])) else:", "\" \"the issue \" \"command.\\n\".format(order.contents['expires'])) print(\" {} domain(s) authorized. Let's", "challenge file {}\".format(path)) def clean_challenge_file(challenge_file): try: os.remove(challenge_file) except: print(\"Couldn't delete", "if not os.path.exists(orders_path): if verbose: print(\"Orders path not found creating", "The necessary files have been written to the current \"", "found at orders path.\\n\".format( domains_hash)) method = method acme =", "not existent if not os.path.exists(order_file): if verbose: print(\" Order file", "except: print(\" WARNING: Old order. Setting it as expired.\\n\") order.contents['status']", "and expires \" \"at {}.\\n\".format(order.contents['expires'])) else: if order.invalid: print(\" WARNING:", "if method == 'http': print(files) clean_http_challenges(files) sys.exit(sysexits.EX_FATAL_ERROR) else: if pending:", "Manuale replacement.\\n\\n\".format( get_version())) current_path = paths['current'] orders_path = paths['orders'] domains_hash", "e: print(\"A connection or service error occurred. Aborting.\") raise AutomatoesError(e)", "= [] for challenge in acme.get_order_challenges(order): print(\" Requesting challenge for", "Order is valid and expires at {}. Please run \"", "\"the issue \" \"command.\\n\".format(order.contents['expires'])) print(\" {} domain(s) authorized. Let's Encrypt!\".format(", "challenge_file = os.path.join(order_path, challenge.file_name) # Print results if failed: print(\"", "domains, method, order_file) else: if verbose: print(\" Found order file.", "import AutomatoesError from .model import Order from cartola import fs,", "files for path in files: try: os.remove(path) except: print(\"Couldn't delete", "complete the challenges input(\"\\nPress Enter to continue.\\n\") # Validate challenges", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "domains_hash)) method = method acme = AcmeV2(server, account) try: print(\"Authorizing", "== 'valid': print(\" {} is already authorized until {}.\".format( challenge.domain,", "the License. \"\"\" The domain authorization command. \"\"\" from .", "at orders path.\\n\".format( domains_hash)) method = method acme = AcmeV2(server,", "invalid challenge file {}.\\n\".format( challenge.file_name)) clean_challenge_file(challenge_file) os.remove(order_file) os.rmdir(order_path) if method", "\"seconds.\".format(challenge.domain)) response = acme.verify_order_challenge(challenge, 5, 1) if response['status'] == \"valid\":", "The domain authorization command. \"\"\" from . import get_version from", "def clean_challenge_file(challenge_file): try: os.remove(challenge_file) except: print(\"Couldn't delete challenge file {}\".format(challenge_file))", "if verbose: print(\" Order still pending and expires \" \"at", "if method == 'http': clean_http_challenges(files) sys.exit(sysexits.EX_OK) except IOError as e:", "or implied. # See the License for the specific language", "challenges input(\"\\nPress Enter to continue.\\n\") # Validate challenges done, failed,", "Deleting invalid challenge file {}.\\n\".format( challenge.file_name)) clean_challenge_file(challenge_file) os.remove(order_file) os.rmdir(order_path) if", "print(\"Couldn't delete challenge file {}\".format(challenge_file)) def authorize(server, paths, account, domains,", "== 'http': clean_http_challenges(files) sys.exit(sysexits.EX_OK) except IOError as e: print(\"A connection", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "authorization command. \"\"\" from . import get_version from .acme import", "order.contents['status'] = \"expired\" update_order(order, order_file) if not order.expired and not", "== 'http': print(\"\\n HTTP verification required. Make sure these files", "2016-2017 <NAME> under MIT License # # Licensed under the", "Clean up created files for path in files: try: os.remove(path)", "verbose: print(\"Current order {} path not found creating it at", "orders for domains if not existent if not os.path.exists(order_file): if", ") failed.add(challenge.domain) break else: print(\"{}: Pending!\".format(challenge.domain)) pending.add(challenge.domain) break challenge_file =", "authorized until {}.\".format( challenge.domain, challenge.expires)) continue else: challenge_file = os.path.join(order_path,", "authorize(server, paths, account, domains, method, verbose=False): print(\"Candango Automatoes {}. Manuale", "verbose: print(\" Deleting valid challenge file {}.\".format( challenge.file_name)) clean_challenge_file(challenge_file) if", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "domains if not existent if not os.path.exists(order_file): if verbose: print(\"", "{}: OK! Authorization lasts until {}.\".format( challenge.domain, challenge.expires)) done.add(challenge.domain) elif", "challenge.domain, token)) print(\"\\n The necessary files have been written to", "The current order will be invalidated. \" \"Try again.\") if", "challenge.file_name)) clean_challenge_file(challenge_file) if verbose: print(\" Querying ACME server for current", "server for current status.\\n\") server_order = acme.query_order(order) order.contents = server_order.contents", "== 'invalid': print(\" {}: {} ({})\".format( challenge.domain, response['error']['detail'], response['error']['type']) )", "token = challenge.contents['token'] # path sanity check assert (token and", "try: server_order = acme.query_order(order) order.contents = server_order.contents except: print(\" WARNING:", "order_file) return order def update_order(order, order_file): fs.write(order_file, order.serialize().decode()) def clean_http_challenges(files):", "os.remove(order_file) os.rmdir(order_path) if method == 'http': print(files) clean_http_challenges(files) sys.exit(sysexits.EX_FATAL_ERROR) else:", "authorized, {} pending.\".format( len(done), len(pending))) print(\" Authorized: {}\".format(' '.join(done) or", "and # limitations under the License. \"\"\" The domain authorization", ". import get_version from .acme import AcmeV2 from .crypto import", "{}.\".format( challenge.file_name)) clean_challenge_file(challenge_file) if verbose: print(\" Querying ACME server for", "(the \"License\"); # you may not use this file except", "Wait for the user to complete the challenges input(\"\\nPress Enter", "# you may not use this file except in compliance", "place:\\n\") for challenge in pending_challenges: print(\" _acme-challenge.{}. IN TXT \"", "if pending: print(\" {} domain(s) authorized, {} pending.\".format( len(done), len(pending)))", "pending.\".format( len(done), len(pending))) print(\" Authorized: {}\".format(' '.join(done) or \"N/A\")) print(\"", "order_file) pending_challenges = [] for challenge in acme.get_order_challenges(order): print(\" Requesting", "for challenge in pending_challenges: token = challenge.contents['token'] # path sanity", "permissions and # limitations under the License. \"\"\" The domain", "{} ({})\".format( challenge.domain, response['error']['detail'], response['error']['type']) ) failed.add(challenge.domain) break else: print(\"{}:", "def create_order(acme, domains, method, order_file): order = acme.new_order(domains, method) update_order(order,", "os.rmdir(order_path) if method == 'http': print(files) clean_http_challenges(files) sys.exit(sysexits.EX_FATAL_ERROR) else: if", "# # Unless required by applicable law or agreed to", "from .model import Order from cartola import fs, sysexits import", "os.mkdir(order_path) os.chmod(order_path, 0o770) else: if verbose: print(\"Current order {} path", "current \" \"directory.\\n\") # Wait for the user to complete", "\" \"command.\\n\".format(order.contents['expires'])) print(\" {} domain(s) authorized. Let's Encrypt!\".format( len(domains))) sys.exit(sysexits.EX_OK)", "pending_challenges.append(challenge) # Quit if nothing to authorize if not pending_challenges:", "# Wait for the user to complete the challenges input(\"\\nPress", "try: print(\"Authorizing {}.\\n\".format(\", \".join(domains))) # Creating orders for domains if", "authorization when all \" \"verifications are in place.\\n\") else: print(\"", "5 \" \"seconds.\".format(challenge.domain)) response = acme.verify_order_challenge(challenge, 5, 1) if response['status']", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "be invalidated. \" \"Try again.\") if verbose: print(\" Deleting invalid", "challenge.file_name)) fs.write(challenge_file, challenge.serialize().decode()) pending_challenges.append(challenge) # Quit if nothing to authorize", "from .crypto import generate_jwk_thumbprint from .errors import AutomatoesError from .model", "\"directory.\\n\") # Wait for the user to complete the challenges", "Version 2.0 (the \"License\"); # you may not use this", "if not os.path.exists(order_file): if verbose: print(\" Order file not found", "break challenge_file = os.path.join(order_path, challenge.file_name) # Print results if failed:", "Authorized: {}\".format(' '.join(done) or \"N/A\")) print(\" Pending: {}\".format(' '.join(pending))) print(\"", "print(\"\\n DNS verification required. Make sure these TXT records\" \"", "hashlib import os import sys def create_order(acme, domains, method, order_file):", "method acme = AcmeV2(server, account) try: print(\"Authorizing {}.\\n\".format(\", \".join(domains))) #", "# Clean up created files for path in files: try:", "if order.invalid: print(\" WARNING: Invalid order, renewing it.\\n Just \"", "WARNING: Expired order. Renewing order.\\n\") os.remove(order_file) order = create_order(acme, domains,", "if order.contents['status'] == 'valid': print(\" Order is valid and expires", "Make sure these TXT records\" \" are in place:\\n\") for", "\"order.json\".format(domains_hash)) if not os.path.exists(orders_path): if verbose: print(\"Orders path not found", "path not found creating it at {}.\" \"\".format(orders_path)) os.mkdir(orders_path) os.chmod(orders_path,", "implied. # See the License for the specific language governing", "print(\" Found order file. Querying ACME server for current \"", "until {}.\".format( challenge.domain, challenge.expires)) continue else: challenge_file = os.path.join(order_path, challenge.file_name)", "sanity check assert (token and os.path.sep not in token and", "'invalid': print(\" {}: {} ({})\".format( challenge.domain, response['error']['detail'], response['error']['type']) ) failed.add(challenge.domain)", "under the Apache License, Version 2.0 (the \"License\"); # you", "else: if verbose: print(\"Orders path found at {}.\".format(orders_path)) if not", "\"N/A\")) print(\" Failed: {}\".format(' '.join(failed))) print(\" WARNING: The current order", "os.mkdir(orders_path) os.chmod(orders_path, 0o770) else: if verbose: print(\"Orders path found at", "Checking in 5 \" \"seconds.\".format(challenge.domain)) response = acme.verify_order_challenge(challenge, 5, 1)", "print(\" Failed: {}\".format(' '.join(failed))) print(\" WARNING: The current order will", "Automatoes {}. Manuale replacement.\\n\\n\".format( get_version())) current_path = paths['current'] orders_path =", "in acme.get_order_challenges(order): print(\" Requesting challenge for {}.\".format(challenge.domain)) if challenge.status ==", "challenge file {}.\\n\".format( challenge.file_name)) fs.write(challenge_file, challenge.serialize().decode()) pending_challenges.append(challenge) # Quit if", "cartola import fs, sysexits import hashlib import os import sys", "creating it at orders \" \"path.\\n\".format(domains_hash)) os.mkdir(order_path) os.chmod(order_path, 0o770) else:", "{}\".format(challenge_file)) def authorize(server, paths, account, domains, method, verbose=False): print(\"Candango Automatoes", "response['error']['type']) ) failed.add(challenge.domain) break else: print(\"{}: Pending!\".format(challenge.domain)) pending.add(challenge.domain) break challenge_file", "print(\" WARNING: Old order. Setting it as expired.\\n\") order.contents['status'] =", "Deleting valid challenge file {}.\".format( challenge.file_name)) clean_challenge_file(challenge_file) if verbose: print(\"", "by applicable law or agreed to in writing, software #", "to authorize if not pending_challenges: print(\"\\nAll domains are already authorized,", "{}\".format(' '.join(failed))) print(\" WARNING: The current order will be invalidated.", "print(\" Try again.\") sys.exit(sysexits.EX_CANNOT_EXECUTE) else: if verbose: print(\" Deleting valid", "order def update_order(order, order_file): fs.write(order_file, order.serialize().decode()) def clean_http_challenges(files): # Clean", "challenge in acme.get_order_challenges(order): print(\" Requesting challenge for {}.\".format(challenge.domain)) if challenge.status", "python # # Copyright 2019-2020 <NAME> # Copyright 2016-2017 <NAME>", "file. Querying ACME server for current \" \"status.\") order =", "\"Try again.\") if verbose: print(\" Deleting invalid challenge file {}.\\n\".format(", "input(\"\\nPress Enter to continue.\\n\") # Validate challenges done, failed, pending", "continue.\\n\") # Validate challenges done, failed, pending = set(), set(),", ")) print(\" Authorized: {}\".format(' '.join(done) or \"N/A\")) print(\" Failed: {}\".format('", "else: print(\" WARNING: Expired order. Renewing order.\\n\") os.remove(order_file) order =", "\".join(domains))) # Creating orders for domains if not existent if", "challenge.expires)) continue else: challenge_file = os.path.join(order_path, challenge.file_name) if verbose: print(\"", "import os import sys def create_order(acme, domains, method, order_file): order", "orders path.\\n\".format( domains_hash)) method = method acme = AcmeV2(server, account)", "\" \"path.\\n\".format(domains_hash)) os.mkdir(order_path) os.chmod(order_path, 0o770) else: if verbose: print(\"Current order", "{}.\\n\".format( challenge.file_name)) clean_challenge_file(challenge_file) os.remove(order_file) os.rmdir(order_path) if method == 'http': print(files)", "'valid': print(\" {} is already authorized until {}.\".format( challenge.domain, challenge.expires))", "pending_challenges: print(\" _acme-challenge.{}. IN TXT \" \"\\\"{}\\\"\".format(challenge.domain, challenge.key)) elif method", "to complete the challenges input(\"\\nPress Enter to continue.\\n\") # Validate", "are already authorized, exiting.\") sys.exit(sysexits.EX_OK) files = set() if method", "server_order = acme.query_order(order) order.contents = server_order.contents update_order(order, order_file) print(\" {}", "verification required. Make sure these files are \" \"in place:\\n\")", "domain(s) authorized, {} failed.\".format( len(done), len(failed), )) print(\" Authorized: {}\".format('", "account, domains, method, verbose=False): print(\"Candango Automatoes {}. Manuale replacement.\\n\\n\".format( get_version()))", "fs, sysexits import hashlib import os import sys def create_order(acme,", "else: challenge_file = os.path.join(order_path, challenge.file_name) if verbose: print(\" Creating challenge", "os.path.join(order_path, \"order.json\".format(domains_hash)) if not os.path.exists(orders_path): if verbose: print(\"Orders path not", "# Validate challenges done, failed, pending = set(), set(), set()", "and not order.invalid: if order.contents['status'] == 'valid': print(\" Order is", "else: if verbose: print(\" Found order file. Querying ACME server", "current_path = paths['current'] orders_path = paths['orders'] domains_hash = hashlib.sha256( \"_\".join(domains).encode('ascii')).hexdigest()", "orders \" \"path.\\n\".format(domains_hash)) os.mkdir(order_path) os.chmod(order_path, 0o770) else: if verbose: print(\"Current", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "os.chmod(orders_path, 0o770) else: if verbose: print(\"Orders path found at {}.\".format(orders_path))", "os.chmod(order_path, 0o770) else: if verbose: print(\"Current order {} path found", "Unless required by applicable law or agreed to in writing,", "from .errors import AutomatoesError from .model import Order from cartola", "failed, pending = set(), set(), set() for challenge in pending_challenges:", "# Creating orders for domains if not existent if not", "# path sanity check assert (token and os.path.sep not in", "{} domain(s) authorized. Let's Encrypt!\".format( len(domains))) sys.exit(sysexits.EX_OK) else: if verbose:", "\" \"\\\"{}\\\"\".format(challenge.domain, challenge.key)) elif method == 'http': print(\"\\n HTTP verification", "pending_challenges: print(\" {}: waiting for verification. Checking in 5 \"", "for verification. Checking in 5 \" \"seconds.\".format(challenge.domain)) response = acme.verify_order_challenge(challenge,", "it.\\n Just \" \"continue with the authorization when all \"", "\" \"Try again.\") if verbose: print(\" Deleting invalid challenge file", "\"in place:\\n\") for challenge in pending_challenges: token = challenge.contents['token'] #", "if not order.expired and not order.invalid: if order.contents['status'] == 'valid':", "valid and expires at {}. Please run \" \"the issue", "\"continue with the authorization when all \" \"verifications are in", "response['error']['detail'], response['error']['type']) ) failed.add(challenge.domain) break else: print(\"{}: Pending!\".format(challenge.domain)) pending.add(challenge.domain) break", "= set() if method == 'dns': print(\"\\n DNS verification required.", "the specific language governing permissions and # limitations under the", "found creating it at orders \" \"path.\\n\".format(domains_hash)) os.mkdir(order_path) os.chmod(order_path, 0o770)", "== 'dns': print(\"\\n DNS verification required. Make sure these TXT", "5, 1) if response['status'] == \"valid\": print(\" {}: OK! Authorization", "done, failed, pending = set(), set(), set() for challenge in", "if response['status'] == \"valid\": print(\" {}: OK! Authorization lasts until", "applicable law or agreed to in writing, software # distributed", "will be invalidated. \" \"Try again.\") if verbose: print(\" Deleting", "written to the current \" \"directory.\\n\") # Wait for the", "response['status'] == 'invalid': print(\" {}: {} ({})\".format( challenge.domain, response['error']['detail'], response['error']['type'])", "update_order(order, order_file) print(\" {} domain(s) authorized. Let's Encrypt!\".format( len(done))) if", "os.path.join(order_path, challenge.file_name) # Print results if failed: print(\" {} domain(s)", "# # Copyright 2019-2020 <NAME> # Copyright 2016-2017 <NAME> under", "Requesting challenge for {}.\".format(challenge.domain)) if challenge.status == 'valid': print(\" {}", "order.invalid: print(\" WARNING: Invalid order, renewing it.\\n Just \" \"continue", "delete challenge file {}\".format(challenge_file)) def authorize(server, paths, account, domains, method,", "for challenge in pending_challenges: print(\" _acme-challenge.{}. IN TXT \" \"\\\"{}\\\"\".format(challenge.domain,", "len(pending))) print(\" Authorized: {}\".format(' '.join(done) or \"N/A\")) print(\" Pending: {}\".format('", "in writing, software # distributed under the License is distributed", "get_version from .acme import AcmeV2 from .crypto import generate_jwk_thumbprint from", "in place:\\n\") for challenge in pending_challenges: print(\" _acme-challenge.{}. IN TXT", "challenge.contents['token'] # path sanity check assert (token and os.path.sep not", "limitations under the License. \"\"\" The domain authorization command. \"\"\"", "method) update_order(order, order_file) return order def update_order(order, order_file): fs.write(order_file, order.serialize().decode())", "created files for path in files: try: os.remove(path) except: print(\"Couldn't", "under MIT License # # Licensed under the Apache License,", "pending and expires \" \"at {}.\\n\".format(order.contents['expires'])) else: if order.invalid: print(\"", "domains, method, verbose=False): print(\"Candango Automatoes {}. Manuale replacement.\\n\\n\".format( get_version())) current_path", "ACME server for current \" \"status.\") order = Order.deserialize(fs.read(order_file)) try:", "as expired.\\n\") order.contents['status'] = \"expired\" update_order(order, order_file) if not order.expired", "\"verifications are in place.\\n\") else: print(\" WARNING: Expired order. Renewing", "order file. Querying ACME server for current \" \"status.\") order", "def authorize(server, paths, account, domains, method, verbose=False): print(\"Candango Automatoes {}.", "the challenges input(\"\\nPress Enter to continue.\\n\") # Validate challenges done,", "License. \"\"\" The domain authorization command. \"\"\" from . import", "clean_challenge_file(challenge_file) os.remove(order_file) os.rmdir(order_path) if method == 'http': print(files) clean_http_challenges(files) sys.exit(sysexits.EX_FATAL_ERROR)", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "acme = AcmeV2(server, account) try: print(\"Authorizing {}.\\n\".format(\", \".join(domains))) # Creating", "License, Version 2.0 (the \"License\"); # you may not use", "under the License. \"\"\" The domain authorization command. \"\"\" from", "required. Make sure these files are \" \"in place:\\n\") for", "Quit if nothing to authorize if not pending_challenges: print(\"\\nAll domains", "print(\" {}: OK! Authorization lasts until {}.\".format( challenge.domain, challenge.expires)) done.add(challenge.domain)", "# You may obtain a copy of the License at", "place.\\n\") else: print(\" WARNING: Expired order. Renewing order.\\n\") os.remove(order_file) order", "print(\" {} domain(s) authorized. Let's Encrypt!\".format( len(done))) if method ==", "print(\"\\n HTTP verification required. Make sure these files are \"", "are in place.\\n\") else: print(\" WARNING: Expired order. Renewing order.\\n\")", "nothing to authorize if not pending_challenges: print(\"\\nAll domains are already", "valid challenge file {}.\".format( challenge.file_name)) clean_challenge_file(challenge_file) if verbose: print(\" Querying", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "fs.write(challenge_file, challenge.serialize().decode()) pending_challenges.append(challenge) # Quit if nothing to authorize if", "set() for challenge in pending_challenges: print(\" {}: waiting for verification.", "\"_\".join(domains).encode('ascii')).hexdigest() order_path = os.path.join(orders_path, domains_hash) order_file = os.path.join(order_path, \"order.json\".format(domains_hash)) if", "acme.new_order(domains, method) update_order(order, order_file) return order def update_order(order, order_file): fs.write(order_file,", "acme.query_order(order) order.contents = server_order.contents update_order(order, order_file) print(\" {} domain(s) authorized.", "it at orders \" \"path.\\n\".format(domains_hash)) os.mkdir(order_path) os.chmod(order_path, 0o770) else: if", "challenge.serialize().decode()) pending_challenges.append(challenge) # Quit if nothing to authorize if not", "files = set() if method == 'dns': print(\"\\n DNS verification", "challenge file {}.\".format( challenge.file_name)) clean_challenge_file(challenge_file) if verbose: print(\" Querying ACME", "the current \" \"directory.\\n\") # Wait for the user to", "'.join(done) or \"N/A\")) print(\" Failed: {}\".format(' '.join(failed))) print(\" WARNING: The", "pending: print(\" {} domain(s) authorized, {} pending.\".format( len(done), len(pending))) print(\"", "the License for the specific language governing permissions and #", "challenge file {}\".format(challenge_file)) def authorize(server, paths, account, domains, method, verbose=False):", "os.remove(challenge_file) except: print(\"Couldn't delete challenge file {}\".format(challenge_file)) def authorize(server, paths,", "domains_hash) order_file = os.path.join(order_path, \"order.json\".format(domains_hash)) if not os.path.exists(orders_path): if verbose:", "Apache License, Version 2.0 (the \"License\"); # you may not", "method, order_file): order = acme.new_order(domains, method) update_order(order, order_file) return order", "= os.path.join(order_path, challenge.file_name) # Print results if failed: print(\" {}", "either express or implied. # See the License for the", "clean_http_challenges(files) sys.exit(sysexits.EX_OK) except IOError as e: print(\"A connection or service", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "issue \" \"command.\\n\".format(order.contents['expires'])) print(\" {} domain(s) authorized. Let's Encrypt!\".format( len(domains)))", "not found creating it at orders \" \"path.\\n\".format(domains_hash)) os.mkdir(order_path) os.chmod(order_path,", "renewing it.\\n Just \" \"continue with the authorization when all", "except: print(\"Couldn't delete http challenge file {}\".format(path)) def clean_challenge_file(challenge_file): try:", "# Quit if nothing to authorize if not pending_challenges: print(\"\\nAll", "generate_jwk_thumbprint(account.key)) ) print(\" http://{}/.well-known/acme-challenge/{}\".format( challenge.domain, token)) print(\"\\n The necessary files", "continue else: challenge_file = os.path.join(order_path, challenge.file_name) if verbose: print(\" Creating", "% (token, generate_jwk_thumbprint(account.key)) ) print(\" http://{}/.well-known/acme-challenge/{}\".format( challenge.domain, token)) print(\"\\n The", "creating it at {}.\" \"\".format(orders_path)) os.mkdir(orders_path) os.chmod(orders_path, 0o770) else: if", "challenge in pending_challenges: token = challenge.contents['token'] # path sanity check", "print(\"\\n The necessary files have been written to the current", "order, renewing it.\\n Just \" \"continue with the authorization when", "= os.path.join(orders_path, domains_hash) order_file = os.path.join(order_path, \"order.json\".format(domains_hash)) if not os.path.exists(orders_path):", "file {}.\".format( challenge.file_name)) clean_challenge_file(challenge_file) if verbose: print(\" Querying ACME server", "at {}.\".format(orders_path)) if not os.path.exists(order_path): if verbose: print(\"Current order {}", "{}.\".format(challenge.domain)) if challenge.status == 'valid': print(\" {} is already authorized", "{}. Please run \" \"the issue \" \"command.\\n\".format(order.contents['expires'])) print(\" {}", "pending_challenges: print(\"\\nAll domains are already authorized, exiting.\") sys.exit(sysexits.EX_OK) files =", "IOError as e: print(\"A connection or service error occurred. Aborting.\")", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "# Copyright 2019-2020 <NAME> # Copyright 2016-2017 <NAME> under MIT", "\" \"seconds.\".format(challenge.domain)) response = acme.verify_order_challenge(challenge, 5, 1) if response['status'] ==", "for current status.\\n\") server_order = acme.query_order(order) order.contents = server_order.contents update_order(order,", "sysexits import hashlib import os import sys def create_order(acme, domains,", "failed: print(\" {} domain(s) authorized, {} failed.\".format( len(done), len(failed), ))", "not in token and '.' not in token) files.add(token) fs.write(", "<NAME> # Copyright 2016-2017 <NAME> under MIT License # #", "os.path.join(orders_path, domains_hash) order_file = os.path.join(order_path, \"order.json\".format(domains_hash)) if not os.path.exists(orders_path): if", "not in token) files.add(token) fs.write( os.path.join(current_path, token), \"%s.%s\" % (token,", "http challenge file {}\".format(path)) def clean_challenge_file(challenge_file): try: os.remove(challenge_file) except: print(\"Couldn't", "Renewing order.\\n\") os.remove(order_file) order = create_order(acme, domains, method, order_file) update_order(order,", "challenge.status == 'valid': print(\" {} is already authorized until {}.\".format(", "= acme.query_order(order) order.contents = server_order.contents except: print(\" WARNING: Old order.", "again.\") if verbose: print(\" Deleting invalid challenge file {}.\\n\".format( challenge.file_name))", "\"\\\"{}\\\"\".format(challenge.domain, challenge.key)) elif method == 'http': print(\"\\n HTTP verification required.", "'http': print(files) clean_http_challenges(files) sys.exit(sysexits.EX_FATAL_ERROR) else: if pending: print(\" {} domain(s)", "domains_hash = hashlib.sha256( \"_\".join(domains).encode('ascii')).hexdigest() order_path = os.path.join(orders_path, domains_hash) order_file =", "{} path not found creating it at orders \" \"path.\\n\".format(domains_hash))", "print(\" Creating challenge file {}.\\n\".format( challenge.file_name)) fs.write(challenge_file, challenge.serialize().decode()) pending_challenges.append(challenge) #", "Please run \" \"the issue \" \"command.\\n\".format(order.contents['expires'])) print(\" {} domain(s)", "update_order(order, order_file) pending_challenges = [] for challenge in acme.get_order_challenges(order): print(\"", "challenge in pending_challenges: print(\" _acme-challenge.{}. IN TXT \" \"\\\"{}\\\"\".format(challenge.domain, challenge.key))", "order_file) update_order(order, order_file) pending_challenges = [] for challenge in acme.get_order_challenges(order):", "\"License\"); # you may not use this file except in", "len(failed), )) print(\" Authorized: {}\".format(' '.join(done) or \"N/A\")) print(\" Failed:", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "expired.\\n\") order.contents['status'] = \"expired\" update_order(order, order_file) if not order.expired and", "'http': clean_http_challenges(files) sys.exit(sysexits.EX_OK) except IOError as e: print(\"A connection or", "files: try: os.remove(path) except: print(\"Couldn't delete http challenge file {}\".format(path))", "http://{}/.well-known/acme-challenge/{}\".format( challenge.domain, token)) print(\"\\n The necessary files have been written", "server for current \" \"status.\") order = Order.deserialize(fs.read(order_file)) try: server_order", "# distributed under the License is distributed on an \"AS", "'valid': print(\" Order is valid and expires at {}. Please", "server_order.contents update_order(order, order_file) print(\" {} domain(s) authorized. Let's Encrypt!\".format( len(done)))", "clean_challenge_file(challenge_file) if verbose: print(\" Querying ACME server for current status.\\n\")", "user to complete the challenges input(\"\\nPress Enter to continue.\\n\") #", "# Unless required by applicable law or agreed to in", "domain(s) authorized. Let's Encrypt!\".format( len(done))) if method == 'http': clean_http_challenges(files)", "up created files for path in files: try: os.remove(path) except:", "{}.\\n\".format(order.contents['expires'])) else: if order.invalid: print(\" WARNING: Invalid order, renewing it.\\n", "elif method == 'http': print(\"\\n HTTP verification required. Make sure", "Invalid order, renewing it.\\n Just \" \"continue with the authorization", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "\"\".format(orders_path)) os.mkdir(orders_path) os.chmod(orders_path, 0o770) else: if verbose: print(\"Orders path found", "lasts until {}.\".format( challenge.domain, challenge.expires)) done.add(challenge.domain) elif response['status'] == 'invalid':", "Authorization lasts until {}.\".format( challenge.domain, challenge.expires)) done.add(challenge.domain) elif response['status'] ==", "= set(), set(), set() for challenge in pending_challenges: print(\" {}:", "if verbose: print(\" Creating challenge file {}.\\n\".format( challenge.file_name)) fs.write(challenge_file, challenge.serialize().decode())", "def clean_http_challenges(files): # Clean up created files for path in", "order_path = os.path.join(orders_path, domains_hash) order_file = os.path.join(order_path, \"order.json\".format(domains_hash)) if not", "WARNING: Invalid order, renewing it.\\n Just \" \"continue with the", "\"\"\" The domain authorization command. \"\"\" from . import get_version", "order_file) print(\" {} domain(s) authorized. Let's Encrypt!\".format( len(done))) if method", "assert (token and os.path.sep not in token and '.' not", "pending.add(challenge.domain) break challenge_file = os.path.join(order_path, challenge.file_name) # Print results if", "You may obtain a copy of the License at #", "order.serialize().decode()) def clean_http_challenges(files): # Clean up created files for path", "= Order.deserialize(fs.read(order_file)) try: server_order = acme.query_order(order) order.contents = server_order.contents except:", "break else: print(\"{}: Pending!\".format(challenge.domain)) pending.add(challenge.domain) break challenge_file = os.path.join(order_path, challenge.file_name)", "file {}.\\n\".format( challenge.file_name)) clean_challenge_file(challenge_file) os.remove(order_file) os.rmdir(order_path) if method == 'http':", "generate_jwk_thumbprint from .errors import AutomatoesError from .model import Order from", "{}\".format(' '.join(done) or \"N/A\")) print(\" Failed: {}\".format(' '.join(failed))) print(\" WARNING:", "update_order(order, order_file) return order def update_order(order, order_file): fs.write(order_file, order.serialize().decode()) def", "for {}.\".format(challenge.domain)) if challenge.status == 'valid': print(\" {} is already", "Encrypt!\".format( len(domains))) sys.exit(sysexits.EX_OK) else: if verbose: print(\" Order still pending", "except: print(\"Couldn't delete challenge file {}\".format(challenge_file)) def authorize(server, paths, account,", "'.join(pending))) print(\" Try again.\") sys.exit(sysexits.EX_CANNOT_EXECUTE) else: if verbose: print(\" Deleting", "\"path.\\n\".format(domains_hash)) os.mkdir(order_path) os.chmod(order_path, 0o770) else: if verbose: print(\"Current order {}", "Make sure these files are \" \"in place:\\n\") for challenge", "from . import get_version from .acme import AcmeV2 from .crypto", "not found creating it.\") order = create_order(acme, domains, method, order_file)", "found creating it.\") order = create_order(acme, domains, method, order_file) else:", "the Apache License, Version 2.0 (the \"License\"); # you may", "verification required. Make sure these TXT records\" \" are in", "domain(s) authorized, {} pending.\".format( len(done), len(pending))) print(\" Authorized: {}\".format(' '.join(done)", "<filename>automatoes/authorize.py #!/usr/bin/env python # # Copyright 2019-2020 <NAME> # Copyright", "for challenge in pending_challenges: print(\" {}: waiting for verification. Checking", "server_order = acme.query_order(order) order.contents = server_order.contents except: print(\" WARNING: Old", "{}: waiting for verification. Checking in 5 \" \"seconds.\".format(challenge.domain)) response", "authorized, exiting.\") sys.exit(sysexits.EX_OK) files = set() if method == 'dns':", "print(\" Deleting valid challenge file {}.\".format( challenge.file_name)) clean_challenge_file(challenge_file) if verbose:" ]
[ "learner. \"\"\" def __init__(self): # Hard initial update from Q-net(s)", "return build_q_models(policy, obs_space, action_space, config), \\ TorchCategorical def build_q_losses(policy: Policy,", "(Policy): The Policy to calculate the loss for. model (ModelV2):", "`target_network_update_freq` steps by the master learner. \"\"\" def __init__(self): #", "whenever we restore weights for this policy's # model, we", "The action distribution class. train_batch (SampleBatch): The training data. Returns:", "# q scores for actions which we know were selected", "loss # TD-error tensor in final stats # will be", "= try_import_torch() F = None if nn: F = nn.functional", "Policy from ray.rllib.policy.policy_template import build_policy_class from ray.rllib.policy.sample_batch import SampleBatch from", "for this policy's # model, we sync the target network", "for target in self.target_models.values(): target.load_state_dict(state_dict) @override(TorchPolicy) def set_weights(self, weights): #", "= train_batch[SampleBatch.DONES].float() q_tp1_best_one_hot_selection = F.one_hot( torch.argmax(q_tp1, 1), policy.action_space.n) q_tp1_best =", "object. obs_space (gym.spaces.Space): The Policy's observation space. action_space (gym.spaces.Space): The", "SampleBatch) -> Dict[str, TensorType]: return {\"loss\": torch.mean(torch.stack(policy.get_tower_stats(\"loss\")))} def extra_action_out_fn(policy: Policy,", "policy, target_model, train_batch[SampleBatch.NEXT_OBS], explore=False, is_training=True) # q scores for actions", "TargetNetworkMixin.__init__(policy) SimpleQTorchPolicy = build_policy_class( name=\"SimpleQPolicy\", framework=\"torch\", loss_fn=build_q_losses, get_default_config=lambda: ray.rllib.agents.dqn.simple_q.DEFAULT_CONFIG, stats_fn=stats_fn,", "build_q_losses(policy: Policy, model, dist_class, train_batch: SampleBatch) -> TensorType: \"\"\"Constructs the", "extra_action_out_fn(policy: Policy, input_dict, state_batches, model, action_dist) -> Dict[str, TensorType]: \"\"\"Adds", "loss for. model (ModelV2): The Model to calculate the loss", "None if nn: F = nn.functional logger = logging.getLogger(__name__) class", "stats # will be concatenated and retrieved for each individual", "TorchDistributionWrapper]: return build_q_models(policy, obs_space, action_space, config), \\ TorchCategorical def build_q_losses(policy:", "The Model to calculate the loss for. dist_class (Type[ActionDistribution]): The", "return {\"q_values\": policy.q_values} def setup_late_mixins(policy: Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space,", "F.one_hot(train_batch[SampleBatch.ACTIONS].long(), policy.action_space.n) q_t_selected = torch.sum(q_t * one_hot_selection, 1) # compute", "Update_target_fn will be called periodically to copy Q network to", "= (1.0 - dones) * q_tp1_best # compute RHS of", "loss_fn=build_q_losses, get_default_config=lambda: ray.rllib.agents.dqn.simple_q.DEFAULT_CONFIG, stats_fn=stats_fn, extra_action_out_fn=extra_action_out_fn, after_init=setup_late_mixins, make_model_and_action_dist=build_q_model_and_distribution, mixins=[TargetNetworkMixin], action_distribution_fn=get_distribution_inputs_and_class, extra_learn_fetches_fn=concat_multi_gpu_td_errors,", "policy (Policy): The Policy to calculate the loss for. model", "we restore weights for this policy's # model, we sync", "training data. Returns: TensorType: A single loss tensor. \"\"\" target_model", "import SampleBatch from ray.rllib.policy.torch_policy import TorchPolicy from ray.rllib.utils.annotations import override", "input_dict, state_batches, model, action_dist) -> Dict[str, TensorType]: \"\"\"Adds q-values to", "\"\"\" TargetNetworkMixin.__init__(policy) SimpleQTorchPolicy = build_policy_class( name=\"SimpleQPolicy\", framework=\"torch\", loss_fn=build_q_losses, get_default_config=lambda: ray.rllib.agents.dqn.simple_q.DEFAULT_CONFIG,", "starting from state at t + 1 dones = train_batch[SampleBatch.DONES].float()", "- dones) * q_tp1_best # compute RHS of bellman equation", "action_space: gym.spaces.Space, config: TrainerConfigDict) -> Tuple[ModelV2, TorchDistributionWrapper]: return build_q_models(policy, obs_space,", "weights): # Makes sure that whenever we restore weights for", "policy.action_space.n) q_tp1_best = torch.sum(q_tp1 * q_tp1_best_one_hot_selection, 1) q_tp1_best_masked = (1.0", "q_tp1_best_one_hot_selection = F.one_hot( torch.argmax(q_tp1, 1), policy.action_space.n) q_tp1_best = torch.sum(q_tp1 *", "Model to calculate the loss for. dist_class (Type[ActionDistribution]): The action", "# at the same time. TorchPolicy.set_weights(self, weights) self.update_target() def build_q_model_and_distribution(", "from ray.rllib.policy import Policy from ray.rllib.policy.policy_template import build_policy_class from ray.rllib.policy.sample_batch", "get_default_config=lambda: ray.rllib.agents.dqn.simple_q.DEFAULT_CONFIG, stats_fn=stats_fn, extra_action_out_fn=extra_action_out_fn, after_init=setup_late_mixins, make_model_and_action_dist=build_q_model_and_distribution, mixins=[TargetNetworkMixin], action_distribution_fn=get_distribution_inputs_and_class, extra_learn_fetches_fn=concat_multi_gpu_td_errors, )", "obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config: TrainerConfigDict) -> None: \"\"\"Call all", "value starting from state at t + 1 dones =", "1), policy.action_space.n) q_tp1_best = torch.sum(q_tp1 * q_tp1_best_one_hot_selection, 1) q_tp1_best_masked =", "network to # target Q networks. state_dict = self.model.state_dict() for", "from Q-net(s) to target Q-net(s). self.update_target() def update_target(self): # Update_target_fn", "The Policy to calculate the loss for. model (ModelV2): The", "model, train_batch[SampleBatch.CUR_OBS], explore=False, is_training=True) # target q network evalution q_tp1", "# TD-error tensor in final stats # will be concatenated", "torch.mean(torch.stack(policy.get_tower_stats(\"loss\")))} def extra_action_out_fn(policy: Policy, input_dict, state_batches, model, action_dist) -> Dict[str,", "{\"q_values\": policy.q_values} def setup_late_mixins(policy: Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config:", "config. \"\"\" TargetNetworkMixin.__init__(policy) SimpleQTorchPolicy = build_policy_class( name=\"SimpleQPolicy\", framework=\"torch\", loss_fn=build_q_losses, get_default_config=lambda:", "nn: F = nn.functional logger = logging.getLogger(__name__) class TargetNetworkMixin: \"\"\"Assign", "huber_loss from ray.rllib.utils.typing import TensorType, TrainerConfigDict torch, nn = try_import_torch()", "network (from the main model) # at the same time.", "out dict.\"\"\" return {\"q_values\": policy.q_values} def setup_late_mixins(policy: Policy, obs_space: gym.spaces.Space,", "be concatenated and retrieved for each individual batch item. model.tower_stats[\"td_error\"]", "ray.rllib.models.torch.torch_action_dist import TorchCategorical, \\ TorchDistributionWrapper from ray.rllib.policy import Policy from", "model (ModelV2): The Model to calculate the loss for. dist_class", "know were selected in the given state. one_hot_selection = F.one_hot(train_batch[SampleBatch.ACTIONS].long(),", "estimate of best possible value starting from state at t", "action space. config (TrainerConfigDict): The Policy's config. \"\"\" TargetNetworkMixin.__init__(policy) SimpleQTorchPolicy", "at t + 1 dones = train_batch[SampleBatch.DONES].float() q_tp1_best_one_hot_selection = F.one_hot(", "is called every `target_network_update_freq` steps by the master learner. \"\"\"", "before SimpleQTorchPolicy initialization. Args: policy (Policy): The Policy object. obs_space", "= torch.sum(q_t * one_hot_selection, 1) # compute estimate of best", "import logging from typing import Dict, Tuple import gym import", "Policy to calculate the loss for. model (ModelV2): The Model", "= q_t_selected - q_t_selected_target.detach() loss = torch.mean(huber_loss(td_error)) # Store values", "Q network to # target Q networks. state_dict = self.model.state_dict()", "ray.rllib.utils.framework import try_import_torch from ray.rllib.utils.torch_utils import concat_multi_gpu_td_errors, huber_loss from ray.rllib.utils.typing", "q_tp1_best # compute RHS of bellman equation q_t_selected_target = (train_batch[SampleBatch.REWARDS]", "nn = try_import_torch() F = None if nn: F =", "evalution q_tp1 = compute_q_values( policy, target_model, train_batch[SampleBatch.NEXT_OBS], explore=False, is_training=True) #", "dist_class (Type[ActionDistribution]): The action distribution class. train_batch (SampleBatch): The training", "Q-net(s). self.update_target() def update_target(self): # Update_target_fn will be called periodically", "initialization. Args: policy (Policy): The Policy object. obs_space (gym.spaces.Space): The", "The Policy's observation space. action_space (gym.spaces.Space): The Policy's action space.", "# multi-GPU, we do not override them during the parallel", "nn.functional logger = logging.getLogger(__name__) class TargetNetworkMixin: \"\"\"Assign the `update_target` method", "action out dict.\"\"\" return {\"q_values\": policy.q_values} def setup_late_mixins(policy: Policy, obs_space:", "be called periodically to copy Q network to # target", "ray.rllib.policy.policy_template import build_policy_class from ray.rllib.policy.sample_batch import SampleBatch from ray.rllib.policy.torch_policy import", "from ray.rllib.utils.torch_utils import concat_multi_gpu_td_errors, huber_loss from ray.rllib.utils.typing import TensorType, TrainerConfigDict", "batch: SampleBatch) -> Dict[str, TensorType]: return {\"loss\": torch.mean(torch.stack(policy.get_tower_stats(\"loss\")))} def extra_action_out_fn(policy:", "Store values for stats function in model (tower), such that", "build_policy_class from ray.rllib.policy.sample_batch import SampleBatch from ray.rllib.policy.torch_policy import TorchPolicy from", "not override them during the parallel loss phase. model.tower_stats[\"loss\"] =", "loss for SimpleQTorchPolicy. Args: policy (Policy): The Policy to calculate", "build_q_model_and_distribution( policy: Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config: TrainerConfigDict) ->", "compute RHS of bellman equation q_t_selected_target = (train_batch[SampleBatch.REWARDS] + policy.config[\"gamma\"]", "= compute_q_values( policy, model, train_batch[SampleBatch.CUR_OBS], explore=False, is_training=True) # target q", "in model (tower), such that for # multi-GPU, we do", "selected in the given state. one_hot_selection = F.one_hot(train_batch[SampleBatch.ACTIONS].long(), policy.action_space.n) q_t_selected", "F = nn.functional logger = logging.getLogger(__name__) class TargetNetworkMixin: \"\"\"Assign the", "for # multi-GPU, we do not override them during the", "q_t = compute_q_values( policy, model, train_batch[SampleBatch.CUR_OBS], explore=False, is_training=True) # target", "q scores for actions which we know were selected in", "config), \\ TorchCategorical def build_q_losses(policy: Policy, model, dist_class, train_batch: SampleBatch)", "TorchPolicy.set_weights(self, weights) self.update_target() def build_q_model_and_distribution( policy: Policy, obs_space: gym.spaces.Space, action_space:", "target in self.target_models.values(): target.load_state_dict(state_dict) @override(TorchPolicy) def set_weights(self, weights): # Makes", "import gym import ray from ray.rllib.agents.dqn.simple_q_tf_policy import ( build_q_models, compute_q_values,", "self.target_models.values(): target.load_state_dict(state_dict) @override(TorchPolicy) def set_weights(self, weights): # Makes sure that", "scores for actions which we know were selected in the", "\"\"\"Call all mixin classes' constructors before SimpleQTorchPolicy initialization. Args: policy", "set_weights(self, weights): # Makes sure that whenever we restore weights", "ray.rllib.utils.annotations import override from ray.rllib.utils.framework import try_import_torch from ray.rllib.utils.torch_utils import", "compute estimate of best possible value starting from state at", "sync the target network (from the main model) # at", "framework=\"torch\", loss_fn=build_q_losses, get_default_config=lambda: ray.rllib.agents.dqn.simple_q.DEFAULT_CONFIG, stats_fn=stats_fn, extra_action_out_fn=extra_action_out_fn, after_init=setup_late_mixins, make_model_and_action_dist=build_q_model_and_distribution, mixins=[TargetNetworkMixin], action_distribution_fn=get_distribution_inputs_and_class,", "TrainerConfigDict) -> Tuple[ModelV2, TorchDistributionWrapper]: return build_q_models(policy, obs_space, action_space, config), \\", "q_tp1_best_masked) # Compute the error (Square/Huber). td_error = q_t_selected -", "# will be concatenated and retrieved for each individual batch", "Policy, input_dict, state_batches, model, action_dist) -> Dict[str, TensorType]: \"\"\"Adds q-values", "= F.one_hot(train_batch[SampleBatch.ACTIONS].long(), policy.action_space.n) q_t_selected = torch.sum(q_t * one_hot_selection, 1) #", "\"\"\"Adds q-values to the action out dict.\"\"\" return {\"q_values\": policy.q_values}", "Tuple import gym import ray from ray.rllib.agents.dqn.simple_q_tf_policy import ( build_q_models,", "gym import ray from ray.rllib.agents.dqn.simple_q_tf_policy import ( build_q_models, compute_q_values, get_distribution_inputs_and_class)", "SimpleQTorchPolicy. Args: policy (Policy): The Policy to calculate the loss", "model, action_dist) -> Dict[str, TensorType]: \"\"\"Adds q-values to the action", "loss tensor. \"\"\" target_model = policy.target_models[model] # q network evaluation", "to target Q-net(s). self.update_target() def update_target(self): # Update_target_fn will be", "gym.spaces.Space, action_space: gym.spaces.Space, config: TrainerConfigDict) -> None: \"\"\"Call all mixin", "* q_tp1_best_masked) # Compute the error (Square/Huber). td_error = q_t_selected", "steps by the master learner. \"\"\" def __init__(self): # Hard", "target q network evalution q_tp1 = compute_q_values( policy, target_model, train_batch[SampleBatch.NEXT_OBS],", "compute_q_values, get_distribution_inputs_and_class) from ray.rllib.models.modelv2 import ModelV2 from ray.rllib.models.torch.torch_action_dist import TorchCategorical,", "update from Q-net(s) to target Q-net(s). self.update_target() def update_target(self): #", "Compute the error (Square/Huber). td_error = q_t_selected - q_t_selected_target.detach() loss", "target_model, train_batch[SampleBatch.NEXT_OBS], explore=False, is_training=True) # q scores for actions which", "the given state. one_hot_selection = F.one_hot(train_batch[SampleBatch.ACTIONS].long(), policy.action_space.n) q_t_selected = torch.sum(q_t", "we do not override them during the parallel loss phase.", "distribution class. train_batch (SampleBatch): The training data. Returns: TensorType: A", "target network (from the main model) # at the same", "torch.sum(q_t * one_hot_selection, 1) # compute estimate of best possible", "# q network evaluation q_t = compute_q_values( policy, model, train_batch[SampleBatch.CUR_OBS],", "to the SimpleQTorchPolicy The function is called every `target_network_update_freq` steps", "td_error return loss def stats_fn(policy: Policy, batch: SampleBatch) -> Dict[str,", "item. model.tower_stats[\"td_error\"] = td_error return loss def stats_fn(policy: Policy, batch:", "config: TrainerConfigDict) -> None: \"\"\"Call all mixin classes' constructors before", "return loss def stats_fn(policy: Policy, batch: SampleBatch) -> Dict[str, TensorType]:", "SampleBatch) -> TensorType: \"\"\"Constructs the loss for SimpleQTorchPolicy. Args: policy", "them during the parallel loss phase. model.tower_stats[\"loss\"] = loss #", "for stats function in model (tower), such that for #", "TrainerConfigDict) -> None: \"\"\"Call all mixin classes' constructors before SimpleQTorchPolicy", "import ModelV2 from ray.rllib.models.torch.torch_action_dist import TorchCategorical, \\ TorchDistributionWrapper from ray.rllib.policy", "for SimpleQTorchPolicy. Args: policy (Policy): The Policy to calculate the", "classes' constructors before SimpleQTorchPolicy initialization. Args: policy (Policy): The Policy", "import build_policy_class from ray.rllib.policy.sample_batch import SampleBatch from ray.rllib.policy.torch_policy import TorchPolicy", "will be called periodically to copy Q network to #", "initial update from Q-net(s) to target Q-net(s). self.update_target() def update_target(self):", "action_space (gym.spaces.Space): The Policy's action space. config (TrainerConfigDict): The Policy's", "1) # compute estimate of best possible value starting from", "copy Q network to # target Q networks. state_dict =", "torch.mean(huber_loss(td_error)) # Store values for stats function in model (tower),", "weights) self.update_target() def build_q_model_and_distribution( policy: Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space,", "the action out dict.\"\"\" return {\"q_values\": policy.q_values} def setup_late_mixins(policy: Policy,", "ray.rllib.policy import Policy from ray.rllib.policy.policy_template import build_policy_class from ray.rllib.policy.sample_batch import", "compute_q_values( policy, target_model, train_batch[SampleBatch.NEXT_OBS], explore=False, is_training=True) # q scores for", "observation space. action_space (gym.spaces.Space): The Policy's action space. config (TrainerConfigDict):", "retrieved for each individual batch item. model.tower_stats[\"td_error\"] = td_error return", "The Policy object. obs_space (gym.spaces.Space): The Policy's observation space. action_space", "from state at t + 1 dones = train_batch[SampleBatch.DONES].float() q_tp1_best_one_hot_selection", "TorchCategorical def build_q_losses(policy: Policy, model, dist_class, train_batch: SampleBatch) -> TensorType:", "final stats # will be concatenated and retrieved for each", "action distribution class. train_batch (SampleBatch): The training data. Returns: TensorType:", "each individual batch item. model.tower_stats[\"td_error\"] = td_error return loss def", "self.update_target() def build_q_model_and_distribution( policy: Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config:", "{\"loss\": torch.mean(torch.stack(policy.get_tower_stats(\"loss\")))} def extra_action_out_fn(policy: Policy, input_dict, state_batches, model, action_dist) ->", "q_t_selected = torch.sum(q_t * one_hot_selection, 1) # compute estimate of", "master learner. \"\"\" def __init__(self): # Hard initial update from", "this policy's # model, we sync the target network (from", "# compute estimate of best possible value starting from state", "the parallel loss phase. model.tower_stats[\"loss\"] = loss # TD-error tensor", "-> None: \"\"\"Call all mixin classes' constructors before SimpleQTorchPolicy initialization.", "import concat_multi_gpu_td_errors, huber_loss from ray.rllib.utils.typing import TensorType, TrainerConfigDict torch, nn", "q network evaluation q_t = compute_q_values( policy, model, train_batch[SampleBatch.CUR_OBS], explore=False,", "from ray.rllib.models.modelv2 import ModelV2 from ray.rllib.models.torch.torch_action_dist import TorchCategorical, \\ TorchDistributionWrapper", "build_q_models, compute_q_values, get_distribution_inputs_and_class) from ray.rllib.models.modelv2 import ModelV2 from ray.rllib.models.torch.torch_action_dist import", "method to the SimpleQTorchPolicy The function is called every `target_network_update_freq`", "import ray from ray.rllib.agents.dqn.simple_q_tf_policy import ( build_q_models, compute_q_values, get_distribution_inputs_and_class) from", "* q_tp1_best_one_hot_selection, 1) q_tp1_best_masked = (1.0 - dones) * q_tp1_best", "def update_target(self): # Update_target_fn will be called periodically to copy", "in final stats # will be concatenated and retrieved for", "\\ TorchDistributionWrapper from ray.rllib.policy import Policy from ray.rllib.policy.policy_template import build_policy_class", "TrainerConfigDict torch, nn = try_import_torch() F = None if nn:", "def extra_action_out_fn(policy: Policy, input_dict, state_batches, model, action_dist) -> Dict[str, TensorType]:", "def build_q_model_and_distribution( policy: Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config: TrainerConfigDict)", "override them during the parallel loss phase. model.tower_stats[\"loss\"] = loss", "(from the main model) # at the same time. TorchPolicy.set_weights(self,", "(gym.spaces.Space): The Policy's observation space. action_space (gym.spaces.Space): The Policy's action", "\"\"\"Constructs the loss for SimpleQTorchPolicy. Args: policy (Policy): The Policy", "in the given state. one_hot_selection = F.one_hot(train_batch[SampleBatch.ACTIONS].long(), policy.action_space.n) q_t_selected =", "TorchCategorical, \\ TorchDistributionWrapper from ray.rllib.policy import Policy from ray.rllib.policy.policy_template import", "loss = torch.mean(huber_loss(td_error)) # Store values for stats function in", "from ray.rllib.policy.sample_batch import SampleBatch from ray.rllib.policy.torch_policy import TorchPolicy from ray.rllib.utils.annotations", "from ray.rllib.agents.dqn.simple_q_tf_policy import ( build_q_models, compute_q_values, get_distribution_inputs_and_class) from ray.rllib.models.modelv2 import", "given state. one_hot_selection = F.one_hot(train_batch[SampleBatch.ACTIONS].long(), policy.action_space.n) q_t_selected = torch.sum(q_t *", "= build_policy_class( name=\"SimpleQPolicy\", framework=\"torch\", loss_fn=build_q_losses, get_default_config=lambda: ray.rllib.agents.dqn.simple_q.DEFAULT_CONFIG, stats_fn=stats_fn, extra_action_out_fn=extra_action_out_fn, after_init=setup_late_mixins,", "evaluation q_t = compute_q_values( policy, model, train_batch[SampleBatch.CUR_OBS], explore=False, is_training=True) #", "(ModelV2): The Model to calculate the loss for. dist_class (Type[ActionDistribution]):", "from ray.rllib.policy.policy_template import build_policy_class from ray.rllib.policy.sample_batch import SampleBatch from ray.rllib.policy.torch_policy", "policy's # model, we sync the target network (from the", "sure that whenever we restore weights for this policy's #", "Policy's config. \"\"\" TargetNetworkMixin.__init__(policy) SimpleQTorchPolicy = build_policy_class( name=\"SimpleQPolicy\", framework=\"torch\", loss_fn=build_q_losses,", "from ray.rllib.utils.typing import TensorType, TrainerConfigDict torch, nn = try_import_torch() F", "logger = logging.getLogger(__name__) class TargetNetworkMixin: \"\"\"Assign the `update_target` method to", "build_q_models(policy, obs_space, action_space, config), \\ TorchCategorical def build_q_losses(policy: Policy, model,", "Policy object. obs_space (gym.spaces.Space): The Policy's observation space. action_space (gym.spaces.Space):", "TensorType, TrainerConfigDict torch, nn = try_import_torch() F = None if", "override from ray.rllib.utils.framework import try_import_torch from ray.rllib.utils.torch_utils import concat_multi_gpu_td_errors, huber_loss", "ray.rllib.agents.dqn.simple_q_tf_policy import ( build_q_models, compute_q_values, get_distribution_inputs_and_class) from ray.rllib.models.modelv2 import ModelV2", "gym.spaces.Space, config: TrainerConfigDict) -> Tuple[ModelV2, TorchDistributionWrapper]: return build_q_models(policy, obs_space, action_space,", "return {\"loss\": torch.mean(torch.stack(policy.get_tower_stats(\"loss\")))} def extra_action_out_fn(policy: Policy, input_dict, state_batches, model, action_dist)", "network evaluation q_t = compute_q_values( policy, model, train_batch[SampleBatch.CUR_OBS], explore=False, is_training=True)", "actions which we know were selected in the given state.", "torch.argmax(q_tp1, 1), policy.action_space.n) q_tp1_best = torch.sum(q_tp1 * q_tp1_best_one_hot_selection, 1) q_tp1_best_masked", "individual batch item. model.tower_stats[\"td_error\"] = td_error return loss def stats_fn(policy:", "to copy Q network to # target Q networks. state_dict", "Hard initial update from Q-net(s) to target Q-net(s). self.update_target() def", "the same time. TorchPolicy.set_weights(self, weights) self.update_target() def build_q_model_and_distribution( policy: Policy,", "called periodically to copy Q network to # target Q", "logging from typing import Dict, Tuple import gym import ray", "q network evalution q_tp1 = compute_q_values( policy, target_model, train_batch[SampleBatch.NEXT_OBS], explore=False,", "`update_target` method to the SimpleQTorchPolicy The function is called every", "import try_import_torch from ray.rllib.utils.torch_utils import concat_multi_gpu_td_errors, huber_loss from ray.rllib.utils.typing import", "import ( build_q_models, compute_q_values, get_distribution_inputs_and_class) from ray.rllib.models.modelv2 import ModelV2 from", "+ policy.config[\"gamma\"] * q_tp1_best_masked) # Compute the error (Square/Huber). td_error", "main model) # at the same time. TorchPolicy.set_weights(self, weights) self.update_target()", "torch.sum(q_tp1 * q_tp1_best_one_hot_selection, 1) q_tp1_best_masked = (1.0 - dones) *", "* one_hot_selection, 1) # compute estimate of best possible value", "multi-GPU, we do not override them during the parallel loss", "def build_q_losses(policy: Policy, model, dist_class, train_batch: SampleBatch) -> TensorType: \"\"\"Constructs", "Returns: TensorType: A single loss tensor. \"\"\" target_model = policy.target_models[model]", "loss def stats_fn(policy: Policy, batch: SampleBatch) -> Dict[str, TensorType]: return", "obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config: TrainerConfigDict) -> Tuple[ModelV2, TorchDistributionWrapper]: return", "ModelV2 from ray.rllib.models.torch.torch_action_dist import TorchCategorical, \\ TorchDistributionWrapper from ray.rllib.policy import", "action_space, config), \\ TorchCategorical def build_q_losses(policy: Policy, model, dist_class, train_batch:", "stats function in model (tower), such that for # multi-GPU,", "get_distribution_inputs_and_class) from ray.rllib.models.modelv2 import ModelV2 from ray.rllib.models.torch.torch_action_dist import TorchCategorical, \\", "tensor in final stats # will be concatenated and retrieved", "bellman equation q_t_selected_target = (train_batch[SampleBatch.REWARDS] + policy.config[\"gamma\"] * q_tp1_best_masked) #", "that for # multi-GPU, we do not override them during", "-> Tuple[ModelV2, TorchDistributionWrapper]: return build_q_models(policy, obs_space, action_space, config), \\ TorchCategorical", "\"\"\" def __init__(self): # Hard initial update from Q-net(s) to", "update_target(self): # Update_target_fn will be called periodically to copy Q", "config (TrainerConfigDict): The Policy's config. \"\"\" TargetNetworkMixin.__init__(policy) SimpleQTorchPolicy = build_policy_class(", "= td_error return loss def stats_fn(policy: Policy, batch: SampleBatch) ->", "for actions which we know were selected in the given", "q_t_selected_target.detach() loss = torch.mean(huber_loss(td_error)) # Store values for stats function", "# Compute the error (Square/Huber). td_error = q_t_selected - q_t_selected_target.detach()", "from ray.rllib.utils.framework import try_import_torch from ray.rllib.utils.torch_utils import concat_multi_gpu_td_errors, huber_loss from", "ray.rllib.utils.typing import TensorType, TrainerConfigDict torch, nn = try_import_torch() F =", "target Q networks. state_dict = self.model.state_dict() for target in self.target_models.values():", "obs_space (gym.spaces.Space): The Policy's observation space. action_space (gym.spaces.Space): The Policy's", "torch, nn = try_import_torch() F = None if nn: F", "SampleBatch from ray.rllib.policy.torch_policy import TorchPolicy from ray.rllib.utils.annotations import override from", "policy.config[\"gamma\"] * q_tp1_best_masked) # Compute the error (Square/Huber). td_error =", "- q_t_selected_target.detach() loss = torch.mean(huber_loss(td_error)) # Store values for stats", "RHS of bellman equation q_t_selected_target = (train_batch[SampleBatch.REWARDS] + policy.config[\"gamma\"] *", "from ray.rllib.utils.annotations import override from ray.rllib.utils.framework import try_import_torch from ray.rllib.utils.torch_utils", "model) # at the same time. TorchPolicy.set_weights(self, weights) self.update_target() def", "class TargetNetworkMixin: \"\"\"Assign the `update_target` method to the SimpleQTorchPolicy The", "Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config: TrainerConfigDict) -> None: \"\"\"Call", "of best possible value starting from state at t +", "tensor. \"\"\" target_model = policy.target_models[model] # q network evaluation q_t", "import override from ray.rllib.utils.framework import try_import_torch from ray.rllib.utils.torch_utils import concat_multi_gpu_td_errors,", "(1.0 - dones) * q_tp1_best # compute RHS of bellman", "time. TorchPolicy.set_weights(self, weights) self.update_target() def build_q_model_and_distribution( policy: Policy, obs_space: gym.spaces.Space,", "restore weights for this policy's # model, we sync the", "Policy's observation space. action_space (gym.spaces.Space): The Policy's action space. config", "to calculate the loss for. model (ModelV2): The Model to", "concat_multi_gpu_td_errors, huber_loss from ray.rllib.utils.typing import TensorType, TrainerConfigDict torch, nn =", "The Policy's action space. config (TrainerConfigDict): The Policy's config. \"\"\"", "by the master learner. \"\"\" def __init__(self): # Hard initial", "model, dist_class, train_batch: SampleBatch) -> TensorType: \"\"\"Constructs the loss for", "F.one_hot( torch.argmax(q_tp1, 1), policy.action_space.n) q_tp1_best = torch.sum(q_tp1 * q_tp1_best_one_hot_selection, 1)", "for. dist_class (Type[ActionDistribution]): The action distribution class. train_batch (SampleBatch): The", "# target Q networks. state_dict = self.model.state_dict() for target in", "TensorType]: return {\"loss\": torch.mean(torch.stack(policy.get_tower_stats(\"loss\")))} def extra_action_out_fn(policy: Policy, input_dict, state_batches, model,", "used for Simple Q-Learning\"\"\" import logging from typing import Dict,", "policy, model, train_batch[SampleBatch.CUR_OBS], explore=False, is_training=True) # target q network evalution", "ray.rllib.models.modelv2 import ModelV2 from ray.rllib.models.torch.torch_action_dist import TorchCategorical, \\ TorchDistributionWrapper from", "weights for this policy's # model, we sync the target", "q_tp1_best = torch.sum(q_tp1 * q_tp1_best_one_hot_selection, 1) q_tp1_best_masked = (1.0 -", "function is called every `target_network_update_freq` steps by the master learner.", "= F.one_hot( torch.argmax(q_tp1, 1), policy.action_space.n) q_tp1_best = torch.sum(q_tp1 * q_tp1_best_one_hot_selection,", "calculate the loss for. dist_class (Type[ActionDistribution]): The action distribution class.", "q_tp1_best_one_hot_selection, 1) q_tp1_best_masked = (1.0 - dones) * q_tp1_best #", "def setup_late_mixins(policy: Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config: TrainerConfigDict) ->", "None: \"\"\"Call all mixin classes' constructors before SimpleQTorchPolicy initialization. Args:", "to # target Q networks. state_dict = self.model.state_dict() for target", "equation q_t_selected_target = (train_batch[SampleBatch.REWARDS] + policy.config[\"gamma\"] * q_tp1_best_masked) # Compute", "explore=False, is_training=True) # q scores for actions which we know", "-> Dict[str, TensorType]: \"\"\"Adds q-values to the action out dict.\"\"\"", "obs_space, action_space, config), \\ TorchCategorical def build_q_losses(policy: Policy, model, dist_class,", "SimpleQTorchPolicy The function is called every `target_network_update_freq` steps by the", "q_tp1_best_masked = (1.0 - dones) * q_tp1_best # compute RHS", "# compute RHS of bellman equation q_t_selected_target = (train_batch[SampleBatch.REWARDS] +", "Dict[str, TensorType]: return {\"loss\": torch.mean(torch.stack(policy.get_tower_stats(\"loss\")))} def extra_action_out_fn(policy: Policy, input_dict, state_batches,", "= loss # TD-error tensor in final stats # will", "the loss for SimpleQTorchPolicy. Args: policy (Policy): The Policy to", "Dict, Tuple import gym import ray from ray.rllib.agents.dqn.simple_q_tf_policy import (", "TorchPolicy from ray.rllib.utils.annotations import override from ray.rllib.utils.framework import try_import_torch from", "the loss for. model (ModelV2): The Model to calculate the", "network evalution q_tp1 = compute_q_values( policy, target_model, train_batch[SampleBatch.NEXT_OBS], explore=False, is_training=True)", "The training data. Returns: TensorType: A single loss tensor. \"\"\"", "if nn: F = nn.functional logger = logging.getLogger(__name__) class TargetNetworkMixin:", "state_dict = self.model.state_dict() for target in self.target_models.values(): target.load_state_dict(state_dict) @override(TorchPolicy) def", "compute_q_values( policy, model, train_batch[SampleBatch.CUR_OBS], explore=False, is_training=True) # target q network", "policy (Policy): The Policy object. obs_space (gym.spaces.Space): The Policy's observation", "Args: policy (Policy): The Policy to calculate the loss for.", "explore=False, is_training=True) # target q network evalution q_tp1 = compute_q_values(", "Tuple[ModelV2, TorchDistributionWrapper]: return build_q_models(policy, obs_space, action_space, config), \\ TorchCategorical def", "(train_batch[SampleBatch.REWARDS] + policy.config[\"gamma\"] * q_tp1_best_masked) # Compute the error (Square/Huber).", "def stats_fn(policy: Policy, batch: SampleBatch) -> Dict[str, TensorType]: return {\"loss\":", "TensorType]: \"\"\"Adds q-values to the action out dict.\"\"\" return {\"q_values\":", "for. model (ModelV2): The Model to calculate the loss for.", "state at t + 1 dones = train_batch[SampleBatch.DONES].float() q_tp1_best_one_hot_selection =", "policy.q_values} def setup_late_mixins(policy: Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config: TrainerConfigDict)", "+ 1 dones = train_batch[SampleBatch.DONES].float() q_tp1_best_one_hot_selection = F.one_hot( torch.argmax(q_tp1, 1),", "TensorType: A single loss tensor. \"\"\" target_model = policy.target_models[model] #", "= self.model.state_dict() for target in self.target_models.values(): target.load_state_dict(state_dict) @override(TorchPolicy) def set_weights(self,", "SimpleQTorchPolicy = build_policy_class( name=\"SimpleQPolicy\", framework=\"torch\", loss_fn=build_q_losses, get_default_config=lambda: ray.rllib.agents.dqn.simple_q.DEFAULT_CONFIG, stats_fn=stats_fn, extra_action_out_fn=extra_action_out_fn,", "the `update_target` method to the SimpleQTorchPolicy The function is called", "self.update_target() def update_target(self): # Update_target_fn will be called periodically to", "single loss tensor. \"\"\" target_model = policy.target_models[model] # q network", "The Policy's config. \"\"\" TargetNetworkMixin.__init__(policy) SimpleQTorchPolicy = build_policy_class( name=\"SimpleQPolicy\", framework=\"torch\",", "1) q_tp1_best_masked = (1.0 - dones) * q_tp1_best # compute", "stats_fn(policy: Policy, batch: SampleBatch) -> Dict[str, TensorType]: return {\"loss\": torch.mean(torch.stack(policy.get_tower_stats(\"loss\")))}", "dones = train_batch[SampleBatch.DONES].float() q_tp1_best_one_hot_selection = F.one_hot( torch.argmax(q_tp1, 1), policy.action_space.n) q_tp1_best", "we know were selected in the given state. one_hot_selection =", "train_batch (SampleBatch): The training data. Returns: TensorType: A single loss", "the master learner. \"\"\" def __init__(self): # Hard initial update", "which we know were selected in the given state. one_hot_selection", "def set_weights(self, weights): # Makes sure that whenever we restore", "best possible value starting from state at t + 1", "Q-net(s) to target Q-net(s). self.update_target() def update_target(self): # Update_target_fn will", "<gh_stars>1-10 \"\"\"PyTorch policy class used for Simple Q-Learning\"\"\" import logging", "phase. model.tower_stats[\"loss\"] = loss # TD-error tensor in final stats", "were selected in the given state. one_hot_selection = F.one_hot(train_batch[SampleBatch.ACTIONS].long(), policy.action_space.n)", "periodically to copy Q network to # target Q networks.", "space. action_space (gym.spaces.Space): The Policy's action space. config (TrainerConfigDict): The", "policy.target_models[model] # q network evaluation q_t = compute_q_values( policy, model,", "the target network (from the main model) # at the", "for Simple Q-Learning\"\"\" import logging from typing import Dict, Tuple", "that whenever we restore weights for this policy's # model,", "\"\"\"PyTorch policy class used for Simple Q-Learning\"\"\" import logging from", "setup_late_mixins(policy: Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config: TrainerConfigDict) -> None:", "ray.rllib.policy.torch_policy import TorchPolicy from ray.rllib.utils.annotations import override from ray.rllib.utils.framework import", "target_model = policy.target_models[model] # q network evaluation q_t = compute_q_values(", "of bellman equation q_t_selected_target = (train_batch[SampleBatch.REWARDS] + policy.config[\"gamma\"] * q_tp1_best_masked)", "# Store values for stats function in model (tower), such", "same time. TorchPolicy.set_weights(self, weights) self.update_target() def build_q_model_and_distribution( policy: Policy, obs_space:", "(SampleBatch): The training data. Returns: TensorType: A single loss tensor.", "concatenated and retrieved for each individual batch item. model.tower_stats[\"td_error\"] =", "state. one_hot_selection = F.one_hot(train_batch[SampleBatch.ACTIONS].long(), policy.action_space.n) q_t_selected = torch.sum(q_t * one_hot_selection,", "q_t_selected_target = (train_batch[SampleBatch.REWARDS] + policy.config[\"gamma\"] * q_tp1_best_masked) # Compute the", "= None if nn: F = nn.functional logger = logging.getLogger(__name__)", "the loss for. dist_class (Type[ActionDistribution]): The action distribution class. train_batch", "# Update_target_fn will be called periodically to copy Q network", "Policy, model, dist_class, train_batch: SampleBatch) -> TensorType: \"\"\"Constructs the loss", "all mixin classes' constructors before SimpleQTorchPolicy initialization. Args: policy (Policy):", "\\ TorchCategorical def build_q_losses(policy: Policy, model, dist_class, train_batch: SampleBatch) ->", "model, we sync the target network (from the main model)", "-> Dict[str, TensorType]: return {\"loss\": torch.mean(torch.stack(policy.get_tower_stats(\"loss\")))} def extra_action_out_fn(policy: Policy, input_dict,", "F = None if nn: F = nn.functional logger =", "policy.action_space.n) q_t_selected = torch.sum(q_t * one_hot_selection, 1) # compute estimate", "TensorType: \"\"\"Constructs the loss for SimpleQTorchPolicy. Args: policy (Policy): The", "from typing import Dict, Tuple import gym import ray from", "Simple Q-Learning\"\"\" import logging from typing import Dict, Tuple import", "TD-error tensor in final stats # will be concatenated and", "-> TensorType: \"\"\"Constructs the loss for SimpleQTorchPolicy. Args: policy (Policy):", "loss for. dist_class (Type[ActionDistribution]): The action distribution class. train_batch (SampleBatch):", "is_training=True) # target q network evalution q_tp1 = compute_q_values( policy,", "= compute_q_values( policy, target_model, train_batch[SampleBatch.NEXT_OBS], explore=False, is_training=True) # q scores", "dist_class, train_batch: SampleBatch) -> TensorType: \"\"\"Constructs the loss for SimpleQTorchPolicy.", "\"\"\"Assign the `update_target` method to the SimpleQTorchPolicy The function is", "import TorchPolicy from ray.rllib.utils.annotations import override from ray.rllib.utils.framework import try_import_torch", "A single loss tensor. \"\"\" target_model = policy.target_models[model] # q", "model.tower_stats[\"loss\"] = loss # TD-error tensor in final stats #", "TargetNetworkMixin: \"\"\"Assign the `update_target` method to the SimpleQTorchPolicy The function", "class used for Simple Q-Learning\"\"\" import logging from typing import", "import TensorType, TrainerConfigDict torch, nn = try_import_torch() F = None", "Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config: TrainerConfigDict) -> Tuple[ModelV2, TorchDistributionWrapper]:", "= policy.target_models[model] # q network evaluation q_t = compute_q_values( policy,", "build_policy_class( name=\"SimpleQPolicy\", framework=\"torch\", loss_fn=build_q_losses, get_default_config=lambda: ray.rllib.agents.dqn.simple_q.DEFAULT_CONFIG, stats_fn=stats_fn, extra_action_out_fn=extra_action_out_fn, after_init=setup_late_mixins, make_model_and_action_dist=build_q_model_and_distribution,", "(Policy): The Policy object. obs_space (gym.spaces.Space): The Policy's observation space.", "# Hard initial update from Q-net(s) to target Q-net(s). self.update_target()", "every `target_network_update_freq` steps by the master learner. \"\"\" def __init__(self):", "will be concatenated and retrieved for each individual batch item.", "SimpleQTorchPolicy initialization. Args: policy (Policy): The Policy object. obs_space (gym.spaces.Space):", "dones) * q_tp1_best # compute RHS of bellman equation q_t_selected_target", "values for stats function in model (tower), such that for", "the main model) # at the same time. TorchPolicy.set_weights(self, weights)", "try_import_torch() F = None if nn: F = nn.functional logger", "q_tp1 = compute_q_values( policy, target_model, train_batch[SampleBatch.NEXT_OBS], explore=False, is_training=True) # q", "# model, we sync the target network (from the main", "the SimpleQTorchPolicy The function is called every `target_network_update_freq` steps by", "one_hot_selection = F.one_hot(train_batch[SampleBatch.ACTIONS].long(), policy.action_space.n) q_t_selected = torch.sum(q_t * one_hot_selection, 1)", "batch item. model.tower_stats[\"td_error\"] = td_error return loss def stats_fn(policy: Policy,", "td_error = q_t_selected - q_t_selected_target.detach() loss = torch.mean(huber_loss(td_error)) # Store", "= (train_batch[SampleBatch.REWARDS] + policy.config[\"gamma\"] * q_tp1_best_masked) # Compute the error", "from ray.rllib.models.torch.torch_action_dist import TorchCategorical, \\ TorchDistributionWrapper from ray.rllib.policy import Policy", "= logging.getLogger(__name__) class TargetNetworkMixin: \"\"\"Assign the `update_target` method to the", "TorchDistributionWrapper from ray.rllib.policy import Policy from ray.rllib.policy.policy_template import build_policy_class from", "ray from ray.rllib.agents.dqn.simple_q_tf_policy import ( build_q_models, compute_q_values, get_distribution_inputs_and_class) from ray.rllib.models.modelv2", "for each individual batch item. model.tower_stats[\"td_error\"] = td_error return loss", "( build_q_models, compute_q_values, get_distribution_inputs_and_class) from ray.rllib.models.modelv2 import ModelV2 from ray.rllib.models.torch.torch_action_dist", "= torch.sum(q_tp1 * q_tp1_best_one_hot_selection, 1) q_tp1_best_masked = (1.0 - dones)", "import Policy from ray.rllib.policy.policy_template import build_policy_class from ray.rllib.policy.sample_batch import SampleBatch", "Dict[str, TensorType]: \"\"\"Adds q-values to the action out dict.\"\"\" return", "train_batch[SampleBatch.CUR_OBS], explore=False, is_training=True) # target q network evalution q_tp1 =", "1 dones = train_batch[SampleBatch.DONES].float() q_tp1_best_one_hot_selection = F.one_hot( torch.argmax(q_tp1, 1), policy.action_space.n)", "(TrainerConfigDict): The Policy's config. \"\"\" TargetNetworkMixin.__init__(policy) SimpleQTorchPolicy = build_policy_class( name=\"SimpleQPolicy\",", "in self.target_models.values(): target.load_state_dict(state_dict) @override(TorchPolicy) def set_weights(self, weights): # Makes sure", "(tower), such that for # multi-GPU, we do not override", "to calculate the loss for. dist_class (Type[ActionDistribution]): The action distribution", "we sync the target network (from the main model) #", "# target q network evalution q_tp1 = compute_q_values( policy, target_model,", "during the parallel loss phase. model.tower_stats[\"loss\"] = loss # TD-error", "import TorchCategorical, \\ TorchDistributionWrapper from ray.rllib.policy import Policy from ray.rllib.policy.policy_template", "policy: Policy, obs_space: gym.spaces.Space, action_space: gym.spaces.Space, config: TrainerConfigDict) -> Tuple[ModelV2,", "train_batch[SampleBatch.DONES].float() q_tp1_best_one_hot_selection = F.one_hot( torch.argmax(q_tp1, 1), policy.action_space.n) q_tp1_best = torch.sum(q_tp1", "Policy, batch: SampleBatch) -> Dict[str, TensorType]: return {\"loss\": torch.mean(torch.stack(policy.get_tower_stats(\"loss\")))} def", "ray.rllib.policy.sample_batch import SampleBatch from ray.rllib.policy.torch_policy import TorchPolicy from ray.rllib.utils.annotations import", "(Square/Huber). td_error = q_t_selected - q_t_selected_target.detach() loss = torch.mean(huber_loss(td_error)) #", "space. config (TrainerConfigDict): The Policy's config. \"\"\" TargetNetworkMixin.__init__(policy) SimpleQTorchPolicy =", "def __init__(self): # Hard initial update from Q-net(s) to target", "Makes sure that whenever we restore weights for this policy's", "to the action out dict.\"\"\" return {\"q_values\": policy.q_values} def setup_late_mixins(policy:", "networks. state_dict = self.model.state_dict() for target in self.target_models.values(): target.load_state_dict(state_dict) @override(TorchPolicy)", "self.model.state_dict() for target in self.target_models.values(): target.load_state_dict(state_dict) @override(TorchPolicy) def set_weights(self, weights):", "= torch.mean(huber_loss(td_error)) # Store values for stats function in model", "(gym.spaces.Space): The Policy's action space. config (TrainerConfigDict): The Policy's config.", "parallel loss phase. model.tower_stats[\"loss\"] = loss # TD-error tensor in", "Policy's action space. config (TrainerConfigDict): The Policy's config. \"\"\" TargetNetworkMixin.__init__(policy)", "dict.\"\"\" return {\"q_values\": policy.q_values} def setup_late_mixins(policy: Policy, obs_space: gym.spaces.Space, action_space:", "action_dist) -> Dict[str, TensorType]: \"\"\"Adds q-values to the action out", "loss phase. model.tower_stats[\"loss\"] = loss # TD-error tensor in final", "called every `target_network_update_freq` steps by the master learner. \"\"\" def", "from ray.rllib.policy.torch_policy import TorchPolicy from ray.rllib.utils.annotations import override from ray.rllib.utils.framework", "try_import_torch from ray.rllib.utils.torch_utils import concat_multi_gpu_td_errors, huber_loss from ray.rllib.utils.typing import TensorType,", "The function is called every `target_network_update_freq` steps by the master", "t + 1 dones = train_batch[SampleBatch.DONES].float() q_tp1_best_one_hot_selection = F.one_hot( torch.argmax(q_tp1,", "constructors before SimpleQTorchPolicy initialization. Args: policy (Policy): The Policy object.", "# Makes sure that whenever we restore weights for this", "typing import Dict, Tuple import gym import ray from ray.rllib.agents.dqn.simple_q_tf_policy", "config: TrainerConfigDict) -> Tuple[ModelV2, TorchDistributionWrapper]: return build_q_models(policy, obs_space, action_space, config),", "data. Returns: TensorType: A single loss tensor. \"\"\" target_model =", "q-values to the action out dict.\"\"\" return {\"q_values\": policy.q_values} def", "target Q-net(s). self.update_target() def update_target(self): # Update_target_fn will be called", "gym.spaces.Space, action_space: gym.spaces.Space, config: TrainerConfigDict) -> Tuple[ModelV2, TorchDistributionWrapper]: return build_q_models(policy,", "mixin classes' constructors before SimpleQTorchPolicy initialization. Args: policy (Policy): The", "state_batches, model, action_dist) -> Dict[str, TensorType]: \"\"\"Adds q-values to the", "__init__(self): # Hard initial update from Q-net(s) to target Q-net(s).", "Q networks. state_dict = self.model.state_dict() for target in self.target_models.values(): target.load_state_dict(state_dict)", "= nn.functional logger = logging.getLogger(__name__) class TargetNetworkMixin: \"\"\"Assign the `update_target`", "at the same time. TorchPolicy.set_weights(self, weights) self.update_target() def build_q_model_and_distribution( policy:", "policy class used for Simple Q-Learning\"\"\" import logging from typing", "model (tower), such that for # multi-GPU, we do not", "ray.rllib.utils.torch_utils import concat_multi_gpu_td_errors, huber_loss from ray.rllib.utils.typing import TensorType, TrainerConfigDict torch,", "\"\"\" target_model = policy.target_models[model] # q network evaluation q_t =", "Q-Learning\"\"\" import logging from typing import Dict, Tuple import gym", "function in model (tower), such that for # multi-GPU, we", "possible value starting from state at t + 1 dones", "Args: policy (Policy): The Policy object. obs_space (gym.spaces.Space): The Policy's", "target.load_state_dict(state_dict) @override(TorchPolicy) def set_weights(self, weights): # Makes sure that whenever", "gym.spaces.Space, config: TrainerConfigDict) -> None: \"\"\"Call all mixin classes' constructors", "class. train_batch (SampleBatch): The training data. Returns: TensorType: A single", "is_training=True) # q scores for actions which we know were", "logging.getLogger(__name__) class TargetNetworkMixin: \"\"\"Assign the `update_target` method to the SimpleQTorchPolicy", "the error (Square/Huber). td_error = q_t_selected - q_t_selected_target.detach() loss =", "such that for # multi-GPU, we do not override them", "name=\"SimpleQPolicy\", framework=\"torch\", loss_fn=build_q_losses, get_default_config=lambda: ray.rllib.agents.dqn.simple_q.DEFAULT_CONFIG, stats_fn=stats_fn, extra_action_out_fn=extra_action_out_fn, after_init=setup_late_mixins, make_model_and_action_dist=build_q_model_and_distribution, mixins=[TargetNetworkMixin],", "import Dict, Tuple import gym import ray from ray.rllib.agents.dqn.simple_q_tf_policy import", "* q_tp1_best # compute RHS of bellman equation q_t_selected_target =", "do not override them during the parallel loss phase. model.tower_stats[\"loss\"]", "(Type[ActionDistribution]): The action distribution class. train_batch (SampleBatch): The training data.", "calculate the loss for. model (ModelV2): The Model to calculate", "q_t_selected - q_t_selected_target.detach() loss = torch.mean(huber_loss(td_error)) # Store values for", "model.tower_stats[\"td_error\"] = td_error return loss def stats_fn(policy: Policy, batch: SampleBatch)", "one_hot_selection, 1) # compute estimate of best possible value starting", "train_batch: SampleBatch) -> TensorType: \"\"\"Constructs the loss for SimpleQTorchPolicy. Args:", "train_batch[SampleBatch.NEXT_OBS], explore=False, is_training=True) # q scores for actions which we", "@override(TorchPolicy) def set_weights(self, weights): # Makes sure that whenever we", "and retrieved for each individual batch item. model.tower_stats[\"td_error\"] = td_error", "action_space: gym.spaces.Space, config: TrainerConfigDict) -> None: \"\"\"Call all mixin classes'", "error (Square/Huber). td_error = q_t_selected - q_t_selected_target.detach() loss = torch.mean(huber_loss(td_error))" ]
[ "'r', 'b', 'ɯ', 'a', 's', 'ʐ', 'η', 'ŋ', 'ɒ', 'ʂ',", "'ʷen', 'ʷiu', 'ʷet', 'ɯəw', 'ʷɛ', 'ʷɤ', 'ɯj', 'oj', 'ăw', 'zi',", "u'gì' : u'ji', u'gì' : u'ji', u'gĩ' : u'ji', u'gị'", "ươ : ɯə1 xõa <-> xoã : swʷa3 ''' #Ở", "u'ô' : u'o', u'ố' : u'o', u'ồ' : u'o', u'ổ'", "list if str(char) in [\"ˈ\",\"ˌ\",\"*\"]: continue print(\"this is not in", "24, u'ừ' : 32, u'ử' : 312, u'ữ' : u'35g',", "'hw', 'nw', 'sw', 'c'] word_pad = [\"_\"] space = [\"", "u'ʷe', u'uơ' : u'ʷɤ', u'uớ' : u'ʷɤ', u'uờ' : u'ʷɤ',", ": u'ă', u'ằ' : u'ă', u'ẳ' : u'ă', u'ẵ' :", "u'ăj', u'uạy' : u'ăj', u'uây' : u'ɤ̆j', u'uấy' : u'ɤ̆j',", ": u'aj', u'ại' : u'aj', u'ay' : u'ăj', u'áy' :", "u'ẽ' : 214, u'ẹ' : 212, u'ế' : 45, u'ề'", "'ʒ', 'ə', 'ʌ', 'm', '!', '∫', 'ð', 'u', 'e', 'w',", "u'ẽ' : u'ɛ', u'ẹ' : u'ɛ', u'ê' : u'e', u'ế'", "u'oẵ' : u'ʷă', u'oặ' : u'ʷă', u'oe' : u'ʷɛ', u'oé'", ": u'ʷă', u'uặ' : u'ʷă', u'uâ' : u'ʷɤ̆', u'uấ' :", ": u'zi', u'gị' : u'zi'} N_qu = {u'quy' : u'kwi',", "u'ẩ' : 4, u'ẫ' : 4, u'ậ' : 6, u'ắ'", "k theo bắc : t theo nam -> custom k", ": u'iə', u'ia' : u'iə', u'iá' : u'iə', u'ià' :", ": 32, u'ổ' : 312, u'ỗ' : u'35g', u'ộ' :", "u'oạo' : u'aw', u'oeo' : u'ew', u'oéo' : u'ew', u'oèo'", "!= u'kw': if ons: ons = ons+u'w' else: ons =", "# Modified 20 Sep 2008 to fix aberrant 33 error", "cod, ton)))+delimit except (TypeError): pass return seq ########################333 from vinorm", ": u'ăw', u'ãu' : u'ăw', u'ạu' : u'ăw', u'ây' :", "u'íu' : u'iw', u'ìu' : u'iw', u'ỉu' : u'iw', u'ĩu'", "else: ton = str('1') # Modifications for closed syllables if", "u'p', u'qu' : u'kw', u'gi' : u'z', u'tr' : u'c',", "u'k', u'c' : u'k', u'm' : u'm', u'n' : u'ŋ',", "u'ew', u'uẻo' : u'ew', u'uẽo' : u'ew', u'uẹo' : u'ew',", ": u'i', u'ỵ' : u'i', u'eo' : u'eo', u'éo' :", "dialect == 'n': onsets, nuclei, codas, tones, onglides, offglides, onoffglides,", "u'oèn' : u'en', u'oẻn' : u'en', u'oẽn' : u'en', u'oẹn'", "4, u'ũ' : 3, u'ụ' : 6, u'ứ' : 5,", "'t', 'k']: ton = u'45' # Modification for 8-tone system", "in offglides: cod = offglides[nucl][-1] nuc = offglides[nucl][:-1] elif word", "u'ɔj', u'ôi' : u'oj', u'ối' : u'oj', u'ồi' : u'oj',", "214, u'ẵ' : 214, u'ặ' : 212, u'é' : 45,", ": u'et' } C_onoffglides = { u'oe' : u'ej', u'oé'", ": u'i', u'ĩ' : u'i', u'ị' : u'i', u'o' :", ": u'ɤ̆j' } Cus_codas = { u'p' : u'p', u't'", "== u't': cod = u'k' if cod == u'n': cod", "u'aj', u'uái' : u'aj', u'uài' : u'aj', u'uải' : u'aj',", "+ \" -> \"+nor) trung +=1 List_pair.append(line) List_token.append(nor) if nor==\"\":", "cod = onoffglides[nucl][-1] nuc = onoffglides[nucl][0:-1] if ons != u'kw':", "u'ng' : u'ŋ', u'nh' : u'n', u'ch' : u't' }", ": u'ɔj', u'õi' : u'ɔj', u'ọi' : u'ɔj', u'ôi' :", "u'n', u'ch' : u'k' } # See Alves 2007 (SEALS", "u'ew', u'uẽo' : u'ew', u'uẹo' : u'ew', u'uai' : u'aj',", "seq return compound def T2IPA(text): sys.path.append('./Rules') # make sure we", "=> k for c , t for t, tʃ for", "u'aj', u'oãi' : u'aj', u'oại' : u'aj', u'oay' : u'ăj',", "u'iə', u'uyề' : u'iə', u'uyể' : u'iə', u'uyễ' : u'iə',", ": u'aj', u'oài' : u'aj', u'oải' : u'aj', u'oãi' :", "u'úy' : u'uj', u'ùy' : u'uj', u'ủy' : u'uj', u'ũy'", ": u'21g', # u'ơ' : 33, u'ớ' : 24, u'ờ'", "allophony (added 17.09.08) if nuc in [u'u', u'o', u'ɔ']: if", "= qu[word][:-1] nuc = qu[word][-1] else: # Something is non-Viet", "toè : twʷɛ2 ua <-> uơ : uə1 ưa <->", ": u'e', u'oẻ' : u'e', u'oẽ' : u'e', u'oẹ' :", "if two-character coda cod = codas[word[l-2:l]] cOffset = 2 elif", ": u'ɤj', u'ỡi' : u'ɤj', u'ợi' : u'ɤj', u'ưi' :", "u'e', u'ɛ']: cod = u'c' # Velar Fronting (Southern and", "'nw', 't∫', 'ɲw', 'eo', 'sw', 'tw', 'ʐw', 'iɛ', 'ʷe', 'i:',", "u'ɔj', u'ói' : u'ɔj', u'òi' : u'ɔj', u'ỏi' : u'ɔj',", ": 214, u'ẽ' : 214, u'ẹ' : 212, u'ế' :", "else: print(\"none\") ''' ################################################### #Step #Vinorm #Underthesea #For each Convert", "u'ʷa', u'uá' : u'ʷa', u'uà' : u'ʷa', u'uả' : u'ʷa',", "'j', 'x', 'ʈ', ',', '4', 'ʊ', 's', 'ŋ', 'a', 'ʃ',", "= ons+u'w' # labialize it, but... else: # if there", ": u'iə', u'iề' : u'iə', u'iể' : u'iə', u'iễ' :", "3: # if you just have 'gi' and a coda...", "S_offglides, S_onoffglides, S_qu, S_gi, C_onsets, C_nuclei, C_codas#, C_tones , C_onglides,", ": 214, u'ẹ' : 212, u'ế' : 45, u'ề' :", "32, u'ở' : 312, u'ỡ' : u'35g', u'ợ' : u'21g',", "'ʈw', 'mw', 'zw', 'fw', 'tw', 'tʰw', 'ɲw', 'cw', 'ʂw', 'ɣw',", "coda... nucl = u'i' ons = u'z' else: nucl =", "u'ở' : 312, u'ỡ' : u'35g', u'ợ' : u'21g', #", "u'oào' : u'aw', u'oảo' : u'aw', u'oão' : u'aw', u'oạo'", "'ʧ', 'ʈ', ' ', 'd', 'i', 'ɣ', 'ɲ', 'ɤ', '?',", "u'f', u'v' : u'v', u'x' : u's', u'd' : u'z',", "u'ʷɛ', u'õe' : u'ʷɛ', u'ọe' : u'ʷɛ', u'ua' : u'ʷa',", ": 4, u'ụ' : 6, u'ứ' : 5, u'ừ' :", "u'yễu' : u'iəw', u'yệu' : u'iəw', u'uôi' : u'uəj', u'uối'", "u'í' : 13, u'ì' : 42, u'ỉ' : 312, u'ĩ'", ": u'ʷi', u'uý' : u'ʷi', u'uỳ' : u'ʷi', u'uỷ' :", "co Mapping #Neu khong, check co nguyen am #Neu co", "u'e', u'oẽ' : u'e', u'oẹ' : u'e', u'oe' : u'e',", "of g C_tones_p = { u'á' : 5, u'à' :", "= onoffglides[nucl][-1] nuc = onoffglides[nucl][0:-1] if ons != u'kw': if", "u'ew', u'ẻo' : u'ew', u'ẽo' : u'ew', u'ẹo' : u'ew',", "u'oẹt' : u'et' } N_onoffglides = { u'oe' : u'ej',", "single hyphens or underscores words = [word for word in", ": u'a', u'oã' : u'a', u'oạ' : u'a', u'óa' :", ": u'a', u'uạ' : u'a', u'uă' : u'ă', u'uắ' :", "u'ɤ̆w', u'ầu': u'ɤ̆w', u'ẩu' : u'ɤ̆w', u'ẫu' : u'ɤ̆w', u'ậu'", "'a', 'ʃ', '?', 'r', ':', 'η', 'f', ';', 'e', 't',", "= [word for word in words if word!=u'-'] words =", "u'ʷɛ', u'oé' : u'ʷɛ', u'oè' : u'ʷɛ', u'oẻ' : u'ʷɛ',", "is a big problem #Same positive #k <-> c #g", "'.', 'ɒ', 'b', 'h', 'n', 'ʂ', 'ɔ', 'ɛ', 'k', 'm',", "giảm trùng nhiều hơn 241->153 case #Tuy nhiên cuối cùng", ": u'uj', u'ụy' : u'uj', u'ơi' : u'ɤj', u'ới' :", "u'o', u'ốô' : u'o', u'ồô' : u'o', u'ổô' : u'o',", "'tʃ', 'ɔɪ', 'xw', 'ʷɤ', 'ɤ̆', 'ŋw', 'ʊə', 'zi', 'ʷă', 'dw',", "u'iə', u'iề' : u'iə', u'iể' : u'iə', u'iễ' : u'iə',", "u'ả' : 312, u'ã' : 312, u'ạ' : u'21g', u'ấ'", "range(0,l) if word[i] in tones] if tonelist: ton = str(tonelist[len(tonelist)-1])", "u'x', u'g' : u'ɣ', u'l' : u'l', u'm' : u'm',", "'gh', 'kʷ' etc ons = onsets[word[0:2]] oOffset = 2 elif", "u'ẳ' : 312, u'ẵ' : u'35g', u'ặ' : u'21g', #", ": u'iu', u'uyu' : u'iu', u'uýu' : u'iu', u'uỳu' :", "if ons: ons = ons+u'w' else: ons = u'w' elif", "symbols def vi2IPA_pitrain(text): epi = epitran.Epitran('vie-Latn') r=epi.transliterate(text) return r def", "for word in words if word!=u'-'] words = [word for", "= { u'á' : 24, u'à' : 32, u'ả' :", "N_onoffglides, N_qu, N_gi, Cus_onsets, Cus_nuclei, Cus_codas#, N_tones , Cus_onglides, Cus_offglides,", "u'uô' : u'uə', u'uố' : u'uə', u'uồ' : u'uə', u'uổ'", "0 palatals = 0 tokenize = 0 delimit = ''", "úy -> wi để phân biệt với úi #Remain '''", "<-> nghễu : ŋɛu3 nghía <-> ngía : ŋiə5 nghịu", ": u'o', u'ồô' : u'o', u'ổô' : u'o', u'ỗô' :", "# if onset is 'nh', 'gh', 'kʷ' etc ons =", ": u'ɤ̆j', u'uấy' : u'ɤ̆j', u'uầy' : u'ɤ̆j', u'uẩy' :", "oOffset = 0 cOffset = 0 l = len(word) if", "u'ɤ̆j', u'uấy' : u'ɤ̆j', u'uầy' : u'ɤ̆j', u'uẩy' : u'ɤ̆j',", ": u'ɤ̆j' } C_codas = { u'p' : u'p', u't'", "word.strip(punctuation).lower() ## 29.03.16: check if tokenize is true ## if", "= list(set(symbols)) symbols.sort(reverse = True,key=len) return symbols def vi2IPA_pitrain(text): epi", "ons = '' nuc = '' cod = '' ton", ": u'ɛj', u'oè' : u'ɛj', u'oẻ' : u'ɛj', u'oẽ' :", "3, u'ỵ' : 6, } Cus_gi = { u'gi' :", ": u'a', u'oá' : u'a', u'oà' : u'a', u'oả' :", "nuclei, codas, tones, onglides, offglides, onoffglides, qu, gi = S_onsets,", "u'uyu' : u'ʷiu', u'uyú' : u'ʷiu', u'uyù' : u'ʷiu', u'uyủ'", "u'aw', u'ào' : u'aw', u'ảo' : u'aw', u'ão' : u'aw',", "u'iə', u'uyễ' : u'iə', u'uyệ' : u'iə', u'uyu' : u'iu',", "u'é' : u'ɛ', u'è' : u'ɛ', u'ẻ' : u'ɛ', u'ẽ'", "IPA=re.sub(' +', ' ', IPA) print(\"IPA Vietnamese: \",IPA) print(\"------------------------------------------------------\") return", "in tess: print(\"------------------------------------------------------\") TN= TTSnorm(text) print(\"------------------------------------------------------\") print(\"Text normalize: \",TN) TK=", "13, u'ầ' : 42, u'ẩ' : 312, u'ẫ' : 312,", "u'ʷă', u'oặ' : u'ʷă', u'oe' : u'ʷɛ', u'oé' : u'ʷɛ',", ": 4, u'ã' : 3, u'ạ' : 6, u'ấ' :", ": u'a', u'òa' : u'a', u'ỏa' : u'a', u'õa' :", "# Obstruent-final nang tones are modal voice if (dialect ==", "if word!=u'_'] for i in range(0,len(words)): word = words[i].strip() ortho", "nuc in [u'i', u'e', u'ɛ']: if cod == u'ɲ': cod", "0 l = len(word) if l > 0: if word[0:3]", "u'eo', u'ẽo': u'eo', u'ẹo' : u'eo', u'êu' : u'ɛu', u'ếu'", "u'ʐ', u's' : u'ʂ', u'gi' : u'j' } C_nuclei =", "'k']: ton = u'6b' # labialized allophony (added 17.09.08) if", "= text if line =='\\n': return \"\" else: compound =", "u'uỡ' : u'ʷɤ', u'uợ' : u'ʷɤ', u'uy' : u'ʷi', u'uý'", "there is an onset... ons = ons+u'w' # labialize it,", "''' #Ở đây tiết kiệm chi phí chạy máy không", ": u'ʷi', u'uỹ' : u'ʷi', u'uỵ' : u'ʷi', u'ơi' :", ": u'ew', u'éo' : u'ew', u'èo' : u'ew', u'ẻo' :", "u'oẹt' : u'et' } S_onoffglides = { u'oe' : u'ej',", "u'13')) and cod in ['p', 't', 'k']: ton = u'45'", "nuc, cod, ton) def convert(word, dialect, glottal, pham, cao, palatals,", "'ɤ̆j', 'ʷiə', 'ɤ̆w', 'ɯəw', 'ʷet', 'iəw', 'uəj', 'ʷen', 'tʰw', 'ʷɤ̆',", "hợp có cách bỏ dấu khác nhau đều gộp chung", "= offglides[nucl][-1] nuc = offglides[nucl][:-1] elif word in gi: #", ": u'ʷen', u'oén' : u'ʷen', u'oèn' : u'ʷen', u'oẻn' :", ": u'ʂ', u'gi': u'j'} Cus_nuclei = { u'a' : u'a',", "== 3: # if you just have 'gi' and a", "'ă', '_', 'æ', 'ɤ', '2', 'ʤ', 'i', '.', 'ɒ', 'b',", "'dw', 'eɪ', 'aɪ', 'ew', 'iə', 'ɣw', 'zw', 'ɯj', 'ʷɛ', 'ɯw',", "TK= word_tokenize(TN) print(\"Vietnamese Tokenize: \",TK) for iuv,under_valid in enumerate(TK): token_under=under_valid.split(\"", "\"uỵ\"] Onset=[\"b\",\"d\",\"h\",\"l\",\"m\",\"n\",\"p\",\"r\",\"s\",\"t\",\"v\",\"x\",\"đ\",\"p\", \"tr\", \"th\", \"ch\", \"ph\",\"nh\",\"kh\",\"gi\",\"qu\", \"ngh\",\"ng\",\"gh\",\"g\",\"k\",\"c\"] #coding: utf-8 #Custom", "u'aj', u'ái' : u'aj', u'ài' : u'aj', u'ải' : u'aj',", "u'ổ' : u'o', u'ỗ' : u'o', u'ộ' : u'o', u'ơ'", "'f', ';', 'e', 't', \"'\"] def Parsing(listParse, text, delimit): undefine_symbol", "= u'ŋ͡m' if cod == u'k': cod = u'k͡p' return", "214, u'ễ' : 214, u'ệ' : 212, u'í' : 45,", "u'gi': u'j'} Cus_nuclei = { u'a' : u'a', u'á' :", "S_qu, S_gi, C_onsets, C_nuclei, C_codas#, C_tones , C_onglides, C_offglides, C_onoffglides,", ": u'uj', u'ũy' : u'uj', u'ụy' : u'uj', #thay để", "codas: # if two-character coda cod = codas[word[l-2:l]] cOffset =", "modifi = [\"k͡p\",\"ŋ͡m\"] symbols = list_phoneme + space+word_pad + English_phoneme", "we investigate work! One is that e language to another", ", cout_same) #Các trường hợp dẫn đến trùng âm là:", "else: nuc = nuclei[nucl] # there's your nucleus else: #", "[word for word in words if word!=u'_'] for i in", "import eng_to_ipa SET=[S_onsets, S_nuclei, S_codas#, S_tones , S_onglides, S_offglides, S_onoffglides,", "2016 ton = u'21' # Modification for sắc in closed", "u'ɔ', u'ỏo' : u'ɔ', u'õo' : u'ɔ', u'ọo' : u'ɔ',", "u'iw', u'ĩu' : u'iw', u'ịu' : u'iw', u'oi' : u'ɔj',", "33, u'ấ' : 24, u'ầ' : 32, u'ẩ' : 312,", "C_offglides, C_onoffglides, C_qu, C_gi elif dialect == 's': onsets, nuclei,", "in ['i','í','ì','ĩ','ỉ','ị']): continue cout_same+=1 print(line+ \" <-> \" + lin2", "u'ʷiə', u'uyệ' : u'ʷiə', u'uyu' : u'ʷiu', u'uyú' : u'ʷiu',", "onglides, offglides, onoffglides, qu, gi = Cus_onsets, Cus_nuclei, Cus_codas, Cus_onglides,", "ʷ to all start o and u as in wiki", "onoffglides, qu, gi = Cus_onsets, Cus_nuclei, Cus_codas, Cus_onglides, Cus_offglides, Cus_onoffglides,", "S_onglides, S_offglides, S_onoffglides, S_qu, S_gi #Custom onsets, nuclei, codas, onglides,", ": u'u', u'ũ' : u'u', u'ụ' : u'u', u'ư' :", "ANH #+Thêm xử lí case không có cũng như case", "qu, gi = C_onsets, C_nuclei, C_codas, C_tones, C_onglides, C_offglides, C_onoffglides,", ": u'ʷa', u'oả' : u'ʷa', u'oã' : u'ʷa', u'oạ' :", ": u'ɔj', u'ỏi' : u'ɔj', u'õi' : u'ɔj', u'ọi' :", "# labialize it, but... else: # if there is no", "ton) = trans(word, dialect, glottal, pham, cao, palatals) if None", "u'ả' : 312, u'ã' : u'35g', u'ạ' : u'21g', u'ấ'", "#blank \"á\",\"ắ\",\"ấ\",\"é\",\"ế\",\"í\",\"ó\",\"ố\",\"ớ\",\"ú\",\"ứ\",\"ý\",\"iế\",\"óa\",\"oắ\",\"óe\",\"oó\",\"uấ\",\"uế\",\"uố\",\"ướ\",\"úy\",\"ướ\",\"uyế\",\"yế\", #grave \"oá\", \"oé\",\"óo\", \"uý\", \"à\",\"ằ\",\"ầ\",\"è\",\"ề\",\"ì\",\"ò\",\"ồ\",\"ờ\",\"ù\",\"ừ\",\"ỳ\",\"iề\",\"òa\",\"oằ\",\"òe\",\"oò\",\"uầ\",\"uề\",\"uồ\",\"ườ\",\"ùy\",\"ườ\",\"uyề\",\"yề\", #acute \"oà\", \"oè\",\"òo\",", ": u'l', u'm' : u'm', u'n': u'n', u'ngh': u'ŋ', u'nh'", "u'ụ' : u'21g', u'ứ' : 24, u'ừ' : 32, u'ử'", "mượn \"tʃ\" trong teach and watch để thay thế =>", "u'oén' : u'en', u'oèn' : u'en', u'oẻn' : u'en', u'oẽn'", "u'b', u't' : u't', u'th' : u'tʰ', u'đ' : u'd',", "See Alves 2007 (SEALS XII), Vũ 1982 C_tones = {", "if cod == u'n': cod = u'ŋ' # Monophthongization (Southern", "'ɤ̆w', 'ɯəw', 'ʷet', 'iəw', 'uəj', 'ʷen', 'tʰw', 'ʷɤ̆', 'ʷiu', 'kwi',", ": u'h', u'p' : u'p', u'qu' : u'kw', u'gi' :", "#check các ipa của tiếng anh #print(vi2IPA_split(\"Another table was prepared", "#Nếu không có trong từ tiếng anh -> đọc từng", "u'ửu' : u'ɯw', u'ữu' : u'ɯw', u'ựu' : u'ɯw', u'iêu'", ": 212, u'ó' : 45, u'ò' : 32, u'ỏ' :", ": u'ɤ̆j', u'ẩy' : u'ɤ̆j', u'ẫy' : u'ɤ̆j', u'ậy' :", "in gi and cod and len(word) == 3: # if", "each Convert to phoneme #Nếu không được check phoneme tiếng", "yêu : iəw1 khoắng <-> khuắng : xwʷăŋ5 khỏe <->", "u'21g', # u'e' : 33, u'é' : 24, u'è' :", "in [u'i', u'e']: if cod == u'k': cod = u't'", "List_pair.append(line) List_token.append(nor) if nor==\"\": cout+=1 print(line) print(\"Number of token can", "u'a', u'ả' : u'a', u'ã' : u'a', u'ạ' : u'a',", ": 312, u'ỹ' : u'35g', u'ỵ' : u'21g', } #", "'ʷen', 'tʰw', 'ʷɤ̆', 'ʷiu', 'kwi', 'ŋ͡m', 'k͡p', 'cw', 'jw', 'uə',", "u'ɤj', u'ời' : u'ɤj', u'ởi' : u'ɤj', u'ỡi' : u'ɤj',", "non-Viet return (None, None, None, None) # Velar Fronting (Northern", ": u'ɯəw', 'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw' } S_onglides", "u'ỡ' : 214, u'ợ' : 212, u'ú' : 45, u'ù'", ": 33, u'ắ' : 24, u'ằ' : 32, u'ẳ' :", ": u'21g', u'ý' : 24, u'ỳ' : 32, u'ỷ' :", "'aɪ', 'ew', 'iə', 'ɣw', 'zw', 'ɯj', 'ʷɛ', 'ɯw', 'ɤj', 'ɔ:',", "= 0 tokenize = 0 delimit = '' dialect='n' #\"c\"\"s\"", "glottal character N_tones_p = { u'á' : 5, u'à' :", ": u'ɯəw', u'ượu' : u'ɯəw' } #Các âm vòng ở", "u'uợ' : u'uə', } Cus_offglides = { u'ai' : u'aj',", ": u'i', u'uỵ' : u'i', u'uya' : u'iə', u'uyá' :", "list_phoneme=list(list_phoneme) English_phoneme=[\"p\",\"b\",\"t\",\"d\",\"t∫\",\"dʒ\",\"k\",\"g\",\"f\",\"v\",\"ð\",\"θ\",\"s\",\"z\",\"∫\",\"ʒ\",\"m\",\"n\",\"η\",\"l\",\"r\",\"w\",\"j\",\"ɪ\",\"i:\",\"ʊ\",\"u:\",\"e\",\"ə\",\"ɜ:\",\"ɒ\",\"ɔ:\",\"æ\",\"ʌ\",\"ɑ:\",\"ɪə\",\"ʊə\",\"eə\",\"eɪ\",\"ɔɪ\",\"aɪ\",\"əʊ\",\"aʊ\",'ʃ',\"ʤ\",\"ʧ\"] Special=['jw', 'ŋw', 'bw', 'vw', 'dw', 'eo', 'ʈw', 'mw',", "is 'nh', 'gh', 'kʷ' etc ons = onsets[word[0:2]] oOffset =", "== u'iə': nuc = u'i' if nuc == u'uə': nuc", "dấu khác nhau đều gộp chung làm một #Disable convert", "ghen : ɣɛn1 ghì <-> gì : ɣi2 ghích <->", "để phân biệt với úi #Remain ''' di <-> gi", "u'ộ' : u'21g', u'ớ' : 24, u'ờ' : 32, u'ở'", "ine,res in enumerate(Results): if res not in check_sym: Results[ine]=\"'\" '''", "u'e', u'uệ' : u'e', u'uơ' : u'ɤ', u'uớ' : u'ɤ',", "# if there is an onset... ons = ons+u'w' #", "cod = u'ɲ' # u'ŋ' elif palatals != 1 and", "line[0]==\"c\") or (lin2[-1] in ['i','í','ì','ĩ','ỉ','ị'] and line[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ']) or", "u'ɤ̆j', u'uậy' : u'ɤ̆j' } S_codas = { u'p' :", "';', 'e', 't', \"'\"] def Parsing(listParse, text, delimit): undefine_symbol =", "-> fix oe from e to ɛ #âm cuối: ch", ": tʰuə4 tòe <-> toè : twʷɛ2 ua <-> uơ", ": u'iəw', u'uôi' : u'uəj', u'uối' : u'uəj', u'uồi' :", "312, u'ữ' : u'35g', u'ự' : u'21g', u'ý' : 24,", "u'ạ' : u'21g', u'ấ' : 13, u'ầ' : 42, u'ẩ'", "u'ng' : u'ŋ', u'nh' : u'ɲ', u'ch' : u'tʃ' }", "\"oé\",\"óo\", \"uý\", \"à\",\"ằ\",\"ầ\",\"è\",\"ề\",\"ì\",\"ò\",\"ồ\",\"ờ\",\"ù\",\"ừ\",\"ỳ\",\"iề\",\"òa\",\"oằ\",\"òe\",\"oò\",\"uầ\",\"uề\",\"uồ\",\"ườ\",\"ùy\",\"ườ\",\"uyề\",\"yề\", #acute \"oà\", \"oè\",\"òo\", \"uỳ\", \"ả\",\"ẳ\",\"ẩ\",\"ẻ\",\"ể\",\"ỉ\",\"ỏ\",\"ổ\",\"ở\",\"ủ\",\"ử\",\"ỷ\",\"iể\",\"ỏa\",\"oẳ\",\"ỏe\",\"oỏ\",\"uẩ\",\"uể\",\"uổ\",\"ưở\",\"ủy\",\"ưở\",\"uyể\",\"yể\", #hook \"oả\",", "T2IPA(tk).replace(\" \",\"_\") if ipa ==\"\": IPA+=tk+\" \" elif ipa[0]==\"[\" and", "IPA=re.sub(delimit+'+', delimit, IPA) IPA=re.sub(' +', ' ', IPA) print(\"IPA Vietnamese:", ": u'ɤ̆j', u'ầy' : u'ɤ̆j', u'ẩy' : u'ɤ̆j', u'ẫy' :", "C_nuclei, C_codas#, C_tones , C_onglides, C_offglides, C_onoffglides, C_qu, C_gi, N_onsets,", "u'ɤ', u'u' : u'u', u'ú' : u'u', u'ù' : u'u',", "u'ỏ' : 312, u'õ' : u'35g', u'ọ' : u'21g', u'ố'", "== tk: #print(\"ENGLISH\",tk) #Đọc tiếng anh từng chữ letter2sound=\"\" for", "<-> gi : zi1 dìm <-> gìm : zim2 din", ": ŋiə5 nghịu <-> ngịu : ŋiw6 nghoèo <-> ngoèo", "#i <-> y #Same negative / need to fix #oe", "text[ic:ic+len(l)]: output+=delimit+l check =1 skip=len(l)-1 break if check == 0:", "two-character coda cod = codas[word[l-2:l]] cOffset = 2 elif word[l-1]", "string import punctuation def trans(word, dialect, glottal, pham, cao, palatals):", "212, u'ó' : 45, u'ò' : 32, u'ỏ' : 214,", "u'ổ' : 4, u'ỗ' : 3, u'ộ' : 6, u'ớ'", "palatals): # This looks ugly, but newer versions of python", "ɣɛn1 ghì <-> gì : ɣi2 ghích <-> gích :", "u'oẻ' : u'ɛj', u'oẽ' : u'ɛj', u'oẹ' : u'ɛj', u'oai'", "there's your nucleus else: nuc = nuclei[nucl] # there's your", "u'eo', u'ẻo' : u'eo', u'ẽo': u'eo', u'ẹo' : u'eo', u'êu'", "';', 'r', 'b', 'ɯ', 'a', 's', 'ʐ', 'η', 'ŋ', 'ɒ',", "or \"[\" in T2IPA(tok): checkinvalid=1 if checkinvalid==1: TK = TK[:iuv]", "S_qu = {u'quy' : u'wi', u'qúy' : u'wi', u'qùy' :", "'aw', 'ɛj', 'iw', 'aj', 'ɜ:', 'kw', 'nw', 't∫', 'ɲw', 'eo',", "IPA+=tk+\" \" elif ipa[0]==\"[\" and ipa[-1]==\"]\": eng = eng_to_ipa.convert(tk) if", "} S_nuclei = { u'a' : u'a', u'á' : u'a',", "u'35g', u'ọ' : u'21g', u'ố' : 24, u'ồ' : 32,", "for the unicode raised glottal character N_tones_p = { u'á'", "\"oẽ\",\"õo\", \"uỹ\", \"ạ\",\"ặ\",\"ậ\",\"ẹ\",\"ệ\",\"ị\",\"ọ\",\"ộ\",\"ợ\",\"ụ\",\"ự\",\"ỵ\",\"iệ\",\"ọa\",\"oặ\",\"ọe\",\"oọ\",\"uậ\",\"uệ\",\"uệ\",\"ượ\",\"ụy\",\"ượ\",\"uyệ\",\"yệ\", #dot \"oạ\", \"oẹ\",\"ọo\", \"uỵ\"] Onset=[\"b\",\"d\",\"h\",\"l\",\"m\",\"n\",\"p\",\"r\",\"s\",\"t\",\"v\",\"x\",\"đ\",\"p\", \"tr\", \"th\",", ": 312, u'ữ' : u'35g', u'ự' : u'21g', # u'y'", "2007 (SEALS XII), Vũ 1982 C_tones = { u'á' :", "'ʤ', 'ɔ', '1', 'ʧ', 'ʈ', ' ', 'd', 'i', 'ɣ',", "6, u'í' : 5, u'ì' : 2, u'ỉ' : 4,", "u'ʷa', u'oã' : u'ʷa', u'oạ' : u'ʷa', u'óa' : u'ʷa',", "} S_gi = { u'gi' : u'ji', u'gí': u'ji', u'gì'", "ons = u'w' elif nucl in offglides: cod = offglides[nucl][-1]", ": 2, u'ẳ' : 4, u'ẵ' : 3, u'ặ' :", "u'uj', u'ủi' : u'uj', u'ũi' : u'uj', u'ụi' : u'uj',", "dialect) if dialect == 'n': if nuc == u'a': if", "212, u'ắ' : 45, u'ằ' : 32, u'ẳ' : 214,", ": u'eo', u'éo' : u'eo', u'èo' : u'eo', u'ẻo' :", "'xw', 'ʷɤ', 'ɤ̆', 'ŋw', 'ʊə', 'zi', 'ʷă', 'dw', 'eɪ', 'aɪ',", ": u'i', u'ỷ' : u'i', u'ỹ' : u'i', u'ỵ' :", "312, u'ạ' : u'21g', u'ấ' : 13, u'ầ' : 42,", "u'ỵ' : 6, } C_gi = { u'gi' : u'ji',", "u'oạ' : u'a', u'óa' : u'a', u'òa' : u'a', u'ỏa'", "in gi: # if word == 'gi', 'gì',... ons =", ": u'ʷa', u'uă' : u'ʷă', u'uắ' : u'ʷă', u'uằ' :", "add a glottal stop else: # otherwise... nuc = nuclei[nucl]", "and ton == u'21g' and cod in ['p', 't', 'k']:", "van print(\" ..................Out of domain word: \" ,ipa) else: IPA+=ipa+\"", "(nhưng nếu thêm vào ảnh hưởng chữ qu cũng ra", "u'ɯəj', u'ượi' : u'ɯəj', u'ươu' : u'ɯəw', u'ướu' : u'ɯəw',", "else: # Something is non-Viet return (None, None, None, None)", "import re def vi2IPA_split(texts,delimit): content=[] with open(\"Popular.txt\",encoding=\"utf-8\") as f: content=f.read().splitlines()", ": u'ʷiu', u'uỳu' : u'ʷiu', u'uỷu' : u'ʷiu', u'uỹu' :", "to add ʷ to all start o and u as", "u'uỗi' : u'uəj', u'uội' : u'uəj', u'ươi' : u'ɯəj', u'ưới'", "'t', 'k']: #if ton == u'21\\u02C0' and cod in ['p',", ": u'ʂ', u'gi' : u'j' } C_nuclei = { u'a'", "u'21' # Modification for sắc in closed syllables (Northern and", "N_tones_p if dialect == 'c': tones_p = C_tones_p if dialect", "cod == u'k': cod = u'k͡p' return (ons, nuc, cod,", "u'qu' : u'kw', u'gi' : u'j', u'tr' : u'ʈ', u'k'", "u'ẹo' : u'eo', u'êu' : u'ɛu', u'ếu' : u'ɛu', u'ều'", "u'uẩ' : u'ʷɤ̆', u'uẫ' : u'ʷɤ̆', u'uậ' : u'ʷɤ̆', u'ue'", "content=[] with open(\"Popular.txt\",encoding=\"utf-8\") as f: content=f.read().splitlines() tess = texts.split(\".\") Results", "ý tưởng mượn \"tʃ\" trong teach and watch để thay", "delimit).strip() # concatenate if len(words) >= 2: ortho += '", "u'ŋ', u'nh' : u'n', u'ch' : u'k' } # See", "newer versions of python complain about \"from x import *\"", ": u'ew', u'iu' : u'iw', u'íu' : u'iw', u'ìu' :", "u'en', u'oẹn' : u'en', u'oet' : u'et', u'oét' : u'et',", "2, u'ẩ' : 4, u'ẫ' : 3, u'ậ' : 6,", "\",TK) IPA=\"\" for tk in TK: ipa = T2IPA(tk).replace(\" \",\"_\")", "checkinvalid=0 print(token_under) if len(token_under) >1: for tok in token_under: if", "u'ɤ', u'ở' : u'ɤ', u'ỡ' : u'ɤ', u'ợ' : u'ɤ',", "qu, gi = N_onsets, N_nuclei, N_codas, N_tones, N_onglides, N_offglides, N_onoffglides,", "== u'n': cod = u'ŋ' # Monophthongization (Southern dialects: Thompson", "u'et', u'oét' : u'et', u'oèt' : u'et', u'oẻt' : u'et',", ": u'ɛ', u'uè' : u'ɛ', u'uẻ' : u'ɛ', u'uẽ' :", "if str(char) in [\"ˈ\",\"ˌ\",\"*\"]: continue print(\"this is not in symbol", "print(\"------------------------------------------------------\") print(\"Text normalize: \",TN) TK= word_tokenize(TN) print(\"Vietnamese Tokenize: \",TK) IPA=\"\"", "u'ừ' : 2, u'ử' : 4, u'ữ' : 3, u'ự'", "codas, tones, onglides, offglides, onoffglides, qu, gi = C_onsets, C_nuclei,", "u'ɤ', u'o', u'ɔ', u'ă', u'ɤ̆']: if cod == u't': cod", "u'uẹ' : u'ʷɛ', u'uê' : u'ʷe', u'uế' : u'ʷe', u'uề'", "Cus_codas#, N_tones , Cus_onglides, Cus_offglides, Cus_onoffglides, Cus_qu, Cus_gi] DICT={} #144", ": u'uə', u'ùa' : u'uə', u'ủa' : u'uə', u'ũa' :", ": u'ej', u'oè' : u'ej', u'oẻ' : u'ej', u'oẽ' :", "\"from x import *\" syntax if dialect == 'n': onsets,", "\"default\": listParse=['ʷiə', 'uəj', 'iəw', 'k͡p', 'ʷɤ̆', 'ɤ̆j', 'ŋ͡m', 'kwi', 'ɤ̆w',", "(tokenize and '-' in word) or (tokenize and '_' in", "anh #+Deal case thống nhất âm vực phoneme -> ok", "u'kwi', u'qúy' : u'kwi', u'qùy' : u'kwi', u'qủy' : u'kwi',", "24, u'ầ' : 32, u'ẩ' : 312, u'ẫ' : u'35g',", "Phương ngữ khác nhau đã thống nhất ở list custom", "u'uj', #u'uy' : u'uj', u'úy' : u'uj', u'ùy' : u'uj',", "u'ua' : u'ʷa', u'uá' : u'ʷa', u'uà' : u'ʷa', u'uả'", ": u'iu', u'uỳu' : u'iu', u'uỷu' : u'iu', u'uỹu' :", "= 0 oOffset = 0 cOffset = 0 l =", "u'uyú' : u'ʷiu', u'uyù' : u'ʷiu', u'uyủ' : u'ʷiu', u'uyũ'", "'i', 'ɣ', 'ɲ', 'ɤ', '?', 'ɪ', 'l', '.', 'j', ':',", "=Pair[T2IPA(line)] if line != lin2: if (lin2[0]==\"k\" and line[0]==\"c\") or", "== 's') and ton == u'21g' and cod in ['p',", "chang không vòm: không có w ở trước => Try", "u'ɤ', u'ỡ' : u'ɤ', u'ợ' : u'ɤ', u'u' : u'u',", ": u'ă', u'uâ' : u'ɤ̆', u'uấ' : u'ɤ̆', u'uầ' :", "u'et' } S_onoffglides = { u'oe' : u'ej', u'oé' :", "không vòm: không có w ở trước như: \"oa,ua,a\" đều", "u'oé' : u'e', u'oè' : u'e', u'oẻ' : u'e', u'oẽ'", "dialect, glottal, pham, cao, palatals) if None in (ons, nuc,", "u'ọo' : u'ɔ', u'oo' : u'ɔ', u'oó' : u'ɔ', u'oò'", "u'ượu' : u'ɯəw' } C_onglides = { u'oa' : u'a',", "u'ʷiu', u'uỹu' : u'ʷiu', u'uỵu' : u'ʷiu', u'oen' : u'ʷen',", "u'ɤ̆', u'ẫ' : u'ɤ̆', u'ậ' : u'ɤ̆', u'ă' : u'ă',", ": u'ă', u'uằ' : u'ă', u'uẳ' : u'ă', u'uẵ' :", "u'ă', u'ẵ' : u'ă', u'ặ' : u'ă', u'e' : u'ɛ',", "print(\"IPA Vietnamese: \",IPA) print(\"------------------------------------------------------\") return IPA def checkDict(): cout=0 trung=0", "-> wi để phân biệt với úi #Remain ''' di", "214, u'ậ' : 212, u'ắ' : 45, u'ằ' : 32,", "list(EN.keys()): letter2sound+=EN[CHAR]+\" \" else: letter2sound+=char+\" \" IPA+=T2IPA_split(letter2sound,delimit)+\" \" else: #Giữ", "u't' } S_tones = { u'á' : 45, u'à' :", ": 42, u'ẳ' : 312, u'ẵ' : 312, u'ặ' :", "u'ʷiu', u'uỵu' : u'ʷiu', u'oen' : u'ʷen', u'oén' : u'ʷen',", ": 3, u'ự' : 6, u'ý' : 5, u'ỳ' :", "24, u'à' : 32, u'ả' : 312, u'ã' : u'35g',", "= [\".\",\",\",\"!\",\":\",\"?\",\";\",\"'\"] #\" ' ( ) Have been removed due", "u'ứu' : u'ɯw', u'ừu' : u'ɯw', u'ửu' : u'ɯw', u'ữu'", "res not in check_sym: Results[ine]=\"'\" ''' return Results.rstrip() def vi2IPA(text):", "twʷɛ2 ua <-> uơ : uə1 ưa <-> ươ :", ": u'ɯə', u'ửa' : u'ɯə', u'ữa' : u'ɯə', u'ựa' :", "u'ặ' : u'ă', u'e' : u'ɛ', u'é' : u'ɛ', u'è'", ": 312, u'ĩ' : 312, u'ị' : u'21g', u'ó' :", "u'uặ' : u'ă', u'uâ' : u'ɤ̆', u'uấ' : u'ɤ̆', u'uầ'", "lwʷɛ5 ngét <-> nghét : ŋɛt5 ngễu <-> nghễu :", ": u'ew', u'ọeo' : u'ew', u'ueo' : u'ew', u'uéo' :", "\"oạ\", \"oẹ\",\"ọo\", \"uỵ\"] Onset=[\"b\",\"d\",\"h\",\"l\",\"m\",\"n\",\"p\",\"r\",\"s\",\"t\",\"v\",\"x\",\"đ\",\"p\", \"tr\", \"th\", \"ch\", \"ph\",\"nh\",\"kh\",\"gi\",\"qu\", \"ngh\",\"ng\",\"gh\",\"g\",\"k\",\"c\"] #coding:", "u'oái' : u'aj', u'oài' : u'aj', u'oải' : u'aj', u'oãi'", "'' ton = 0 seq = '' try: (ons, nuc,", "pham, cao, palatals, delimit): \"\"\"Convert a single orthographic string to", "u'oet' : u'ʷet', u'oét' : u'ʷet', u'oèt' : u'ʷet', u'oẻt'", ": u'iəw', u'iếu' : u'iəw', u'iều' : u'iəw', u'iểu' :", "is non-Viet return (None, None, None, None) # Velar Fronting", "symbols = list_phoneme + space+word_pad + English_phoneme + punctuation +", "= N_onsets, N_nuclei, N_codas, N_tones, N_onglides, N_offglides, N_onoffglides, N_qu, N_gi", "u'uế' : u'e', u'uề' : u'e', u'uể' : u'e', u'uễ'", "u'uễ' : u'ʷe', u'uệ' : u'ʷe', u'uơ' : u'ʷɤ', u'uớ'", "u'ɛ' # Final palatals (Northern dialect) if nuc not in", "u'uy' : u'ʷi', u'úy' : u'uj', u'ùy' : u'uj', u'ủy'", "line[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ']) or (lin2[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ'] and line[-1] in", ": u'ew', u'òeo' : u'ew', u'ỏeo' : u'ew', u'õeo' :", "dialect == 's': if cod in [u'm', u'p']: if nuc", "in wiki # *** Problem with ủy onglide and off-glide", "vòm: không có w ở trước như: \"oa,ua,a\" đều như", ": u'uə', u'uỡ' : u'uə', u'uợ' : u'uə', } N_offglides", ": u'ɯ', u'ữ' : u'ɯ', u'ự' : u'ɯ', u'y' :", "u'ị' : u'i', u'o' : u'ɔ', u'ó' : u'ɔ', u'ò'", "u'iə', u'uyế' : u'iə', u'uyề' : u'iə', u'uyể' : u'iə',", "'p', 'ʃ', 'æ', \"'\", 'h', 'o', 'k', '5', 'g', '4',", "import punctuation def trans(word, dialect, glottal, pham, cao, palatals): #", "u'uế' : u'ʷe', u'uề' : u'ʷe', u'uể' : u'ʷe', u'uễ'", "u'o' : u'ɔ', u'ó' : u'ɔ', u'ò' : u'ɔ', u'ỏ'", ": u'tʃ' } Cus_tones_p = { u'á' : 5, u'à'", "u'et' } N_onoffglides = { u'oe' : u'ej', u'oé' :", "u'ũy' : u'uj', u'ụy' : u'uj', u'ơi' : u'ɤj', u'ới'", "'ɯj', 'ʷɛ', 'ɯw', 'ɤj', 'ɔ:', 'əʊ', 'ʷa', 'mw', 'ɑ:', 'hw',", "312, u'ễ' : 312, u'ệ' : u'21g', u'í' : 13,", "u'iu', u'uỵu' : u'iu', u'oen' : u'en', u'oén' : u'en',", "u'ão' : u'aw', u'ạo' : u'aw', u'au' : u'ăw', u'áu'", "4, u'ỵ' : 6, } S_gi = { u'gi' :", "u'ý' : u'i', u'ỳ' : u'i', u'ỷ' : u'i', u'ỹ'", "in Pair: lin2 =Pair[T2IPA(line)] if line != lin2: if (lin2[0]==\"k\"", "modify the nuc accordingly if ons: # if there is", "u'oẻn' : u'ʷen', u'oẽn' : u'ʷen', u'oẹn' : u'ʷen', u'oet'", "u'ew', u'éo' : u'ew', u'èo' : u'ew', u'ẻo' : u'ew',", "# u'e' : 33, u'é' : 24, u'è' : 32,", "due to none sound modifi = [\"k͡p\",\"ŋ͡m\"] symbols = list_phoneme", "\"+delimit+\".\"+delimit+\" \" #For checking: need much memory ''' check_sym=\"ɯəjɤ̆jʷiəɤ̆wɯəwʷetiəwuəjʷentʰwʷɤ̆ʷiukwiŋ͡mk͡pcwjwuəeəbwojʷivwăwʈwʂwaʊfwɛutʰtʃɔɪxwʷɤɤ̆ŋwʊəziʷădweɪaɪewiəɣwzwɯjʷɛɯwɤjɔ:əʊʷamwɑ:hwɔjujlwɪəăju:awɛjiwajɜ:kwnwt∫ɲweoswtwʐwiɛʷei:ɯədʒɲθʌlw1ɪɯd∫pəuo3ɣ!ðʧ6ʒʐzvgă_æɤ2ʤi.ɒbhnʂɔɛkm5cjxʈ,4ʊsŋaʃ?r:ηf;et'\" for", "= { u'gi' : u'zi', u'gí': u'zi', u'gì' : u'zi',", "case #Tuy nhiên cuối cùng \"ch\" \"c\" \"t\" không phân", "'ʊ', 's', 'ŋ', 'a', 'ʃ', '?', 'r', ':', 'η', 'f',", ": u'k', u'c' : u'k', u'gh' : u'ɣ', u'r' :", "in TK: ipa = T2IPA_split(tk,delimit).replace(\" \",\"_\") if ipa ==\"\": IPA+=delimit+tk+delimit+\"", "#if ton == u'21\\u02C0' and cod in ['p', 't', 'k']:", "u'ái' : u'aj', u'ài' : u'aj', u'ải' : u'aj', u'ãi'", "u'o', u'ɔ']: if cod == u'ŋ': cod = u'ŋ͡m' if", "u'ew', u'oeo' : u'ew', u'óeo' : u'ew', u'òeo' : u'ew',", "u'uẹ' : u'ɛ', u'uê' : u'e', u'uế' : u'e', u'uề'", "if dialect == 'n': if nuc == u'a': if cod", "== u'5' and cod in ['p', 't', 'k']: ton =", "tự #Now #+Thêm kí tự IPA của tiếng ANH #+Thêm", "u'oẽt' : u'ʷet', u'oẹt' : u'ʷet' } Cus_onoffglides = {", "u'gị' : u'ji' } S_qu = {u'quy' : u'wi', u'qúy'", "word in words if len(word)>0] ## hack to get rid", "u'et' } C_onoffglides = { u'oe' : u'ej', u'oé' :", "lin2: if (lin2[0]==\"k\" and line[0]==\"c\") or (lin2[-1] in ['i','í','ì','ĩ','ỉ','ị'] and", "u'ph' : u'f', u'v' : u'v', u'x' : u's', u'd'", "312, u'ặ' : u'21g', u'é' : 13, u'è' : 42,", "'hw', 'ɔj', 'uj', 'lw', 'ɪə', 'ăj', 'u:', 'aw', 'ɛj', 'iw',", "hưởng chữ qu cũng ra w) #Try to add ʷ", "your nucleus elif nucl in onglides and ons != u'kw':", "u'ʷă', u'uằ' : u'ʷă', u'uẳ' : u'ʷă', u'uẵ' : u'ʷă',", "check co nguyen am #Neu co de nguyen #Neu khong", "= len(word) if l > 0: if word[0:3] in onsets:", "glottal, pham, cao, palatals, delimit).strip() # concatenate if len(words) >=", ": u'ʷe', u'uề' : u'ʷe', u'uể' : u'ʷe', u'uễ' :", "u'ew', u'oẽo' : u'ew', u'oẹo' : u'ew', u'oeo' : u'ew',", "u'oò' : u'ɔ', u'oỏ' : u'ɔ', u'oõ' : u'ɔ', u'oọ'", "[u'm', u'p']: if nuc == u'iə': nuc = u'i' if", "32, u'ỏ' : 312, u'õ' : u'35g', u'ọ' : u'21g',", "not in content or \"[\" in T2IPA(tok): checkinvalid=1 if checkinvalid==1:", "u'uə', u'ùa' : u'uə', u'ủa' : u'uə', u'ũa' : u'uə',", "S_onglides = { u'oa' : u'a', u'oá' : u'a', u'oà'", "TK: ipa = T2IPA_split(tk,delimit).replace(\" \",\"_\") if ipa ==\"\": IPA+=delimit+tk+delimit+\" \"", "'l', 'w', '1', 'ɪ', 'ɯ', 'd', '∫', 'p', 'ə', 'u',", "Cus_qu = {u'quy' : u'kwi', u'qúy' : u'kwi', u'qùy' :", "u'ji' } S_qu = {u'quy' : u'wi', u'qúy' : u'wi',", "cuối cùng \"ch\" \"c\" \"t\" không phân âm được =>", "5, u'è' : 2, u'ẻ' : 4, u'ẽ' : 3,", "u'ɛ', u'uẽ' : u'ɛ', u'uẹ' : u'ɛ', u'uê' : u'e',", "u'ở' : 214, u'ỡ' : 214, u'ợ' : 212, u'ú'", "# There is also this reverse fronting, see Thompson 1965:94", ": u'ew', u'õeo' : u'ew', u'ọeo' : u'ew', u'ueo' :", "bỏ dấu khác nhau đều gộp chung làm một #Disable", "in (ons, nuc, cod, ton): seq = u'['+word+u']' else: seq", "u'ễ' : u'35g', u'ệ' : u'21g', u'í' : 24, u'ì'", "u'ej', u'oè' : u'ej', u'oẻ' : u'ej', u'oẽ' : u'ej',", "#Nếu không được check phoneme tiếng anh #Nếu không có", "'ʈw', 'ʂw', 'aʊ', 'fw', 'ɛu', 'tʰ', 'tʃ', 'ɔɪ', 'xw', 'ʷɤ',", "word word = word.strip(punctuation).lower() ## 29.03.16: check if tokenize is", "ton): seq = u'['+word+u']' else: seq = delimit+delimit.join(filter(None, (ons, nuc,", ": u'aw', u'ào' : u'aw', u'ảo' : u'aw', u'ão' :", "= True,key=len) output=\"\" skip=0 for ic,char in enumerate(text): #print(char,skip) check", ": u'o', u'ốô' : u'o', u'ồô' : u'o', u'ổô' :", "or cao): if dialect == 'c': ton = str('35') else:", ": u'iə', u'ìa' : u'iə', u'ỉa' : u'iə', u'ĩa' :", "accordingly if ons: # if there is an onset... ons", "13, u'ừ' : 42, u'ử' : 312, u'ữ' : 312,", "Have been removed due to none sound modifi = [\"k͡p\",\"ŋ͡m\"]", "u'uậ' : u'ʷɤ̆', u'ue' : u'ʷɛ', u'ué' : u'ʷɛ', u'uè'", "4, u'ĩ' : 3, u'ị' : 6, u'ó' : 5,", "Convert to phoneme #Nếu không được check phoneme tiếng anh", "u'ẽo': u'eo', u'ẹo' : u'eo', u'êu' : u'ɛu', u'ếu' :", "u'k', u'm' : u'm', u'n' : u'n', u'ng' : u'ŋ',", ": 6, } S_gi = { u'gi' : u'ji', u'gí':", ": u'uə', u'uợ' : u'uə', } C_offglides = { u'ai'", "u'ũi' : u'uj', u'ụi' : u'uj', u'uy' : u'uj', u'úy'", "u'ặ' : u'21g', u'é' : 24, u'è' : 32, u'ẻ'", "Tokenize: \",TK) for iuv,under_valid in enumerate(TK): token_under=under_valid.split(\" \") checkinvalid=0 print(token_under)", "u'uý' : u'ʷi', u'uỳ' : u'ʷi', u'uỷ' : u'ʷi', u'uỹ'", "4, u'õ' : 4, u'ọ' : 6, u'ố' : 5,", "word[0] in onsets: # if single onset ons = onsets[word[0]]", "in ['p', 't', 'k']: ton = u'45' # Modification for", "else: ton = str('33') else: ton = str('1') # Modifications", ": u'ɯəw', u'ướu' : u'ɯəw', u'ườu' : u'ɯəw', u'ưởu' :", "u'oj', u'ồi' : u'oj', u'ổi' : u'oj', u'ỗi' : u'oj',", "Cus_nuclei, Cus_codas#, N_tones , Cus_onglides, Cus_offglides, Cus_onoffglides, Cus_qu, Cus_gi] DICT={}", "nuc = u'i' if nuc == u'uə': nuc = u'u'", "khua <-> khuơ : xuə1 lóe <-> loé : lwʷɛ5", "# u'i' : 33, u'í' : 24, u'ì' : 32,", ": swʷa3 ''' #Ở đây tiết kiệm chi phí chạy", "#Neu co Mapping #Neu khong, check co nguyen am #Neu", "u'ặ' : 6, u'é' : 5, u'è' : 2, u'ẻ'", ": u'e', u'ọe' : u'e', u'ua' : u'a', u'uá' :", "u'35g', u'ụ' : u'21g', # u'ư' : 33, u'ứ' :", ": u'en', u'oẽn' : u'en', u'oẹn' : u'en', u'oet' :", "for line in content: #nor_tr = vi2IPA_pitrain(line) #nor = vi2IPA(line)", "to IPA.\"\"\" ons = '' nuc = '' cod =", "u'ỗ' : 3, u'ộ' : 6, u'ớ' : 5, u'ờ'", "= lt cout_same=0 with open(\"Popular.txt\", encoding=\"utf-8\") as f: content=f.read().splitlines() for", "tiết kiệm chi phí chạy máy không normal phoneme về", "u'ểu' : u'ɛu', u'ễu': u'ɛu', u'ệu' : u'ɛu', u'ia' :", "u'21g', # u'ư' : 33, u'ứ' : 24, u'ừ' :", "u'nh' : u'ɲ', u'ch' : u'tʃ' } Cus_tones_p = {", "with open(\"Popular.txt\", encoding=\"utf-8\") as f: content=f.read().splitlines() for line in content:", "u'h' : u'h', u'p' : u'p', u'qu' : u'w', u'gi'", "########################333 from vinorm import * from underthesea import word_tokenize import", "u'ỡ' : u'ɤ', u'ợ' : u'ɤ', u'u' : u'u', u'ú'", ": u'iə', u'iả' : u'iə', u'iã' : u'iə', u'iạ' :", "u'ớ' : 24, u'ờ' : 32, u'ở' : 312, u'ỡ'", "u'a': if cod == u'k' and cOffset == 2: nuc", "= qu[word][-1] else: # Something is non-Viet return (None, None,", "u'ầ' : 32, u'ẩ' : 214, u'ẫ' : 214, u'ậ'", "print(\"------------------------------------------------------\") TN= TTSnorm(text) print(\"------------------------------------------------------\") print(\"Text normalize: \",TN) TK= word_tokenize(TN) print(\"Vietnamese", "N_qu, N_gi, Cus_onsets, Cus_nuclei, Cus_codas#, N_tones , Cus_onglides, Cus_offglides, Cus_onoffglides,", "C_onglides, C_offglides, C_onoffglides, C_qu, C_gi, N_onsets, N_nuclei, N_codas#, N_tones ,", "# add a glottal stop else: # otherwise... nuc =", "u'ɔ', u'óo' : u'ɔ', u'òo' : u'ɔ', u'ỏo' : u'ɔ',", "u'e', u'ễ' : u'e', u'ệ' : u'e', u'i' : u'i',", "u'ổ' : 4, u'ỗ' : 4, u'ộ' : 6, u'ớ'", ": 312, u'ẽ' : u'35g', u'ẹ' : u'21g', # u'ê'", ": u'ă', u'uẳ' : u'ă', u'uẵ' : u'ă', u'uặ' :", "u'uyệ' : u'ʷiə', u'uyu' : u'ʷiu', u'uyú' : u'ʷiu', u'uyù'", "there's your nucleus elif nucl in onglides and ons !=", ": u'35g', u'ệ' : u'21g', u'í' : 24, u'ì' :", "6, } N_gi = { u'gi' : u'zi', u'gí': u'zi',", "[tones[word[i]] for i in range(0,l) if word[i] in tones] if", "nucl = word[oOffset:l-cOffset] if nucl in nuclei: if oOffset ==", "'uəj', 'iəw', 'k͡p', 'ʷɤ̆', 'ɤ̆j', 'ŋ͡m', 'kwi', 'ɤ̆w', 'ɯəj', 'ʷen',", "S_nuclei, S_codas#, S_tones , S_onglides, S_offglides, S_onoffglides, S_qu, S_gi, C_onsets,", "and cod in ['p', 't', 'k']: #if ton == u'21\\u02C0'", "u'õ' : u'35g', u'ọ' : u'21g', # u'ô' : 33,", "if word == 'gi', 'gì',... ons = gi[word][0] nuc =", "compound + seq return compound def T2IPA(text): sys.path.append('./Rules') # make", "to use \\u02C0 for raised glottal instead of g C_tones_p", "u'ẵ' : 4, u'ặ' : 6, u'é' : 5, u'è'", ": u'ɯəj', u'ươu' : u'ɯəw', u'ướu' : u'ɯəw', u'ườu' :", "Vietnamese: \",IPA) print(\"------------------------------------------------------\") return IPA def checkDict(): cout=0 trung=0 List_token=[]", "u'uă' : u'ă', u'uắ' : u'ă', u'uằ' : u'ă', u'uẳ'", "u'oỏ' : u'ɔ', u'oõ' : u'ɔ', u'oọ' : u'ɔ', u'ôô'", "u'uỗ' : u'uə', u'uộ' : u'uə', u'ưa' : u'ɯə', u'ứa'", "u'21g', u'ắ' : 13, u'ằ' : 42, u'ẳ' : 312,", ": u'ɯə', u'ườ' : u'ɯə', u'ưở' : u'ɯə', u'ưỡ' :", ": u'ɯə', u'ữa' : u'ɯə', u'ựa' : u'ɯə', u'ươ' :", "'ʷi', 'eɪ', 'ɤj', 'ɯw', 'ɛj', 'ɔj', 'i:', 't∫', 'ɪə', 'ʷă',", "= [\"_\"] space = [\" \"] tone=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"] punctuation = [\".\",\",\",\"!\",\":\",\"?\",\";\",\"'\"]", "<-> gíp : zip5 gen <-> ghen : ɣɛn1 ghì", "u'oọ' : u'ɔ', u'ôô' : u'o', u'ốô' : u'o', u'ồô'", "[u'i', u'e', u'ɛ']: if cod == u'ɲ': cod = u'ɲ'#u'ŋ'", "you just have 'gi' and a coda... nucl = u'i'", "single orthographic string to IPA.\"\"\" ons = '' nuc =", "u'kwi'} ####################################################### # North # #coding: utf-8 N_onsets = {", "= {u'quy' : u'wi', u'qúy' : u'wi', u'qùy' : u'wi',", "Modifications for closed syllables if cOffset !=0: # Obstruent-final nang", "u'21g', u'í' : 13, u'ì' : 42, u'ỉ' : 312,", "u'ji', u'gì' : u'ji', u'gĩ' : u'ji', u'gị' : u'ji'", "break if check == 0: #Case symbol not in list", "u'a', u'oã' : u'a', u'oạ' : u'a', u'óa' : u'a',", "\"th\", \"ch\", \"ph\",\"nh\",\"kh\",\"gi\",\"qu\", \"ngh\",\"ng\",\"gh\",\"g\",\"k\",\"c\"] #coding: utf-8 #Custom phoneme follow the", "' if i < len(words)-1: seq = seq+u' ' compound", "import *\" syntax if dialect == 'n': onsets, nuclei, codas,", "u'ấ' : 13, u'ầ' : 42, u'ẩ' : 312, u'ẫ'", "tonelist: ton = str(tonelist[len(tonelist)-1]) else: if not (pham or cao):", "(dialect == 'c' and ton == u'13')) and cod in", ": u'ɤ', u'uờ' : u'ɤ', u'uở' : u'ɤ', u'uỡ' :", "# u'ă' : 33, u'ắ' : 24, u'ằ' : 32,", "u'oà' : u'ʷa', u'oả' : u'ʷa', u'oã' : u'ʷa', u'oạ'", "if len(word)>0] ## hack to get rid of single hyphens", ": u'ʷiə', u'uyệ' : u'ʷiə', u'uyu' : u'ʷiu', u'uyú' :", "for x in values] seq = ''.join(v+d for v,d in", "i in range(0,l) if word[i] in tones] if tonelist: ton", "u'uơ' : u'uə', u'uở' : u'uə', u'uờ': u'uə', u'uở' :", "if dialect == 'c': ton = str('35') else: ton =", "u'iw', u'íu' : u'iw', u'ìu' : u'iw', u'ỉu' : u'iw',", "return seq ########################333 from vinorm import * from underthesea import", ": u'21g', # u'y' : 33, u'ý' : 24, u'ỳ'", ": u'eo', u'ẽo': u'eo', u'ẹo' : u'eo', u'êu' : u'ɛu',", "u'ưu' : u'ɯw', u'ứu' : u'ɯw', u'ừu' : u'ɯw', u'ửu'", "to fix #oe <-> uê -> fix oe from e", ": u'n', u'ch' : u't' } S_tones = { u'á'", ": u'ɯəw', u'ượu' : u'ɯəw' } S_onglides = { u'oa'", ": 212, u'ý' : 45, u'ỳ' : 32, u'ỷ' :", "(Northern and Central only) if ((dialect == 'n' and ton", "'.', 'j', ':', 't', 'ʒ', 'ə', 'ʌ', 'm', '!', '∫',", ": u'ew', u'èo' : u'ew', u'ẻo' : u'ew', u'ẽo' :", ": 32, u'ẻ' : 214, u'ẽ' : 214, u'ẹ' :", "u'ɤ̆w', u'ẩu' : u'ɤ̆w', u'ẫu' : u'ɤ̆w', u'ậu' : u'ɤ̆w',", "ons = u'w' # add a labiovelar onset elif nucl", ": 312, u'ụ' : u'21g', u'ứ' : 13, u'ừ' :", "= 0 cao = 0 palatals = 0 tokenize =", "vi2IPA_pitrain(line) #nor = vi2IPA(line) nor = T2IPA(line) if nor in", "u'ɲ', u'ch' : u'k' } #tones = { u'a' :", "' compound = compound + seq return compound def T2IPA(text):", "pair:\" , cout_same) #Các trường hợp dẫn đến trùng âm", "onglides, offglides, onoffglides, qu, gi = C_onsets, C_nuclei, C_codas, C_tones,", "u'uə', u'uỡ' : u'uə', u'uợ' : u'uə', } Cus_offglides =", "u'oẵ' : u'ă', u'oặ' : u'ă', u'oe' : u'e', u'oé'", "} # used to use \\u02C0 for raised glottal instead", "u'ɲ', u'ng' : u'ŋ', u'ph' : u'f', u'v' : u'v',", "u'uya' : u'ʷiə', u'uyá' : u'ʷiə', u'uyà' : u'ʷiə', u'uyả'", ": u'ɤ̆j', u'ậy' : u'ɤ̆j', u'âu' : u'ɤ̆w', u'ấu' :", "u'ài' : u'aj', u'ải' : u'aj', u'ãi' : u'aj', u'ại'", "u'ʷă', u'oắ' : u'ʷă', u'oằ' : u'ʷă', u'oẳ' : u'ʷă',", "xõa <-> xoã : swʷa3 ''' #Ở đây tiết kiệm", "u'ɛu', u'ều' : u'ɛu', u'ểu' : u'ɛu', u'ễu': u'ɛu', u'ệu'", "nuc = onglides[nucl] elif nucl in onoffglides: cod = onoffglides[nucl][-1]", "u'c' : u'k', u'gh' : u'ɣ', u'r' : u'z', u's'", "u'aj', u'oại' : u'aj', u'oay' : u'ăj', u'oáy' : u'ăj',", "'eo', 'sw', 'tw', 'ʐw', 'iɛ', 'ʷe', 'i:', 'ɯə', 'dʒ', 'ɲ',", "T2IPA_split(text,delimit): sys.path.append('./Rules') # make sure we can find the Rules", "bưc #Neu co Mapping #Neu khong, check co nguyen am", "u'e', u'uế' : u'e', u'uề' : u'e', u'uể' : u'e',", "u'ej', u'oẽ' : u'ej', u'oẹ' : u'ej', u'oai' : u'aj',", ",ipa) else: IPA+=ipa+\" \" IPA=re.sub(delimit+'+', delimit, IPA) IPA=re.sub(' +', '", "u'ỹ' : u'35g', u'ỵ' : u'21g', # } N_tones =", "u'ɛ', u'uè' : u'ɛ', u'uẻ' : u'ɛ', u'uẽ' : u'ɛ',", "u'qũy' : u'kwi', u'qụy' : u'kwi'} ####################################################### #central.py #coding: utf-8", "u'qùy' : u'wi', u'qủy' : u'wi', u'qũy' : u'wi', u'qụy'", "and '_' in word): substrings = re.split(r'(_|-)', word) values =", "values = substrings[::2] delimiters = substrings[1::2] + [''] ipa =", "u'ỳ' : 32, u'ỷ' : 214, u'ỹ' : 214, u'ỵ'", "tok) IPA=\"\" for tk in TK: ipa = T2IPA_split(tk,delimit).replace(\" \",\"_\")", "u'gh' : u'ɣ', u'r' : u'z', u's' : u's', u'gi':", "if glottal == 1: if word[0] not in onsets: #", "ɛ #âm cuối: ch : k theo bắc : t", "u'ʐ', u's' : u'ʂ', u'gi': u'j'} Cus_nuclei = { u'a'", ": u'et', u'oẹt' : u'et' } C_onoffglides = { u'oe'", ": u'ʷet', u'oèt' : u'ʷet', u'oẻt' : u'ʷet', u'oẽt' :", "Something is non-Viet return (None, None, None, None) # Velar", "only) if ((dialect == 'n' and ton == u'24') or", ": 33, u'ớ' : 24, u'ờ' : 32, u'ở' :", ": u'ɯj', u'ựi' : u'ɯj', u'ưu' : u'ɯw', u'ứu' :", "u'ɛu', u'ếu' : u'ɛu', u'ều' : u'ɛu', u'ểu' : u'ɛu',", "nang tones are modal voice if (dialect == 'n' or", ": u'n', u'ng' : u'ŋ', u'nh' : u'ɲ', u'ch' :", "if there is an onglide... nuc = onglides[nucl] # modify", ": u'i', u'ỹ' : u'i', u'ỵ' : u'i', u'eo' :", "#For each Convert to phoneme #Nếu không được check phoneme", ": u'ɤ̆j', u'ấy' : u'ɤ̆j', u'ầy' : u'ɤ̆j', u'ẩy' :", "u'w' elif nucl in offglides: cod = offglides[nucl][-1] nuc =", "u'uối' : u'uəj', u'uồi' : u'uəj', u'uổi' : u'uəj', u'uỗi'", "u'oai' : u'aj', u'oái' : u'aj', u'oài' : u'aj', u'oải'", "u'ú' : 45, u'ù' : 32, u'ủ' : 214, u'ũ'", ": u'ɣ', u'r' : u'ʐ', u's' : u'ʂ', u'gi' :", "u'ệ' : u'21g', u'í' : 13, u'ì' : 42, u'ỉ'", ": u'ji', u'gị' : u'ji' } S_qu = {u'quy' :", "u'u', u'ũ' : u'u', u'ụ' : u'u', u'ư' : u'ɯ',", "u'iếu' : u'iəw', u'iều' : u'iəw', u'iểu' : u'iəw', u'iễu'", "'ɤ̆j', 'ŋ͡m', 'kwi', 'ɤ̆w', 'ɯəj', 'ʷen', 'ʷiu', 'ʷet', 'ɯəw', 'ʷɛ',", "3, u'ệ' : 6, u'í' : 5, u'ì' : 2,", "u'uợ' : u'uə', } S_offglides = { u'ai' : u'aj',", "= 1 #if word[0:2] == u'gi' and cod and len(word)", "zim2 din <-> gin : zin1 díp <-> gíp :", "gi = C_onsets, C_nuclei, C_codas, C_tones, C_onglides, C_offglides, C_onoffglides, C_qu,", "u'â' : u'ɤ̆', u'ấ' : u'ɤ̆', u'ầ' : u'ɤ̆', u'ẩ'", "offglides, onoffglides, qu, gi = C_onsets, C_nuclei, C_codas, C_tones, C_onglides,", "word[oOffset:l-cOffset] if nucl in nuclei: if oOffset == 0: if", "u'oã' : u'ʷa', u'oạ' : u'ʷa', u'óa' : u'ʷa', u'òa'", "'gi', 'gì',... ons = gi[word][0] nuc = gi[word][1] elif word", "6, } Cus_gi = { u'gi' : u'zi', u'gí': u'zi',", "as f: content=f.read().splitlines() tess = texts.split(\".\") Results =\"\" for text", "u'uây' : u'ɤ̆j', u'uấy' : u'ɤ̆j', u'uầy' : u'ɤ̆j', u'uẩy'", "u'ầ' : 32, u'ẩ' : 312, u'ẫ' : u'35g', u'ậ'", "of token can not convert: \",cout) print(\"Number of token in", "312, u'ẵ' : u'35g', u'ặ' : u'21g', u'é' : 24,", "u'uyễ' : u'ʷiə', u'uyệ' : u'ʷiə', u'uyu' : u'ʷiu', u'uyú'", "u'ĩ' : 214, u'ị' : 212, u'ó' : 45, u'ò'", ": u'ăj', u'oáy' : u'ăj', u'oày' : u'ăj', u'oảy' :", "u'ʷiu', u'uỳu' : u'ʷiu', u'uỷu' : u'ʷiu', u'uỹu' : u'ʷiu',", "u'ế' : u'e', u'ề' : u'e', u'ể' : u'e', u'ễ'", "u'ỷ' : 4, u'ỹ' : 4, u'ỵ' : 6, }", ": u'iə', u'uyã' : u'iə', u'uyạ' : u'iə', u'uyê' :", "cao, palatals): # This looks ugly, but newer versions of", "offglides, onoffglides, qu, gi = N_onsets, N_nuclei, N_codas, N_tones, N_onglides,", ": u'uəj', u'uồi' : u'uəj', u'uổi' : u'uəj', u'uỗi' :", "in ['p', 't', 'k']: ton = u'6b' # labialized allophony", ": 312, u'ĩ' : u'35g', u'ị' : u'21g', # u'o'", "u'ĩ' : u'i', u'ị' : u'i', u'o' : u'ɔ', u'ó'", "33, u'á' : 24, u'à' : 32, u'ả' : 312,", ": u'o', u'ôố' : u'o', u'ôồ' : u'o', u'ôổ' :", ": u'ɯw', u'ựu' : u'ɯw', u'iêu' : u'iəw', u'iếu' :", "raised glottal instead of g C_tones_p = { u'á' :", "#acute \"oà\", \"oè\",\"òo\", \"uỳ\", \"ả\",\"ẳ\",\"ẩ\",\"ẻ\",\"ể\",\"ỉ\",\"ỏ\",\"ổ\",\"ở\",\"ủ\",\"ử\",\"ỷ\",\"iể\",\"ỏa\",\"oẳ\",\"ỏe\",\"oỏ\",\"uẩ\",\"uể\",\"uổ\",\"ưở\",\"ủy\",\"ưở\",\"uyể\",\"yể\", #hook \"oả\", \"oẻ\",\"ỏo\", \"uỷ\", \"ã\",\"ẵ\",\"ẫ\",\"ẽ\",\"ễ\",\"ĩ\",\"õ\",\"ỗ\",\"ỡ\",\"ũ\",\"ữ\",\"ỹ\",\"iễ\",\"õa\",\"oẵ\",\"õe\",\"oõ\",\"uẫ\",\"uễ\",\"uỗ\",\"ưỡ\",\"ũy\",\"ưỡ\",\"uyễ\",\"yễ\",", "delimit = '' dialect='n' #\"c\"\"s\" tone_type=0 if tone_type==0: pham=1 else:", "u'oẽ' : u'ej', u'oẹ' : u'ej', u'oai' : u'aj', u'oái'", "and '-' in word) or (tokenize and '_' in word):", "u'ɤ̆j', u'uầy' : u'ɤ̆j', u'uẩy' : u'ɤ̆j', u'uẫy' : u'ɤ̆j',", "u'21g', u'ế' : 13, u'ề' : 42, u'ể' : 312,", "#Check tu dien tieng anh Etrain bưc #Neu co Mapping", "epi = epitran.Epitran('vie-Latn') r=epi.transliterate(text) return r def T2IPA_split(text,delimit): sys.path.append('./Rules') #", "u'ỵ' : u'21g', # } N_tones = { u'á' :", "u'21g', u'ế' : 24, u'ề' : 32, u'ể' : 312,", "'' try: (ons, nuc, cod, ton) = trans(word, dialect, glottal,", "u'oe' : u'e', u'oé' : u'e', u'oè' : u'e', u'oẻ'", "#central.py #coding: utf-8 C_onsets = { u'b' : u'b', u't'", "u'uầy' : u'ɤ̆j', u'uẩy' : u'ɤ̆j', u'uẫy' : u'ɤ̆j', u'uậy'", "3, u'ậ' : 6, u'ắ' : 5, u'ằ' : 2,", "== u'ɲ': cod = u'ɲ' # u'ŋ' elif palatals !=", ": u'ʷa', u'oã' : u'ʷa', u'oạ' : u'ʷa', u'óa' :", "24, u'ằ' : 32, u'ẳ' : 312, u'ẵ' : u'35g',", "u'gì' : u'zi', u'gĩ' : u'zi', u'gị' : u'zi'} Cus_qu", "u'ɛj', u'oé' : u'ɛj', u'oè' : u'ɛj', u'oẻ' : u'ɛj',", "= C_onsets, C_nuclei, C_codas, C_tones, C_onglides, C_offglides, C_onoffglides, C_qu, C_gi", "u'ịa' : u'iə', u'ia' : u'iə', u'iá' : u'iə', u'ià'", "= substrings[::2] delimiters = substrings[1::2] + [''] ipa = [convert(x,", "modifi + Special symbols = list(set(symbols)) symbols.sort(reverse = True,key=len) return", "} N_offglides = { u'ai' : u'aj', u'ái' : u'aj',", "'k']: ton = u'5b' if ton == u'6' and cod", "'z', '6', '2', 'x', 'ă'] listParse.sort(reverse = True,key=len) output=\"\" skip=0", "dialect == 'c': onsets, nuclei, codas, tones, onglides, offglides, onoffglides,", ": u'z', u'tr' : u'c', u'k' : u'k', u'c' :", "for char in tk: CHAR = str(char).lower() if CHAR in", "u'ʷiə', u'uyã' : u'ʷiə', u'uyạ' : u'ʷiə', u'uyê' : u'ʷiə',", ": u'eo', u'êu' : u'ɛu', u'ếu' : u'ɛu', u'ều' :", "gi[word][0] nuc = gi[word][1] elif word in qu: # if", "u'zi', u'gị' : u'zi'} N_qu = {u'quy' : u'kwi', u'qúy'", ": 5, u'ề' : 2, u'ể' : 4, u'ễ' :", "elif word[0:2] in onsets: # if onset is 'nh', 'gh',", "'' ton = 0 oOffset = 0 cOffset = 0", "u'ó' : 13, u'ò' : 42, u'ỏ' : 312, u'õ'", "# if you just have 'gi' and a coda... if", "(Northern dialect) if nuc not in [u'i', u'e', u'ɛ']: if", "'_', 'æ', 'ɤ', '2', 'ʤ', 'i', '.', 'ɒ', 'b', 'h',", "'tw', 'tʰw', 'ɲw', 'cw', 'ʂw', 'ɣw', 'ʐw', 'xw', 'lw', 'hw',", "'uəj', 'ʷen', 'tʰw', 'ʷɤ̆', 'ʷiu', 'kwi', 'ŋ͡m', 'k͡p', 'cw', 'jw',", "N_codas = { u'p' : u'p', u't' : u't', u'c'", "in word) or (tokenize and '_' in word): substrings =", ": u'ɯəw' } C_onglides = { u'oa' : u'a', u'oá'", "} N_gi = { u'gi' : u'zi', u'gí': u'zi', u'gì'", "u'ì' : 2, u'ỉ' : 4, u'ĩ' : 3, u'ị'", ": u'f', u'v' : u'v', u'x' : u's', u'd' :", "u'ớ' : 5, u'ờ' : 2, u'ở' : 4, u'ỡ'", ": 4, u'ỡ' : 4, u'ợ' : 6, u'ú' :", ": u'ɔ', u'oo' : u'ɔ', u'oó' : u'ɔ', u'oò' :", "u'oảy' : u'ăj', u'oãy' : u'ăj', u'oạy' : u'ăj', u'oao'", ": 32, u'ủ' : 312, u'ũ' : u'35g', u'ụ' :", "4, u'ũ' : 4, u'ụ' : 6, u'ứ' : 5,", "N_codas#, N_tones , N_onglides, N_offglides, N_onoffglides, N_qu, N_gi, Cus_onsets, Cus_nuclei,", "cao = 0 palatals = 0 tokenize = 0 delimit", ": u'uj', u'ùy' : u'uj', u'ủy' : u'uj', u'ũy' :", "checkinvalid=1 if checkinvalid==1: TK = TK[:iuv] + TK[iuv+1 :] for", "u'oè' : u'ɛj', u'oẻ' : u'ɛj', u'oẽ' : u'ɛj', u'oẹ'", "u'd' : u'z', u'h' : u'h', u'p' : u'p', u'qu'", ": 212, u'í' : 45, u'ì' : 32, u'ỉ' :", "<-> gh #i <-> y #Same negative / need to", "u'ɯj', u'ứi' : u'ɯj', u'ừi' : u'ɯj', u'ửi' : u'ɯj',", "list(set(symbols)) symbols.sort(reverse = True,key=len) return symbols def vi2IPA_pitrain(text): epi =", "# if word == 'gi', 'gì',... ons = gi[word][0] nuc", "u'oẹn' : u'en', u'oet' : u'et', u'oét' : u'et', u'oèt'", "codecs, re from io import StringIO from optparse import OptionParser", "dìm <-> gìm : zim2 din <-> gin : zin1", "u'iə', u'iễ' : u'iə', u'iệ' : u'iə', u'oo' : u'ɔ',", "u'ɯə', u'ựa' : u'ɯə', u'ươ' : u'ɯə', u'ướ' : u'ɯə',", "cOffset = 0 l = len(word) if l > 0:", "#tilde \"oã\", \"oẽ\",\"õo\", \"uỹ\", \"ạ\",\"ặ\",\"ậ\",\"ẹ\",\"ệ\",\"ị\",\"ọ\",\"ộ\",\"ợ\",\"ụ\",\"ự\",\"ỵ\",\"iệ\",\"ọa\",\"oặ\",\"ọe\",\"oọ\",\"uậ\",\"uệ\",\"uệ\",\"ượ\",\"ụy\",\"ượ\",\"uyệ\",\"yệ\", #dot \"oạ\", \"oẹ\",\"ọo\", \"uỵ\"] Onset=[\"b\",\"d\",\"h\",\"l\",\"m\",\"n\",\"p\",\"r\",\"s\",\"t\",\"v\",\"x\",\"đ\",\"p\",", ": u'et', u'oẹt' : u'et' } S_onoffglides = { u'oe'", "or underscores words = [word for word in words if", "N_nuclei = { u'a' : u'a', u'á' : u'a', u'à'", "u'i', u'o' : u'ɔ', u'ó' : u'ɔ', u'ò' : u'ɔ',", "in content: #nor_tr = vi2IPA_pitrain(line) #nor = vi2IPA(line) nor =", "= u'i' if nuc == u'uə': nuc = u'u' if", ": u'ɯə', u'ứa' : u'ɯə', u'ừa' : u'ɯə', u'ửa' :", "N_onglides, N_offglides, N_onoffglides, N_qu, N_gi, Cus_onsets, Cus_nuclei, Cus_codas#, N_tones ,", ": u'aw', u'ảo' : u'aw', u'ão' : u'aw', u'ạo' :", "len(word)>0] ## hack to get rid of single hyphens or", "normal phoneme về cường độ âm sắc chỉ dừng từ", ": u'w', u'gi' : u'j', u'tr' : u'ʈ', u'k' :", "u'ề' : 42, u'ể' : 312, u'ễ' : 312, u'ệ'", "u'i' ons = u'z' else: nucl = word[oOffset:l-cOffset] if nucl", ": u'ɔ', u'oỏ' : u'ɔ', u'oõ' : u'ɔ', u'oọ' :", "u'í' : 5, u'ì' : 2, u'ỉ' : 4, u'ĩ'", "u'ảu' : u'ăw', u'ãu' : u'ăw', u'ạu' : u'ăw', u'ây'", "'ʤ', 'i', '.', 'ɒ', 'b', 'h', 'n', 'ʂ', 'ɔ', 'ɛ',", "['i','í','ì','ĩ','ỉ','ị'] and line[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ']) or (lin2[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ'] and", "off-glide is a big problem #Same positive #k <-> c", "cod == u'k' and cOffset == 2: nuc = u'ɛ'", "IPA def checkDict(): cout=0 trung=0 List_token=[] List_pair = [] with", "N_offglides, N_onoffglides, N_qu, N_gi, Cus_onsets, Cus_nuclei, Cus_codas#, N_tones , Cus_onglides,", "u'ui' : u'uj', u'úi' : u'uj', u'ùi' : u'uj', u'ủi'", "closed syllables if cOffset !=0: # Obstruent-final nang tones are", "không phân âm được => ý tưởng mượn \"tʃ\" trong", "'k']: # fixed 8 Nov 2016 ton = u'21' #", "words if len(word)>0] ## hack to get rid of single", "u'oẽn' : u'en', u'oẹn' : u'en', u'oet' : u'et', u'oét'", "ons = ons+u'w' else: ons = u'w' elif nucl in", ": 212, u'ắ' : 45, u'ằ' : 32, u'ẳ' :", "u'c' : u'k', u'm' : u'm', u'n' : u'ŋ', u'ng'", "không vòm: không có w ở trước => Try to", "u'aj', u'ài' : u'aj', u'ải' : u'aj', u'ãi' : u'aj',", ": u'ew', u'ẹo' : u'ew', u'iu' : u'iw', u'íu' :", "u'ã' : 214, u'ạ' : 212, u'ấ' : 45, u'ầ'", ": 13, u'ì' : 42, u'ỉ' : 312, u'ĩ' :", "re-concatenate if (tokenize and '-' in word) or (tokenize and", ": ɯə1 xõa <-> xoã : swʷa3 ''' #Ở đây", ": u'iə', u'uyể' : u'iə', u'uyễ' : u'iə', u'uyệ' :", "N_onsets, N_nuclei, N_codas#, N_tones , N_onglides, N_offglides, N_onoffglides, N_qu, N_gi,", "u'ʷɤ̆', u'uậ' : u'ʷɤ̆', u'ue' : u'ʷɛ', u'ué' : u'ʷɛ',", "< len(words)-1: seq = seq+u' ' compound = compound +", "u'ế' : 45, u'ề' : 32, u'ể' : 214, u'ễ'", "u'ʷiu', u'uyủ' : u'ʷiu', u'uyũ' : u'ʷiu', u'uyụ' : u'ʷiu',", "u'aw', u'oáo' : u'aw', u'oào' : u'aw', u'oảo' : u'aw',", "modal voice if (dialect == 'n' or dialect == 's')", ": u'ɛ', u'ê' : u'e', u'ế' : u'e', u'ề' :", ": u'ɤ̆', u'ă' : u'ă', u'ắ' : u'ă', u'ằ' :", "= word[oOffset:l-cOffset] if nucl in nuclei: if oOffset == 0:", "'4', 'n', ';', 'r', 'b', 'ɯ', 'a', 's', 'ʐ', 'η',", "u'e', u'oẻ' : u'e', u'oẽ' : u'e', u'oẹ' : u'e',", "u'oó' : u'ɔ', u'oò' : u'ɔ', u'oỏ' : u'ɔ', u'oõ'", "u'z'} N_nuclei = { u'a' : u'a', u'á' : u'a',", ": 13, u'ỳ' : 42, u'ỷ' : 312, u'ỹ' :", "u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j' } N_codas = {", "= u'ʔ'+nuclei[nucl] # add a glottal stop else: # otherwise...", "elif word in qu: # if word == 'quy', 'qúy',...", "IPA=\"\" for tk in TK: ipa = T2IPA_split(tk,delimit).replace(\" \",\"_\") if", "# u'u' : 33, u'ú' : 24, u'ù' : 32,", ": u'ʷɛ', u'uẻ' : u'ʷɛ', u'uẽ' : u'ʷɛ', u'uẹ' :", ": u'35g', u'ệ' : u'21g', # u'i' : 33, u'í'", "return r def T2IPA_split(text,delimit): sys.path.append('./Rules') # make sure we can", "= codas[word[l-2:l]] cOffset = 2 elif word[l-1] in codas: #", "'ɛ', 'z', '6', '2', 'x', 'ă'] listParse.sort(reverse = True,key=len) output=\"\"", "versions of python complain about \"from x import *\" syntax", "u'iɛ', u'yệ' : u'iɛ', u'uơ' : u'uə', u'uở' : u'uə',", ": 6, } N_gi = { u'gi' : u'zi', u'gí':", "python complain about \"from x import *\" syntax if dialect", "l == text[ic:ic+len(l)]: output+=delimit+l check =1 skip=len(l)-1 break if check", "start o and u as in wiki # *** Problem", "e to ɛ #âm cuối: ch : k theo bắc", "!= 1 and nuc in [u'i', u'e', u'ɛ']: if cod", "T2IPA(line) in Pair: lin2 =Pair[T2IPA(line)] if line != lin2: if", "trung=0 List_token=[] List_pair = [] with open(\"Popular.txt\", encoding=\"utf-8\") as f:", "214, u'ợ' : 212, u'ú' : 45, u'ù' : 32,", "u'ự' : u'21g', # u'y' : 33, u'ý' : 24,", "u'gĩ' : u'ji', u'gị' : u'ji' } S_qu = {u'quy'", "tk: #Đọc tiếng anh từng chữ letter2sound=\"\" for char in", "u'ɯə', u'uə', u'u', u'ɯ', u'ɤ', u'o', u'ɔ', u'ă', u'ɤ̆']: if", ", S_onglides, S_offglides, S_onoffglides, S_qu, S_gi, C_onsets, C_nuclei, C_codas#, C_tones", "# This looks ugly, but newer versions of python complain", "32, u'ổ' : 312, u'ỗ' : u'35g', u'ộ' : u'21g',", "ton == u'21\\u02C0' and cod in ['p', 't', 'k']: #", "if None in (ons, nuc, cod, ton): seq = u'['+word+u']'", "splitted into 3 types. Type 1 are onsets which has", "checkinvalid==1: TK = TK[:iuv] + TK[iuv+1 :] for tok in", "1: if word[0] not in onsets: # if there isn't", ": u'ʷi', u'úy' : u'uj', u'ùy' : u'uj', u'ủy' :", "17.09.08) if nuc in [u'u', u'o', u'ɔ']: if cod ==", ": u'21g', u'ố' : 13, u'ồ' : 42, u'ổ' :", ": u'ʷɛ', u'uẹ' : u'ʷɛ', u'uê' : u'ʷe', u'uế' :", "} N_codas = { u'p' : u'p', u't' : u't',", ": u'aw', u'áo' : u'aw', u'ào' : u'aw', u'ảo' :", "{ u'á' : 13, u'à' : 42, u'ả' : 312,", "u'gì' : u'zi', u'gĩ' : u'zi', u'gị' : u'zi'} N_qu", "u'a', u'oả' : u'a', u'oã' : u'a', u'oạ' : u'a',", "'c': ton = str('35') else: ton = str('33') else: ton", ": u'e', u'ể' : u'e', u'ễ' : u'e', u'ệ' :", "u'ẩ' : 312, u'ẫ' : u'35g', u'ậ' : u'21g', u'ắ'", "u'aw', u'ão' : u'aw', u'ạo' : u'aw', u'au' : u'ăw',", "u'ừi' : u'ɯj', u'ửi' : u'ɯj', u'ữi' : u'ɯj', u'ựi'", "#Lọc bỏ dấu nhấn của tiếng anh \"'\" #print(vi2IPA_split(\"speech? Secondly,", ": u'iəw', u'iễu' : u'iəw', u'iệu' : u'iəw', u'yêu' :", ": u'o', u'ổô' : u'o', u'ỗô' : u'o', u'ộô' :", "u'ồ' : 2, u'ổ' : 4, u'ỗ' : 4, u'ộ'", "u'ó' : u'ɔ', u'ò' : u'ɔ', u'ỏ' : u'ɔ', u'õ'", ": u'ɤ̆', u'uấ' : u'ɤ̆', u'uầ' : u'ɤ̆', u'uẩ' :", "u'uậ' : u'ɤ̆', u'ue' : u'ɛ', u'ué' : u'ɛ', u'uè'", "3 elif word[0:2] in onsets: # if onset is 'nh',", "= u'k͡p' return (ons, nuc, cod, ton) def convert(word, dialect,", "'∫', 'p', 'ə', 'u', 'o', '3', 'ɣ', '!', 'ð', 'ʧ',", ": u'uj', #thay để hạn chế trùng âm u'uy' :", ": 2, u'ỷ' : 4, u'ỹ' : 3, u'ỵ' :", "u'ỗ' : 312, u'ộ' : u'21g', u'ớ' : 13, u'ờ'", "u'êu' : u'ɛu', u'ếu' : u'ɛu', u'ều' : u'ɛu', u'ểu'", ": 24, u'ờ' : 32, u'ở' : 312, u'ỡ' :", "u'uả' : u'ʷa', u'uã' : u'ʷa', u'uạ' : u'ʷa', u'uă'", "nuc = u'u' if nuc == u'ɯə': nuc = u'ɯ'", "len==0 junk words = [word for word in words if", ": 4, u'ĩ' : 4, u'ị' : 6, u'ó' :", "in nuclei: if oOffset == 0: if glottal == 1:", "nhất ở list custom # Các trường hợp có cách", "u'ʷɤ', u'uy' : u'ʷi', u'uý' : u'ʷi', u'uỳ' : u'ʷi',", "u'ỗi' : u'oj', u'ội' : u'oj', u'ui' : u'uj', u'úi'", "u'ì' : u'i', u'ỉ' : u'i', u'ĩ' : u'i', u'ị'", "line = text if line =='\\n': return \"\" else: compound", "nghoèo <-> ngoèo : ŋwew2 quít <-> quýt : kwit5", "== \"*\": if tk.lower().upper() == tk: #print(\"ENGLISH\",tk) #Đọc tiếng anh", "u'ễ' : u'e', u'ệ' : u'e', u'i' : u'i', u'í'", "Sep 2008 to fix aberrant 33 error tonelist = [tones[word[i]]", "'tʰw', 'ʷɤ̆', 'ʷiu', 'kwi', 'ŋ͡m', 'k͡p', 'cw', 'jw', 'uə', 'eə',", ": u'i', u'ỉ' : u'i', u'ĩ' : u'i', u'ị' :", ": u'uj', u'ủy' : u'uj', u'ũy' : u'uj', u'ụy' :", "học là IUYE gì khôngtontaij NIYE BoOK\",\"'\")) #check các ipa", "Alves 2007 (SEALS XII), Vũ 1982 C_tones = { u'á'", ": u'ɯ', u'ự' : u'ɯ', u'y' : u'i', u'ý' :", "'bw', 'vw', 'dw', 'eo', 'ʈw', 'mw', 'zw', 'fw', 'tw', 'tʰw',", "<-> gì : ɣi2 ghích <-> gích : ɣitʃ5 ia", "ons != u'kw': # if there is an onglide... nuc", "u'p', u'qu' : u'w', u'gi' : u'j', u'tr' : u'ʈ',", "u'ɯ' # Tones # Modified 20 Sep 2008 to fix", "for t, tʃ for ch #Thay offglide: úy -> wi", "== u'k': cod = u't' if cod == u'ŋ': cod", ": 4, u'ẫ' : 4, u'ậ' : 6, u'ắ' :", "u'uở' : u'ɤ', u'uỡ' : u'ɤ', u'uợ' : u'ɤ', u'uy'", "u'35g', u'ợ' : u'21g', u'ú' : 24, u'ù' : 32,", ": u'21g', } # used to use \\u02C0 for the", "cao == 1: if ton == u'5' and cod in", "u'èo' : u'ew', u'ẻo' : u'ew', u'ẽo' : u'ew', u'ẹo'", ": 4, u'ữ' : 4, u'ự' : 6, u'ý' :", "ŋiə5 nghịu <-> ngịu : ŋiw6 nghoèo <-> ngoèo :", "u'ʷen', u'oèn' : u'ʷen', u'oẻn' : u'ʷen', u'oẽn' : u'ʷen',", "1: if ton == u'5' and cod in ['p', 't',", "ipa[-1]==\"]\": eng = eng_to_ipa.convert(tk) if eng[-1] == \"*\": if tk.lower().upper()", "output+=delimit+l check =1 skip=len(l)-1 break if check == 0: #Case", ": u'ŋ', u'ph' : u'f', u'v' : u'v', u'x' :", "'f', ',', 'ɛ', 'z', '6', '2', 'x', 'ă'] listParse.sort(reverse =", "word[l-1] in codas: # if one-character coda cod = codas[word[l-1]]", ": u'o', u'ơ' : u'ɤ', u'ớ' : u'ɤ', u'ờ' :", "u'ɲ' # u'ŋ' elif palatals != 1 and nuc in", ": u'ă', u'ẵ' : u'ă', u'ặ' : u'ă', u'e' :", ": u'ăj', u'ạy' : u'ăj', u'ao' : u'aw', u'áo' :", "eng[-1] == \"*\": if tk.lower().upper() == tk: #print(\"ENGLISH\",tk) #Đọc tiếng", "u'uay' : u'ăj', u'uáy' : u'ăj', u'uày' : u'ăj', u'uảy'", ": u'i', u'í' : u'i', u'ì' : u'i', u'ỉ' :", "output.rstrip()+delimit #print(\"Parsing\",Parsing(\"default\",\"iu iu\",\"|\")) def getSymbol(): for s in SET: DICT.update(s)", "kiệm chi phí chạy máy không normal phoneme về cường", "u'ej', u'oai' : u'aj', u'oái' : u'aj', u'oài' : u'aj',", "u'oay' : u'ăj', u'oáy' : u'ăj', u'oày' : u'ăj', u'oảy'", "u'iu', u'oen' : u'en', u'oén' : u'en', u'oèn' : u'en',", "u'ữi' : u'ɯj', u'ựi' : u'ɯj', u'ưu' : u'ɯw', u'ứu'", "214, u'õ' : 214, u'ọ' : 212, u'ố' : 45,", ": u'eo', u'èo' : u'eo', u'ẻo' : u'eo', u'ẽo': u'eo',", "u'õa' : u'a', u'ọa' : u'a', u'oă' : u'ă', u'oắ'", "nguyên IPA+=Parsing(\"default\",tk.lower(),delimit)+\" \" else: IPA+=Parsing(\"default\",eng,delimit)+\" \" #Check tu dien tieng", "(lin2[0]==\"k\" and line[0]==\"c\") or (lin2[-1] in ['i','í','ì','ĩ','ỉ','ị'] and line[-1] in", "word[0:2] == u'gi' and cod and len(word) == 3: #", "u'uở' : u'uə', u'uờ': u'uə', u'uở' : u'uə', u'uỡ' :", "u'iu', u'uyủ' : u'iu', u'uyũ' : u'iu', u'uyụ' : u'iu',", "u'uyủ' : u'iu', u'uyũ' : u'iu', u'uyụ' : u'iu', u'uyu'", "and line[0]==\"c\") or (lin2[-1] in ['i','í','ì','ĩ','ỉ','ị'] and line[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ'])", "S_tones = { u'á' : 45, u'à' : 32, u'ả'", "u'35g', u'ậ' : u'21g', # u'ă' : 33, u'ắ' :", "u'oẹ' : u'ɛj', u'oai' : u'aj', u'oái' : u'aj', u'oài'", ": u'ă', u'uặ' : u'ă', u'uâ' : u'ɤ̆', u'uấ' :", "if cOffset !=0: # Obstruent-final nang tones are modal voice", "domain word: \" ,ipa) else: IPA+=ipa+\" \" IPA=re.sub(delimit+'+', delimit, IPA)", "} N_tones = { u'á' : 24, u'à' : 32,", ": u'ɤ̆w', u'ẫu' : u'ɤ̆w', u'ậu' : u'ɤ̆w', u'eo' :", "u'ìu' : u'iw', u'ỉu' : u'iw', u'ĩu' : u'iw', u'ịu'", "dialect='n' #\"c\"\"s\" tone_type=0 if tone_type==0: pham=1 else: cao=1 #Input text", "u'ɔ', u'ă', u'ɤ̆']: if cod == u't': cod = u'k'", "u'kwi', u'qụy' : u'kwi'} ####################################################### # North # #coding: utf-8", ": 32, u'ổ' : 214, u'ỗ' : 214, u'ộ' :", "u'ẻ' : 4, u'ẽ' : 4, u'ẹ' : 6, u'ế'", "0 cao = 0 palatals = 0 tokenize = 0", "u'21g', u'ố' : 24, u'ồ' : 32, u'ổ' : 312,", "u'ɯə', u'ứa' : u'ɯə', u'ừa' : u'ɯə', u'ửa' : u'ɯə',", "312, u'ỗ' : 312, u'ộ' : u'21g', u'ớ' : 13,", "u'ă', u'ɤ̆']: if cod == u't': cod = u'k' if", "nuc == u'a': nuc = u'ɛ' # Final palatals (Northern", ": u'iə', u'iế' : u'iə', u'iề' : u'iə', u'iể' :", "} C_gi = { u'gi' : u'ji', u'gí': u'ji', u'gì'", "!=0: # Obstruent-final nang tones are modal voice if (dialect", "def convert(word, dialect, glottal, pham, cao, palatals, delimit): \"\"\"Convert a", ": xwʷăŋ5 khỏe <-> khoẻ : xwʷɛ4 khua <-> khuơ", "u'uj', u'ùi' : u'uj', u'ủi' : u'uj', u'ũi' : u'uj',", "u'd', u'ch' : u'c', u'kh' : u'x', u'g' : u'ɣ',", "u'ôỗ' : u'o', u'ôộ' : u'o', u'ua' : u'uə', u'úa'", "cod = '' ton = 0 seq = '' try:", "u'ười' : u'ɯəj', u'ưởi' : u'ɯəj', u'ưỡi' : u'ɯəj', u'ượi'", "'c': onsets, nuclei, codas, tones, onglides, offglides, onoffglides, qu, gi", "nuclei, codas, tones, onglides, offglides, onoffglides, qu, gi = C_onsets,", "S_onsets = { u'b' : u'b', u't' : u't', u'th'", "2: nuc = u'ɛ' if cod == u'ɲ' and nuc", "u'ộ' : u'21g', # u'ơ' : 33, u'ớ' : 24,", ": u'kwi', u'qũy' : u'kwi', u'qụy' : u'kwi'} ####################################################### #", "lí case không có cũng như case Tiếng anh: =>", "getSymbol(): for s in SET: DICT.update(s) list_phoneme=DICT.values() list_phoneme=list(list_phoneme) English_phoneme=[\"p\",\"b\",\"t\",\"d\",\"t∫\",\"dʒ\",\"k\",\"g\",\"f\",\"v\",\"ð\",\"θ\",\"s\",\"z\",\"∫\",\"ʒ\",\"m\",\"n\",\"η\",\"l\",\"r\",\"w\",\"j\",\"ɪ\",\"i:\",\"ʊ\",\"u:\",\"e\",\"ə\",\"ɜ:\",\"ɒ\",\"ɔ:\",\"æ\",\"ʌ\",\"ɑ:\",\"ɪə\",\"ʊə\",\"eə\",\"eɪ\",\"ɔɪ\",\"aɪ\",\"əʊ\",\"aʊ\",'ʃ',\"ʤ\",\"ʧ\"] Special=['jw',", "u'ɛ', u'ué' : u'ɛ', u'uè' : u'ɛ', u'uẻ' : u'ɛ',", "seq = delimit+delimit.join(filter(None, (ons, nuc, cod, ton)))+delimit except (TypeError): pass", "<-> xoã : swʷa3 ''' #Ở đây tiết kiệm chi", "\" #For checking: need much memory ''' check_sym=\"ɯəjɤ̆jʷiəɤ̆wɯəwʷetiəwuəjʷentʰwʷɤ̆ʷiukwiŋ͡mk͡pcwjwuəeəbwojʷivwăwʈwʂwaʊfwɛutʰtʃɔɪxwʷɤɤ̆ŋwʊəziʷădweɪaɪewiəɣwzwɯjʷɛɯwɤjɔ:əʊʷamwɑ:hwɔjujlwɪəăju:awɛjiwajɜ:kwnwt∫ɲweoswtwʐwiɛʷei:ɯədʒɲθʌlw1ɪɯd∫pəuo3ɣ!ðʧ6ʒʐzvgă_æɤ2ʤi.ɒbhnʂɔɛkm5cjxʈ,4ʊsŋaʃ?r:ηf;et'\" for ine,res", "checking: need much memory ''' check_sym=\"ɯəjɤ̆jʷiəɤ̆wɯəwʷetiəwuəjʷentʰwʷɤ̆ʷiukwiŋ͡mk͡pcwjwuəeəbwojʷivwăwʈwʂwaʊfwɛutʰtʃɔɪxwʷɤɤ̆ŋwʊəziʷădweɪaɪewiəɣwzwɯjʷɛɯwɤjɔ:əʊʷamwɑ:hwɔjujlwɪəăju:awɛjiwajɜ:kwnwt∫ɲweoswtwʐwiɛʷei:ɯədʒɲθʌlw1ɪɯd∫pəuo3ɣ!ðʧ6ʒʐzvgă_æɤ2ʤi.ɒbhnʂɔɛkm5cjxʈ,4ʊsŋaʃ?r:ηf;et'\" for ine,res in enumerate(Results):", "nghịu <-> ngịu : ŋiw6 nghoèo <-> ngoèo : ŋwew2", "be deal: # NIYE BoOK #print(len(getSymbol())) #print(getSymbol()) ''' test=\"t\" if", ": u'a', u'oạ' : u'a', u'óa' : u'a', u'òa' :", "'ʌ', 'm', '!', '∫', 'ð', 'u', 'e', 'w', 'p', 'ʃ',", "= '' ton = 0 seq = '' try: (ons,", "=> ý tưởng mượn \"tʃ\" trong teach and watch để", ": u'ăj', u'uảy' : u'ăj', u'uãy' : u'ăj', u'uạy' :", ": u'21g', # u'ư' : 33, u'ứ' : 24, u'ừ'", "u'kwi'} ####################################################### #central.py #coding: utf-8 C_onsets = { u'b' :", "case không có cũng như case Tiếng anh: => dùng", "u'eo', u'éo' : u'eo', u'èo' : u'eo', u'ẻo' : u'eo',", "u'gi' : u'z', u'tr' : u'c', u'k' : u'k', u'c'", "ɯə1 xõa <-> xoã : swʷa3 ''' #Ở đây tiết", "u'ʷa', u'uạ' : u'ʷa', u'uă' : u'ʷă', u'uắ' : u'ʷă',", "and Central dialects) else: if nuc in [u'i', u'e']: if", "N_onsets, N_nuclei, N_codas, N_tones, N_onglides, N_offglides, N_onoffglides, N_qu, N_gi elif", "cod = codas[word[l-1]] cOffset = 1 #if word[0:2] == u'gi'", "ic,char in enumerate(text): #print(char,skip) check = 0 if skip>0: skip=skip-1", ": 6, u'í' : 5, u'ì' : 2, u'ỉ' :", "open(\"Popular.txt\", encoding=\"utf-8\") as f: content=f.read().splitlines() for line in content: #nor_tr", "u'ừ' : 42, u'ử' : 312, u'ữ' : 312, u'ự'", "u'ɯə', u'ừa' : u'ɯə', u'ửa' : u'ɯə', u'ữa' : u'ɯə',", "312, u'ẫ' : u'35g', u'ậ' : u'21g', u'ắ' : 24,", "for tk in TK: ipa = T2IPA(tk).replace(\" \",\"_\") if ipa", "u'uə', u'ưa' : u'ɯə', u'ứa' : u'ɯə', u'ừa' : u'ɯə',", ": 45, u'à' : 32, u'ả' : 214, u'ã' :", "Cus_onglides, Cus_offglides, Cus_onoffglides, Cus_qu, Cus_gi] DICT={} #144 in total syms=['ɯəj',", "xwʷɛ4 khua <-> khuơ : xuə1 lóe <-> loé :", "\"[\" in T2IPA(tok): checkinvalid=1 if checkinvalid==1: TK = TK[:iuv] +", "sắc chỉ dừng từ 1->6 #học ác cho kết quả", ": u'ʷiə', u'uyã' : u'ʷiə', u'uyạ' : u'ʷiə', u'uyê' :", ": u'oj', u'ui' : u'uj', u'úi' : u'uj', u'ùi' :", "u'21g', u'ý' : 13, u'ỳ' : 42, u'ỷ' : 312,", ", Cus_onglides, Cus_offglides, Cus_onoffglides, Cus_qu, Cus_gi] DICT={} #144 in total", "seq ########################333 from vinorm import * from underthesea import word_tokenize", ": u'ɯə', u'yê' : u'iɛ', u'yế' : u'iɛ', u'yề' :", "and l == text[ic:ic+len(l)]: output+=delimit+l check =1 skip=len(l)-1 break if", ": u'ʷiə', u'uyể' : u'ʷiə', u'uyễ' : u'ʷiə', u'uyệ' :", "= re.split(r'(_|-)', word) values = substrings[::2] delimiters = substrings[1::2] +", "u'uắ' : u'ʷă', u'uằ' : u'ʷă', u'uẳ' : u'ʷă', u'uẵ'", ": u'aj', u'oải' : u'aj', u'oãi' : u'aj', u'oại' :", "[\"ˈ\",\"ˌ\",\"*\"]: continue print(\"this is not in symbol :\"+ char+\":\") output+=delimit+undefine_symbol", "} Cus_codas = { u'p' : u'p', u't' : u't',", "utf-8 #Custom phoneme follow the https://vi.wikipedia.org/wiki/%C3%82m_v%E1%BB%8B_h%E1%BB%8Dc_ti%E1%BA%BFng_Vi%E1%BB%87t #Improve pronoune between N", "t, tʃ for ch #Thay offglide: úy -> wi để", ": 214, u'ậ' : 212, u'ắ' : 45, u'ằ' :", "iə1 iêu <-> yêu : iəw1 khoắng <-> khuắng :", "tok in token_under: if tok not in content or \"[\"", "u'aw', u'oeo' : u'ew', u'oéo' : u'ew', u'oèo' : u'ew',", "u'ew', u'èo' : u'ew', u'ẻo' : u'ew', u'ẽo' : u'ew',", "u'ỡi' : u'ɤj', u'ợi' : u'ɤj', u'ưi' : u'ɯj', u'ứi'", "212, u'é' : 45, u'è' : 32, u'ẻ' : 214,", ": 32, u'ỷ' : 312, u'ỹ' : u'35g', u'ỵ' :", ": 2, u'ả' : 4, u'ã' : 4, u'ạ' :", "cout_same) #Các trường hợp dẫn đến trùng âm là: #", "4, u'ỹ' : 3, u'ỵ' : 6, } N_gi =", "Fronting (Northern dialect) if dialect == 'n': if nuc ==", "in [u'i', u'e', u'ɛ']: if cod == u'ɲ': cod =", "ngét <-> nghét : ŋɛt5 ngễu <-> nghễu : ŋɛu3", ": 32, u'ở' : 214, u'ỡ' : 214, u'ợ' :", "u'j'} Cus_nuclei = { u'a' : u'a', u'á' : u'a',", "u'ổ' : 214, u'ỗ' : 214, u'ộ' : 212, u'ớ'", "Cus_offglides, Cus_onoffglides, Cus_qu, Cus_gi] DICT={} #144 in total syms=['ɯəj', 'ɤ̆j',", "'nh', 'gh', 'kʷ' etc ons = onsets[word[0:2]] oOffset = 2", "u'ʷen', u'oẹn' : u'ʷen', u'oet' : u'ʷet', u'oét' : u'ʷet',", "vi2IPA(line) nor = T2IPA(line) if nor in List_token: print(line +", "u'ũ' : 4, u'ụ' : 6, u'ứ' : 5, u'ừ'", "u'è' : 42, u'ẻ' : 312, u'ẽ' : 312, u'ẹ'", "in ['y','ý','ỳ','ỷ','ỹ','ỵ']) or (lin2[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ'] and line[-1] in ['i','í','ì','ĩ','ỉ','ị']):", "gì : ɣi2 ghích <-> gích : ɣitʃ5 ia <->", ": u'iəw', u'iều' : u'iəw', u'iểu' : u'iəw', u'iễu' :", "u'k', u'c' : u'k', u'gh' : u'ɣ', u'r' : u'z',", "need much memory ''' check_sym=\"ɯəjɤ̆jʷiəɤ̆wɯəwʷetiəwuəjʷentʰwʷɤ̆ʷiukwiŋ͡mk͡pcwjwuəeəbwojʷivwăwʈwʂwaʊfwɛutʰtʃɔɪxwʷɤɤ̆ŋwʊəziʷădweɪaɪewiəɣwzwɯjʷɛɯwɤjɔ:əʊʷamwɑ:hwɔjujlwɪəăju:awɛjiwajɜ:kwnwt∫ɲweoswtwʐwiɛʷei:ɯədʒɲθʌlw1ɪɯd∫pəuo3ɣ!ðʧ6ʒʐzvgă_æɤ2ʤi.ɒbhnʂɔɛkm5cjxʈ,4ʊsŋaʃ?r:ηf;et'\" for ine,res in enumerate(Results): if", "42, u'ổ' : 312, u'ỗ' : 312, u'ộ' : u'21g',", "u'p', u't' : u't', u'c' : u'k', u'm' : u'm',", "tiếng anh từng chữ letter2sound=\"\" for char in tk: CHAR", "u'z', u's' : u's', u'gi': u'z'} N_nuclei = { u'a'", "29.03.16: check if tokenize is true ## if true, call", "\",IPA) print(\"------------------------------------------------------\") Results+= IPA.rstrip()+\" \"+delimit+\".\"+delimit+\" \" #For checking: need much", "= '' try: (ons, nuc, cod, ton) = trans(word, dialect,", "# Modification for sắc in closed syllables (Northern and Central", ": u'p', u'qu' : u'kw', u'gi' : u'j', u'tr' :", "line in content: #nor_tr = vi2IPA_pitrain(line) #nor = vi2IPA(line) nor", "u's' : u'ʂ', u'gi': u'j'} Cus_nuclei = { u'a' :", "u'ɯəw', u'ượu' : u'ɯəw' } C_onglides = { u'oa' :", "u'iw', u'oi' : u'ɔj', u'ói' : u'ɔj', u'òi' : u'ɔj',", ": 312, u'ễ' : u'35g', u'ệ' : u'21g', u'í' :", "u'5' and cod in ['p', 't', 'k']: ton = u'5b'", "{ u'oe' : u'ɛj', u'oé' : u'ɛj', u'oè' : u'ɛj',", ": 3, u'ặ' : 6, u'é' : 5, u'è' :", "u'ɔ', u'ọo' : u'ɔ', u'oo' : u'ɔ', u'oó' : u'ɔ',", ": 6, u'é' : 5, u'è' : 2, u'ẻ' :", "#coding: utf-8 C_onsets = { u'b' : u'b', u't' :", "C_gi, N_onsets, N_nuclei, N_codas#, N_tones , N_onglides, N_offglides, N_onoffglides, N_qu,", ": u'kwi', u'qùy' : u'kwi', u'qủy' : u'kwi', u'qũy' :", "dialect == 'n': tones_p = N_tones_p if dialect == 'c':", "in onglides and ons == u'kw': nuc = onglides[nucl] elif", "3, u'ị' : 6, u'ó' : 5, u'ò' : 2,", "check_sym: Results[ine]=\"'\" ''' return Results.rstrip() def vi2IPA(text): print(\"------------------------------------------------------\") TN= TTSnorm(text)", "types. Type 1 are onsets which has one letter \",\"/\"))", "u'ự' : u'21g', u'ý' : 24, u'ỳ' : 32, u'ỷ'", "word == 'quy', 'qúy',... ons = qu[word][:-1] nuc = qu[word][-1]", "'_' in word): substrings = re.split(r'(_|-)', word) values = substrings[::2]", "!= lin2: if (lin2[0]==\"k\" and line[0]==\"c\") or (lin2[-1] in ['i','í','ì','ĩ','ỉ','ị']", "u'ựu' : u'ɯw', u'iêu' : u'iəw', u'iếu' : u'iəw', u'iều'", "u'iəw', u'yễu' : u'iəw', u'yệu' : u'iəw', u'uôi' : u'uəj',", "= 0 delimit = '' dialect='n' #\"c\"\"s\" tone_type=0 if tone_type==0:", ": 312, u'ỡ' : 312, u'ợ' : u'21g', u'ú' :", "u'o', u'ỗô' : u'o', u'ộô' : u'o', u'ôô' : u'o',", "teach and watch để thay thế => k for c", "u'21g', u'ố' : 13, u'ồ' : 42, u'ổ' : 312,", "anh Etrain bưc #Neu co Mapping #Neu khong, check co", "u'ậ' : 212, u'ắ' : 45, u'ằ' : 32, u'ẳ'", "nucleus else: # otherwise... nuc = nuclei[nucl] # there's your", ": u'e', u'ệ' : u'e', u'i' : u'i', u'í' :", "u'ʷi', u'uỳ' : u'ʷi', u'uỷ' : u'ʷi', u'uỹ' : u'ʷi',", "u'uj', u'ũy' : u'uj', u'ụy' : u'uj', u'uy' : u'ʷi',", "cOffset !=0: # Obstruent-final nang tones are modal voice if", "''' test=\"t\" if test in syms: print(test) else: print(\"none\") '''", "onsets. Onsets are splitted into 3 types. Type 1 are", "6, u'ắ' : 5, u'ằ' : 2, u'ẳ' : 4,", "2 elif word[0] in onsets: # if single onset ons", "vào ảnh hưởng chữ qu cũng ra w) #Try to", "string to IPA.\"\"\" ons = '' nuc = '' cod", "'n' and ton == u'24') or (dialect == 'c' and", "nuc = nuclei[nucl] # there's your nucleus else: nuc =", "ghích <-> gích : ɣitʃ5 ia <-> iê : iə1", "u'ji', u'gị' : u'ji' } S_qu = {u'quy' : u'wi',", "ton) def convert(word, dialect, glottal, pham, cao, palatals, delimit): \"\"\"Convert", "content: #nor_tr = vi2IPA_pitrain(line) #nor = vi2IPA(line) nor = T2IPA(line)", "else: if not (pham or cao): if dialect == 'c':", "u'ỉ' : 312, u'ĩ' : u'35g', u'ị' : u'21g', #", "> must consider (nhưng nếu thêm vào ảnh hưởng chữ", "có cũng như case Tiếng anh: => dùng etrain cho", ": u'21g', u'é' : 13, u'è' : 42, u'ẻ' :", "consider (nhưng nếu thêm vào ảnh hưởng chữ qu cũng", "u'ɯw', u'ữu' : u'ɯw', u'ựu' : u'ɯw', u'iêu' : u'iəw',", "Cus_gi if pham or cao: if dialect == 'n': tones_p", ": 4, u'ĩ' : 3, u'ị' : 6, u'ó' :", "== 0: #Case symbol not in list if str(char) in", "u'õa' : u'ʷa', u'ọa' : u'ʷa', u'oă' : u'ʷă', u'oắ'", "\"oẹ\",\"ọo\", \"uỵ\"] Onset=[\"b\",\"d\",\"h\",\"l\",\"m\",\"n\",\"p\",\"r\",\"s\",\"t\",\"v\",\"x\",\"đ\",\"p\", \"tr\", \"th\", \"ch\", \"ph\",\"nh\",\"kh\",\"gi\",\"qu\", \"ngh\",\"ng\",\"gh\",\"g\",\"k\",\"c\"] #coding: utf-8", "## toss len==0 junk words = [word for word in", "u'oẹ' : u'ʷɛ', u'oe' : u'ʷɛ', u'óe' : u'ʷɛ', u'òe'", "output+=delimit+undefine_symbol return output.rstrip()+delimit #print(\"Parsing\",Parsing(\"default\",\"iu iu\",\"|\")) def getSymbol(): for s in", ": u'ɔ', u'óo' : u'ɔ', u'òo' : u'ɔ', u'ỏo' :", "import StringIO from optparse import OptionParser from string import punctuation", "compound = compound + seq return compound def T2IPA(text): sys.path.append('./Rules')", "nuclei, codas, onglides, offglides, onoffglides, qu, gi = Cus_onsets, Cus_nuclei,", ": u't' } S_tones = { u'á' : 45, u'à'", ": 4, u'ỹ' : 4, u'ỵ' : 6, } C_gi", ": u'ăj', u'ao' : u'aw', u'áo' : u'aw', u'ào' :", "u'ʷă', u'oằ' : u'ʷă', u'oẳ' : u'ʷă', u'oẵ' : u'ʷă',", "díp <-> gíp : zip5 gen <-> ghen : ɣɛn1", ": 32, u'ẩ' : 312, u'ẫ' : u'35g', u'ậ' :", "2, u'ỏ' : 4, u'õ' : 4, u'ọ' : 6,", "4, u'ã' : 3, u'ạ' : 6, u'ấ' : 5,", ": u'ăj', u'ày' : u'ăj', u'ảy' : u'ăj', u'ãy' :", ": u'm', u'n' : u'n', u'ng' : u'ŋ', u'nh' :", "from io import StringIO from optparse import OptionParser from string", "u'qũy' : u'kwi', u'qụy' : u'kwi'} ####################################################### # North #", "tiếng ANH #+Thêm xử lí case không có cũng như", "} S_qu = {u'quy' : u'wi', u'qúy' : u'wi', u'qùy'", "<-> y #Same negative / need to fix #oe <->", "4, u'ị' : 6, u'ó' : 5, u'ò' : 2,", ": u'u', u'ú' : u'u', u'ù' : u'u', u'ủ' :", "onset is 'ngh' ons = onsets[word[0:3]] oOffset = 3 elif", "= { u'p' : u'p', u't' : u'k', u'c' :", "'ʐw', 'iɛ', 'ʷe', 'i:', 'ɯə', 'dʒ', 'ɲ', 'θ', 'ʌ', 'l',", ": u'ɯəw', 'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw' } N_onglides", "ua <-> uơ : uə1 ưa <-> ươ : ɯə1", "#print(\"ENGLISH\",tk) #Đọc tiếng anh từng chữ letter2sound=\"\" for char in", ": u'ɯə', u'ưỡ' : u'ɯə', u'ượ' : u'ɯə', u'yê' :", "nghét : ŋɛt5 ngễu <-> nghễu : ŋɛu3 nghía <->", "u'ɤ̆j', u'ậy' : u'ɤ̆j', u'âu' : u'ɤ̆w', u'ấu' : u'ɤ̆w',", ": u'o', u'ồ' : u'o', u'ổ' : u'o', u'ỗ' :", "underscores words = [word for word in words if word!=u'-']", "=> Try to add ʷ Cus_onglides = { u'oa' :", ": u'kw', u'gi' : u'j', u'tr' : u'ʈ', u'k' :", "onglide and off-glide is a big problem #Same positive #k", "fix aberrant 33 error tonelist = [tones[word[i]] for i in", ": 312, u'ỗ' : 312, u'ộ' : u'21g', u'ớ' :", "u'e', u'i' : u'i', u'í' : u'i', u'ì' : u'i',", ": u'ɛj', u'oé' : u'ɛj', u'oè' : u'ɛj', u'oẻ' :", "u'e' : 33, u'é' : 24, u'è' : 32, u'ẻ'", "== tk: #Đọc tiếng anh từng chữ letter2sound=\"\" for char", "24, u'ì' : 32, u'ỉ' : 312, u'ĩ' : u'35g',", "u'i', u'uya' : u'iə', u'uyá' : u'iə', u'uyà' : u'iə',", "u'ẹo' : u'ew', u'iu' : u'iw', u'íu' : u'iw', u'ìu'", ": 32, u'ẳ' : 312, u'ẵ' : u'35g', u'ặ' :", ": u'21g', u'ú' : 13, u'ù' : 42, u'ủ' :", ": 4, u'ễ' : 4, u'ệ' : 6, u'í' :", "= { u'gi' : u'ji', u'gí': u'ji', u'gì' : u'ji',", "u'ỉ' : 4, u'ĩ' : 4, u'ị' : 6, u'ó'", "encoding=\"utf-8\") as f: content=f.read().splitlines() for line in content: if T2IPA(line)", "there is no onset... ons = u'w' # add a", "ons = u'ʔ'+nuclei[nucl] # add a glottal stop else: #", "nor in List_token: print(line + \" -> \"+nor) trung +=1", "# *** Problem with ủy onglide and off-glide is a", "C_onglides, C_offglides, C_onoffglides, C_qu, C_gi elif dialect == 's': onsets,", "u'ỵ' : u'21g', } # used to use \\u02C0 for", "unicode raised glottal character N_tones_p = { u'á' : 5,", ": u'ʷɛ', u'oẽ' : u'ʷɛ', u'oẹ' : u'ʷɛ', u'oe' :", "ngịu : ŋiw6 nghoèo <-> ngoèo : ŋwew2 quít <->", "phân biệt với úi #Remain ''' di <-> gi :", "u'a', u'óa' : u'a', u'òa' : u'a', u'ỏa' : u'a',", "ủy onglide and off-glide is a big problem #Same positive", "'_', 'f', ',', 'ɛ', 'z', '6', '2', 'x', 'ă'] listParse.sort(reverse", "u'ùy' : u'uj', u'ủy' : u'uj', u'ũy' : u'uj', u'ụy'", "nuc in [u'u', u'o', u'ɔ']: if cod == u'ŋ': cod", "'uə', 'aj', 'iə', 'iw', 'əʊ', 'ɑ:', 'tʃ', 'ʷe', 'ɛu', 'ɔɪ',", "= ons+u'w' else: ons = u'w' elif nucl in offglides:", "thế => k for c , t for t, tʃ", "u'ɯj', u'ừi' : u'ɯj', u'ửi' : u'ɯj', u'ữi' : u'ɯj',", "u'ẫ' : u'ɤ̆', u'ậ' : u'ɤ̆', u'ă' : u'ă', u'ắ'", "để thay thế => k for c , t for", "tones are modal voice if (dialect == 'n' or dialect", "45, u'ì' : 32, u'ỉ' : 214, u'ĩ' : 214,", "u'uj', u'uy' : u'ʷi', u'úy' : u'uj', u'ùy' : u'uj',", "u'ùi' : u'uj', u'ủi' : u'uj', u'ũi' : u'uj', u'ụi'", ": 2, u'ỏ' : 4, u'õ' : 3, u'ọ' :", ": u'ɤ̆', u'ẫ' : u'ɤ̆', u'ậ' : u'ɤ̆', u'ă' :", ": 2, u'ở' : 4, u'ỡ' : 3, u'ợ' :", "in listParse: if len(l) <= len(text[ic:]) and l == text[ic:ic+len(l)]:", "in enumerate(TK): token_under=under_valid.split(\" \") checkinvalid=0 print(token_under) if len(token_under) >1: for", ": u'ɛu', u'ễu': u'ɛu', u'ệu' : u'ɛu', u'ia' : u'iə',", "== 'n' and ton == u'24') or (dialect == 'c'", "pass return seq ########################333 from vinorm import * from underthesea", "u'òo' : u'ɔ', u'ỏo' : u'ɔ', u'õo' : u'ɔ', u'ọo'", "312, u'ị' : u'21g', u'ó' : 13, u'ò' : 42,", "u'21g', # u'ô' : 33, u'ố' : 24, u'ồ' :", "5, u'ỳ' : 2, u'ỷ' : 4, u'ỹ' : 3,", ": u'ʷe', u'uệ' : u'ʷe', u'uơ' : u'ʷɤ', u'uớ' :", "in enumerate(Results): if res not in check_sym: Results[ine]=\"'\" ''' return", "u'et', u'oẻt' : u'et', u'oẽt' : u'et', u'oẹt' : u'et'", ": 42, u'ở' : 312, u'ỡ' : 312, u'ợ' :", ": 6, u'ế' : 5, u'ề' : 2, u'ể' :", "word[0:2] in onsets: # if onset is 'nh', 'gh', 'kʷ'", "u'ọe' : u'ʷɛ', u'ua' : u'ʷa', u'uá' : u'ʷa', u'uà'", "{u'quy' : u'kwi', u'qúy' : u'kwi', u'qùy' : u'kwi', u'qủy'", "CHAR in list(EN.keys()): letter2sound+=EN[CHAR]+\" \" else: letter2sound+=char+\" \" IPA+=T2IPA_split(letter2sound,\"\")+\" \"", ": u'zi', u'gĩ' : u'zi', u'gị' : u'zi'} N_qu =", "Parsing(listParse, text, delimit): undefine_symbol = \"'\" if listParse == \"default\":", "word!=u'-'] words = [word for word in words if word!=u'_']", "'eə', 'bw', 'oj', 'ʷi', 'vw', 'ăw', 'ʈw', 'ʂw', 'aʊ', 'fw',", "quýt : kwit5 thủa <-> thuở : tʰuə4 tòe <->", "u'oẽ' : u'ʷɛ', u'oẹ' : u'ʷɛ', u'oe' : u'ʷɛ', u'óe'", "'fw', 'ɛu', 'tʰ', 'tʃ', 'ɔɪ', 'xw', 'ʷɤ', 'ɤ̆', 'ŋw', 'ʊə',", "tess: print(\"------------------------------------------------------\") TN= TTSnorm(text) print(\"------------------------------------------------------\") print(\"Text normalize: \",TN) TK= word_tokenize(TN)", "u'uỡ' : u'uə', u'uợ' : u'uə', } C_offglides = {", "else: IPA+=Parsing(\"default\",eng,delimit)+\" \" #Check tu dien tieng anh Etrain bưc", "u'ăj', u'oày' : u'ăj', u'oảy' : u'ăj', u'oãy' : u'ăj',", "the same mapping:\",trung) List_token = list(set(List_token)) #print(List_token) print(len(List_token)) ################################ #Looking", "nuc = qu[word][-1] else: # Something is non-Viet return (None,", "hyphens or underscores words = [word for word in words", "'aj', 'ɜ:', 'kw', 'nw', 't∫', 'ɲw', 'eo', 'sw', 'tw', 'ʐw',", "u'u', u'ụ' : u'u', u'ư' : u'ɯ', u'ứ' : u'ɯ',", ": u'iə', u'uyả' : u'iə', u'uyã' : u'iə', u'uyạ' :", ": u'ew', u'uẻo' : u'ew', u'uẽo' : u'ew', u'uẹo' :", "if line != lin2: if (lin2[0]==\"k\" and line[0]==\"c\") or (lin2[-1]", "l in listParse: if len(l) <= len(text[ic:]) and l ==", "'ɪ', 'ɯ', 'd', '∫', 'p', 'ə', 'u', 'o', '3', 'ɣ',", "u'oáy' : u'ăj', u'oày' : u'ăj', u'oảy' : u'ăj', u'oãy'", "u'ỵ' : 6, } Cus_gi = { u'gi' : u'zi',", "u'uỡ' : u'uə', u'uợ' : u'uə', } Cus_offglides = {", "an onset.... ons = u'ʔ'+nuclei[nucl] # add a glottal stop", "u'35g', u'ộ' : u'21g', u'ớ' : 24, u'ờ' : 32,", ": u'ăj', u'oao' : u'aw', u'oáo' : u'aw', u'oào' :", "def getSymbol(): for s in SET: DICT.update(s) list_phoneme=DICT.values() list_phoneme=list(list_phoneme) English_phoneme=[\"p\",\"b\",\"t\",\"d\",\"t∫\",\"dʒ\",\"k\",\"g\",\"f\",\"v\",\"ð\",\"θ\",\"s\",\"z\",\"∫\",\"ʒ\",\"m\",\"n\",\"η\",\"l\",\"r\",\"w\",\"j\",\"ɪ\",\"i:\",\"ʊ\",\"u:\",\"e\",\"ə\",\"ɜ:\",\"ɒ\",\"ɔ:\",\"æ\",\"ʌ\",\"ɑ:\",\"ɪə\",\"ʊə\",\"eə\",\"eɪ\",\"ɔɪ\",\"aɪ\",\"əʊ\",\"aʊ\",'ʃ',\"ʤ\",\"ʧ\"]", "\"ạ\",\"ặ\",\"ậ\",\"ẹ\",\"ệ\",\"ị\",\"ọ\",\"ộ\",\"ợ\",\"ụ\",\"ự\",\"ỵ\",\"iệ\",\"ọa\",\"oặ\",\"ọe\",\"oọ\",\"uậ\",\"uệ\",\"uệ\",\"ượ\",\"ụy\",\"ượ\",\"uyệ\",\"yệ\", #dot \"oạ\", \"oẹ\",\"ọo\", \"uỵ\"] Onset=[\"b\",\"d\",\"h\",\"l\",\"m\",\"n\",\"p\",\"r\",\"s\",\"t\",\"v\",\"x\",\"đ\",\"p\", \"tr\", \"th\", \"ch\", \"ph\",\"nh\",\"kh\",\"gi\",\"qu\",", "character N_tones_p = { u'á' : 5, u'à' : 2,", "u'a', u'oă' : u'ă', u'oắ' : u'ă', u'oằ' : u'ă',", "if nor in List_token: print(line + \" -> \"+nor) trung", "u'uj', u'ũi' : u'uj', u'ụi' : u'uj', u'uy' : u'uj',", "tk: CHAR = str(char).lower() if CHAR in list(EN.keys()): letter2sound+=EN[CHAR]+\" \"", "offglide: úy -> wi để phân biệt với úi #Remain", "không có w ở trước => Try to add ʷ", ": 13, u'ù' : 42, u'ủ' : 312, u'ũ' :", "u'uyã' : u'ʷiə', u'uyạ' : u'ʷiə', u'uyê' : u'ʷiə', u'uyế'", "u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j' } S_codas = {", "u'ă', u'ẳ' : u'ă', u'ẵ' : u'ă', u'ặ' : u'ă',", ": u'ew', u'ueo' : u'ew', u'uéo' : u'ew', u'uèo' :", "45, u'ò' : 32, u'ỏ' : 214, u'õ' : 214,", "return compound EN={\"a\":\"ây\",\"ă\":\"á\",\"â\":\"ớ\",\"b\":\"bi\",\"c\":\"si\",\"d\":\"đi\",\"đ\":\"đê\",\"e\":\"i\",\"ê\":\"ê\",\"f\":\"ép\",\"g\":\"giy\",\"h\":\"ếch\",\"i\":\"ai\",\"j\":\"giây\",\"k\":\"cây\",\"l\":\"eo\",\"m\":\"em\",\"n\":\"en\",\"o\":\"âu\",\"ô\":\"ô\",\"ơ\":\"ơ\",\"p\":\"pi\",\"q\":\"kiu\",\"r\":\"a\",\"s\":\"ét\",\"t\":\"ti\",\"u\":\"diu\",\"ư\":\"ư\",\"v\":\"vi\",\"w\":\"đắp liu\",\"x\":\"ít\",\"y\":\"quai\",\"z\":\"giét\"} import re def vi2IPA_split(texts,delimit): content=[] with", "u'iể' : u'iə', u'iễ' : u'iə', u'iệ' : u'iə', u'oo'", "'4', 'ʊ', 's', 'ŋ', 'a', 'ʃ', '?', 'r', ':', 'η',", "u'ɛ']: cod = u'c' # Velar Fronting (Southern and Central", "tieng anh Etrain bưc #Neu co Mapping #Neu khong, check", "checkDict(): cout=0 trung=0 List_token=[] List_pair = [] with open(\"Popular.txt\", encoding=\"utf-8\")", "'ʈ', ',', '4', 'ʊ', 's', 'ŋ', 'a', 'ʃ', '?', 'r',", "312, u'ỡ' : 312, u'ợ' : u'21g', u'ú' : 13,", "= 0 tokenize = 0 dialect='n' #\"c\"\"s\" tone_type=0 if tone_type==0:", "'ʐw', 'xw', 'lw', 'hw', 'nw', 'sw', 'c'] word_pad = [\"_\"]", "u'k' } #tones = { u'a' : 33, u'á' :", "with open(\"Popular.txt\",encoding=\"utf-8\") as f: content=f.read().splitlines() tess = texts.split(\".\") Results =\"\"", "= T2IPA_split(tk,delimit).replace(\" \",\"_\") if ipa ==\"\": IPA+=delimit+tk+delimit+\" \" elif ipa[0]==\"[\"", "} Cus_gi = { u'gi' : u'zi', u'gí': u'zi', u'gì'", "= u'ɲ' # u'ŋ' elif palatals != 1 and nuc", "word = word.strip(punctuation).lower() ## 29.03.16: check if tokenize is true", ": 42, u'ỉ' : 312, u'ĩ' : 312, u'ị' :", "u'ʷa', u'ọa' : u'ʷa', u'oă' : u'ʷă', u'oắ' : u'ʷă',", "word = words[i].strip() ortho += word word = word.strip(punctuation).lower() ##", "u'ũ' : u'35g', u'ụ' : u'21g', u'ứ' : 24, u'ừ'", "== u'13')) and cod in ['p', 't', 'k']: ton =", "nuc, cod, ton)))+delimit except (TypeError): pass return seq ########################333 from", "'sw', 'c'] word_pad = [\"_\"] space = [\" \"] tone=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"]", "u'uỵ' : u'i', u'uya' : u'iə', u'uyá' : u'iə', u'uyà'", ": 312, u'ữ' : 312, u'ự' : u'21g', u'ý' :", "'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw' } C_onglides = {", "u'ố' : 5, u'ồ' : 2, u'ổ' : 4, u'ỗ'", "u'qũy' : u'wi', u'qụy' : u'wi'} ################################################3 import sys, codecs,", "= u'6b' # labialized allophony (added 17.09.08) if nuc in", ": 312, u'ã' : u'35g', u'ạ' : u'21g', u'ấ' :", "u'ẳ' : 4, u'ẵ' : 4, u'ặ' : 6, u'é'", "fixed 8 Nov 2016 ton = u'21' # Modification for", "kết quả \"c\" khác nhau ################################################### checkDict() #print(vi2IPA_split(\"!Singapo english? đại", "liu\",\"x\":\"ít\",\"y\":\"quai\",\"z\":\"giét\"} import re def vi2IPA_split(texts,delimit): content=[] with open(\"Popular.txt\",encoding=\"utf-8\") as f:", "nó giảm trùng nhiều hơn 241->153 case #Tuy nhiên cuối", "u'uồi' : u'uəj', u'uổi' : u'uəj', u'uỗi' : u'uəj', u'uội'", "u'21g', u'ú' : 24, u'ù' : 32, u'ủ' : 312,", ": 2, u'ẳ' : 4, u'ẵ' : 4, u'ặ' :", "} S_codas = { u'p' : u'p', u't' : u't',", "= {u'quy' : u'kwi', u'qúy' : u'kwi', u'qùy' : u'kwi',", "= { u'oa' : u'ʷa', u'oá' : u'ʷa', u'oà' :", "':', 'η', 'f', ';', 'e', 't', \"'\"] def Parsing(listParse, text,", "u'ã' : u'35g', u'ạ' : u'21g', # u'â' : 33,", "= u'c' # Velar Fronting (Southern and Central dialects) else:", "= Cus_onsets, Cus_nuclei, Cus_codas, Cus_onglides, Cus_offglides, Cus_onoffglides, Cus_qu, Cus_gi if", "u'ự' : 212, u'ý' : 45, u'ỳ' : 32, u'ỷ'", "u'ứ' : 24, u'ừ' : 32, u'ử' : 312, u'ữ'", "'s', 'ŋ', 'a', 'ʃ', '?', 'r', ':', 'η', 'f', ';',", "u'ỡ' : 312, u'ợ' : u'21g', u'ú' : 13, u'ù'", "nuc accordingly if ons: # if there is an onset...", ": u'ɤ', u'ớ' : u'ɤ', u'ờ' : u'ɤ', u'ở' :", "for word in words if len(word)>0] ## hack to get", ": u'35g', u'ụ' : u'21g', # u'ư' : 33, u'ứ'", "'tʰ', 'tʃ', 'ɔɪ', 'xw', 'ʷɤ', 'ɤ̆', 'ŋw', 'ʊə', 'zi', 'ʷă',", ": u'ɔ', u'oò' : u'ɔ', u'oỏ' : u'ɔ', u'oõ' :", ": u'ɤ̆j', u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j' } C_codas", "ortho += word word = word.strip(punctuation).lower() ## 29.03.16: check if", "u'ĩ' : 3, u'ị' : 6, u'ó' : 5, u'ò'", ": u'aw', u'oạo' : u'aw', u'oeo' : u'ew', u'oéo' :", "['p', 't', 'k']: # fixed 8 Nov 2016 ton =", "+ seq return compound EN={\"a\":\"ây\",\"ă\":\"á\",\"â\":\"ớ\",\"b\":\"bi\",\"c\":\"si\",\"d\":\"đi\",\"đ\":\"đê\",\"e\":\"i\",\"ê\":\"ê\",\"f\":\"ép\",\"g\":\"giy\",\"h\":\"ếch\",\"i\":\"ai\",\"j\":\"giây\",\"k\":\"cây\",\"l\":\"eo\",\"m\":\"em\",\"n\":\"en\",\"o\":\"âu\",\"ô\":\"ô\",\"ơ\":\"ơ\",\"p\":\"pi\",\"q\":\"kiu\",\"r\":\"a\",\"s\":\"ét\",\"t\":\"ti\",\"u\":\"diu\",\"ư\":\"ư\",\"v\":\"vi\",\"w\":\"đắp liu\",\"x\":\"ít\",\"y\":\"quai\",\"z\":\"giét\"} import re def vi2IPA_split(texts,delimit):", ": 32, u'ả' : 312, u'ã' : u'35g', u'ạ' :", "C_qu, C_gi, N_onsets, N_nuclei, N_codas#, N_tones , N_onglides, N_offglides, N_onoffglides,", ": u'ʷa', u'oá' : u'ʷa', u'oà' : u'ʷa', u'oả' :", ": u'f', u'v' : u'j', u'x' : u's', u'd' :", "u'ew', u'uẹo' : u'ew', u'uai' : u'aj', u'uái' : u'aj',", "u'ề' : 32, u'ể' : 312, u'ễ' : u'35g', u'ệ'", "u'21\\u02C0' and cod in ['p', 't', 'k']: # fixed 8", ": u'ɯəw' } #Các âm vòng ở đây i chang", "..................Out of domain word: \" ,ipa) else: IPA+=ipa+\" \" IPA=re.sub('", "312, u'ụ' : u'21g', u'ứ' : 13, u'ừ' : 42,", "312, u'ỵ' : u'21g', } # used to use \\u02C0", "u'è' : 2, u'ẻ' : 4, u'ẽ' : 4, u'ẹ'", ": 312, u'ữ' : u'35g', u'ự' : u'21g', u'ý' :", "\"á\",\"ắ\",\"ấ\",\"é\",\"ế\",\"í\",\"ó\",\"ố\",\"ớ\",\"ú\",\"ứ\",\"ý\",\"iế\",\"óa\",\"oắ\",\"óe\",\"oó\",\"uấ\",\"uế\",\"uố\",\"ướ\",\"úy\",\"ướ\",\"uyế\",\"yế\", #grave \"oá\", \"oé\",\"óo\", \"uý\", \"à\",\"ằ\",\"ầ\",\"è\",\"ề\",\"ì\",\"ò\",\"ồ\",\"ờ\",\"ù\",\"ừ\",\"ỳ\",\"iề\",\"òa\",\"oằ\",\"òe\",\"oò\",\"uầ\",\"uề\",\"uồ\",\"ườ\",\"ùy\",\"ườ\",\"uyề\",\"yề\", #acute \"oà\", \"oè\",\"òo\", \"uỳ\",", ": u'iəw', u'yêu' : u'iəw', u'yếu' : u'iəw', u'yều' :", "u'ựa' : u'ɯə', u'ươ' : u'ɯə', u'ướ' : u'ɯə', u'ườ'", "u'oã' : u'a', u'oạ' : u'a', u'óa' : u'a', u'òa'", ": u'iu', u'uỵu' : u'iu', u'oen' : u'en', u'oén' :", "#Các âm vòng ở đây i chang không vòm: không", "u'ɯəj', u'ười' : u'ɯəj', u'ưởi' : u'ɯəj', u'ưỡi' : u'ɯəj',", "u'ẵ' : u'35g', u'ặ' : u'21g', u'é' : 24, u'è'", "= compound + seq return compound EN={\"a\":\"ây\",\"ă\":\"á\",\"â\":\"ớ\",\"b\":\"bi\",\"c\":\"si\",\"d\":\"đi\",\"đ\":\"đê\",\"e\":\"i\",\"ê\":\"ê\",\"f\":\"ép\",\"g\":\"giy\",\"h\":\"ếch\",\"i\":\"ai\",\"j\":\"giây\",\"k\":\"cây\",\"l\":\"eo\",\"m\":\"em\",\"n\":\"en\",\"o\":\"âu\",\"ô\":\"ô\",\"ơ\":\"ơ\",\"p\":\"pi\",\"q\":\"kiu\",\"r\":\"a\",\"s\":\"ét\",\"t\":\"ti\",\"u\":\"diu\",\"ư\":\"ư\",\"v\":\"vi\",\"w\":\"đắp liu\",\"x\":\"ít\",\"y\":\"quai\",\"z\":\"giét\"} import re", "pronoune between N C S Cus_onsets = { u'b' :", "' ', 'c', 'j', 'x', 'ʈ', ',', '4', 'ʊ', 's',", "u'v' : u'v', u'x' : u's', u'd' : u'z', u'h'", "u'ɤ̆j', u'ẩy' : u'ɤ̆j', u'ẫy' : u'ɤ̆j', u'ậy' : u'ɤ̆j',", "elif nucl in onoffglides: cod = onoffglides[nucl][-1] nuc = onoffglides[nucl][0:-1]", "concatenate if len(words) >= 2: ortho += ' ' if", "len(words) >= 2: ortho += ' ' if i <", ": u'ɤ̆j', u'uẩy' : u'ɤ̆j', u'uẫy' : u'ɤ̆j', u'uậy' :", ": 6, u'ứ' : 5, u'ừ' : 2, u'ử' :", "u'í' : 24, u'ì' : 32, u'ỉ' : 312, u'ĩ'", "tk: #print(\"ENGLISH\",tk) #Đọc tiếng anh từng chữ letter2sound=\"\" for char", "(lin2[-1] in ['i','í','ì','ĩ','ỉ','ị'] and line[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ']) or (lin2[-1] in", "u'ɛj', u'oai' : u'aj', u'oái' : u'aj', u'oài' : u'aj',", "'k͡p', 'cw', 'jw', 'uə', 'eə', 'bw', 'oj', 'ʷi', 'vw', 'ăw',", "u'ẻo' : u'ew', u'ẽo' : u'ew', u'ẹo' : u'ew', u'iu'", "u'ʷe', u'uễ' : u'ʷe', u'uệ' : u'ʷe', u'uơ' : u'ʷɤ',", "u'ʷɛ', u'oẹ' : u'ʷɛ', u'oe' : u'ʷɛ', u'óe' : u'ʷɛ',", "cho kết quả \"c\" khác nhau ################################################### checkDict() #print(vi2IPA_split(\"!Singapo english?", "máy không normal phoneme về cường độ âm sắc chỉ", ": u'ʷen', u'oẹn' : u'ʷen', u'oet' : u'ʷet', u'oét' :", "/ need to fix #oe <-> uê -> fix oe", "u'qu' : u'kw', u'gi' : u'z', u'tr' : u'c', u'k'", "N_tones , N_onglides, N_offglides, N_onoffglides, N_qu, N_gi, Cus_onsets, Cus_nuclei, Cus_codas#,", "'ɣw', 'zw', 'ɯj', 'ʷɛ', 'ɯw', 'ɤj', 'ɔ:', 'əʊ', 'ʷa', 'mw',", "cod = u'k͡p' return (ons, nuc, cod, ton) def convert(word,", "u'i', u'uỳ' : u'i', u'uỷ' : u'i', u'uỹ' : u'i',", "we paper, we investigate work! One is that e language", "in [u'i', u'e', u'ɛ']: cod = u'c' # Velar Fronting", "of domain word: \" ,ipa) else: IPA+=ipa+\" \" IPA=re.sub(delimit+'+', delimit,", ": u'uə', } S_offglides = { u'ai' : u'aj', u'ái'", "enumerate(Results): if res not in check_sym: Results[ine]=\"'\" ''' return Results.rstrip()", "check_sym=\"ɯəjɤ̆jʷiəɤ̆wɯəwʷetiəwuəjʷentʰwʷɤ̆ʷiukwiŋ͡mk͡pcwjwuəeəbwojʷivwăwʈwʂwaʊfwɛutʰtʃɔɪxwʷɤɤ̆ŋwʊəziʷădweɪaɪewiəɣwzwɯjʷɛɯwɤjɔ:əʊʷamwɑ:hwɔjujlwɪəăju:awɛjiwajɜ:kwnwt∫ɲweoswtwʐwiɛʷei:ɯədʒɲθʌlw1ɪɯd∫pəuo3ɣ!ðʧ6ʒʐzvgă_æɤ2ʤi.ɒbhnʂɔɛkm5cjxʈ,4ʊsŋaʃ?r:ηf;et'\" for ine,res in enumerate(Results): if res not in check_sym:", "u'ỏ' : 312, u'õ' : 312, u'ọ' : u'21g', u'ố'", "nucl in onglides and ons == u'kw': nuc = onglides[nucl]", ": u'ʷă', u'oắ' : u'ʷă', u'oằ' : u'ʷă', u'oẳ' :", "compound + seq return compound EN={\"a\":\"ây\",\"ă\":\"á\",\"â\":\"ớ\",\"b\":\"bi\",\"c\":\"si\",\"d\":\"đi\",\"đ\":\"đê\",\"e\":\"i\",\"ê\":\"ê\",\"f\":\"ép\",\"g\":\"giy\",\"h\":\"ếch\",\"i\":\"ai\",\"j\":\"giây\",\"k\":\"cây\",\"l\":\"eo\",\"m\":\"em\",\"n\":\"en\",\"o\":\"âu\",\"ô\":\"ô\",\"ơ\":\"ơ\",\"p\":\"pi\",\"q\":\"kiu\",\"r\":\"a\",\"s\":\"ét\",\"t\":\"ti\",\"u\":\"diu\",\"ư\":\"ư\",\"v\":\"vi\",\"w\":\"đắp liu\",\"x\":\"ít\",\"y\":\"quai\",\"z\":\"giét\"} import re def", "u'uỡ' : u'uə', u'uợ' : u'uə', } N_offglides = {", ": u'oj', u'ội' : u'oj', u'ui' : u'uj', u'úi' :", "onset... ons = ons+u'w' # labialize it, but... else: #", "but newer versions of python complain about \"from x import", "u'ɔ', u'òo' : u'ɔ', u'ỏo' : u'ɔ', u'õo' : u'ɔ',", "also this reverse fronting, see Thompson 1965:94 ff. elif nuc", "5, u'ồ' : 2, u'ổ' : 4, u'ỗ' : 3,", "Cus_onglides = { u'oa' : u'ʷa', u'oá' : u'ʷa', u'oà'", "u'ồ' : 32, u'ổ' : 312, u'ỗ' : u'35g', u'ộ'", "= Cus_tones_p tones = tones_p ons = '' nuc =", ": u'iw', u'ĩu' : u'iw', u'ịu' : u'iw', u'oi' :", "'ʷe', 'ɛu', 'ɔɪ', 'ʷi', 'eɪ', 'ɤj', 'ɯw', 'ɛj', 'ɔj', 'i:',", ": 4, u'ị' : 6, u'ó' : 5, u'ò' :", "Special=['jw', 'ŋw', 'bw', 'vw', 'dw', 'eo', 'ʈw', 'mw', 'zw', 'fw',", "u'uỷ' : u'ʷi', u'uỹ' : u'ʷi', u'uỵ' : u'ʷi', u'ơi'", "} C_nuclei = { u'a' : u'a', u'á' : u'a',", "if CHAR in list(EN.keys()): letter2sound+=EN[CHAR]+\" \" else: letter2sound+=char+\" \" IPA+=T2IPA_split(letter2sound,\"\")+\"", "= { u'ai' : u'aj', u'ái' : u'aj', u'ài' :", ": u'ɤ̆j', u'uậy' : u'ɤ̆j' } Cus_codas = { u'p'", "'ʷɛ', 'ɯw', 'ɤj', 'ɔ:', 'əʊ', 'ʷa', 'mw', 'ɑ:', 'hw', 'ɔj',", ": u'et' } S_onoffglides = { u'oe' : u'ej', u'oé'", "S_tones_p = { u'á' : 5, u'à' : 2, u'ả'", "S_onoffglides, S_qu, S_gi, C_onsets, C_nuclei, C_codas#, C_tones , C_onglides, C_offglides,", "= 0 palatals = 0 tokenize = 0 dialect='n' #\"c\"\"s\"", "u'w' # add a labiovelar onset elif nucl in onglides", "u'uẵ' : u'ʷă', u'uặ' : u'ʷă', u'uâ' : u'ʷɤ̆', u'uấ'", "u'ɤj', u'ỡi' : u'ɤj', u'ợi' : u'ɤj', u'ưi' : u'ɯj',", ": u'iəw', u'iểu' : u'iəw', u'iễu' : u'iəw', u'iệu' :", "u'ả' : 214, u'ã' : 214, u'ạ' : 212, u'ấ'", "u'ể' : 4, u'ễ' : 4, u'ệ' : 6, u'í'", "u'uj', u'ụi' : u'uj', #u'uy' : u'uj', u'úy' : u'uj',", "u'ừ' : 32, u'ử' : 312, u'ữ' : u'35g', u'ự'", "u'oảo' : u'aw', u'oão' : u'aw', u'oạo' : u'aw', u'oeo'", "\"oẻ\",\"ỏo\", \"uỷ\", \"ã\",\"ẵ\",\"ẫ\",\"ẽ\",\"ễ\",\"ĩ\",\"õ\",\"ỗ\",\"ỡ\",\"ũ\",\"ữ\",\"ỹ\",\"iễ\",\"õa\",\"oẵ\",\"õe\",\"oõ\",\"uẫ\",\"uễ\",\"uỗ\",\"ưỡ\",\"ũy\",\"ưỡ\",\"uyễ\",\"yễ\", #tilde \"oã\", \"oẽ\",\"õo\", \"uỹ\", \"ạ\",\"ặ\",\"ậ\",\"ẹ\",\"ệ\",\"ị\",\"ọ\",\"ộ\",\"ợ\",\"ụ\",\"ự\",\"ỵ\",\"iệ\",\"ọa\",\"oặ\",\"ọe\",\"oọ\",\"uậ\",\"uệ\",\"uệ\",\"ượ\",\"ụy\",\"ượ\",\"uyệ\",\"yệ\", #dot \"oạ\",", "214, u'ọ' : 212, u'ố' : 45, u'ồ' : 32,", ": 312, u'ẵ' : 312, u'ặ' : u'21g', u'é' :", "u'iu', u'uỳu' : u'iu', u'uỷu' : u'iu', u'uỹu' : u'iu',", "'2', 'ʤ', 'i', '.', 'ɒ', 'b', 'h', 'n', 'ʂ', 'ɔ',", "Results =\"\" for text in tess: print(\"------------------------------------------------------\") TN= TTSnorm(text) print(\"------------------------------------------------------\")", "nuc = offglides[nucl][:-1] elif word in gi: # if word", "'2', 'x', 'ă'] listParse.sort(reverse = True,key=len) output=\"\" skip=0 for ic,char", "u'ẻ' : 214, u'ẽ' : 214, u'ẹ' : 212, u'ế'", "+ seq return compound def T2IPA(text): sys.path.append('./Rules') # make sure", "'tʰw', 'ɲw', 'cw', 'ʂw', 'ɣw', 'ʐw', 'xw', 'lw', 'hw', 'nw',", "Results.rstrip() def vi2IPA(text): print(\"------------------------------------------------------\") TN= TTSnorm(text) print(\"------------------------------------------------------\") print(\"Text normalize: \",TN)", "your nucleus else: nuc = nuclei[nucl] # there's your nucleus", ": u'en', u'oet' : u'et', u'oét' : u'et', u'oèt' :", ": u'iə', u'uyê' : u'iə', u'uyế' : u'iə', u'uyề' :", "'ɲ'' in north #Các âm vòng ở đây i chang", "32, u'ỷ' : 214, u'ỹ' : 214, u'ỵ' : 212,", "u'iễu' : u'iəw', u'iệu' : u'iəw', u'yêu' : u'iəw', u'yếu'", "-> \"+nor) trung +=1 List_pair.append(line) List_token.append(nor) if nor==\"\": cout+=1 print(line)", ": u'ɛu', u'ếu' : u'ɛu', u'ều' : u'ɛu', u'ểu' :", "convert from 'ɲ' to 'ɲ'' in north #Các âm vòng", "cuối: ch : k theo bắc : t theo nam", "t for t, tʃ for ch #Thay offglide: úy ->", "'tw', 'ʐw', 'iɛ', 'ʷe', 'i:', 'ɯə', 'dʒ', 'ɲ', 'θ', 'ʌ',", "u'21g', u'é' : 13, u'è' : 42, u'ẻ' : 312,", "u'ʷa', u'oạ' : u'ʷa', u'óa' : u'ʷa', u'òa' : u'ʷa',", "u'' words = line.split() ## toss len==0 junk words =", "N C S Cus_onsets = { u'b' : u'b', u't'", "u'ừa' : u'ɯə', u'ửa' : u'ɯə', u'ữa' : u'ɯə', u'ựa'", "'ʒ', 'ʐ', 'z', 'v', 'g', 'ă', '_', 'æ', 'ɤ', '2',", ": u'21g', # u'e' : 33, u'é' : 24, u'è'", "Cus_qu, Cus_gi if pham or cao: if dialect == 'n':", "## 29.03.16: check if tokenize is true ## if true,", ": 212, u'é' : 45, u'è' : 32, u'ẻ' :", ": xuə1 lóe <-> loé : lwʷɛ5 ngét <-> nghét", "not in check_sym: Results[ine]=\"'\" ''' return Results.rstrip() def vi2IPA(text): print(\"------------------------------------------------------\")", "{ u'ai' : u'aj', u'ái' : u'aj', u'ài' : u'aj',", "an onset... ons = ons+u'w' # labialize it, but... else:", ": u'ăj', u'áy' : u'ăj', u'ày' : u'ăj', u'ảy' :", ": u'ɤ̆', u'uậ' : u'ɤ̆', u'ue' : u'ɛ', u'ué' :", "IPA của tiếng ANH #+Thêm xử lí case không có", ": u'e', u'ế' : u'e', u'ề' : u'e', u'ể' :", "u'èo' : u'eo', u'ẻo' : u'eo', u'ẽo': u'eo', u'ẹo' :", "#print(char,skip) check = 0 if skip>0: skip=skip-1 continue for l", "N_codas, N_tones, N_onglides, N_offglides, N_onoffglides, N_qu, N_gi elif dialect ==", "u'ẵ' : 3, u'ặ' : 6, u'é' : 5, u'è'", "u'ɛ', u'ẽ' : u'ɛ', u'ẹ' : u'ɛ', u'ê' : u'e',", "+ tone + modifi + Special symbols = list(set(symbols)) symbols.sort(reverse", "u'm' : u'm', u'n': u'n', u'ngh': u'ŋ', u'nh' : u'ɲ',", "u'aj', u'oay' : u'ăj', u'oáy' : u'ăj', u'oày' : u'ăj',", "'s') and ton == u'21g' and cod in ['p', 't',", "u'ŋ͡m' if cod == u'k': cod = u'k͡p' return (ons,", "u'ch' : u'k' } #tones = { u'a' : 33,", ": u'ɤ̆j', u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j' } S_codas", "#print(vi2IPA_split(\"speech? Secondly, we paper, we investigate work! One is that", "w ở trước như: \"oa,ua,a\" đều như một > must", "as in wiki # *** Problem with ủy onglide and", "'c' and ton == u'13')) and cod in ['p', 't',", "'s': onsets, nuclei, codas, tones, onglides, offglides, onoffglides, qu, gi", ": 24, u'ằ' : 32, u'ẳ' : 312, u'ẵ' :", "'ɔ:', 'ăj', 'ʷa', 'eə', 'u:', 'uj', 'aʊ', 'uə', 'aj', 'iə',", "[\"_\"] space = [\" \"] tone=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"] punctuation = [\".\",\",\",\"!\",\":\",\"?\",\";\",\"'\"] #\"", "u'oé' : u'ɛj', u'oè' : u'ɛj', u'oẻ' : u'ɛj', u'oẽ'", "u'uỵ' : u'ʷi', u'uya' : u'ʷiə', u'uyá' : u'ʷiə', u'uyà'", "''' ################################################### #Step #Vinorm #Underthesea #For each Convert to phoneme", "ton = 0 oOffset = 0 cOffset = 0 l", "u'nh' : u'ɲ', u'ch' : u'k' } #tones = {", "and cod in ['p', 't', 'k']: ton = u'6b' #", ": 5, u'ầ' : 2, u'ẩ' : 4, u'ẫ' :", ": 312, u'ễ' : 312, u'ệ' : u'21g', u'í' :", "u'uá' : u'ʷa', u'uà' : u'ʷa', u'uả' : u'ʷa', u'uã'", ": 24, u'ò' : 32, u'ỏ' : 312, u'õ' :", ": 212, u'ế' : 45, u'ề' : 32, u'ể' :", "42, u'ẳ' : 312, u'ẵ' : 312, u'ặ' : u'21g',", "u'oé' : u'ej', u'oè' : u'ej', u'oẻ' : u'ej', u'oẽ'", "'ð', 'ʧ', '6', 'ʒ', 'ʐ', 'z', 'v', 'g', 'ă', '_',", "watch để thay thế => k for c , t", "in north #Các âm vòng ở đây i chang không", ": 42, u'ỏ' : 312, u'õ' : 312, u'ọ' :", "u'uã' : u'ʷa', u'uạ' : u'ʷa', u'uă' : u'ʷă', u'uắ'", "u'ọeo' : u'ew', u'ueo' : u'ew', u'uéo' : u'ew', u'uèo'", ": u'ji', u'gị' : u'ji' } C_qu = {u'quy' :", "u'ỵ' : 6, } S_gi = { u'gi' : u'ji',", "u't' : u'k', u'c' : u'k', u'm' : u'm', u'n'", ": 45, u'ỳ' : 32, u'ỷ' : 214, u'ỹ' :", "# Modifications for closed syllables if cOffset !=0: # Obstruent-final", "orthographic string to IPA.\"\"\" ons = '' nuc = ''", "'ʂ', '_', 'f', ',', 'ɛ', 'z', '6', '2', 'x', 'ă']", "from vinorm import * from underthesea import word_tokenize import eng_to_ipa", "u'uậy' : u'ɤ̆j' } Cus_codas = { u'p' : u'p',", ": u'ʷiu', u'uyù' : u'ʷiu', u'uyủ' : u'ʷiu', u'uyũ' :", "u'aj', u'uại' : u'aj', u'uay' : u'ăj', u'uáy' : u'ăj',", "#Custom onsets, nuclei, codas, onglides, offglides, onoffglides, qu, gi =", "u'ɯəj', u'ưỡi' : u'ɯəj', u'ượi' : u'ɯəj', u'ươu' : u'ɯəw',", "u'uyù' : u'ʷiu', u'uyủ' : u'ʷiu', u'uyũ' : u'ʷiu', u'uyụ'", ": u'uə', u'ủa' : u'uə', u'ũa' : u'uə', u'ụa' :", "214, u'ạ' : 212, u'ấ' : 45, u'ầ' : 32,", "u'yêu' : u'iəw', u'yếu' : u'iəw', u'yều' : u'iəw', u'yểu'", "letter2sound+=char+\" \" IPA+=T2IPA_split(letter2sound,\"\")+\" \" else: #Giữ nguyên IPA+=Parsing(\"default\",tk,\"\")+\" \" else:", "u'ʷa', u'òa' : u'ʷa', u'ỏa' : u'ʷa', u'õa' : u'ʷa',", "u'ɛ', u'uẹ' : u'ɛ', u'uê' : u'e', u'uế' : u'e',", "if word[0] not in onsets: # if there isn't an", ": u'a', u'oă' : u'ă', u'oắ' : u'ă', u'oằ' :", "214, u'ụ' : 212, u'ứ' : 45, u'ừ' : 32,", "'zi', 'kw', 'aɪ', 'iɛ', 'ɤ̆', 'ɔ:', 'ăj', 'ʷa', 'eə', 'u:',", "212, u'ớ' : 45, u'ờ' : 32, u'ở' : 214,", "4, u'õ' : 3, u'ọ' : 6, u'ố' : 5,", ": u'ɛ', u'uẽ' : u'ɛ', u'uẹ' : u'ɛ', u'uê' :", "0: if word[0:3] in onsets: # if onset is 'ngh'", "u'ấ' : 5, u'ầ' : 2, u'ẩ' : 4, u'ẫ'", "no onset... ons = u'w' # add a labiovelar onset", "# otherwise... nuc = nuclei[nucl] # there's your nucleus elif", "glottal instead of g C_tones_p = { u'á' : 5,", "available onsets. Onsets are splitted into 3 types. Type 1", "nucl = u'i' ons = u'z' else: nucl = word[oOffset:l-cOffset]", "optparse import OptionParser from string import punctuation def trans(word, dialect,", "== u'kw': nuc = onglides[nucl] elif nucl in onoffglides: cod", "import * from underthesea import word_tokenize import eng_to_ipa SET=[S_onsets, S_nuclei,", "tk.lower().upper() == tk: #Đọc tiếng anh từng chữ letter2sound=\"\" for", "u'uj', u'ụy' : u'uj', u'uy' : u'ʷi', u'úy' : u'uj',", "re.split(r'(_|-)', word) values = substrings[::2] delimiters = substrings[1::2] + ['']", "u'ʷă', u'uẵ' : u'ʷă', u'uặ' : u'ʷă', u'uâ' : u'ʷɤ̆',", "normalize: \",TN) TK= word_tokenize(TN) print(\"Vietnamese Tokenize: \",TK) IPA=\"\" for tk", "u'uə', u'uợ' : u'uə', } C_offglides = { u'ai' :", "u'gị' : u'zi'} Cus_qu = {u'quy' : u'kwi', u'qúy' :", ": u'iə', u'ỉa' : u'iə', u'ĩa' : u'iə', u'ịa' :", "(None, None, None, None) # Velar Fronting (Northern dialect) if", "onglides[nucl] elif nucl in onoffglides: cod = onoffglides[nucl][-1] nuc =", "the nuc accordingly if ons: # if there is an", ": u'ăw', u'ây' : u'ɤ̆j', u'ấy' : u'ɤ̆j', u'ầy' :", ": u'35g', u'ị' : u'21g', # u'o' : 33, u'ó'", "C S Cus_onsets = { u'b' : u'b', u't' :", "C_offglides = { u'ai' : u'aj', u'ái' : u'aj', u'ài'", "glottal, pham, cao, palatals, delimit).strip() for x in values] seq", "u'ɯw', u'ứu' : u'ɯw', u'ừu' : u'ɯw', u'ửu' : u'ɯw',", "prepared to show available onsets. Onsets are splitted into 3", "codas[word[l-1]] cOffset = 1 #if word[0:2] == u'gi' and cod", "ff. elif nuc in [u'iə', u'ɯə', u'uə', u'u', u'ɯ', u'ɤ',", "u'ʷa', u'oà' : u'ʷa', u'oả' : u'ʷa', u'oã' : u'ʷa',", "list(EN.keys()): letter2sound+=EN[CHAR]+\" \" else: letter2sound+=char+\" \" IPA+=T2IPA_split(letter2sound,\"\")+\" \" else: #Giữ", "45, u'ờ' : 32, u'ở' : 214, u'ỡ' : 214,", "u'i', u'uý' : u'i', u'uỳ' : u'i', u'uỷ' : u'i',", "'ʷi', 'vw', 'ăw', 'ʈw', 'ʂw', 'aʊ', 'fw', 'ɛu', 'tʰ', 'tʃ',", ": u'ʷɛ', u'ué' : u'ʷɛ', u'uè' : u'ʷɛ', u'uẻ' :", "if palatals == 1: if cod == u'k' and nuc", "u'ʷɤ', u'uỡ' : u'ʷɤ', u'uợ' : u'ʷɤ', u'uy' : u'ʷi',", ": u'ɛu', u'ểu' : u'ɛu', u'ễu': u'ɛu', u'ệu' : u'ɛu',", "routine for each substring ## and re-concatenate if (tokenize and", ": 2, u'ử' : 4, u'ữ' : 3, u'ự' :", "5, u'ò' : 2, u'ỏ' : 4, u'õ' : 3,", "u'é' : 24, u'è' : 32, u'ẻ' : 312, u'ẽ'", "from e to ɛ #âm cuối: ch : k theo", "u'iệ' : u'iə', u'oo' : u'ɔ', u'óo' : u'ɔ', u'òo'", "ton = u'5b' if ton == u'6' and cod in", "skip=len(l)-1 break if check == 0: #Case symbol not in", "của tiếng ANH #+Thêm xử lí case không có cũng", ": 4, u'ẫ' : 3, u'ậ' : 6, u'ắ' :", "u'ỹ' : 4, u'ỵ' : 6, } S_gi = {", "IPA+=Parsing(\"default\",tk.lower(),delimit)+\" \" else: IPA+=Parsing(\"default\",eng,delimit)+\" \" #Check tu dien tieng anh", "if T2IPA(line) in Pair: lin2 =Pair[T2IPA(line)] if line != lin2:", "onsets: # if onset is 'nh', 'gh', 'kʷ' etc ons", "junk words = [word for word in words if len(word)>0]", "u'uə', u'uỗ' : u'uə', u'uộ' : u'uə', u'ưa' : u'ɯə',", "u'ây' : u'ɤ̆j', u'ấy' : u'ɤ̆j', u'ầy' : u'ɤ̆j', u'ẩy'", "need to fix #oe <-> uê -> fix oe from", "45, u'ồ' : 32, u'ổ' : 214, u'ỗ' : 214,", ": u'ʷɛ', u'ỏe' : u'ʷɛ', u'õe' : u'ʷɛ', u'ọe' :", "u'y' : u'i', u'ý' : u'i', u'ỳ' : u'i', u'ỷ'", "Cus_offglides, Cus_onoffglides, Cus_qu, Cus_gi if pham or cao: if dialect", "u'o', u'ɔ', u'ă', u'ɤ̆']: if cod == u't': cod =", "u'uèo' : u'ew', u'uẻo' : u'ew', u'uẽo' : u'ew', u'uẹo'", "thay thế => k for c , t for t,", "print(\"IPA Vietnamese: \",IPA) print(\"------------------------------------------------------\") Results+= IPA.rstrip()+\" \"+delimit+\".\"+delimit+\" \" #For checking:", "u'ɯ', u'y' : u'i', u'ý' : u'i', u'ỳ' : u'i',", "'tʃ', 'ʷe', 'ɛu', 'ɔɪ', 'ʷi', 'eɪ', 'ɤj', 'ɯw', 'ɛj', 'ɔj',", "u'iệu' : u'iəw', u'yêu' : u'iəw', u'yếu' : u'iəw', u'yều'", "u'ẩu' : u'ɤ̆w', u'ẫu' : u'ɤ̆w', u'ậu' : u'ɤ̆w', u'eo'", "u'ấu' : u'ɤ̆w', u'ầu': u'ɤ̆w', u'ẩu' : u'ɤ̆w', u'ẫu' :", "u'c' : u'k', u'm' : u'm', u'n' : u'n', u'ng'", "u'ɤ̆']: if cod == u't': cod = u'k' if cod", "nhấn của tiếng anh \"'\" #print(vi2IPA_split(\"speech? Secondly, we paper, we", "u'ɤ̆', u'uậ' : u'ɤ̆', u'ue' : u'ɛ', u'ué' : u'ɛ',", ": u'iə', u'iể' : u'iə', u'iễ' : u'iə', u'iệ' :", "u'oét' : u'ʷet', u'oèt' : u'ʷet', u'oẻt' : u'ʷet', u'oẽt'", "u'ưởu' : u'ɯəw', 'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw' }", "'1', 'ʧ', 'ʈ', ' ', 'd', 'i', 'ɣ', 'ɲ', 'ɤ',", "u'o', u'ôố' : u'o', u'ôồ' : u'o', u'ôổ' : u'o',", "u'ào' : u'aw', u'ảo' : u'aw', u'ão' : u'aw', u'ạo'", "u'o', u'ộ' : u'o', u'ơ' : u'ɤ', u'ớ' : u'ɤ',", ": u'ăw', u'ạu' : u'ăw', u'ây' : u'ɤ̆j', u'ấy' :", "== 'gi', 'gì',... ons = gi[word][0] nuc = gi[word][1] elif", "u'ỳ' : 42, u'ỷ' : 312, u'ỹ' : 312, u'ỵ'", ": u'e', u'oé' : u'e', u'oè' : u'e', u'oẻ' :", "= 0 cOffset = 0 l = len(word) if l", "phoneme #Nếu không được check phoneme tiếng anh #Nếu không", "word): substrings = re.split(r'(_|-)', word) values = substrings[::2] delimiters =", ": 32, u'ả' : 214, u'ã' : 214, u'ạ' :", "4, u'ỗ' : 4, u'ộ' : 6, u'ớ' : 5,", "u'ɤ', u'uỡ' : u'ɤ', u'uợ' : u'ɤ', u'uy' : u'i',", ": u'e', u'i' : u'i', u'í' : u'i', u'ì' :", "(ons, nuc, cod, ton): seq = u'['+word+u']' else: seq =", "u'òeo' : u'ew', u'ỏeo' : u'ew', u'õeo' : u'ew', u'ọeo'", ": u'ɛ', u'uẹ' : u'ɛ', u'uê' : u'e', u'uế' :", "0 delimit = '' dialect='n' #\"c\"\"s\" tone_type=0 if tone_type==0: pham=1", "hợp dẫn đến trùng âm là: # Phương ngữ khác", "<-> ghen : ɣɛn1 ghì <-> gì : ɣi2 ghích", "u'ướ' : u'ɯə', u'ườ' : u'ɯə', u'ưở' : u'ɯə', u'ưỡ'", ": u'iə', u'uyà' : u'iə', u'uyả' : u'iə', u'uyã' :", "nghía <-> ngía : ŋiə5 nghịu <-> ngịu : ŋiw6", "'w', '1', 'ɪ', 'ɯ', 'd', '∫', 'p', 'ə', 'u', 'o',", "u'ợ' : u'21g', u'ú' : 13, u'ù' : 42, u'ủ'", "u'è' : 32, u'ẻ' : 312, u'ẽ' : u'35g', u'ẹ'", "not (pham or cao): if dialect == 'c': ton =", ": u'uə', u'uộ' : u'uə', u'ưa' : u'ɯə', u'ứa' :", "if (lin2[0]==\"k\" and line[0]==\"c\") or (lin2[-1] in ['i','í','ì','ĩ','ỉ','ị'] and line[-1]", "substrings[1::2] + [''] ipa = [convert(x, dialect, glottal, pham, cao,", "for tk in TK: ipa = T2IPA_split(tk,delimit).replace(\" \",\"_\") if ipa", "'ɤ̆', 'ŋw', 'ʊə', 'zi', 'ʷă', 'dw', 'eɪ', 'aɪ', 'ew', 'iə',", "is that e language to another by\",\"/\").replace(\"/\",\"\")) #Case need to", "system if cao == 1: if ton == u'5' and", "'' dialect='n' #\"c\"\"s\" tone_type=0 if tone_type==0: pham=1 else: cao=1 #Input", "pham = 0 cao = 0 palatals = 0 tokenize", "u'ù' : u'u', u'ủ' : u'u', u'ũ' : u'u', u'ụ'", "# used to use \\u02C0 for the unicode raised glottal", "palatals != 1 and nuc in [u'i', u'e', u'ɛ']: if", "compound def T2IPA(text): sys.path.append('./Rules') # make sure we can find", ": u'ʷiə', u'uyế' : u'ʷiə', u'uyề' : u'ʷiə', u'uyể' :", "iêu <-> yêu : iəw1 khoắng <-> khuắng : xwʷăŋ5", "fronting, see Thompson 1965:94 ff. elif nuc in [u'iə', u'ɯə',", "u'ʷɛ', u'uẹ' : u'ʷɛ', u'uê' : u'ʷe', u'uế' : u'ʷe',", "u'ờ' : 42, u'ở' : 312, u'ỡ' : 312, u'ợ'", "cod == u'ɲ': cod = u'ɲ' # u'ŋ' elif palatals", "cod in ['p', 't', 'k']: #if ton == u'21\\u02C0' and", ": 4, u'ặ' : 6, u'é' : 5, u'è' :", "syntax if dialect == 'n': onsets, nuclei, codas, tones, onglides,", "u'uẹo' : u'ew', u'uai' : u'aj', u'uái' : u'aj', u'uài'", ": u'ew', u'ẻo' : u'ew', u'ẽo' : u'ew', u'ẹo' :", ": 5, u'ừ' : 2, u'ử' : 4, u'ữ' :", ": 6, } C_gi = { u'gi' : u'ji', u'gí':", "u'ồ' : 2, u'ổ' : 4, u'ỗ' : 3, u'ộ'", "qu[word][-1] else: # Something is non-Viet return (None, None, None,", ": 312, u'ũ' : u'35g', u'ụ' : u'21g', u'ứ' :", "\"*\": if tk.lower().upper() == tk: #print(\"ENGLISH\",tk) #Đọc tiếng anh từng", "check if tokenize is true ## if true, call this", "#grave \"oá\", \"oé\",\"óo\", \"uý\", \"à\",\"ằ\",\"ầ\",\"è\",\"ề\",\"ì\",\"ò\",\"ồ\",\"ờ\",\"ù\",\"ừ\",\"ỳ\",\"iề\",\"òa\",\"oằ\",\"òe\",\"oò\",\"uầ\",\"uề\",\"uồ\",\"ườ\",\"ùy\",\"ườ\",\"uyề\",\"yề\", #acute \"oà\", \"oè\",\"òo\", \"uỳ\", \"ả\",\"ẳ\",\"ẩ\",\"ẻ\",\"ể\",\"ỉ\",\"ỏ\",\"ổ\",\"ở\",\"ủ\",\"ử\",\"ỷ\",\"iể\",\"ỏa\",\"oẳ\",\"ỏe\",\"oỏ\",\"uẩ\",\"uể\",\"uổ\",\"ưở\",\"ủy\",\"ưở\",\"uyể\",\"yể\",", "onsets which has one letter \",\"/\")) #Lọc bỏ dấu nhấn", "by\",\"/\").replace(\"/\",\"\")) #Case need to be deal: # NIYE BoOK #print(len(getSymbol()))", "Cus_onsets = { u'b' : u'b', u't' : u't', u'th'", "gíp : zip5 gen <-> ghen : ɣɛn1 ghì <->", "u'ỡ' : 3, u'ợ' : 6, u'ú' : 5, u'ù'", "# u'ê' : 33, u'ế' : 24, u'ề' : 32,", "trùng âm là: # Phương ngữ khác nhau đã thống", "u'ũy' : u'uj', u'ụy' : u'uj', #thay để hạn chế", ": u'ɤ', u'u' : u'u', u'ú' : u'u', u'ù' :", "u'ửa' : u'ɯə', u'ữa' : u'ɯə', u'ựa' : u'ɯə', u'ươ'", "2008 to fix aberrant 33 error tonelist = [tones[word[i]] for", "u'é' : 5, u'è' : 2, u'ẻ' : 4, u'ẽ'", ": 3, u'ỵ' : 6, } N_gi = { u'gi'", "for i in range(0,len(words)): word = words[i].strip() ortho += word", "################################ #Looking for pair Pair = {} for lt in", "= onglides[nucl] elif nucl in onoffglides: cod = onoffglides[nucl][-1] nuc", "u'21g', } # used to use \\u02C0 for raised glottal", "u'ɯj', u'ựi' : u'ɯj', u'ưu' : u'ɯw', u'ứu' : u'ɯw',", "if nor==\"\": cout+=1 print(line) print(\"Number of token can not convert:", ": 3, u'ợ' : 6, u'ú' : 5, u'ù' :", "u'ʷi', u'uỵ' : u'ʷi', u'ơi' : u'ɤj', u'ới' : u'ɤj',", ": u'21g', u'ắ' : 13, u'ằ' : 42, u'ẳ' :", "u'ườ' : u'ɯə', u'ưở' : u'ɯə', u'ưỡ' : u'ɯə', u'ượ'", "u'ʷi', u'uỵ' : u'ʷi', u'uya' : u'ʷiə', u'uyá' : u'ʷiə',", "labiovelar onset elif nucl in onglides and ons == u'kw':", "u'uậy' : u'ɤ̆j' } N_codas = { u'p' : u'p',", "cout+=1 print(line) print(\"Number of token can not convert: \",cout) print(\"Number", ": u'ɛ', u'è' : u'ɛ', u'ẻ' : u'ɛ', u'ẽ' :", ": u'o', u'ôô' : u'o', u'ôố' : u'o', u'ôồ' :", "u'óe' : u'e', u'òe' : u'e', u'ỏe' : u'e', u'õe'", "<-> toè : twʷɛ2 ua <-> uơ : uə1 ưa", "u'ả' : 4, u'ã' : 3, u'ạ' : 6, u'ấ'", "u'uyệ' : u'iə', u'uyu' : u'iu', u'uyú' : u'iu', u'uyù'", "u'ặ' : 212, u'é' : 45, u'è' : 32, u'ẻ'", ": u'iw', u'íu' : u'iw', u'ìu' : u'iw', u'ỉu' :", "u'ʷɛ', u'uẽ' : u'ʷɛ', u'uẹ' : u'ʷɛ', u'uê' : u'ʷe',", "u'uợ' : u'uə', } N_offglides = { u'ai' : u'aj',", "nucl in onoffglides: cod = onoffglides[nucl][-1] nuc = onoffglides[nucl][0:-1] if", "u'6' and cod in ['p', 't', 'k']: ton = u'6b'", "u'gi': u'z'} N_nuclei = { u'a' : u'a', u'á' :", "'g', '4', 'n', ';', 'r', 'b', 'ɯ', 'a', 's', 'ʐ',", "độ âm sắc chỉ dừng từ 1->6 #học ác cho", "delimit, IPA) IPA=re.sub(' +', ' ', IPA) print(\"IPA Vietnamese: \",IPA)", "u'uệ' : u'e', u'uơ' : u'ɤ', u'uớ' : u'ɤ', u'uờ'", "u'ầ' : 2, u'ẩ' : 4, u'ẫ' : 4, u'ậ'", "Pair = {} for lt in List_pair: Pair[T2IPA(lt)] = lt", "1 if word[l-2:l] in codas: # if two-character coda cod", "u'ɯə', u'ửa' : u'ɯə', u'ữa' : u'ɯə', u'ựa' : u'ɯə',", "u'35g', u'ỵ' : u'21g', } # used to use \\u02C0", "'aj', 'iə', 'iw', 'əʊ', 'ɑ:', 'tʃ', 'ʷe', 'ɛu', 'ɔɪ', 'ʷi',", "u'ew', u'ueo' : u'ew', u'uéo' : u'ew', u'uèo' : u'ew',", "'t∫', 'ɪə', 'ʷă', 'ɜ:', 'tʰ', 'dʒ', 'ew', 'ʊə', 'ɯə', 'aw',", "khuơ : xuə1 lóe <-> loé : lwʷɛ5 ngét <->", "u'ế' : 13, u'ề' : 42, u'ể' : 312, u'ễ'", "ton)))+delimit except (TypeError): pass return seq ########################333 from vinorm import", ": u'e', u'oe' : u'e', u'óe' : u'e', u'òe' :", "in [u'u', u'o', u'ɔ']: if cod == u'ŋ': cod =", "u'ăj', u'uáy' : u'ăj', u'uày' : u'ăj', u'uảy' : u'ăj',", "S_onoffglides = { u'oe' : u'ej', u'oé' : u'ej', u'oè'", "== 's': tones_p = S_tones_p #Custom tones_p = Cus_tones_p tones", "gin : zin1 díp <-> gíp : zip5 gen <->", "in ['p', 't', 'k']: ton = u'5b' if ton ==", "[\".\",\",\",\"!\",\":\",\"?\",\";\",\"'\"] #\" ' ( ) Have been removed due to", "=> dùng etrain cho tiếng anh #+Deal case thống nhất", "3, u'ự' : 6, u'ý' : 5, u'ỳ' : 2,", "word[i] in tones] if tonelist: ton = str(tonelist[len(tonelist)-1]) else: if", "t theo nam -> custom k vì nó giảm trùng", "u'iə', u'ĩa' : u'iə', u'ịa' : u'iə', u'ia' : u'iə',", "u'uắ' : u'ă', u'uằ' : u'ă', u'uẳ' : u'ă', u'uẵ'", "u'ữ' : 214, u'ự' : 212, u'ý' : 45, u'ỳ'", "u'k': cod = u'k͡p' return (ons, nuc, cod, ton) def", "u'iə', u'uyả' : u'iə', u'uyã' : u'iə', u'uyạ' : u'iə',", "u'iə', u'iạ' : u'iə', u'iê' : u'iə', u'iế' : u'iə',", "u'uyu' : u'iu', u'uyú' : u'iu', u'uyù' : u'iu', u'uyủ'", "chung làm một #Disable convert from 'ɲ' to 'ɲ'' in", "in tones] if tonelist: ton = str(tonelist[len(tonelist)-1]) else: if not", "6, } S_gi = { u'gi' : u'ji', u'gí': u'ji',", ": u'uə', u'úa' : u'uə', u'ùa' : u'uə', u'ủa' :", "u'j', u'h' : u'h', u'p' : u'p', u'qu' : u'w',", "if tok not in content or \"[\" in T2IPA(tok): checkinvalid=1", "= '' cod = '' ton = 0 seq =", "u'a', u'uà' : u'a', u'uả' : u'a', u'uã' : u'a',", "312, u'ệ' : u'21g', u'í' : 13, u'ì' : 42,", ": u'a', u'oả' : u'a', u'oã' : u'a', u'oạ' :", "u'ói' : u'ɔj', u'òi' : u'ɔj', u'ỏi' : u'ɔj', u'õi'", "= u't' if cod == u'ŋ': cod = u'n' #", "u'iə', u'iệ' : u'iə', u'oo' : u'ɔ', u'óo' : u'ɔ',", "if CHAR in list(EN.keys()): letter2sound+=EN[CHAR]+\" \" else: letter2sound+=char+\" \" IPA+=T2IPA_split(letter2sound,delimit)+\"", "u'r' : u'ʐ', u's' : u'ʂ', u'gi': u'j'} Cus_nuclei =", "xử lí case không có cũng như case Tiếng anh:", "u'ì' : 32, u'ỉ' : 214, u'ĩ' : 214, u'ị'", "== 1: if cod == u'k' and nuc in [u'i',", "u'en', u'oèn' : u'en', u'oẻn' : u'en', u'oẽn' : u'en',", "'θ', 'v', 'ʊ', 'ʤ', 'ɔ', '1', 'ʧ', 'ʈ', ' ',", "một #Disable convert from 'ɲ' to 'ɲ'' in north #Các", "voice if (dialect == 'n' or dialect == 's') and", "## hack to get rid of single hyphens or underscores", "u'ɤ̆j', u'uậy' : u'ɤ̆j' } Cus_codas = { u'p' :", "if res not in check_sym: Results[ine]=\"'\" ''' return Results.rstrip() def", ": 214, u'ỹ' : 214, u'ỵ' : 212, } S_tones_p", ": u'ɯəj', u'ưởi' : u'ɯəj', u'ưỡi' : u'ɯəj', u'ượi' :", "để hạn chế trùng âm u'uy' : u'ʷi', u'uý' :", ": u'et', u'oẻt' : u'et', u'oẽt' : u'et', u'oẹt' :", "'ɜ:', 'kw', 'nw', 't∫', 'ɲw', 'eo', 'sw', 'tw', 'ʐw', 'iɛ',", "4, u'ỹ' : 3, u'ỵ' : 6, } Cus_gi =", "u'aw', u'oão' : u'aw', u'oạo' : u'aw', u'oeo' : u'ew',", "there isn't an onset.... ons = u'ʔ'+nuclei[nucl] # add a", "8-tone system if cao == 1: if ton == u'5'", "= u'' words = line.split() ## toss len==0 junk words", "u'aj', u'oải' : u'aj', u'oãi' : u'aj', u'oại' : u'aj',", ": u'ŋ', u'nh' : u'ɲ', u'ch' : u'tʃ' } Cus_tones_p", "'ʊə', 'zi', 'ʷă', 'dw', 'eɪ', 'aɪ', 'ew', 'iə', 'ɣw', 'zw',", "N_offglides, N_onoffglides, N_qu, N_gi elif dialect == 'c': onsets, nuclei,", "onoffglides[nucl][0:-1] if ons != u'kw': if ons: ons = ons+u'w'", "#For checking: need much memory ''' check_sym=\"ɯəjɤ̆jʷiəɤ̆wɯəwʷetiəwuəjʷentʰwʷɤ̆ʷiukwiŋ͡mk͡pcwjwuəeəbwojʷivwăwʈwʂwaʊfwɛutʰtʃɔɪxwʷɤɤ̆ŋwʊəziʷădweɪaɪewiəɣwzwɯjʷɛɯwɤjɔ:əʊʷamwɑ:hwɔjujlwɪəăju:awɛjiwajɜ:kwnwt∫ɲweoswtwʐwiɛʷei:ɯədʒɲθʌlw1ɪɯd∫pəuo3ɣ!ðʧ6ʒʐzvgă_æɤ2ʤi.ɒbhnʂɔɛkm5cjxʈ,4ʊsŋaʃ?r:ηf;et'\" for ine,res in", "6, u'ế' : 5, u'ề' : 2, u'ể' : 4,", "u'ồi' : u'oj', u'ổi' : u'oj', u'ỗi' : u'oj', u'ội'", "0 cOffset = 0 l = len(word) if l >", ": u'uj', u'ụi' : u'uj', u'uy' : u'uj', u'úy' :", "if eng[-1] == \"*\": if tk.lower().upper() == tk: #Đọc tiếng", "v,d in zip(ipa, delimiters)) else: seq = convert(word, dialect, glottal,", "in onsets: # if there isn't an onset.... ons =", "u'u', u'ù' : u'u', u'ủ' : u'u', u'ũ' : u'u',", "1 are onsets which has one letter \",\"/\")) #Lọc bỏ", "not in onsets: # if there isn't an onset.... ons", "(ons, nuc, cod, ton) = trans(word, dialect, glottal, pham, cao,", "cod = u'ŋ͡m' if cod == u'k': cod = u'k͡p'", ": u'35g', u'ậ' : u'21g', # u'ă' : 33, u'ắ'", "u'uễ' : u'e', u'uệ' : u'e', u'uơ' : u'ɤ', u'uớ'", "def T2IPA_split(text,delimit): sys.path.append('./Rules') # make sure we can find the", ": 45, u'ờ' : 32, u'ở' : 214, u'ỡ' :", "\"à\",\"ằ\",\"ầ\",\"è\",\"ề\",\"ì\",\"ò\",\"ồ\",\"ờ\",\"ù\",\"ừ\",\"ỳ\",\"iề\",\"òa\",\"oằ\",\"òe\",\"oò\",\"uầ\",\"uề\",\"uồ\",\"ườ\",\"ùy\",\"ườ\",\"uyề\",\"yề\", #acute \"oà\", \"oè\",\"òo\", \"uỳ\", \"ả\",\"ẳ\",\"ẩ\",\"ẻ\",\"ể\",\"ỉ\",\"ỏ\",\"ổ\",\"ở\",\"ủ\",\"ử\",\"ỷ\",\"iể\",\"ỏa\",\"oẳ\",\"ỏe\",\"oỏ\",\"uẩ\",\"uể\",\"uổ\",\"ưở\",\"ủy\",\"ưở\",\"uyể\",\"yể\", #hook \"oả\", \"oẻ\",\"ỏo\", \"uỷ\",", "u'ŋ', u'nh' : u'n', u'ch' : u't' } S_tones =", "if skip>0: skip=skip-1 continue for l in listParse: if len(l)", ": u'ɤj', u'ời' : u'ɤj', u'ởi' : u'ɤj', u'ỡi' :", ": u'35g', u'ạ' : u'21g', u'ấ' : 24, u'ầ' :", ": u'ăj', u'uây' : u'ɤ̆j', u'uấy' : u'ɤ̆j', u'uầy' :", ": u's', u'd' : u'j', u'h' : u'h', u'p' :", "pham, cao, palatals, delimit).strip() for x in values] seq =", "u'oẻt' : u'et', u'oẽt' : u'et', u'oẹt' : u'et' }", ": zip5 gen <-> ghen : ɣɛn1 ghì <-> gì", "u'oă' : u'ʷă', u'oắ' : u'ʷă', u'oằ' : u'ʷă', u'oẳ'", "\"t\" không phân âm được => ý tưởng mượn \"tʃ\"", "đều như một > must consider (nhưng nếu thêm vào", "u'uạ' : u'a', u'uă' : u'ă', u'uắ' : u'ă', u'uằ'", ": u'e', u'uễ' : u'e', u'uệ' : u'e', u'uơ' :", "u'i', u'uỵ' : u'i', u'uya' : u'iə', u'uyá' : u'iə',", "u'n', u'ng' : u'ŋ', u'nh' : u'ɲ', u'ch' : u'k'", "u'ỏo' : u'ɔ', u'õo' : u'ɔ', u'ọo' : u'ɔ', u'oo'", "removed due to none sound modifi = [\"k͡p\",\"ŋ͡m\"] symbols =", "#print(vi2IPA_split(\"Another table was prepared to show available onsets. Onsets are", "u'ể' : 312, u'ễ' : u'35g', u'ệ' : u'21g', #", ": u'ew', u'uèo' : u'ew', u'uẻo' : u'ew', u'uẽo' :", "u'ɯ', u'ɤ', u'o', u'ɔ', u'ă', u'ɤ̆']: if cod == u't':", "investigate work! One is that e language to another by\",\"/\").replace(\"/\",\"\"))", "u'ɤ̆j' } C_codas = { u'p' : u'p', u't' :", "312, u'ẵ' : u'35g', u'ặ' : u'21g', # u'e' :", ": u'21g', # u'u' : 33, u'ú' : 24, u'ù'", "u'ỏe' : u'ʷɛ', u'õe' : u'ʷɛ', u'ọe' : u'ʷɛ', u'ua'", "u'ủ' : 214, u'ũ' : 214, u'ụ' : 212, u'ứ'", "u'uə', u'uồ' : u'uə', u'uổ' : u'uə', u'uỗ' : u'uə',", ": 312, u'ẫ' : 312, u'ậ' : u'21g', u'ắ' :", "= [\"k͡p\",\"ŋ͡m\"] symbols = list_phoneme + space+word_pad + English_phoneme +", "2, u'ể' : 4, u'ễ' : 3, u'ệ' : 6,", "if (tokenize and '-' in word) or (tokenize and '_'", "cod, ton): seq = u'['+word+u']' else: seq = delimit+delimit.join(filter(None, (ons,", "C_onoffglides, C_qu, C_gi, N_onsets, N_nuclei, N_codas#, N_tones , N_onglides, N_offglides,", "IPA.rstrip()+\" \"+delimit+\".\"+delimit+\" \" #For checking: need much memory ''' check_sym=\"ɯəjɤ̆jʷiəɤ̆wɯəwʷetiəwuəjʷentʰwʷɤ̆ʷiukwiŋ͡mk͡pcwjwuəeəbwojʷivwăwʈwʂwaʊfwɛutʰtʃɔɪxwʷɤɤ̆ŋwʊəziʷădweɪaɪewiəɣwzwɯjʷɛɯwɤjɔ:əʊʷamwɑ:hwɔjujlwɪəăju:awɛjiwajɜ:kwnwt∫ɲweoswtwʐwiɛʷei:ɯədʒɲθʌlw1ɪɯd∫pəuo3ɣ!ðʧ6ʒʐzvgă_æɤ2ʤi.ɒbhnʂɔɛkm5cjxʈ,4ʊsŋaʃ?r:ηf;et'\"", "u'kwi', u'qũy' : u'kwi', u'qụy' : u'kwi'} ####################################################### #central.py #coding:", "= gi[word][1] elif word in qu: # if word ==", "nuc == u'a': if cod == u'k' and cOffset ==", "trong từ tiếng anh -> đọc từng kí tự #Now", "ton == u'21g' and cod in ['p', 't', 'k']: #if", "'k']: ton = u'45' # Modification for 8-tone system if", "u'ɤ', u'ợ' : u'ɤ', u'u' : u'u', u'ú' : u'u',", ": u'et', u'oẹt' : u'et' } N_onoffglides = { u'oe'", "+ punctuation + tone + modifi + Special symbols =", "'jw', 'uə', 'eə', 'bw', 'oj', 'ʷi', 'vw', 'ăw', 'ʈw', 'ʂw',", "(tokenize and '_' in word): substrings = re.split(r'(_|-)', word) values", "u'ía' : u'iə', u'ìa' : u'iə', u'ỉa' : u'iə', u'ĩa'", "đây i chang không vòm: không có w ở trước", ": 2, u'ủ' : 4, u'ũ' : 4, u'ụ' :", "u'ũy' : u'uj', u'ụy' : u'uj', u'uy' : u'ʷi', u'úy'", "4, u'ỵ' : 6, } C_gi = { u'gi' :", "iuv,under_valid in enumerate(TK): token_under=under_valid.split(\" \") checkinvalid=0 print(token_under) if len(token_under) >1:", ": u'ɤ̆j', u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j' } Cus_codas", ": u'et' } N_onoffglides = { u'oe' : u'ej', u'oé'", "33, u'ớ' : 24, u'ờ' : 32, u'ở' : 312,", "'ɲw', 'cw', 'ʂw', 'ɣw', 'ʐw', 'xw', 'lw', 'hw', 'nw', 'sw',", "u'ỳ' : 32, u'ỷ' : 312, u'ỹ' : u'35g', u'ỵ'", "> 0: if word[0:3] in onsets: # if onset is", "nuc = gi[word][1] elif word in qu: # if word", "= TK[:iuv] + TK[iuv+1 :] for tok in reversed(token_under): TK.insert(iuv,", "w ở trước => Try to add ʷ Cus_onglides =", "u'ʷiə', u'uyễ' : u'ʷiə', u'uyệ' : u'ʷiə', u'uyu' : u'ʷiu',", "if there is no onset... ons = u'w' # add", "'zi', 'ʷă', 'dw', 'eɪ', 'aɪ', 'ew', 'iə', 'ɣw', 'zw', 'ɯj',", "#Same negative / need to fix #oe <-> uê ->", "'ɤ̆w', 'ɯəj', 'ʷen', 'ʷiu', 'ʷet', 'ɯəw', 'ʷɛ', 'ʷɤ', 'ɯj', 'oj',", "u'ỳ' : 2, u'ỷ' : 4, u'ỹ' : 3, u'ỵ'", "'k']: #if ton == u'21\\u02C0' and cod in ['p', 't',", "oe from e to ɛ #âm cuối: ch : k", "N_onoffglides, N_qu, N_gi elif dialect == 'c': onsets, nuclei, codas,", "u'zi', u'gĩ' : u'zi', u'gị' : u'zi'} N_qu = {u'quy'", "u'zi', u'gì' : u'zi', u'gĩ' : u'zi', u'gị' : u'zi'}", "4, u'ĩ' : 4, u'ị' : 6, u'ó' : 5,", "u'ại' : u'aj', u'ay' : u'ăj', u'áy' : u'ăj', u'ày'", "u'a', u'ỏa' : u'a', u'õa' : u'a', u'ọa' : u'a',", "u'ɛ']: if cod == u'ɲ': cod = u'ɲ' # u'ŋ'", "== 2: nuc = u'ɛ' if cod == u'ɲ' and", "'əʊ', 'ɑ:', 'tʃ', 'ʷe', 'ɛu', 'ɔɪ', 'ʷi', 'eɪ', 'ɤj', 'ɯw',", "'ɔ:', 'əʊ', 'ʷa', 'mw', 'ɑ:', 'hw', 'ɔj', 'uj', 'lw', 'ɪə',", "u'é' : 13, u'è' : 42, u'ẻ' : 312, u'ẽ'", "u'ẫy' : u'ɤ̆j', u'ậy' : u'ɤ̆j', u'âu' : u'ɤ̆w', u'ấu'", "u'ễ' : 4, u'ệ' : 6, u'í' : 5, u'ì'", "u'ɛj', u'oè' : u'ɛj', u'oẻ' : u'ɛj', u'oẽ' : u'ɛj',", "'uə', 'eə', 'bw', 'oj', 'ʷi', 'vw', 'ăw', 'ʈw', 'ʂw', 'aʊ',", "'ʷɤ̆', 'ɤ̆j', 'ŋ͡m', 'kwi', 'ɤ̆w', 'ɯəj', 'ʷen', 'ʷiu', 'ʷet', 'ɯəw',", ": u'uə', u'uổ' : u'uə', u'uỗ' : u'uə', u'uộ' :", "'ɣw', 'ʐw', 'xw', 'lw', 'hw', 'nw', 'sw', 'c'] word_pad =", "<-> ngịu : ŋiw6 nghoèo <-> ngoèo : ŋwew2 quít", "8 Nov 2016 ton = u'21' # Modification for sắc", "C_qu = {u'quy' : u'wi', u'qúy' : u'wi', u'qùy' :", "u'ởi' : u'ɤj', u'ỡi' : u'ɤj', u'ợi' : u'ɤj', u'ưi'", "#print(List_token) print(len(List_token)) ################################ #Looking for pair Pair = {} for", ": 13, u'ờ' : 42, u'ở' : 312, u'ỡ' :", ": u'aj', u'ay' : u'ăj', u'áy' : u'ăj', u'ày' :", ": u'ɯəw', u'ượu' : u'ɯəw' } N_onglides = { u'oa'", "= \"'\" if listParse == \"default\": listParse=['ʷiə', 'uəj', 'iəw', 'k͡p',", "u'ʷɛ', u'ué' : u'ʷɛ', u'uè' : u'ʷɛ', u'uẻ' : u'ʷɛ',", ": u'a', u'ọa' : u'a', u'oă' : u'ă', u'oắ' :", "find the Rules files #Setup option glottal = 0 pham", "4, u'ọ' : 6, u'ố' : 5, u'ồ' : 2,", "'kʷ' etc ons = onsets[word[0:2]] oOffset = 2 elif word[0]", "#Neu co de nguyen #Neu khong danh van print(\" ..................Out", "u'ưa' : u'ɯə', u'ứa' : u'ɯə', u'ừa' : u'ɯə', u'ửa'", "#Same positive #k <-> c #g <-> gh #i <->", "u'ủy' : u'uj', u'ũy' : u'uj', u'ụy' : u'uj', #thay", "u'35g', u'ự' : u'21g', u'ý' : 24, u'ỳ' : 32,", "u'ăj', u'ày' : u'ăj', u'ảy' : u'ăj', u'ãy' : u'ăj',", "'ʌ', 'l', 'w', '1', 'ɪ', 'ɯ', 'd', '∫', 'p', 'ə',", "'i:', 't∫', 'ɪə', 'ʷă', 'ɜ:', 'tʰ', 'dʒ', 'ew', 'ʊə', 'ɯə',", "u'35g', u'ị' : u'21g', # u'o' : 33, u'ó' :", "u'ʷɛ', u'òe' : u'ʷɛ', u'ỏe' : u'ʷɛ', u'õe' : u'ʷɛ',", "== u'24') or (dialect == 'c' and ton == u'13'))", "TK[iuv+1 :] for tok in reversed(token_under): TK.insert(iuv, tok) IPA=\"\" for", "and ipa[-1]==\"]\": eng = eng_to_ipa.convert(tk) if eng[-1] == \"*\": if", "u'ueo' : u'ew', u'uéo' : u'ew', u'uèo' : u'ew', u'uẻo'", "u'ẫ' : 312, u'ậ' : u'21g', u'ắ' : 13, u'ằ'", "u'ŋ' elif palatals != 1 and nuc in [u'i', u'e',", "elif palatals != 1 and nuc in [u'i', u'e', u'ɛ']:", "#Đọc tiếng anh từng chữ letter2sound=\"\" for char in tk:", "undefine_symbol = \"'\" if listParse == \"default\": listParse=['ʷiə', 'uəj', 'iəw',", "if tokenize is true ## if true, call this routine", "', IPA) print(\"IPA Vietnamese: \",IPA) print(\"------------------------------------------------------\") return IPA def checkDict():", "214, u'ẹ' : 212, u'ế' : 45, u'ề' : 32,", "tiếng anh -> đọc từng kí tự #Now #+Thêm kí", ": u'i', u'ỳ' : u'i', u'ỷ' : u'i', u'ỹ' :", "'i', '.', 'ɒ', 'b', 'h', 'n', 'ʂ', 'ɔ', 'ɛ', 'k',", "len(l) <= len(text[ic:]) and l == text[ic:ic+len(l)]: output+=delimit+l check =1", "u'iu', u'uyũ' : u'iu', u'uyụ' : u'iu', u'uyu' : u'iu',", ": u'k', u'gh' : u'ɣ', u'r' : u'z', u's' :", "line != lin2: if (lin2[0]==\"k\" and line[0]==\"c\") or (lin2[-1] in", "a glottal stop else: # otherwise... nuc = nuclei[nucl] #", "SET=[S_onsets, S_nuclei, S_codas#, S_tones , S_onglides, S_offglides, S_onoffglides, S_qu, S_gi,", "N_tones = { u'á' : 24, u'à' : 32, u'ả'", "cũng ra w) #Try to add ʷ to all start", ": 312, u'ộ' : u'21g', u'ớ' : 13, u'ờ' :", "from optparse import OptionParser from string import punctuation def trans(word,", "tokenize = 0 delimit = '' dialect='n' #\"c\"\"s\" tone_type=0 if", "in check_sym: Results[ine]=\"'\" ''' return Results.rstrip() def vi2IPA(text): print(\"------------------------------------------------------\") TN=", "elif nucl in offglides: cod = offglides[nucl][-1] nuc = offglides[nucl][:-1]", "in symbol :\"+ char+\":\") output+=delimit+undefine_symbol return output.rstrip()+delimit #print(\"Parsing\",Parsing(\"default\",\"iu iu\",\"|\")) def", ": u'uə', u'uợ' : u'uə', } S_offglides = { u'ai'", "312, u'ĩ' : u'35g', u'ị' : u'21g', u'ó' : 24,", ": u'ɯə', u'ướ' : u'ɯə', u'ườ' : u'ɯə', u'ưở' :", ": u'ă', u'oẳ' : u'ă', u'oẵ' : u'ă', u'oặ' :", "u'eo', u'ẹo' : u'eo', u'êu' : u'ɛu', u'ếu' : u'ɛu',", "u'ỹ' : u'i', u'ỵ' : u'i', u'eo' : u'eo', u'éo'", ": u'et', u'oét' : u'et', u'oèt' : u'et', u'oẻt' :", "chữ letter2sound=\"\" for char in tk: CHAR = str(char).lower() if", ": u'ɤ', u'uớ' : u'ɤ', u'uờ' : u'ɤ', u'uở' :", ": 42, u'ổ' : 312, u'ỗ' : 312, u'ộ' :", "cod = codas[word[l-2:l]] cOffset = 2 elif word[l-1] in codas:", ": 4, u'ộ' : 6, u'ớ' : 5, u'ờ' :", "from string import punctuation def trans(word, dialect, glottal, pham, cao,", "0 oOffset = 0 cOffset = 0 l = len(word)", "N_onglides = { u'oa' : u'a', u'oá' : u'a', u'oà'", "nuclei[nucl] # there's your nucleus else: # otherwise... nuc =", "ton = u'21' # Modification for sắc in closed syllables", ": u'ew', u'uẽo' : u'ew', u'uẹo' : u'ew', u'uai' :", "= u'u' if nuc == u'ɯə': nuc = u'ɯ' #", ": 24, u'ỳ' : 32, u'ỷ' : 312, u'ỹ' :", "(lin2[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ'] and line[-1] in ['i','í','ì','ĩ','ỉ','ị']): continue cout_same+=1 print(line+", "S_codas#, S_tones , S_onglides, S_offglides, S_onoffglides, S_qu, S_gi, C_onsets, C_nuclei,", "check == 0: #Case symbol not in list if str(char)", ": u'21g', u'ứ' : 13, u'ừ' : 42, u'ử' :", "u'ʷɛ', u'oè' : u'ʷɛ', u'oẻ' : u'ʷɛ', u'oẽ' : u'ʷɛ',", "a coda... nucl = u'i' ons = u'z' else: nucl", ": u'zi', u'gị' : u'zi'} Cus_qu = {u'quy' : u'kwi',", "'ɯ', 'd', '∫', 'p', 'ə', 'u', 'o', '3', 'ɣ', '!',", "u'oặ' : u'ă', u'oe' : u'e', u'oé' : u'e', u'oè'", "u'oẹt' : u'et' } C_onoffglides = { u'oe' : u'ej',", ": 45, u'ầ' : 32, u'ẩ' : 214, u'ẫ' :", "u'ɔ', u'oò' : u'ɔ', u'oỏ' : u'ɔ', u'oõ' : u'ɔ',", "u'ɤ̆w', u'ẫu' : u'ɤ̆w', u'ậu' : u'ɤ̆w', u'eo' : u'ew',", "cao): if dialect == 'c': ton = str('35') else: ton", ": u'ɯ', u'ừ' : u'ɯ', u'ử' : u'ɯ', u'ữ' :", "u'ò' : u'ɔ', u'ỏ' : u'ɔ', u'õ' : u'ɔ', u'ọ'", "u'ưới' : u'ɯəj', u'ười' : u'ɯəj', u'ưởi' : u'ɯəj', u'ưỡi'", "u'ɤ̆j', u'âu' : u'ɤ̆w', u'ấu' : u'ɤ̆w', u'ầu': u'ɤ̆w', u'ẩu'", "5, u'ờ' : 2, u'ở' : 4, u'ỡ' : 4,", "u'oen' : u'ʷen', u'oén' : u'ʷen', u'oèn' : u'ʷen', u'oẻn'", "u'ữu' : u'ɯw', u'ựu' : u'ɯw', u'iêu' : u'iəw', u'iếu'", "u'ều' : u'ɛu', u'ểu' : u'ɛu', u'ễu': u'ɛu', u'ệu' :", "5, u'ù' : 2, u'ủ' : 4, u'ũ' : 4,", "None, None, None) # Velar Fronting (Northern dialect) if dialect", "u'o', u'ổô' : u'o', u'ỗô' : u'o', u'ộô' : u'o',", "ons = gi[word][0] nuc = gi[word][1] elif word in qu:", "u'ɯəw', 'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw' } C_onglides =", ": u'ɤj', u'ởi' : u'ɤj', u'ỡi' : u'ɤj', u'ợi' :", "C_nuclei, C_codas, C_tones, C_onglides, C_offglides, C_onoffglides, C_qu, C_gi elif dialect", "u'uỹu' : u'ʷiu', u'uỵu' : u'ʷiu', u'oen' : u'ʷen', u'oén'", "u'ʷa', u'oă' : u'ʷă', u'oắ' : u'ʷă', u'oằ' : u'ʷă',", "u'ʷiu', u'oen' : u'ʷen', u'oén' : u'ʷen', u'oèn' : u'ʷen',", "u'ỷ' : 312, u'ỹ' : 312, u'ỵ' : u'21g', }", "u'ẹ' : 6, u'ế' : 5, u'ề' : 2, u'ể'", ": u'uə', u'uồ' : u'uə', u'uổ' : u'uə', u'uỗ' :", "u'uê' : u'e', u'uế' : u'e', u'uề' : u'e', u'uể'", ": u'x', u'g' : u'ɣ', u'l' : u'l', u'm' :", "are modal voice if (dialect == 'n' or dialect ==", "':', 't', 'ʒ', 'ə', 'ʌ', 'm', '!', '∫', 'ð', 'u',", ": u'ʷiu', u'uýu' : u'ʷiu', u'uỳu' : u'ʷiu', u'uỷu' :", "u'ɤ̆j', u'ấy' : u'ɤ̆j', u'ầy' : u'ɤ̆j', u'ẩy' : u'ɤ̆j',", "0 pham = 0 cao = 0 palatals = 0", "word[0:3] in onsets: # if onset is 'ngh' ons =", "cao=1 #Input text line = text if line =='\\n': return", "u'a', u'uă' : u'ă', u'uắ' : u'ă', u'uằ' : u'ă',", "u'oá' : u'ʷa', u'oà' : u'ʷa', u'oả' : u'ʷa', u'oã'", "u'uẽ' : u'ɛ', u'uẹ' : u'ɛ', u'uê' : u'e', u'uế'", "nor = T2IPA(line) if nor in List_token: print(line + \"", "u'ʷɛ', u'oẽ' : u'ʷɛ', u'oẹ' : u'ʷɛ', u'oe' : u'ʷɛ',", "u'ɔj', u'ỏi' : u'ɔj', u'õi' : u'ɔj', u'ọi' : u'ɔj',", "u'o', u'ồ' : u'o', u'ổ' : u'o', u'ỗ' : u'o',", "u'ɯəw', 'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw' } N_onglides =", "if nuc == u'iə': nuc = u'i' if nuc ==", "ở trước => Try to add ʷ Cus_onglides = {", "in words if word!=u'-'] words = [word for word in", ": 45, u'è' : 32, u'ẻ' : 214, u'ẽ' :", ": u'i', u'eo' : u'eo', u'éo' : u'eo', u'èo' :", "u'ʷɛ', u'uẻ' : u'ʷɛ', u'uẽ' : u'ʷɛ', u'uẹ' : u'ʷɛ',", "'iɛ', 'ɤ̆', 'ɔ:', 'ăj', 'ʷa', 'eə', 'u:', 'uj', 'aʊ', 'uə',", "u'ɤj', u'ới' : u'ɤj', u'ời' : u'ɤj', u'ởi' : u'ɤj',", ": u'ŋ', u'ng' : u'ŋ', u'nh' : u'n', u'ch' :", "u'o', u'ồô' : u'o', u'ổô' : u'o', u'ỗô' : u'o',", "u'i' : 33, u'í' : 24, u'ì' : 32, u'ỉ'", "u'ịu' : u'iw', u'oi' : u'ɔj', u'ói' : u'ɔj', u'òi'", ": 214, u'ạ' : 212, u'ấ' : 45, u'ầ' :", ": 312, u'ọ' : u'21g', u'ố' : 13, u'ồ' :", "Try to add ʷ Cus_onglides = { u'oa' : u'ʷa',", "u'qúy' : u'wi', u'qùy' : u'wi', u'qủy' : u'wi', u'qũy'", "word_tokenize import eng_to_ipa SET=[S_onsets, S_nuclei, S_codas#, S_tones , S_onglides, S_offglides,", "utf-8 N_onsets = { u'b' : u'b', u't' : u't',", "u'qu' : u'w', u'gi' : u'j', u'tr' : u'ʈ', u'k'", "etrain cho tiếng anh #+Deal case thống nhất âm vực", "2: ortho += ' ' if i < len(words)-1: seq", "u'yểu' : u'iəw', u'yễu' : u'iəw', u'yệu' : u'iəw', u'uôi'", ": u'a', u'uá' : u'a', u'uà' : u'a', u'uả' :", "u'ị' : u'21g', u'ó' : 13, u'ò' : 42, u'ỏ'", "u'ọ' : u'21g', # u'ô' : 33, u'ố' : 24,", "u'oải' : u'aj', u'oãi' : u'aj', u'oại' : u'aj', u'oay'", "u'ở' : 312, u'ỡ' : 312, u'ợ' : u'21g', u'ú'", "u'ẫ' : 4, u'ậ' : 6, u'ắ' : 5, u'ằ'", "u'ý' : 5, u'ỳ' : 2, u'ỷ' : 4, u'ỹ'", "u'ʷɛ', u'uè' : u'ʷɛ', u'uẻ' : u'ʷɛ', u'uẽ' : u'ʷɛ',", "u'oằ' : u'ă', u'oẳ' : u'ă', u'oẵ' : u'ă', u'oặ'", "u'a', u'ọa' : u'a', u'oă' : u'ă', u'oắ' : u'ă',", ": 4, u'ọ' : 6, u'ố' : 5, u'ồ' :", "212, u'ấ' : 45, u'ầ' : 32, u'ẩ' : 214,", "if you just have 'gi' and a coda... nucl =", "anh #Nếu không có trong từ tiếng anh -> đọc", "{ u'a' : u'a', u'á' : u'a', u'à' : u'a',", "in values] seq = ''.join(v+d for v,d in zip(ipa, delimiters))", ": 4, u'ẹ' : 6, u'ế' : 5, u'ề' :", "content=f.read().splitlines() for line in content: if T2IPA(line) in Pair: lin2", ": u'ew', u'uẹo' : u'ew', u'uai' : u'aj', u'uái' :", "u'uỷ' : u'ʷi', u'uỹ' : u'ʷi', u'uỵ' : u'ʷi', u'uya'", "if len(words) >= 2: ortho += ' ' if i", "u'ɤ', u'ờ' : u'ɤ', u'ở' : u'ɤ', u'ỡ' : u'ɤ',", "else: #Giữ nguyên IPA+=Parsing(\"default\",tk,\"\")+\" \" else: IPA+=eng+\" \" #Check tu", "u'gi' : u'zi', u'gí': u'zi', u'gì' : u'zi', u'gì' :", "N_offglides = { u'ai' : u'aj', u'ái' : u'aj', u'ài'", ": u'ɤj', u'ới' : u'ɤj', u'ời' : u'ɤj', u'ởi' :", "IPA) print(\"IPA Vietnamese: \",IPA) print(\"------------------------------------------------------\") Results+= IPA.rstrip()+\" \"+delimit+\".\"+delimit+\" \" #For", "IPA+=Parsing(\"default\",tk,\"\")+\" \" else: IPA+=eng+\" \" #Check tu dien tieng anh", "u'uê' : u'ʷe', u'uế' : u'ʷe', u'uề' : u'ʷe', u'uể'", "+', ' ', IPA) print(\"IPA Vietnamese: \",IPA) print(\"------------------------------------------------------\") return IPA", "elif word in gi: # if word == 'gi', 'gì',...", "u'oạy' : u'ăj', u'oao' : u'aw', u'oáo' : u'aw', u'oào'", "sys, codecs, re from io import StringIO from optparse import", "u'ĩ' : 4, u'ị' : 6, u'ó' : 5, u'ò'", "ʷ Cus_onglides = { u'oa' : u'ʷa', u'oá' : u'ʷa',", ": u'ɤ̆', u'ầ' : u'ɤ̆', u'ẩ' : u'ɤ̆', u'ẫ' :", "u'ew', u'ẽo' : u'ew', u'ẹo' : u'ew', u'iu' : u'iw',", "or (lin2[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ'] and line[-1] in ['i','í','ì','ĩ','ỉ','ị']): continue cout_same+=1", "'ɯw', 'ɤj', 'ɔ:', 'əʊ', 'ʷa', 'mw', 'ɑ:', 'hw', 'ɔj', 'uj',", "u'uy' : u'uj', u'úy' : u'uj', u'ùy' : u'uj', u'ủy'", "', 'c', 'j', 'x', 'ʈ', ',', '4', 'ʊ', 's', 'ŋ',", "u'ăj', u'oạy' : u'ăj', u'oao' : u'aw', u'oáo' : u'aw',", "# Something is non-Viet return (None, None, None, None) #", "<-> gìm : zim2 din <-> gin : zin1 díp", "u'uỳ' : u'ʷi', u'uỷ' : u'ʷi', u'uỹ' : u'ʷi', u'uỵ'", "'k', 'm', '5', ' ', 'c', 'j', 'x', 'ʈ', ',',", "punctuation + tone + modifi + Special symbols = list(set(symbols))", "[u'i', u'e', u'ɛ']: cod = u'c' # Velar Fronting (Southern", ": u'iə', u'iạ' : u'iə', u'iê' : u'iə', u'iế' :", "u'ảy' : u'ăj', u'ãy' : u'ăj', u'ạy' : u'ăj', u'ao'", ": u'35g', u'ộ' : u'21g', u'ớ' : 24, u'ờ' :", "'ʧ', '6', 'ʒ', 'ʐ', 'z', 'v', 'g', 'ă', '_', 'æ',", "make sure we can find the Rules files #Setup option", "= T2IPA(line) if nor in List_token: print(line + \" ->", "letter \",\"/\")) #Lọc bỏ dấu nhấn của tiếng anh \"'\"", "tok not in content or \"[\" in T2IPA(tok): checkinvalid=1 if", "'oj', 'ăw', 'zi', 'kw', 'aɪ', 'iɛ', 'ɤ̆', 'ɔ:', 'ăj', 'ʷa',", "'ɣ', '!', 'ð', 'ʧ', '6', 'ʒ', 'ʐ', 'z', 'v', 'g',", "u'ủ' : 312, u'ũ' : u'35g', u'ụ' : u'21g', u'ứ'", "u'oẽn' : u'ʷen', u'oẹn' : u'ʷen', u'oet' : u'ʷet', u'oét'", ": u'iə', u'ià' : u'iə', u'iả' : u'iə', u'iã' :", "nuc = '' cod = '' ton = 0 oOffset", "u'24') or (dialect == 'c' and ton == u'13')) and", "u'ă' : 33, u'ắ' : 24, u'ằ' : 32, u'ẳ'", "(Northern dialect) if dialect == 'n': if nuc == u'a':", "def vi2IPA(text): print(\"------------------------------------------------------\") TN= TTSnorm(text) print(\"------------------------------------------------------\") print(\"Text normalize: \",TN) TK=", "khoẻ : xwʷɛ4 khua <-> khuơ : xuə1 lóe <->", "S_gi #Custom onsets, nuclei, codas, onglides, offglides, onoffglides, qu, gi", ": u'ʷiu', u'uyủ' : u'ʷiu', u'uyũ' : u'ʷiu', u'uyụ' :", "= convert(word, dialect, glottal, pham, cao, palatals, delimit).strip() # concatenate", "u'ẩ' : u'ɤ̆', u'ẫ' : u'ɤ̆', u'ậ' : u'ɤ̆', u'ă'", "cùng \"ch\" \"c\" \"t\" không phân âm được => ý", "u'35g', u'ỵ' : u'21g', # } N_tones = { u'á'", "u'x' : u's', u'd' : u'j', u'h' : u'h', u'p'", "u'uẫ' : u'ʷɤ̆', u'uậ' : u'ʷɤ̆', u'ue' : u'ʷɛ', u'ué'", "u'ɯəw' } N_onglides = { u'oa' : u'a', u'oá' :", "u'ŋ': cod = u'n' # There is also this reverse", "= u'ɲ'#u'ŋ' if palatals == 1: if cod == u'k'", "ngía : ŋiə5 nghịu <-> ngịu : ŋiw6 nghoèo <->", "'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw' } N_onglides = {", "str('35') else: ton = str('33') else: ton = str('1') #", "'tʰ', 'dʒ', 'ew', 'ʊə', 'ɯə', 'aw', '3', 'θ', 'v', 'ʊ',", "u'ộô' : u'o', u'ôô' : u'o', u'ôố' : u'o', u'ôồ'", "u'ʷi', u'uý' : u'ʷi', u'uỳ' : u'ʷi', u'uỷ' : u'ʷi',", ": u'ɛj', u'oẽ' : u'ɛj', u'oẹ' : u'ɛj', u'oai' :", ": u'et', u'oẽt' : u'et', u'oẹt' : u'et' } N_onoffglides", "u'u', u'ɯ', u'ɤ', u'o', u'ɔ', u'ă', u'ɤ̆']: if cod ==", ": u'ew', u'oéo' : u'ew', u'oèo' : u'ew', u'oẻo' :", "u'oj', u'ội' : u'oj', u'ui' : u'uj', u'úi' : u'uj',", "and ons == u'kw': nuc = onglides[nucl] elif nucl in", "u'oẽ' : u'ɛj', u'oẹ' : u'ɛj', u'oai' : u'aj', u'oái'", "zin1 díp <-> gíp : zip5 gen <-> ghen :", "u'e', u'oé' : u'e', u'oè' : u'e', u'oẻ' : u'e',", "u'ẫ' : u'35g', u'ậ' : u'21g', # u'ă' : 33,", "nuc not in [u'i', u'e', u'ɛ']: if cod == u'ɲ':", "'o', '3', 'ɣ', '!', 'ð', 'ʧ', '6', 'ʒ', 'ʐ', 'z',", "else: #Giữ nguyên IPA+=Parsing(\"default\",tk.lower(),delimit)+\" \" else: IPA+=Parsing(\"default\",eng,delimit)+\" \" #Check tu", "u'ʷă', u'oẳ' : u'ʷă', u'oẵ' : u'ʷă', u'oặ' : u'ʷă',", "'x', 'ă'] listParse.sort(reverse = True,key=len) output=\"\" skip=0 for ic,char in", "u'eo' : u'eo', u'éo' : u'eo', u'èo' : u'eo', u'ẻo'", "với úi #Remain ''' di <-> gi : zi1 dìm", "212, u'ý' : 45, u'ỳ' : 32, u'ỷ' : 214,", "u'zi'} N_qu = {u'quy' : u'kwi', u'qúy' : u'kwi', u'qùy'", "u'aw', u'oảo' : u'aw', u'oão' : u'aw', u'oạo' : u'aw',", ": u'uə', } N_offglides = { u'ai' : u'aj', u'ái'", "print(line) print(\"Number of token can not convert: \",cout) print(\"Number of", "u'yệu' : u'iəw', u'uôi' : u'uəj', u'uối' : u'uəj', u'uồi'", "u'ɤ', u'ớ' : u'ɤ', u'ờ' : u'ɤ', u'ở' : u'ɤ',", "u'k' if cod == u'n': cod = u'ŋ' # Monophthongization", "'dʒ', 'ɲ', 'θ', 'ʌ', 'l', 'w', '1', 'ɪ', 'ɯ', 'd',", "== u'k' and nuc in [u'i', u'e', u'ɛ']: cod =", "word in words if word!=u'_'] for i in range(0,len(words)): word", "tess = texts.split(\".\") Results =\"\" for text in tess: print(\"------------------------------------------------------\")", "and line[-1] in ['i','í','ì','ĩ','ỉ','ị']): continue cout_same+=1 print(line+ \" <-> \"", "', 'd', 'i', 'ɣ', 'ɲ', 'ɤ', '?', 'ɪ', 'l', '.',", "'η', 'f', ';', 'e', 't', \"'\"] def Parsing(listParse, text, delimit):", "âm vòng ở đây i chang không vòm: không có", "Cus_codas, Cus_onglides, Cus_offglides, Cus_onoffglides, Cus_qu, Cus_gi if pham or cao:", "u'uə', u'uỡ' : u'uə', u'uợ' : u'uə', } N_offglides =", "\"oè\",\"òo\", \"uỳ\", \"ả\",\"ẳ\",\"ẩ\",\"ẻ\",\"ể\",\"ỉ\",\"ỏ\",\"ổ\",\"ở\",\"ủ\",\"ử\",\"ỷ\",\"iể\",\"ỏa\",\"oẳ\",\"ỏe\",\"oỏ\",\"uẩ\",\"uể\",\"uổ\",\"ưở\",\"ủy\",\"ưở\",\"uyể\",\"yể\", #hook \"oả\", \"oẻ\",\"ỏo\", \"uỷ\", \"ã\",\"ẵ\",\"ẫ\",\"ẽ\",\"ễ\",\"ĩ\",\"õ\",\"ỗ\",\"ỡ\",\"ũ\",\"ữ\",\"ỹ\",\"iễ\",\"õa\",\"oẵ\",\"õe\",\"oõ\",\"uẫ\",\"uễ\",\"uỗ\",\"ưỡ\",\"ũy\",\"ưỡ\",\"uyễ\",\"yễ\", #tilde \"oã\",", "u'ắ' : 5, u'ằ' : 2, u'ẳ' : 4, u'ẵ'", "u'35g', u'ạ' : u'21g', # u'â' : 33, u'ấ' :", "u'uỹ' : u'ʷi', u'uỵ' : u'ʷi', u'uya' : u'ʷiə', u'uyá'", "1982 C_tones = { u'á' : 13, u'à' : 42,", "in the same mapping:\",trung) List_token = list(set(List_token)) #print(List_token) print(len(List_token)) ################################", "u'ʈ', u'k' : u'k', u'c' : u'k', u'gh' : u'ɣ',", ": u'21g', # u'ê' : 33, u'ế' : 24, u'ề'", ": u'iə', u'uyạ' : u'iə', u'uyê' : u'iə', u'uyế' :", "} C_offglides = { u'ai' : u'aj', u'ái' : u'aj',", "u'uè' : u'ɛ', u'uẻ' : u'ɛ', u'uẽ' : u'ɛ', u'uẹ'", "u'ệu' : u'ɛu', u'ia' : u'iə', u'ía' : u'iə', u'ìa'", ": u'iə', u'uyễ' : u'iə', u'uyệ' : u'iə', u'uyu' :", "u'ɤ̆j' } Cus_codas = { u'p' : u'p', u't' :", "u'ɤj', u'ởi' : u'ɤj', u'ỡi' : u'ɤj', u'ợi' : u'ɤj',", "cod = u't' if cod == u'ŋ': cod = u'n'", "\"ch\", \"ph\",\"nh\",\"kh\",\"gi\",\"qu\", \"ngh\",\"ng\",\"gh\",\"g\",\"k\",\"c\"] #coding: utf-8 #Custom phoneme follow the https://vi.wikipedia.org/wiki/%C3%82m_v%E1%BB%8B_h%E1%BB%8Dc_ti%E1%BA%BFng_Vi%E1%BB%87t", "# if onset is 'ngh' ons = onsets[word[0:3]] oOffset =", "u'ʷɤ̆', u'uấ' : u'ʷɤ̆', u'uầ' : u'ʷɤ̆', u'uẩ' : u'ʷɤ̆',", "u'ôô' : u'o', u'ốô' : u'o', u'ồô' : u'o', u'ổô'", ": ŋɛu3 nghía <-> ngía : ŋiə5 nghịu <-> ngịu", "== u'k': cod = u'k͡p' return (ons, nuc, cod, ton)", ": u'ŋ', u'nh' : u'n', u'ch' : u't' } S_tones", "not in symbol :\"+ char+\":\") output+=delimit+undefine_symbol return output.rstrip()+delimit #print(\"Parsing\",Parsing(\"default\",\"iu iu\",\"|\"))", "== 1: if ton == u'5' and cod in ['p',", "u'á' : 13, u'à' : 42, u'ả' : 312, u'ã'", "3, u'ẹ' : 6, u'ế' : 5, u'ề' : 2,", "u'ew', u'ọeo' : u'ew', u'ueo' : u'ew', u'uéo' : u'ew',", "u'21g', # } N_tones = { u'á' : 24, u'à'", "u'ă', u'uẳ' : u'ă', u'uẵ' : u'ă', u'uặ' : u'ă',", ": 312, u'ẽ' : 312, u'ẹ' : u'21g', u'ế' :", "từ 1->6 #học ác cho kết quả \"c\" khác nhau", ": 13, u'ừ' : 42, u'ử' : 312, u'ữ' :", "in list(EN.keys()): letter2sound+=EN[CHAR]+\" \" else: letter2sound+=char+\" \" IPA+=T2IPA_split(letter2sound,\"\")+\" \" else:", "'a', 's', 'ʐ', 'η', 'ŋ', 'ɒ', 'ʂ', '_', 'f', ',',", "u'oèt' : u'et', u'oẻt' : u'et', u'oẽt' : u'et', u'oẹt'", "#coding: utf-8 S_onsets = { u'b' : u'b', u't' :", "u'o', u'ôổ' : u'o', u'ôỗ' : u'o', u'ôộ' : u'o',", "u'uyũ' : u'ʷiu', u'uyụ' : u'ʷiu', u'uyu' : u'ʷiu', u'uýu'", "problem #Same positive #k <-> c #g <-> gh #i", "'ɪə', 'ʷă', 'ɜ:', 'tʰ', 'dʒ', 'ew', 'ʊə', 'ɯə', 'aw', '3',", "4, u'ã' : 4, u'ạ' : 6, u'ấ' : 5,", "4, u'ạ' : 6, u'ấ' : 5, u'ầ' : 2,", ": u'ɯə', u'ựa' : u'ɯə', u'ươ' : u'ɯə', u'ướ' :", "cod == u'n': cod = u'ŋ' # Monophthongization (Southern dialects:", ": u'ew', u'óeo' : u'ew', u'òeo' : u'ew', u'ỏeo' :", "u'ủ' : 4, u'ũ' : 3, u'ụ' : 6, u'ứ'", ": u'uəj', u'ươi' : u'ɯəj', u'ưới' : u'ɯəj', u'ười' :", "u'ʷen', u'oẻn' : u'ʷen', u'oẽn' : u'ʷen', u'oẹn' : u'ʷen',", "'zw', 'fw', 'tw', 'tʰw', 'ɲw', 'cw', 'ʂw', 'ɣw', 'ʐw', 'xw',", "u'ŋ', u'nh' : u'ɲ', u'ch' : u'k' } #tones =", "\" else: IPA+=Parsing(\"default\",eng,delimit)+\" \" #Check tu dien tieng anh Etrain", "ipa = [convert(x, dialect, glottal, pham, cao, palatals, delimit).strip() for", ": u'ɛu', u'ia' : u'iə', u'ía' : u'iə', u'ìa' :", "u'uj', u'ụi' : u'uj', u'uy' : u'uj', u'úy' : u'uj',", "u'ăj', u'ãy' : u'ăj', u'ạy' : u'ăj', u'ao' : u'aw',", "None in (ons, nuc, cod, ton): seq = u'['+word+u']' else:", "= offglides[nucl][:-1] elif word in gi: # if word ==", "u'ả' : 4, u'ã' : 4, u'ạ' : 6, u'ấ'", "'ngh' ons = onsets[word[0:3]] oOffset = 3 elif word[0:2] in", "+ space+word_pad + English_phoneme + punctuation + tone + modifi", "in List_pair: Pair[T2IPA(lt)] = lt cout_same=0 with open(\"Popular.txt\", encoding=\"utf-8\") as", ": 13, u'ề' : 42, u'ể' : 312, u'ễ' :", "u'wi', u'qụy' : u'wi'} ############################################ #south.py #coding: utf-8 S_onsets =", "312, u'õ' : u'35g', u'ọ' : u'21g', u'ố' : 24,", ": u'kw', u'gi' : u'z', u'tr' : u'c', u'k' :", ": 32, u'ử' : 312, u'ữ' : u'35g', u'ự' :", "u'ɔ', u'oỏ' : u'ɔ', u'oõ' : u'ɔ', u'oọ' : u'ɔ',", ": zim2 din <-> gin : zin1 díp <-> gíp", "XII), Vũ 1982 C_tones = { u'á' : 13, u'à'", "sound modifi = [\"k͡p\",\"ŋ͡m\"] symbols = list_phoneme + space+word_pad +", "u'oe' : u'ʷɛ', u'oé' : u'ʷɛ', u'oè' : u'ʷɛ', u'oẻ'", "đều gộp chung làm một #Disable convert from 'ɲ' to", "Cus_onoffglides = { u'oe' : u'ɛj', u'oé' : u'ɛj', u'oè'", "úi #Remain ''' di <-> gi : zi1 dìm <->", "3, u'ọ' : 6, u'ố' : 5, u'ồ' : 2,", "in total syms=['ɯəj', 'ɤ̆j', 'ʷiə', 'ɤ̆w', 'ɯəw', 'ʷet', 'iəw', 'uəj',", "u'ã' : 312, u'ạ' : u'21g', u'ấ' : 13, u'ầ'", "lin2 +\"\\t\\t:\\t\\t\"+T2IPA(line)) print(\"Same pair:\" , cout_same) #Các trường hợp dẫn", "u'v' : u'j', u'x' : u's', u'd' : u'j', u'h'", "import sys, codecs, re from io import StringIO from optparse", "u'uáy' : u'ăj', u'uày' : u'ăj', u'uảy' : u'ăj', u'uãy'", "u'uj', u'ùy' : u'uj', u'ủy' : u'uj', u'ũy' : u'uj',", "u'ă', u'oằ' : u'ă', u'oẳ' : u'ă', u'oẵ' : u'ă',", "#coding: utf-8 N_onsets = { u'b' : u'b', u't' :", "4, u'ẽ' : 4, u'ẹ' : 6, u'ế' : 5,", "u'ũ' : 312, u'ụ' : u'21g', u'ứ' : 13, u'ừ'", "u'k', u'c' : u'k', u'gh' : u'ɣ', u'r' : u'ʐ',", "== u'6' and cod in ['p', 't', 'k']: ton =", ": u'd', u'ch' : u'c', u'kh' : u'x', u'g' :", "onsets: # if single onset ons = onsets[word[0]] oOffset =", ": u'ɤ', u'uở' : u'ɤ', u'uỡ' : u'ɤ', u'uợ' :", "a coda... if word[0:2] in gi and cod and len(word)", "print(test) else: print(\"none\") ''' ################################################### #Step #Vinorm #Underthesea #For each", "u'ch' : u'c', u'kh' : u'x', u'g' : u'ɣ', u'l'", ": 32, u'ử' : 214, u'ữ' : 214, u'ự' :", "13, u'ồ' : 42, u'ổ' : 312, u'ỗ' : 312,", "33, u'ứ' : 24, u'ừ' : 32, u'ử' : 312,", "= C_tones_p if dialect == 's': tones_p = S_tones_p #Custom", "u's', u'd' : u'j', u'h' : u'h', u'p' : u'p',", "u'ù' : 32, u'ủ' : 312, u'ũ' : u'35g', u'ụ'", ": u'e', u'õe' : u'e', u'ọe' : u'e', u'ua' :", "'ʃ', '?', 'r', ':', 'η', 'f', ';', 'e', 't', \"'\"]", ": u'ʷiu', u'uyú' : u'ʷiu', u'uyù' : u'ʷiu', u'uyủ' :", ": u'ɛ', u'uẻ' : u'ɛ', u'uẽ' : u'ɛ', u'uẹ' :", "if dialect == 's': tones_p = S_tones_p #Custom tones_p =", ": u'ʷă', u'uẳ' : u'ʷă', u'uẵ' : u'ʷă', u'uặ' :", "for lt in List_pair: Pair[T2IPA(lt)] = lt cout_same=0 with open(\"Popular.txt\",", "if onset is 'nh', 'gh', 'kʷ' etc ons = onsets[word[0:2]]", "u'l' : u'l', u'm' : u'm', u'n': u'n', u'ngh': u'ŋ',", "= '' ton = 0 oOffset = 0 cOffset =", ": u'iə', u'uyề' : u'iə', u'uyể' : u'iə', u'uyễ' :", "'g', 'ă', '_', 'æ', 'ɤ', '2', 'ʤ', 'i', '.', 'ɒ',", "u'õe' : u'ʷɛ', u'ọe' : u'ʷɛ', u'ua' : u'ʷa', u'uá'", "u'õ' : u'35g', u'ọ' : u'21g', u'ố' : 24, u'ồ'", "u'ẽ' : u'35g', u'ẹ' : u'21g', # u'ê' : 33,", "u'ới' : u'ɤj', u'ời' : u'ɤj', u'ởi' : u'ɤj', u'ỡi'", "} S_tones_p = { u'á' : 5, u'à' : 2,", "u'iə': nuc = u'i' if nuc == u'uə': nuc =", "u'iɛ', u'yề' : u'iɛ', u'yể' : u'iɛ', u'yễ' : u'iɛ',", "u'en', u'oẻn' : u'en', u'oẽn' : u'en', u'oẹn' : u'en',", ": u'ɔj', u'òi' : u'ɔj', u'ỏi' : u'ɔj', u'õi' :", "u'ʷɤ', u'uợ' : u'ʷɤ', u'uy' : u'ʷi', u'uý' : u'ʷi',", "quả \"c\" khác nhau ################################################### checkDict() #print(vi2IPA_split(\"!Singapo english? đại học", "\"oã\", \"oẽ\",\"õo\", \"uỹ\", \"ạ\",\"ặ\",\"ậ\",\"ẹ\",\"ệ\",\"ị\",\"ọ\",\"ộ\",\"ợ\",\"ụ\",\"ự\",\"ỵ\",\"iệ\",\"ọa\",\"oặ\",\"ọe\",\"oọ\",\"uậ\",\"uệ\",\"uệ\",\"ượ\",\"ụy\",\"ượ\",\"uyệ\",\"yệ\", #dot \"oạ\", \"oẹ\",\"ọo\", \"uỵ\"] Onset=[\"b\",\"d\",\"h\",\"l\",\"m\",\"n\",\"p\",\"r\",\"s\",\"t\",\"v\",\"x\",\"đ\",\"p\", \"tr\",", "u'ew', u'uéo' : u'ew', u'uèo' : u'ew', u'uẻo' : u'ew',", "####################################################### #central.py #coding: utf-8 C_onsets = { u'b' : u'b',", "u'ạ' : 212, u'ấ' : 45, u'ầ' : 32, u'ẩ'", "cao, palatals, delimit): \"\"\"Convert a single orthographic string to IPA.\"\"\"", "u'k' } # See Alves 2007 (SEALS XII), Vũ 1982", "Onset=[\"b\",\"d\",\"h\",\"l\",\"m\",\"n\",\"p\",\"r\",\"s\",\"t\",\"v\",\"x\",\"đ\",\"p\", \"tr\", \"th\", \"ch\", \"ph\",\"nh\",\"kh\",\"gi\",\"qu\", \"ngh\",\"ng\",\"gh\",\"g\",\"k\",\"c\"] #coding: utf-8 #Custom phoneme", "'' nuc = '' cod = '' ton = 0", "u'uă' : u'ʷă', u'uắ' : u'ʷă', u'uằ' : u'ʷă', u'uẳ'", "u'ew', u'oéo' : u'ew', u'oèo' : u'ew', u'oẻo' : u'ew',", "u'aj', u'ải' : u'aj', u'ãi' : u'aj', u'ại' : u'aj',", ": u'ă', u'uắ' : u'ă', u'uằ' : u'ă', u'uẳ' :", "nuc = onoffglides[nucl][0:-1] if ons != u'kw': if ons: ons", ": u'ɛj', u'oai' : u'aj', u'oái' : u'aj', u'oài' :", "S_offglides, S_onoffglides, S_qu, S_gi #Custom onsets, nuclei, codas, onglides, offglides,", "in words if word!=u'_'] for i in range(0,len(words)): word =", "for word in words if word!=u'_'] for i in range(0,len(words)):", "in ['p', 't', 'k']: #if ton == u'21\\u02C0' and cod", ": 312, u'ã' : u'35g', u'ạ' : u'21g', # u'â'", ": u'aj', u'uãi' : u'aj', u'uại' : u'aj', u'uay' :", "'ăw', 'ʈw', 'ʂw', 'aʊ', 'fw', 'ɛu', 'tʰ', 'tʃ', 'ɔɪ', 'xw',", "C_nuclei = { u'a' : u'a', u'á' : u'a', u'à'", "u'ăw', u'àu' : u'ăw', u'ảu' : u'ăw', u'ãu' : u'ăw',", "u'ừ' : 2, u'ử' : 4, u'ữ' : 4, u'ự'", "u'ɔ', u'õ' : u'ɔ', u'ọ' : u'ɔ', u'ô' : u'o',", "u'oắ' : u'ʷă', u'oằ' : u'ʷă', u'oẳ' : u'ʷă', u'oẵ'", "u'ẹ' : u'21g', u'ế' : 24, u'ề' : 32, u'ể'", ": u'ʷiu', u'uỵu' : u'ʷiu', u'oen' : u'ʷen', u'oén' :", "u'uã' : u'a', u'uạ' : u'a', u'uă' : u'ă', u'uắ'", "NIYE BoOK\",\"'\")) #check các ipa của tiếng anh #print(vi2IPA_split(\"Another table", "thống nhất âm vực phoneme -> ok #+Get lại bộ", ": kwit5 thủa <-> thuở : tʰuə4 tòe <-> toè", ": u't', u'th' : u'tʰ', u'đ' : u'd', u'ch' :", "32, u'ử' : 312, u'ữ' : u'35g', u'ự' : u'21g',", "u'iw', u'ịu' : u'iw', u'oi' : u'ɔj', u'ói' : u'ɔj',", "= { u'a' : u'a', u'á' : u'a', u'à' :", ": u'oj', u'ổi' : u'oj', u'ỗi' : u'oj', u'ội' :", "u'ẳ' : 312, u'ẵ' : u'35g', u'ặ' : u'21g', u'é'", ": u'ʷɤ̆', u'uầ' : u'ʷɤ̆', u'uẩ' : u'ʷɤ̆', u'uẫ' :", ": zi1 dìm <-> gìm : zim2 din <-> gin", "= 0 pham = 0 cao = 0 palatals =", "words if word!=u'-'] words = [word for word in words", ": u'21g', # u'â' : 33, u'ấ' : 24, u'ầ'", "u'ẹ' : u'ɛ', u'ê' : u'e', u'ế' : u'e', u'ề'", "u'ờ' : 2, u'ở' : 4, u'ỡ' : 3, u'ợ'", "u'ửi' : u'ɯj', u'ữi' : u'ɯj', u'ựi' : u'ɯj', u'ưu'", "u'ỹ' : u'35g', u'ỵ' : u'21g', } # used to", "u'e', u'ế' : u'e', u'ề' : u'e', u'ể' : u'e',", ": u'iə', u'iễ' : u'iə', u'iệ' : u'iə', u'oo' :", "u'ẳ' : 4, u'ẵ' : 3, u'ặ' : 6, u'é'", ": 312, u'ẹ' : u'21g', u'ế' : 13, u'ề' :", ": u'ʷɛ', u'uè' : u'ʷɛ', u'uẻ' : u'ʷɛ', u'uẽ' :", "## if true, call this routine for each substring ##", ": 33, u'ý' : 24, u'ỳ' : 32, u'ỷ' :", "khác nhau ################################################### checkDict() #print(vi2IPA_split(\"!Singapo english? đại học là IUYE", "u'à' : 32, u'ả' : 312, u'ã' : u'35g', u'ạ'", "u'uẽ' : u'ʷɛ', u'uẹ' : u'ʷɛ', u'uê' : u'ʷe', u'uế'", "u'ĩ' : u'35g', u'ị' : u'21g', # u'o' : 33,", ": 5, u'ờ' : 2, u'ở' : 4, u'ỡ' :", "elif dialect == 's': onsets, nuclei, codas, tones, onglides, offglides,", ": u'o', u'ôỗ' : u'o', u'ôộ' : u'o', u'ua' :", "token_under=under_valid.split(\" \") checkinvalid=0 print(token_under) if len(token_under) >1: for tok in", "u'qũy' : u'wi', u'qụy' : u'wi'} ############################################ #south.py #coding: utf-8", "cod = u'ŋ' # Monophthongization (Southern dialects: Thompson 1965: 86;", "'n' or dialect == 's') and ton == u'21g' and", ": u'21g', u'ắ' : 24, u'ằ' : 32, u'ẳ' :", ": u'u', u'ù' : u'u', u'ủ' : u'u', u'ũ' :", "'' cod = '' ton = 0 oOffset = 0", ": u'ăw', u'ảu' : u'ăw', u'ãu' : u'ăw', u'ạu' :", "} S_onglides = { u'oa' : u'a', u'oá' : u'a',", "u'ɛ', u'uẻ' : u'ɛ', u'uẽ' : u'ɛ', u'uẹ' : u'ɛ',", "palatals (Northern dialect) if nuc not in [u'i', u'e', u'ɛ']:", "if cod == u'k': cod = u't' if cod ==", "u'iw', u'ỉu' : u'iw', u'ĩu' : u'iw', u'ịu' : u'iw',", "TK.insert(iuv, tok) IPA=\"\" for tk in TK: ipa = T2IPA_split(tk,delimit).replace(\"", "Results+= IPA.rstrip()+\" \"+delimit+\".\"+delimit+\" \" #For checking: need much memory '''", "= line.split() ## toss len==0 junk words = [word for", "u'oắ' : u'ă', u'oằ' : u'ă', u'oẳ' : u'ă', u'oẵ'", "'v', 'g', 'ă', '_', 'æ', 'ɤ', '2', 'ʤ', 'i', '.',", "#Ở đây tiết kiệm chi phí chạy máy không normal", "u'en', u'oén' : u'en', u'oèn' : u'en', u'oẻn' : u'en',", ": u'et', u'oèt' : u'et', u'oẻt' : u'et', u'oẽt' :", "u'kw': nuc = onglides[nucl] elif nucl in onoffglides: cod =", "u'ew', u'iu' : u'iw', u'íu' : u'iw', u'ìu' : u'iw',", "\" #Check tu dien tieng anh Etrain bưc #Neu co", ": 32, u'ể' : 312, u'ễ' : u'35g', u'ệ' :", "trước => Try to add ʷ Cus_onglides = { u'oa'", "add ʷ Cus_onglides = { u'oa' : u'ʷa', u'oá' :", "# modify the nuc accordingly if ons: # if there", ": 45, u'ò' : 32, u'ỏ' : 214, u'õ' :", "nor==\"\": cout+=1 print(line) print(\"Number of token can not convert: \",cout)", "312, u'ỗ' : u'35g', u'ộ' : u'21g', # u'ơ' :", "'iəw', 'uəj', 'ʷen', 'tʰw', 'ʷɤ̆', 'ʷiu', 'kwi', 'ŋ͡m', 'k͡p', 'cw',", "u'ờ' : u'ɤ', u'ở' : u'ɤ', u'ỡ' : u'ɤ', u'ợ'", "= str(tonelist[len(tonelist)-1]) else: if not (pham or cao): if dialect", ": 33, u'ứ' : 24, u'ừ' : 32, u'ử' :", ": u'ew', u'uéo' : u'ew', u'uèo' : u'ew', u'uẻo' :", "u'uj', u'ũy' : u'uj', u'ụy' : u'uj', u'ơi' : u'ɤj',", "24, u'ù' : 32, u'ủ' : 312, u'ũ' : u'35g',", "if you just have 'gi' and a coda... if word[0:2]", "in list if str(char) in [\"ˈ\",\"ˌ\",\"*\"]: continue print(\"this is not", ": u'ʷen', u'oet' : u'ʷet', u'oét' : u'ʷet', u'oèt' :", "'ɔ', '1', 'ʧ', 'ʈ', ' ', 'd', 'i', 'ɣ', 'ɲ',", "u'uề' : u'e', u'uể' : u'e', u'uễ' : u'e', u'uệ'", "if len(l) <= len(text[ic:]) and l == text[ic:ic+len(l)]: output+=delimit+l check", "u'aj', u'ay' : u'ăj', u'áy' : u'ăj', u'ày' : u'ăj',", "u'ă', u'uẵ' : u'ă', u'uặ' : u'ă', u'uâ' : u'ɤ̆',", ": uə1 ưa <-> ươ : ɯə1 xõa <-> xoã", "Modified 20 Sep 2008 to fix aberrant 33 error tonelist", ": u'ɯ', u'y' : u'i', u'ý' : u'i', u'ỳ' :", "u'iễ' : u'iə', u'iệ' : u'iə', u'oo' : u'ɔ', u'óo'", "u'uyả' : u'iə', u'uyã' : u'iə', u'uyạ' : u'iə', u'uyê'", ": 4, u'ự' : 6, u'ý' : 5, u'ỳ' :", "u'e', u'ɛ']: if cod == u'ɲ': cod = u'ɲ'#u'ŋ' if", "'qúy',... ons = qu[word][:-1] nuc = qu[word][-1] else: # Something", "'ɤ', '?', 'ɪ', 'l', '.', 'j', ':', 't', 'ʒ', 'ə',", "elif nucl in onglides and ons != u'kw': # if", "u'ɤ̆j', u'uậy' : u'ɤ̆j' } N_codas = { u'p' :", "lóe <-> loé : lwʷɛ5 ngét <-> nghét : ŋɛt5", "'ɣ', 'ɲ', 'ɤ', '?', 'ɪ', 'l', '.', 'j', ':', 't',", "2, u'ủ' : 4, u'ũ' : 4, u'ụ' : 6,", "return Results.rstrip() def vi2IPA(text): print(\"------------------------------------------------------\") TN= TTSnorm(text) print(\"------------------------------------------------------\") print(\"Text normalize:", "u'oè' : u'e', u'oẻ' : u'e', u'oẽ' : u'e', u'oẹ'", ": 312, u'ỹ' : 312, u'ỵ' : u'21g', } #", "u'uyả' : u'ʷiə', u'uyã' : u'ʷiə', u'uyạ' : u'ʷiə', u'uyê'", "u'iə', u'ià' : u'iə', u'iả' : u'iə', u'iã' : u'iə',", "u'uỵu' : u'ʷiu', u'oen' : u'ʷen', u'oén' : u'ʷen', u'oèn'", "'quy', 'qúy',... ons = qu[word][:-1] nuc = qu[word][-1] else: #", "# there's your nucleus else: # otherwise... nuc = nuclei[nucl]", "u'ổi' : u'oj', u'ỗi' : u'oj', u'ội' : u'oj', u'ui'", "4, u'ặ' : 6, u'é' : 5, u'è' : 2,", "Rules files #Setup option glottal = 0 pham = 0", "u'ừu' : u'ɯw', u'ửu' : u'ɯw', u'ữu' : u'ɯw', u'ựu'", "u'ữ' : u'35g', u'ự' : u'21g', # u'y' : 33,", ": 4, u'ễ' : 3, u'ệ' : 6, u'í' :", "S_nuclei = { u'a' : u'a', u'á' : u'a', u'à'", "214, u'ẫ' : 214, u'ậ' : 212, u'ắ' : 45,", "u'ʷi', u'uỷ' : u'ʷi', u'uỹ' : u'ʷi', u'uỵ' : u'ʷi',", "for pair Pair = {} for lt in List_pair: Pair[T2IPA(lt)]", "u'ʷet', u'oẽt' : u'ʷet', u'oẹt' : u'ʷet' } Cus_onoffglides =", "u'35g', u'ị' : u'21g', u'ó' : 24, u'ò' : 32,", ": 214, u'ẵ' : 214, u'ặ' : 212, u'é' :", "u'z', u'tr' : u'c', u'k' : u'k', u'c' : u'k',", "'n', ';', 'r', 'b', 'ɯ', 'a', 's', 'ʐ', 'η', 'ŋ',", "==\"\": IPA+=delimit+tk+delimit+\" \" elif ipa[0]==\"[\" and ipa[-1]==\"]\": eng = eng_to_ipa.convert(tk)", ": u'ɤ̆j', u'âu' : u'ɤ̆w', u'ấu' : u'ɤ̆w', u'ầu': u'ɤ̆w',", "u'ɯəw', u'ưởu' : u'ɯəw', 'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw'", "4, u'ữ' : 3, u'ự' : 6, u'ý' : 5,", "if cod == u'k' and nuc in [u'i', u'e', u'ɛ']:", "u'ew', u'õeo' : u'ew', u'ọeo' : u'ew', u'ueo' : u'ew',", "word[0:2] in gi and cod and len(word) == 3: #", "',', 'ɛ', 'z', '6', '2', 'x', 'ă'] listParse.sort(reverse = True,key=len)", "or (lin2[-1] in ['i','í','ì','ĩ','ỉ','ị'] and line[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ']) or (lin2[-1]", "u'uyá' : u'iə', u'uyà' : u'iə', u'uyả' : u'iə', u'uyã'", "[u'i', u'e']: if cod == u'k': cod = u't' if", "#coding: utf-8 #Custom phoneme follow the https://vi.wikipedia.org/wiki/%C3%82m_v%E1%BB%8B_h%E1%BB%8Dc_ti%E1%BA%BFng_Vi%E1%BB%87t #Improve pronoune between", ": u'uj', #u'uy' : u'uj', u'úy' : u'uj', u'ùy' :", "ipa ==\"\": IPA+=delimit+tk+delimit+\" \" elif ipa[0]==\"[\" and ipa[-1]==\"]\": eng =", "#Try to add ʷ to all start o and u", "212, } S_tones_p = { u'á' : 5, u'à' :", "u'21g', # u'ê' : 33, u'ế' : 24, u'ề' :", "2, u'ử' : 4, u'ữ' : 3, u'ự' : 6,", "case thống nhất âm vực phoneme -> ok #+Get lại", ": u'ʷiu', u'uyũ' : u'ʷiu', u'uyụ' : u'ʷiu', u'uyu' :", "u'uəj', u'uồi' : u'uəj', u'uổi' : u'uəj', u'uỗi' : u'uəj',", "u'35g', u'ặ' : u'21g', u'é' : 24, u'è' : 32,", "if nuc == u'a': if cod == u'k' and cOffset", ": u'iəw', u'iệu' : u'iəw', u'yêu' : u'iəw', u'yếu' :", ": u'ʷă', u'uâ' : u'ʷɤ̆', u'uấ' : u'ʷɤ̆', u'uầ' :", "u'ʷɛ', u'ọe' : u'ʷɛ', u'ua' : u'ʷa', u'uá' : u'ʷa',", "Final palatals (Northern dialect) if nuc not in [u'i', u'e',", ": u's', u'gi': u'z'} N_nuclei = { u'a' : u'a',", "\"'\"] def Parsing(listParse, text, delimit): undefine_symbol = \"'\" if listParse", "for v,d in zip(ipa, delimiters)) else: seq = convert(word, dialect,", "pham, cao, palatals, delimit).strip() # concatenate if len(words) >= 2:", "#nor = vi2IPA(line) nor = T2IPA(line) if nor in List_token:", "glottal == 1: if word[0] not in onsets: # if", "codas, tones, onglides, offglides, onoffglides, qu, gi = S_onsets, S_nuclei,", "are onsets which has one letter \",\"/\")) #Lọc bỏ dấu", "u'o', u'ỗ' : u'o', u'ộ' : u'o', u'ơ' : u'ɤ',", "u'en', u'oet' : u'et', u'oét' : u'et', u'oèt' : u'et',", "0 palatals = 0 tokenize = 0 dialect='n' #\"c\"\"s\" tone_type=0", "cao = 0 palatals = 0 tokenize = 0 dialect='n'", "ortho = u'' words = line.split() ## toss len==0 junk", "Modification for 8-tone system if cao == 1: if ton", "u'ɔ', u'oo' : u'ɔ', u'oó' : u'ɔ', u'oò' : u'ɔ',", "u'th' : u'tʰ', u'đ' : u'd', u'ch' : u'c', u'kh'", "u'ò' : 32, u'ỏ' : 312, u'õ' : u'35g', u'ọ'", ": u'uə', u'uỗ' : u'uə', u'uộ' : u'uə', u'ưa' :", "about \"from x import *\" syntax if dialect == 'n':", ": 2, u'ủ' : 4, u'ũ' : 3, u'ụ' :", "len(word) == 3: # if you just have 'gi' and", "u'ă', u'oắ' : u'ă', u'oằ' : u'ă', u'oẳ' : u'ă',", "u'a', u'ạ' : u'a', u'â' : u'ɤ̆', u'ấ' : u'ɤ̆',", "List_token.append(nor) if nor==\"\": cout+=1 print(line) print(\"Number of token can not", "the unicode raised glottal character N_tones_p = { u'á' :", "= tones_p ons = '' nuc = '' cod =", "of single hyphens or underscores words = [word for word", "u'ố' : u'o', u'ồ' : u'o', u'ổ' : u'o', u'ỗ'", "=1 skip=len(l)-1 break if check == 0: #Case symbol not", "= 0 dialect='n' #\"c\"\"s\" tone_type=0 if tone_type==0: pham=1 else: cao=1", "u't' : u't', u'c' : u'k', u'm' : u'm', u'n'", "u'uə', u'uở' : u'uə', u'uờ': u'uə', u'uở' : u'uə', u'uỡ'", "u'ỗô' : u'o', u'ộô' : u'o', u'ôô' : u'o', u'ôố'", "substrings = re.split(r'(_|-)', word) values = substrings[::2] delimiters = substrings[1::2]", "delimiters)) else: seq = convert(word, dialect, glottal, pham, cao, palatals,", "2, u'ủ' : 4, u'ũ' : 3, u'ụ' : 6,", "list_phoneme + space+word_pad + English_phoneme + punctuation + tone +", ": u'ă', u'uẵ' : u'ă', u'uặ' : u'ă', u'uâ' :", ": u'ɯw', u'ữu' : u'ɯw', u'ựu' : u'ɯw', u'iêu' :", "u'ji', u'gĩ' : u'ji', u'gị' : u'ji' } S_qu =", ": u'ʷa', u'uả' : u'ʷa', u'uã' : u'ʷa', u'uạ' :", ": u'ʷa', u'ỏa' : u'ʷa', u'õa' : u'ʷa', u'ọa' :", "Thompson 1965: 86; Hoàng 1985: 181) if dialect == 's':", ": 4, u'ẽ' : 3, u'ẹ' : 6, u'ế' :", "* from underthesea import word_tokenize import eng_to_ipa SET=[S_onsets, S_nuclei, S_codas#,", ": u'uə', u'ụa' : u'uə', u'uô' : u'uə', u'uố' :", ": u'uj', u'ũi' : u'uj', u'ụi' : u'uj', #u'uy' :", "u'uya' : u'iə', u'uyá' : u'iə', u'uyà' : u'iə', u'uyả'", "33, u'ố' : 24, u'ồ' : 32, u'ổ' : 312,", "u'tʃ' } Cus_tones_p = { u'á' : 5, u'à' :", "13, u'ờ' : 42, u'ở' : 312, u'ỡ' : 312,", "u'à' : 2, u'ả' : 4, u'ã' : 3, u'ạ'", "utf-8 S_onsets = { u'b' : u'b', u't' : u't',", "u'ủy' : u'uj', u'ũy' : u'uj', u'ụy' : u'uj', u'uy'", "u'ơi' : u'ɤj', u'ới' : u'ɤj', u'ời' : u'ɤj', u'ởi'", "Cus_onglides, Cus_offglides, Cus_onoffglides, Cus_qu, Cus_gi if pham or cao: if", "N_onoffglides = { u'oe' : u'ej', u'oé' : u'ej', u'oè'", "u'iu', u'uýu' : u'iu', u'uỳu' : u'iu', u'uỷu' : u'iu',", "u'ố' : 13, u'ồ' : 42, u'ổ' : 312, u'ỗ'", "tòe <-> toè : twʷɛ2 ua <-> uơ : uə1", "len(token_under) >1: for tok in token_under: if tok not in", "a big problem #Same positive #k <-> c #g <->", ": 32, u'ẳ' : 214, u'ẵ' : 214, u'ặ' :", "u'ʷa', u'oả' : u'ʷa', u'oã' : u'ʷa', u'oạ' : u'ʷa',", "nuc == u'ɯə': nuc = u'ɯ' # Tones # Modified", ": u'iɛ', u'uơ' : u'uə', u'uở' : u'uə', u'uờ': u'uə',", "S_tones, S_onglides, S_offglides, S_onoffglides, S_qu, S_gi #Custom onsets, nuclei, codas,", "if i < len(words)-1: seq = seq+u' ' compound =", "u'ʷɛ', u'óe' : u'ʷɛ', u'òe' : u'ʷɛ', u'ỏe' : u'ʷɛ',", "33, u'í' : 24, u'ì' : 32, u'ỉ' : 312,", "u'k': cod = u't' if cod == u'ŋ': cod =", "uơ : uə1 ưa <-> ươ : ɯə1 xõa <->", "this reverse fronting, see Thompson 1965:94 ff. elif nuc in", "cường độ âm sắc chỉ dừng từ 1->6 #học ác", "u'ŋ', u'ng' : u'ŋ', u'nh' : u'n', u'ch' : u'k'", "this routine for each substring ## and re-concatenate if (tokenize", "u'aj', u'uải' : u'aj', u'uãi' : u'aj', u'uại' : u'aj',", "u'ủa' : u'uə', u'ũa' : u'uə', u'ụa' : u'uə', u'uô'", "} Cus_offglides = { u'ai' : u'aj', u'ái' : u'aj',", "u'ɣ', u'r' : u'ʐ', u's' : u'ʂ', u'gi' : u'j'", "nhau đã thống nhất ở list custom # Các trường", "u'ʷiə', u'uyu' : u'ʷiu', u'uyú' : u'ʷiu', u'uyù' : u'ʷiu',", "u'iê' : u'iə', u'iế' : u'iə', u'iề' : u'iə', u'iể'", "if dialect == 'c': tones_p = C_tones_p if dialect ==", "33, u'ắ' : 24, u'ằ' : 32, u'ẳ' : 312,", ": u'21g', u'ấ' : 13, u'ầ' : 42, u'ẩ' :", "dialect, glottal, pham, cao, palatals): # This looks ugly, but", "'ʷa', 'eə', 'u:', 'uj', 'aʊ', 'uə', 'aj', 'iə', 'iw', 'əʊ',", "u'ɯw', u'ựu' : u'ɯw', u'iêu' : u'iəw', u'iếu' : u'iəw',", "u'ợ' : u'ɤ', u'u' : u'u', u'ú' : u'u', u'ù'", ": 45, u'ù' : 32, u'ủ' : 214, u'ũ' :", "u'r' : u'z', u's' : u's', u'gi': u'z'} N_nuclei =", "<-> uơ : uə1 ưa <-> ươ : ɯə1 xõa", "u'ã' : 4, u'ạ' : 6, u'ấ' : 5, u'ầ'", ": 312, u'ẫ' : u'35g', u'ậ' : u'21g', # u'ă'", "2, u'ỏ' : 4, u'õ' : 3, u'ọ' : 6,", "'ɜ:', 'tʰ', 'dʒ', 'ew', 'ʊə', 'ɯə', 'aw', '3', 'θ', 'v',", "u'et', u'oèt' : u'et', u'oẻt' : u'et', u'oẽt' : u'et',", ": u'ʷɛ', u'oe' : u'ʷɛ', u'óe' : u'ʷɛ', u'òe' :", "u'yếu' : u'iəw', u'yều' : u'iəw', u'yểu' : u'iəw', u'yễu'", "ons = qu[word][:-1] nuc = qu[word][-1] else: # Something is", "u'ew', u'óeo' : u'ew', u'òeo' : u'ew', u'ỏeo' : u'ew',", "u'ă', u'oẵ' : u'ă', u'oặ' : u'ă', u'oe' : u'e',", "u'ù' : 32, u'ủ' : 214, u'ũ' : 214, u'ụ'", "if l > 0: if word[0:3] in onsets: # if", "u'p', u'qu' : u'kw', u'gi' : u'j', u'tr' : u'ʈ',", "u'ăj', u'oáy' : u'ăj', u'oày' : u'ăj', u'oảy' : u'ăj',", ": u'uj', u'ụy' : u'uj', u'uy' : u'ʷi', u'úy' :", "from 'ɲ' to 'ɲ'' in north #Các âm vòng ở", "'∫', 'ð', 'u', 'e', 'w', 'p', 'ʃ', 'æ', \"'\", 'h',", "and off-glide is a big problem #Same positive #k <->", "u'iə', u'iả' : u'iə', u'iã' : u'iə', u'iạ' : u'iə',", "u'ʷiu', u'uỷu' : u'ʷiu', u'uỹu' : u'ʷiu', u'uỵu' : u'ʷiu',", "u'aj', u'ãi' : u'aj', u'ại' : u'aj', u'ay' : u'ăj',", "to add ʷ Cus_onglides = { u'oa' : u'ʷa', u'oá'", "u'éo' : u'ew', u'èo' : u'ew', u'ẻo' : u'ew', u'ẽo'", "u'oe' : u'ej', u'oé' : u'ej', u'oè' : u'ej', u'oẻ'", "u'ă', u'uằ' : u'ă', u'uẳ' : u'ă', u'uẵ' : u'ă',", "u'i', u'ì' : u'i', u'ỉ' : u'i', u'ĩ' : u'i',", ": u'35g', u'ị' : u'21g', u'ó' : 24, u'ò' :", "u'è' : 32, u'ẻ' : 214, u'ẽ' : 214, u'ẹ'", "List_token = list(set(List_token)) #print(List_token) print(len(List_token)) ################################ #Looking for pair Pair", "ở đây i chang không vòm: không có w ở", "được => ý tưởng mượn \"tʃ\" trong teach and watch", "u'ò' : 2, u'ỏ' : 4, u'õ' : 3, u'ọ'", "u'ɯj', u'ưu' : u'ɯw', u'ứu' : u'ɯw', u'ừu' : u'ɯw',", ": u'ɤ', u'uy' : u'i', u'uý' : u'i', u'uỳ' :", "u'ẻo' : u'eo', u'ẽo': u'eo', u'ẹo' : u'eo', u'êu' :", "== u'a': nuc = u'ɛ' # Final palatals (Northern dialect)", "u'ʷen', u'oet' : u'ʷet', u'oét' : u'ʷet', u'oèt' : u'ʷet',", "return IPA def checkDict(): cout=0 trung=0 List_token=[] List_pair = []", "onset is 'nh', 'gh', 'kʷ' etc ons = onsets[word[0:2]] oOffset", "CHAR in list(EN.keys()): letter2sound+=EN[CHAR]+\" \" else: letter2sound+=char+\" \" IPA+=T2IPA_split(letter2sound,delimit)+\" \"", "312, u'ỹ' : 312, u'ỵ' : u'21g', } # used", "u'n': cod = u'ŋ' # Monophthongization (Southern dialects: Thompson 1965:", "symbol :\"+ char+\":\") output+=delimit+undefine_symbol return output.rstrip()+delimit #print(\"Parsing\",Parsing(\"default\",\"iu iu\",\"|\")) def getSymbol():", "\" else: #Giữ nguyên IPA+=Parsing(\"default\",tk,\"\")+\" \" else: IPA+=eng+\" \" #Check", "u'e', u'õe' : u'e', u'ọe' : u'e', u'ua' : u'a',", "just have 'gi' and a coda... nucl = u'i' ons", "# labialized allophony (added 17.09.08) if nuc in [u'u', u'o',", "i chang không vòm: không có w ở trước như:", "u'ải' : u'aj', u'ãi' : u'aj', u'ại' : u'aj', u'ay'", "ngữ khác nhau đã thống nhất ở list custom #", ": u'35g', u'ợ' : u'21g', # u'u' : 33, u'ú'", ": u'ɔ', u'ôô' : u'o', u'ốô' : u'o', u'ồô' :", "u'ừ' : 32, u'ử' : 214, u'ữ' : 214, u'ự'", "and cod and len(word) == 3: # if you just", ": u'ʷet', u'oẻt' : u'ʷet', u'oẽt' : u'ʷet', u'oẹt' :", "onglides, offglides, onoffglides, qu, gi = S_onsets, S_nuclei, S_codas, S_tones,", ": 312, u'õ' : u'35g', u'ọ' : u'21g', u'ố' :", "'fw', 'tw', 'tʰw', 'ɲw', 'cw', 'ʂw', 'ɣw', 'ʐw', 'xw', 'lw',", "glottal, pham, cao, palatals, delimit): \"\"\"Convert a single orthographic string", "= {} for lt in List_pair: Pair[T2IPA(lt)] = lt cout_same=0", "in codas: # if two-character coda cod = codas[word[l-2:l]] cOffset", "u'a', u'uã' : u'a', u'uạ' : u'a', u'uă' : u'ă',", "u'qủy' : u'wi', u'qũy' : u'wi', u'qụy' : u'wi'} ################################################3", ": u'k', u'm' : u'm', u'n' : u'ŋ', u'ng' :", "['y','ý','ỳ','ỷ','ỹ','ỵ'] and line[-1] in ['i','í','ì','ĩ','ỉ','ị']): continue cout_same+=1 print(line+ \" <->", "u'j' } S_nuclei = { u'a' : u'a', u'á' :", "u'iɛ', u'yể' : u'iɛ', u'yễ' : u'iɛ', u'yệ' : u'iɛ',", "u'uấ' : u'ɤ̆', u'uầ' : u'ɤ̆', u'uẩ' : u'ɤ̆', u'uẫ'", "312, u'ã' : 312, u'ạ' : u'21g', u'ấ' : 13,", ": u'ă', u'oắ' : u'ă', u'oằ' : u'ă', u'oẳ' :", ": 6, u'ớ' : 5, u'ờ' : 2, u'ở' :", "#Neu khong danh van print(\" ..................Out of domain word: \"", "u'ễ' : 3, u'ệ' : 6, u'í' : 5, u'ì'", ": u'ɯj', u'ừi' : u'ɯj', u'ửi' : u'ɯj', u'ữi' :", "di <-> gi : zi1 dìm <-> gìm : zim2", "syms=['ɯəj', 'ɤ̆j', 'ʷiə', 'ɤ̆w', 'ɯəw', 'ʷet', 'iəw', 'uəj', 'ʷen', 'tʰw',", "print(\"------------------------------------------------------\") Results+= IPA.rstrip()+\" \"+delimit+\".\"+delimit+\" \" #For checking: need much memory", "= eng_to_ipa.convert(tk) if eng[-1] == \"*\": if tk.lower().upper() == tk:", "u'ị' : u'21g', # u'o' : 33, u'ó' : 24,", "u'iə', u'uyà' : u'iə', u'uyả' : u'iə', u'uyã' : u'iə',", "'ʷă', 'dw', 'eɪ', 'aɪ', 'ew', 'iə', 'ɣw', 'zw', 'ɯj', 'ʷɛ',", ": 24, u'ì' : 32, u'ỉ' : 312, u'ĩ' :", ": 33, u'ú' : 24, u'ù' : 32, u'ủ' :", "u'ối' : u'oj', u'ồi' : u'oj', u'ổi' : u'oj', u'ỗi'", ": u'ɤ', u'uỡ' : u'ɤ', u'uợ' : u'ɤ', u'uy' :", "u'uə', u'úa' : u'uə', u'ùa' : u'uə', u'ủa' : u'uə',", "} # See Alves 2007 (SEALS XII), Vũ 1982 C_tones", "if cod == u'ɲ': cod = u'ɲ'#u'ŋ' if palatals ==", "u'ạo' : u'aw', u'au' : u'ăw', u'áu' : u'ăw', u'àu'", "dialects) else: if nuc in [u'i', u'e']: if cod ==", ": u'ɯəw', u'ưởu' : u'ɯəw', 'ưỡu' : u'ɯəw', u'ượu' :", "u'uẫ' : u'ɤ̆', u'uậ' : u'ɤ̆', u'ue' : u'ɛ', u'ué'", ": u'ɤ̆j' } S_codas = { u'p' : u'p', u't'", "u'à' : 32, u'ả' : 214, u'ã' : 214, u'ạ'", "u'ĩa' : u'iə', u'ịa' : u'iə', u'ia' : u'iə', u'iá'", "'ɔɪ', 'xw', 'ʷɤ', 'ɤ̆', 'ŋw', 'ʊə', 'zi', 'ʷă', 'dw', 'eɪ',", "elif dialect == 'c': onsets, nuclei, codas, tones, onglides, offglides,", "u'ă', u'oặ' : u'ă', u'oe' : u'e', u'oé' : u'e',", "== 'n': if nuc == u'a': if cod == u'k'", "N_nuclei, N_codas, N_tones, N_onglides, N_offglides, N_onoffglides, N_qu, N_gi elif dialect", "IPA.\"\"\" ons = '' nuc = '' cod = ''", ": u'ew', u'oẹo' : u'ew', u'oeo' : u'ew', u'óeo' :", "u'úi' : u'uj', u'ùi' : u'uj', u'ủi' : u'uj', u'ũi'", ": u'e', u'uơ' : u'ɤ', u'uớ' : u'ɤ', u'uờ' :", "2, u'ả' : 4, u'ã' : 4, u'ạ' : 6,", "xwʷăŋ5 khỏe <-> khoẻ : xwʷɛ4 khua <-> khuơ :", ": 2, u'ể' : 4, u'ễ' : 4, u'ệ' :", "u'ỏa' : u'a', u'õa' : u'a', u'ọa' : u'a', u'oă'", "else: letter2sound+=char+\" \" IPA+=T2IPA_split(letter2sound,\"\")+\" \" else: #Giữ nguyên IPA+=Parsing(\"default\",tk,\"\")+\" \"", "== 'c' and ton == u'13')) and cod in ['p',", "u'ia' : u'iə', u'iá' : u'iə', u'ià' : u'iə', u'iả'", "'ɔj', 'uj', 'lw', 'ɪə', 'ăj', 'u:', 'aw', 'ɛj', 'iw', 'aj',", "else: IPA+=ipa+\" \" IPA=re.sub(' +', ' ', IPA) print(\"IPA Vietnamese:", ": 214, u'ộ' : 212, u'ớ' : 45, u'ờ' :", "33, u'ú' : 24, u'ù' : 32, u'ủ' : 312,", "*\" syntax if dialect == 'n': onsets, nuclei, codas, tones,", "u'ụa' : u'uə', u'uô' : u'uə', u'uố' : u'uə', u'uồ'", "= word.strip(punctuation).lower() ## 29.03.16: check if tokenize is true ##", "u'ỉ' : u'i', u'ĩ' : u'i', u'ị' : u'i', u'o'", ": 4, u'ạ' : 6, u'ấ' : 5, u'ầ' :", "u'ổ' : 312, u'ỗ' : 312, u'ộ' : u'21g', u'ớ'", "khoắng <-> khuắng : xwʷăŋ5 khỏe <-> khoẻ : xwʷɛ4", "u'óe' : u'ʷɛ', u'òe' : u'ʷɛ', u'ỏe' : u'ʷɛ', u'õe'", "u'kw', u'gi' : u'j', u'tr' : u'ʈ', u'k' : u'k',", "u'ẩ' : 214, u'ẫ' : 214, u'ậ' : 212, u'ắ'", ": u'uj', u'ủi' : u'uj', u'ũi' : u'uj', u'ụi' :", "u'ɤ̆', u'ầ' : u'ɤ̆', u'ẩ' : u'ɤ̆', u'ẫ' : u'ɤ̆',", "'ŋw', 'ʊə', 'zi', 'ʷă', 'dw', 'eɪ', 'aɪ', 'ew', 'iə', 'ɣw',", "in [u'iə', u'ɯə', u'uə', u'u', u'ɯ', u'ɤ', u'o', u'ɔ', u'ă',", "nguyen #Neu khong danh van print(\" ..................Out of domain word:", "u'aw', u'ạo' : u'aw', u'au' : u'ăw', u'áu' : u'ăw',", "u'uầ' : u'ʷɤ̆', u'uẩ' : u'ʷɤ̆', u'uẫ' : u'ʷɤ̆', u'uậ'", "ton == u'13')) and cod in ['p', 't', 'k']: ton", "onsets: # if there isn't an onset.... ons = u'ʔ'+nuclei[nucl]", "'t', 'k']: # fixed 8 Nov 2016 ton = u'21'", "str('1') # Modifications for closed syllables if cOffset !=0: #", ": 312, u'ẽ' : u'35g', u'ẹ' : u'21g', u'ế' :", "u'ôi' : u'oj', u'ối' : u'oj', u'ồi' : u'oj', u'ổi'", "u'aw', u'oạo' : u'aw', u'oeo' : u'ew', u'oéo' : u'ew',", "tokenize is true ## if true, call this routine for", ": u'a', u'oà' : u'a', u'oả' : u'a', u'oã' :", "hơn 241->153 case #Tuy nhiên cuối cùng \"ch\" \"c\" \"t\"", "call this routine for each substring ## and re-concatenate if", "u'ʷi', u'uya' : u'ʷiə', u'uyá' : u'ʷiə', u'uyà' : u'ʷiə',", "u'oeo' : u'ew', u'óeo' : u'ew', u'òeo' : u'ew', u'ỏeo'", "u'21g', u'ớ' : 24, u'ờ' : 32, u'ở' : 312,", "u'zi', u'gì' : u'zi', u'gì' : u'zi', u'gĩ' : u'zi',", "u'gh' : u'ɣ', u'r' : u'ʐ', u's' : u'ʂ', u'gi':", ": u'ɤ̆', u'uầ' : u'ɤ̆', u'uẩ' : u'ɤ̆', u'uẫ' :", "u'oãi' : u'aj', u'oại' : u'aj', u'oay' : u'ăj', u'oáy'", "từ tiếng anh -> đọc từng kí tự #Now #+Thêm", "212, u'ế' : 45, u'ề' : 32, u'ể' : 214,", "u'o', u'ôồ' : u'o', u'ôổ' : u'o', u'ôỗ' : u'o',", "u'd' : u'j', u'h' : u'h', u'p' : u'p', u'qu'", "u'iə', u'ỉa' : u'iə', u'ĩa' : u'iə', u'ịa' : u'iə',", "u'35g', u'ệ' : u'21g', u'í' : 24, u'ì' : 32,", "letter2sound+=EN[CHAR]+\" \" else: letter2sound+=char+\" \" IPA+=T2IPA_split(letter2sound,\"\")+\" \" else: #Giữ nguyên", ": u'ej', u'oẽ' : u'ej', u'oẹ' : u'ej', u'oai' :", "N_tones , Cus_onglides, Cus_offglides, Cus_onoffglides, Cus_qu, Cus_gi] DICT={} #144 in", "Problem with ủy onglide and off-glide is a big problem", "= epitran.Epitran('vie-Latn') r=epi.transliterate(text) return r def T2IPA_split(text,delimit): sys.path.append('./Rules') # make", "u't', u'c' : u'k', u'm' : u'm', u'n' : u'ŋ',", "'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw' } S_onglides = {", "u'a', u'uá' : u'a', u'uà' : u'a', u'uả' : u'a',", "cod, ton) = trans(word, dialect, glottal, pham, cao, palatals) if", "'ə', 'ʌ', 'm', '!', '∫', 'ð', 'u', 'e', 'w', 'p',", "len(text[ic:]) and l == text[ic:ic+len(l)]: output+=delimit+l check =1 skip=len(l)-1 break", "if nuc not in [u'i', u'e', u'ɛ']: if cod ==", "u'uặ' : u'ʷă', u'uâ' : u'ʷɤ̆', u'uấ' : u'ʷɤ̆', u'uầ'", "u'et', u'oẹt' : u'et' } S_onoffglides = { u'oe' :", "''' di <-> gi : zi1 dìm <-> gìm :", "offglides[nucl][-1] nuc = offglides[nucl][:-1] elif word in gi: # if", "u'ŋ', u'ng' : u'ŋ', u'nh' : u'n', u'ch' : u't'", "One is that e language to another by\",\"/\").replace(\"/\",\"\")) #Case need", "u'ẻ' : 312, u'ẽ' : u'35g', u'ẹ' : u'21g', u'ế'", "u'qụy' : u'kwi'} ####################################################### #central.py #coding: utf-8 C_onsets = {", "u'oẽt' : u'et', u'oẹt' : u'et' } N_onoffglides = {", "= vi2IPA(line) nor = T2IPA(line) if nor in List_token: print(line", ": u'o', u'ổ' : u'o', u'ỗ' : u'o', u'ộ' :", "show available onsets. Onsets are splitted into 3 types. Type", ": u'35g', u'ặ' : u'21g', u'é' : 24, u'è' :", ": 3, u'ậ' : 6, u'ắ' : 5, u'ằ' :", "u'ỵ' : 212, } S_tones_p = { u'á' : 5,", "4, u'ữ' : 4, u'ự' : 6, u'ý' : 5,", "1985: 181) if dialect == 's': if cod in [u'm',", "= [word for word in words if word!=u'_'] for i", "if word[0:2] in gi and cod and len(word) == 3:", "u'ắ' : 24, u'ằ' : 32, u'ẳ' : 312, u'ẵ'", "4, u'ẵ' : 4, u'ặ' : 6, u'é' : 5,", "u'ọ' : u'ɔ', u'ô' : u'o', u'ố' : u'o', u'ồ'", ": 4, u'ẵ' : 4, u'ặ' : 6, u'é' :", "4, u'ợ' : 6, u'ú' : 5, u'ù' : 2,", ": 32, u'ẻ' : 312, u'ẽ' : u'35g', u'ẹ' :", "['p', 't', 'k']: ton = u'6b' # labialized allophony (added", "u'j', u'tr' : u'ʈ', u'k' : u'k', u'c' : u'k',", "line in content: if T2IPA(line) in Pair: lin2 =Pair[T2IPA(line)] if", "u't' if cod == u'ŋ': cod = u'n' # There", "if tk.lower().upper() == tk: #print(\"ENGLISH\",tk) #Đọc tiếng anh từng chữ", "32, u'ể' : 214, u'ễ' : 214, u'ệ' : 212,", "u'ợ' : 6, u'ú' : 5, u'ù' : 2, u'ủ'", "ton = u'45' # Modification for 8-tone system if cao", "for tok in reversed(token_under): TK.insert(iuv, tok) IPA=\"\" for tk in", "'r', ':', 'η', 'f', ';', 'e', 't', \"'\"] def Parsing(listParse,", "2, u'ổ' : 4, u'ỗ' : 3, u'ộ' : 6,", "been removed due to none sound modifi = [\"k͡p\",\"ŋ͡m\"] symbols", "== u'gi' and cod and len(word) == 3: # if", "in SET: DICT.update(s) list_phoneme=DICT.values() list_phoneme=list(list_phoneme) English_phoneme=[\"p\",\"b\",\"t\",\"d\",\"t∫\",\"dʒ\",\"k\",\"g\",\"f\",\"v\",\"ð\",\"θ\",\"s\",\"z\",\"∫\",\"ʒ\",\"m\",\"n\",\"η\",\"l\",\"r\",\"w\",\"j\",\"ɪ\",\"i:\",\"ʊ\",\"u:\",\"e\",\"ə\",\"ɜ:\",\"ɒ\",\"ɔ:\",\"æ\",\"ʌ\",\"ɑ:\",\"ɪə\",\"ʊə\",\"eə\",\"eɪ\",\"ɔɪ\",\"aɪ\",\"əʊ\",\"aʊ\",'ʃ',\"ʤ\",\"ʧ\"] Special=['jw', 'ŋw', 'bw', 'vw',", ": u'wi', u'qũy' : u'wi', u'qụy' : u'wi'} ################################################3 import", "Cus_onoffglides, Cus_qu, Cus_gi if pham or cao: if dialect ==", "214, u'ỡ' : 214, u'ợ' : 212, u'ú' : 45,", "\"oà\", \"oè\",\"òo\", \"uỳ\", \"ả\",\"ẳ\",\"ẩ\",\"ẻ\",\"ể\",\"ỉ\",\"ỏ\",\"ổ\",\"ở\",\"ủ\",\"ử\",\"ỷ\",\"iể\",\"ỏa\",\"oẳ\",\"ỏe\",\"oỏ\",\"uẩ\",\"uể\",\"uổ\",\"ưở\",\"ủy\",\"ưở\",\"uyể\",\"yể\", #hook \"oả\", \"oẻ\",\"ỏo\", \"uỷ\", \"ã\",\"ẵ\",\"ẫ\",\"ẽ\",\"ễ\",\"ĩ\",\"õ\",\"ỗ\",\"ỡ\",\"ũ\",\"ữ\",\"ỹ\",\"iễ\",\"õa\",\"oẵ\",\"õe\",\"oõ\",\"uẫ\",\"uễ\",\"uỗ\",\"ưỡ\",\"ũy\",\"ưỡ\",\"uyễ\",\"yễ\", #tilde", "onset elif nucl in onglides and ons == u'kw': nuc", "(Southern and Central dialects) else: if nuc in [u'i', u'e']:", ": u'o', u'ua' : u'uə', u'úa' : u'uə', u'ùa' :", "== 's': onsets, nuclei, codas, tones, onglides, offglides, onoffglides, qu,", "u'a': nuc = u'ɛ' # Final palatals (Northern dialect) if", ": u'zi'} N_qu = {u'quy' : u'kwi', u'qúy' : u'kwi',", "u'u' : u'u', u'ú' : u'u', u'ù' : u'u', u'ủ'", "= u'w' elif nucl in offglides: cod = offglides[nucl][-1] nuc", "u'è' : u'ɛ', u'ẻ' : u'ɛ', u'ẽ' : u'ɛ', u'ẹ'", ": u'ew', u'oẽo' : u'ew', u'oẹo' : u'ew', u'oeo' :", "42, u'ử' : 312, u'ữ' : 312, u'ự' : u'21g',", "symbol not in list if str(char) in [\"ˈ\",\"ˌ\",\"*\"]: continue print(\"this", "epitran.Epitran('vie-Latn') r=epi.transliterate(text) return r def T2IPA_split(text,delimit): sys.path.append('./Rules') # make sure", "# Modification for 8-tone system if cao == 1: if", "u'uyê' : u'ʷiə', u'uyế' : u'ʷiə', u'uyề' : u'ʷiə', u'uyể'", "S_nuclei, S_codas, S_tones, S_onglides, S_offglides, S_onoffglides, S_qu, S_gi #Custom onsets,", "== text[ic:ic+len(l)]: output+=delimit+l check =1 skip=len(l)-1 break if check ==", ": 3, u'ỵ' : 6, } Cus_gi = { u'gi'", "33, u'é' : 24, u'è' : 32, u'ẻ' : 312,", "u'kwi', u'qùy' : u'kwi', u'qủy' : u'kwi', u'qũy' : u'kwi',", "' ( ) Have been removed due to none sound", "Các trường hợp có cách bỏ dấu khác nhau đều", ": u'ɔ', u'ọo' : u'ɔ', u'oo' : u'ɔ', u'oó' :", "IPA=\"\" for tk in TK: ipa = T2IPA(tk).replace(\" \",\"_\") if", "u'ị' : u'21g', u'ó' : 24, u'ò' : 32, u'ỏ'", "u'í' : u'i', u'ì' : u'i', u'ỉ' : u'i', u'ĩ'", "u'e']: if cod == u'k': cod = u't' if cod", "u'ʷa', u'uă' : u'ʷă', u'uắ' : u'ʷă', u'uằ' : u'ʷă',", "4, u'ự' : 6, u'ý' : 5, u'ỳ' : 2,", "u'ó' : 5, u'ò' : 2, u'ỏ' : 4, u'õ'", "cod = '' ton = 0 oOffset = 0 cOffset", "cũng như case Tiếng anh: => dùng etrain cho tiếng", "vòm: không có w ở trước => Try to add", "gộp chung làm một #Disable convert from 'ɲ' to 'ɲ''", "u'a', u'ã' : u'a', u'ạ' : u'a', u'â' : u'ɤ̆',", "u'ỗ' : 214, u'ộ' : 212, u'ớ' : 45, u'ờ'", "u'ŋ', u'ph' : u'f', u'v' : u'v', u'x' : u's',", "kwit5 thủa <-> thuở : tʰuə4 tòe <-> toè :", "u'ơ' : u'ɤ', u'ớ' : u'ɤ', u'ờ' : u'ɤ', u'ở'", "u'c', u'kh' : u'x', u'g' : u'ɣ', u'l' : u'l',", "<-> yêu : iəw1 khoắng <-> khuắng : xwʷăŋ5 khỏe", "\"ã\",\"ẵ\",\"ẫ\",\"ẽ\",\"ễ\",\"ĩ\",\"õ\",\"ỗ\",\"ỡ\",\"ũ\",\"ữ\",\"ỹ\",\"iễ\",\"õa\",\"oẵ\",\"õe\",\"oõ\",\"uẫ\",\"uễ\",\"uỗ\",\"ưỡ\",\"ũy\",\"ưỡ\",\"uyễ\",\"yễ\", #tilde \"oã\", \"oẽ\",\"õo\", \"uỹ\", \"ạ\",\"ặ\",\"ậ\",\"ẹ\",\"ệ\",\"ị\",\"ọ\",\"ộ\",\"ợ\",\"ụ\",\"ự\",\"ỵ\",\"iệ\",\"ọa\",\"oặ\",\"ọe\",\"oọ\",\"uậ\",\"uệ\",\"uệ\",\"ượ\",\"ụy\",\"ượ\",\"uyệ\",\"yệ\", #dot \"oạ\", \"oẹ\",\"ọo\", \"uỵ\"]", "u'iu', u'uỷu' : u'iu', u'uỹu' : u'iu', u'uỵu' : u'iu',", ": u'ʷă', u'oẳ' : u'ʷă', u'oẵ' : u'ʷă', u'oặ' :", ": u'ʷiə', u'uyạ' : u'ʷiə', u'uyê' : u'ʷiə', u'uyế' :", "u'iề' : u'iə', u'iể' : u'iə', u'iễ' : u'iə', u'iệ'", ": u'ɤ̆', u'ue' : u'ɛ', u'ué' : u'ɛ', u'uè' :", ": 4, u'ỹ' : 3, u'ỵ' : 6, } N_gi", "u'uôi' : u'uəj', u'uối' : u'uəj', u'uồi' : u'uəj', u'uổi'", ": u'uə', } Cus_offglides = { u'ai' : u'aj', u'ái'", "u'ʷi', u'úy' : u'uj', u'ùy' : u'uj', u'ủy' : u'uj',", "u'ứa' : u'ɯə', u'ừa' : u'ɯə', u'ửa' : u'ɯə', u'ữa'", "tone_type=0 if tone_type==0: pham=1 else: cao=1 #Input text line =", "list custom # Các trường hợp có cách bỏ dấu", ": u'kwi', u'qụy' : u'kwi'} ####################################################### # North # #coding:", "if dialect == 'n': onsets, nuclei, codas, tones, onglides, offglides,", "if word!=u'-'] words = [word for word in words if", ": 214, u'ụ' : 212, u'ứ' : 45, u'ừ' :", ": u'ŋ', u'nh' : u'ɲ', u'ch' : u'k' } #tones", "but... else: # if there is no onset... ons =", "0 dialect='n' #\"c\"\"s\" tone_type=0 if tone_type==0: pham=1 else: cao=1 #Input", "u'o', u'ôô' : u'o', u'ôố' : u'o', u'ôồ' : u'o',", "'kw', 'aɪ', 'iɛ', 'ɤ̆', 'ɔ:', 'ăj', 'ʷa', 'eə', 'u:', 'uj',", "u'oẽt' : u'et', u'oẹt' : u'et' } C_onoffglides = {", "in TK: ipa = T2IPA(tk).replace(\" \",\"_\") if ipa ==\"\": IPA+=tk+\"", "bắc : t theo nam -> custom k vì nó", ": 312, u'ỡ' : u'35g', u'ợ' : u'21g', u'ú' :", "u'iu', u'uyú' : u'iu', u'uyù' : u'iu', u'uyủ' : u'iu',", "same mapping:\",trung) List_token = list(set(List_token)) #print(List_token) print(len(List_token)) ################################ #Looking for", "#print(vi2IPA_split(\"!Singapo english? đại học là IUYE gì khôngtontaij NIYE BoOK\",\"'\"))", "u'i', u'ỵ' : u'i', u'eo' : u'eo', u'éo' : u'eo',", "u'iə', u'iế' : u'iə', u'iề' : u'iə', u'iể' : u'iə',", ": 13, u'ò' : 42, u'ỏ' : 312, u'õ' :", "ipa ==\"\": IPA+=tk+\" \" elif ipa[0]==\"[\" and ipa[-1]==\"]\": eng =", "if cao == 1: if ton == u'5' and cod", "phoneme follow the https://vi.wikipedia.org/wiki/%C3%82m_v%E1%BB%8B_h%E1%BB%8Dc_ti%E1%BA%BFng_Vi%E1%BB%87t #Improve pronoune between N C S", "âm u'uy' : u'ʷi', u'uý' : u'ʷi', u'uỳ' : u'ʷi',", "'ɯə', 'aw', '3', 'θ', 'v', 'ʊ', 'ʤ', 'ɔ', '1', 'ʧ',", "utf-8 C_onsets = { u'b' : u'b', u't' : u't',", "u'ăj', u'uày' : u'ăj', u'uảy' : u'ăj', u'uãy' : u'ăj',", ": 32, u'ỏ' : 312, u'õ' : u'35g', u'ọ' :", "u'ọa' : u'ʷa', u'oă' : u'ʷă', u'oắ' : u'ʷă', u'oằ'", ": u'a', u'ã' : u'a', u'ạ' : u'a', u'â' :", ": u'aj', u'oại' : u'aj', u'oay' : u'ăj', u'oáy' :", ": u'ʷă', u'oằ' : u'ʷă', u'oẳ' : u'ʷă', u'oẵ' :", "if word[i] in tones] if tonelist: ton = str(tonelist[len(tonelist)-1]) else:", "word_tokenize(TN) print(\"Vietnamese Tokenize: \",TK) for iuv,under_valid in enumerate(TK): token_under=under_valid.split(\" \")", "u'ể' : u'e', u'ễ' : u'e', u'ệ' : u'e', u'i'", "[word for word in words if len(word)>0] ## hack to", "u'45' # Modification for 8-tone system if cao == 1:", "u'gì' : u'ji', u'gĩ' : u'ji', u'gị' : u'ji' }", "S_tones , S_onglides, S_offglides, S_onoffglides, S_qu, S_gi, C_onsets, C_nuclei, C_codas#,", ": 4, u'ỗ' : 3, u'ộ' : 6, u'ớ' :", "u'z' else: nucl = word[oOffset:l-cOffset] if nucl in nuclei: if", ": u'aj', u'uay' : u'ăj', u'uáy' : u'ăj', u'uày' :", "u'uỳu' : u'ʷiu', u'uỷu' : u'ʷiu', u'uỹu' : u'ʷiu', u'uỵu'", "'t∫', 'ɲw', 'eo', 'sw', 'tw', 'ʐw', 'iɛ', 'ʷe', 'i:', 'ɯə',", "'3', 'ɣ', '!', 'ð', 'ʧ', '6', 'ʒ', 'ʐ', 'z', 'v',", ": u'ɯəw' } N_onglides = { u'oa' : u'a', u'oá'", "= u'ŋ' # Monophthongization (Southern dialects: Thompson 1965: 86; Hoàng", "u'oe' : u'ʷɛ', u'óe' : u'ʷɛ', u'òe' : u'ʷɛ', u'ỏe'", "= u'k' if cod == u'n': cod = u'ŋ' #", "N_nuclei, N_codas#, N_tones , N_onglides, N_offglides, N_onoffglides, N_qu, N_gi, Cus_onsets,", "u'ẫu' : u'ɤ̆w', u'ậu' : u'ɤ̆w', u'eo' : u'ew', u'éo'", "= substrings[1::2] + [''] ipa = [convert(x, dialect, glottal, pham,", "u'oẻ' : u'ʷɛ', u'oẽ' : u'ʷɛ', u'oẹ' : u'ʷɛ', u'oe'", "u'35g', u'ọ' : u'21g', # u'ô' : 33, u'ố' :", "u'ữ' : 3, u'ự' : 6, u'ý' : 5, u'ỳ'", "u'ă', u'uặ' : u'ă', u'uâ' : u'ɤ̆', u'uấ' : u'ɤ̆',", "312, u'ĩ' : u'35g', u'ị' : u'21g', # u'o' :", "we can find the Rules files #Setup option glottal =", "= onsets[word[0:3]] oOffset = 3 elif word[0:2] in onsets: #", ": 3, u'ẹ' : 6, u'ế' : 5, u'ề' :", "u'òe' : u'e', u'ỏe' : u'e', u'õe' : u'e', u'ọe'", "u'ỗ' : u'35g', u'ộ' : u'21g', u'ớ' : 24, u'ờ'", "u'ɛ', u'é' : u'ɛ', u'è' : u'ɛ', u'ẻ' : u'ɛ',", "onsets[word[0:2]] oOffset = 2 elif word[0] in onsets: # if", "in onoffglides: cod = onoffglides[nucl][-1] nuc = onoffglides[nucl][0:-1] if ons", "u'uyề' : u'ʷiə', u'uyể' : u'ʷiə', u'uyễ' : u'ʷiə', u'uyệ'", "\\u02C0 for raised glottal instead of g C_tones_p = {", "tk.lower().upper() == tk: #print(\"ENGLISH\",tk) #Đọc tiếng anh từng chữ letter2sound=\"\"", "+\"\\t\\t:\\t\\t\"+T2IPA(line)) print(\"Same pair:\" , cout_same) #Các trường hợp dẫn đến", "in onsets: # if single onset ons = onsets[word[0]] oOffset", "u'òa' : u'ʷa', u'ỏa' : u'ʷa', u'õa' : u'ʷa', u'ọa'", "'ɤ', '2', 'ʤ', 'i', '.', 'ɒ', 'b', 'h', 'n', 'ʂ',", "'ăj', 'ʷa', 'eə', 'u:', 'uj', 'aʊ', 'uə', 'aj', 'iə', 'iw',", "u'ʷet', u'oẹt' : u'ʷet' } Cus_onoffglides = { u'oe' :", ": 2, u'ỉ' : 4, u'ĩ' : 3, u'ị' :", "dialect == 's': tones_p = S_tones_p #Custom tones_p = Cus_tones_p", "u'ʷa', u'uã' : u'ʷa', u'uạ' : u'ʷa', u'uă' : u'ʷă',", "u'en', u'oẽn' : u'en', u'oẹn' : u'en', u'oet' : u'et',", "u'kwi', u'qụy' : u'kwi'} ####################################################### #central.py #coding: utf-8 C_onsets =", "List_token=[] List_pair = [] with open(\"Popular.txt\", encoding=\"utf-8\") as f: content=f.read().splitlines()", "just have 'gi' and a coda... if word[0:2] in gi", "'6', '2', 'x', 'ă'] listParse.sort(reverse = True,key=len) output=\"\" skip=0 for", ": u'k', u'gh' : u'ɣ', u'r' : u'ʐ', u's' :", ": 4, u'ậ' : 6, u'ắ' : 5, u'ằ' :", "theo bắc : t theo nam -> custom k vì", "u'p', u't' : u'k', u'c' : u'k', u'm' : u'm',", ": u'ʷe', u'uễ' : u'ʷe', u'uệ' : u'ʷe', u'uơ' :", "eng[-1] == \"*\": if tk.lower().upper() == tk: #Đọc tiếng anh", "u'ɤ̆', u'uấ' : u'ɤ̆', u'uầ' : u'ɤ̆', u'uẩ' : u'ɤ̆',", "u'á' : 45, u'à' : 32, u'ả' : 214, u'ã'", ": u'ɤ̆w', u'eo' : u'ew', u'éo' : u'ew', u'èo' :", "32, u'ẻ' : 312, u'ẽ' : u'35g', u'ẹ' : u'21g',", "e language to another by\",\"/\").replace(\"/\",\"\")) #Case need to be deal:", "underthesea import word_tokenize import eng_to_ipa SET=[S_onsets, S_nuclei, S_codas#, S_tones ,", ": 5, u'ỳ' : 2, u'ỷ' : 4, u'ỹ' :", "u'ằ' : 32, u'ẳ' : 214, u'ẵ' : 214, u'ặ'", "'5', ' ', 'c', 'j', 'x', 'ʈ', ',', '4', 'ʊ',", ": 312, u'ỡ' : u'35g', u'ợ' : u'21g', # u'u'", "'n': tones_p = N_tones_p if dialect == 'c': tones_p =", "codas, onglides, offglides, onoffglides, qu, gi = Cus_onsets, Cus_nuclei, Cus_codas,", "= nuclei[nucl] # there's your nucleus elif nucl in onglides", "+ modifi + Special symbols = list(set(symbols)) symbols.sort(reverse = True,key=len)", "u'aw', u'oào' : u'aw', u'oảo' : u'aw', u'oão' : u'aw',", "6, u'ú' : 5, u'ù' : 2, u'ủ' : 4,", "tone_type==0: pham=1 else: cao=1 #Input text line = text if", "cod == u'k' and nuc in [u'i', u'e', u'ɛ']: cod", "u'ẹ' : 212, u'ế' : 45, u'ề' : 32, u'ể'", "an onglide... nuc = onglides[nucl] # modify the nuc accordingly", ": u'ʷiu', u'uyu' : u'ʷiu', u'uýu' : u'ʷiu', u'uỳu' :", "u'ọ' : u'21g', u'ố' : 24, u'ồ' : 32, u'ổ'", "u'a', u'òa' : u'a', u'ỏa' : u'a', u'õa' : u'a',", "của tiếng anh #print(vi2IPA_split(\"Another table was prepared to show available", "u'ỵ' : 6, } N_gi = { u'gi' : u'zi',", "u'uổi' : u'uəj', u'uỗi' : u'uəj', u'uội' : u'uəj', u'ươi'", "u'oèn' : u'ʷen', u'oẻn' : u'ʷen', u'oẽn' : u'ʷen', u'oẹn'", "u'ẩy' : u'ɤ̆j', u'ẫy' : u'ɤ̆j', u'ậy' : u'ɤ̆j', u'âu'", "'!', '∫', 'ð', 'u', 'e', 'w', 'p', 'ʃ', 'æ', \"'\",", "= [convert(x, dialect, glottal, pham, cao, palatals, delimit).strip() for x", "convert(word, dialect, glottal, pham, cao, palatals, delimit): \"\"\"Convert a single", "if ipa ==\"\": IPA+=delimit+tk+delimit+\" \" elif ipa[0]==\"[\" and ipa[-1]==\"]\": eng", "u'uyế' : u'iə', u'uyề' : u'iə', u'uyể' : u'iə', u'uyễ'", "5, u'ừ' : 2, u'ử' : 4, u'ữ' : 4,", "u'ʷe', u'uể' : u'ʷe', u'uễ' : u'ʷe', u'uệ' : u'ʷe',", "tones, onglides, offglides, onoffglides, qu, gi = S_onsets, S_nuclei, S_codas,", "if nuc == u'ɯə': nuc = u'ɯ' # Tones #", "# } N_tones = { u'á' : 24, u'à' :", "if there is an onset... ons = ons+u'w' # labialize", "5, u'ề' : 2, u'ể' : 4, u'ễ' : 4,", "u'oét' : u'et', u'oèt' : u'et', u'oẻt' : u'et', u'oẽt'", "u'e', u'ệ' : u'e', u'i' : u'i', u'í' : u'i',", "# if there isn't an onset.... ons = u'ʔ'+nuclei[nucl] #", ": 32, u'ở' : 312, u'ỡ' : u'35g', u'ợ' :", "to fix aberrant 33 error tonelist = [tones[word[i]] for i", "u'u', u'ủ' : u'u', u'ũ' : u'u', u'ụ' : u'u',", "'?', 'ɪ', 'l', '.', 'j', ':', 't', 'ʒ', 'ə', 'ʌ',", "cout_same=0 with open(\"Popular.txt\", encoding=\"utf-8\") as f: content=f.read().splitlines() for line in", "Cus_nuclei, Cus_codas, Cus_onglides, Cus_offglides, Cus_onoffglides, Cus_qu, Cus_gi if pham or", "'c': tones_p = C_tones_p if dialect == 's': tones_p =", "u'ăj', u'uảy' : u'ăj', u'uãy' : u'ăj', u'uạy' : u'ăj',", "= 2 elif word[0] in onsets: # if single onset", "to none sound modifi = [\"k͡p\",\"ŋ͡m\"] symbols = list_phoneme +", "1 and nuc in [u'i', u'e', u'ɛ']: if cod ==", "u'ở' : u'ɤ', u'ỡ' : u'ɤ', u'ợ' : u'ɤ', u'u'", "u'éo' : u'eo', u'èo' : u'eo', u'ẻo' : u'eo', u'ẽo':", "'e', 'w', 'p', 'ʃ', 'æ', \"'\", 'h', 'o', 'k', '5',", "<-> c #g <-> gh #i <-> y #Same negative", "if cod == u'ɲ': cod = u'ɲ' # u'ŋ' elif", "u'ɤ̆', u'ậ' : u'ɤ̆', u'ă' : u'ă', u'ắ' : u'ă',", "24, u'ồ' : 32, u'ổ' : 312, u'ỗ' : u'35g',", ": u'ɛj', u'oẹ' : u'ɛj', u'oai' : u'aj', u'oái' :", "u'ʷe', u'uế' : u'ʷe', u'uề' : u'ʷe', u'uể' : u'ʷe',", "<-> khuơ : xuə1 lóe <-> loé : lwʷɛ5 ngét", "= 3 elif word[0:2] in onsets: # if onset is", "u'òa' : u'a', u'ỏa' : u'a', u'õa' : u'a', u'ọa'", "u'oặ' : u'ʷă', u'oe' : u'ʷɛ', u'oé' : u'ʷɛ', u'oè'", "u'uơ' : u'ɤ', u'uớ' : u'ɤ', u'uờ' : u'ɤ', u'uở'", "u'ữ' : u'35g', u'ự' : u'21g', u'ý' : 24, u'ỳ'", "zi1 dìm <-> gìm : zim2 din <-> gin :", "= [] with open(\"Popular.txt\", encoding=\"utf-8\") as f: content=f.read().splitlines() for line", "syllables if cOffset !=0: # Obstruent-final nang tones are modal", "in List_token: print(line + \" -> \"+nor) trung +=1 List_pair.append(line)", ": u'ʷɤ̆', u'uậ' : u'ʷɤ̆', u'ue' : u'ʷɛ', u'ué' :", "u'qụy' : u'kwi'} ####################################################### # North # #coding: utf-8 N_onsets", "in list(EN.keys()): letter2sound+=EN[CHAR]+\" \" else: letter2sound+=char+\" \" IPA+=T2IPA_split(letter2sound,delimit)+\" \" else:", ": u'aj', u'ãi' : u'aj', u'ại' : u'aj', u'ay' :", "if word[l-2:l] in codas: # if two-character coda cod =", ": u'ɔ', u'ọ' : u'ɔ', u'ô' : u'o', u'ố' :", "N_tones, N_onglides, N_offglides, N_onoffglides, N_qu, N_gi elif dialect == 'c':", "not in [u'i', u'e', u'ɛ']: if cod == u'ɲ': cod", "u'uợ' : u'ɤ', u'uy' : u'i', u'uý' : u'i', u'uỳ'", "'l', '.', 'j', ':', 't', 'ʒ', 'ə', 'ʌ', 'm', '!',", "C_onoffglides = { u'oe' : u'ej', u'oé' : u'ej', u'oè'", "onset... ons = u'w' # add a labiovelar onset elif", "#\"c\"\"s\" tone_type=0 if tone_type==0: pham=1 else: cao=1 #Input text line", "print(token_under) if len(token_under) >1: for tok in token_under: if tok", ": u'ji', u'gì' : u'ji', u'gĩ' : u'ji', u'gị' :", ": u'i', u'o' : u'ɔ', u'ó' : u'ɔ', u'ò' :", "u'â' : 33, u'ấ' : 24, u'ầ' : 32, u'ẩ'", "complain about \"from x import *\" syntax if dialect ==", ": u'35g', u'ậ' : u'21g', u'ắ' : 24, u'ằ' :", "u'yều' : u'iəw', u'yểu' : u'iəw', u'yễu' : u'iəw', u'yệu'", "u'ọ' : u'21g', u'ố' : 13, u'ồ' : 42, u'ổ'", "u'iểu' : u'iəw', u'iễu' : u'iəw', u'iệu' : u'iəw', u'yêu'", "u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j' } Cus_codas = {", "u'uə': nuc = u'u' if nuc == u'ɯə': nuc =", ": u'o', u'ỗ' : u'o', u'ộ' : u'o', u'ơ' :", "24, u'ỳ' : 32, u'ỷ' : 312, u'ỹ' : u'35g',", "################################################### #Step #Vinorm #Underthesea #For each Convert to phoneme #Nếu", "0 seq = '' try: (ons, nuc, cod, ton) =", "u'iɛ', u'uơ' : u'uə', u'uở' : u'uə', u'uờ': u'uə', u'uở'", "u'i', u'eo' : u'eo', u'éo' : u'eo', u'èo' : u'eo',", ": u'et', u'oẽt' : u'et', u'oẹt' : u'et' } C_onoffglides", "labialize it, but... else: # if there is no onset...", "ortho += ' ' if i < len(words)-1: seq =", "u'ʷet', u'oét' : u'ʷet', u'oèt' : u'ʷet', u'oẻt' : u'ʷet',", "if pham or cao: if dialect == 'n': tones_p =", "if tonelist: ton = str(tonelist[len(tonelist)-1]) else: if not (pham or", "5, u'ì' : 2, u'ỉ' : 4, u'ĩ' : 3,", "u'uẳ' : u'ă', u'uẵ' : u'ă', u'uặ' : u'ă', u'uâ'", "u'ý' : 45, u'ỳ' : 32, u'ỷ' : 214, u'ỹ'", "tiếng anh #print(vi2IPA_split(\"Another table was prepared to show available onsets.", "có trong từ tiếng anh -> đọc từng kí tự", "u'uỹ' : u'i', u'uỵ' : u'i', u'uya' : u'iə', u'uyá'", "u'uở' : u'uə', u'uỡ' : u'uə', u'uợ' : u'uə', }", "gi: # if word == 'gi', 'gì',... ons = gi[word][0]", "u'k', u'gh' : u'ɣ', u'r' : u'z', u's' : u's',", "in enumerate(text): #print(char,skip) check = 0 if skip>0: skip=skip-1 continue", ": u'ʷa', u'oạ' : u'ʷa', u'óa' : u'ʷa', u'òa' :", "'ɑ:', 'tʃ', 'ʷe', 'ɛu', 'ɔɪ', 'ʷi', 'eɪ', 'ɤj', 'ɯw', 'ɛj',", "\"'\" #print(vi2IPA_split(\"speech? Secondly, we paper, we investigate work! One is", "u'ụi' : u'uj', u'uy' : u'uj', u'úy' : u'uj', u'ùy'", "u'wi'} ############################################ #south.py #coding: utf-8 S_onsets = { u'b' :", "<-> ngoèo : ŋwew2 quít <-> quýt : kwit5 thủa", "45, u'ề' : 32, u'ể' : 214, u'ễ' : 214,", "print(\"none\") ''' ################################################### #Step #Vinorm #Underthesea #For each Convert to", ": 212, u'ú' : 45, u'ù' : 32, u'ủ' :", "and u as in wiki # *** Problem with ủy", ": u'ɛ', u'ẽ' : u'ɛ', u'ẹ' : u'ɛ', u'ê' :", "u'uợ' : u'ʷɤ', u'uy' : u'ʷi', u'uý' : u'ʷi', u'uỳ'", ": 312, u'ợ' : u'21g', u'ú' : 13, u'ù' :", ": 312, u'ỗ' : u'35g', u'ộ' : u'21g', u'ớ' :", "\" ,ipa) else: IPA+=ipa+\" \" IPA=re.sub(' +', ' ', IPA)", "u'21g' and cod in ['p', 't', 'k']: #if ton ==", "u'ɛu', u'ểu' : u'ɛu', u'ễu': u'ɛu', u'ệu' : u'ɛu', u'ia'", "4, u'ẫ' : 4, u'ậ' : 6, u'ắ' : 5,", "S_qu, S_gi #Custom onsets, nuclei, codas, onglides, offglides, onoffglides, qu,", "u'ầ' : 42, u'ẩ' : 312, u'ẫ' : 312, u'ậ'", "NIYE BoOK #print(len(getSymbol())) #print(getSymbol()) ''' test=\"t\" if test in syms:", "u'ew', u'oèo' : u'ew', u'oẻo' : u'ew', u'oẽo' : u'ew',", "u'uj', u'ủy' : u'uj', u'ũy' : u'uj', u'ụy' : u'uj',", "u'ế' : 5, u'ề' : 2, u'ể' : 4, u'ễ'", "u'ựi' : u'ɯj', u'ưu' : u'ɯw', u'ứu' : u'ɯw', u'ừu'", "u'ph' : u'f', u'v' : u'j', u'x' : u's', u'd'", ": 3, u'ạ' : 6, u'ấ' : 5, u'ầ' :", "u'ọe' : u'e', u'ua' : u'a', u'uá' : u'a', u'uà'", "words = [word for word in words if len(word)>0] ##", ": u'en', u'oén' : u'en', u'oèn' : u'en', u'oẻn' :", "u'ʷiu', u'uyụ' : u'ʷiu', u'uyu' : u'ʷiu', u'uýu' : u'ʷiu',", "'ʷɤ', 'ɤ̆', 'ŋw', 'ʊə', 'zi', 'ʷă', 'dw', 'eɪ', 'aɪ', 'ew',", ": u'zi'} Cus_qu = {u'quy' : u'kwi', u'qúy' : u'kwi',", "u'ɯ', u'ử' : u'ɯ', u'ữ' : u'ɯ', u'ự' : u'ɯ',", "DICT={} #144 in total syms=['ɯəj', 'ɤ̆j', 'ʷiə', 'ɤ̆w', 'ɯəw', 'ʷet',", "tones_p = S_tones_p #Custom tones_p = Cus_tones_p tones = tones_p", "u'21g', u'ớ' : 13, u'ờ' : 42, u'ở' : 312,", "token can not convert: \",cout) print(\"Number of token in the", "== u'ŋ': cod = u'ŋ͡m' if cod == u'k': cod", "if nuc in [u'i', u'e']: if cod == u'k': cod", ": 4, u'ỹ' : 4, u'ỵ' : 6, } S_gi", ": u'ew', u'oeo' : u'ew', u'óeo' : u'ew', u'òeo' :", ": u'e', u'óe' : u'e', u'òe' : u'e', u'ỏe' :", "'ʷa', 'mw', 'ɑ:', 'hw', 'ɔj', 'uj', 'lw', 'ɪə', 'ăj', 'u:',", ": u'ʷă', u'uắ' : u'ʷă', u'uằ' : u'ʷă', u'uẳ' :", "if cod in [u'm', u'p']: if nuc == u'iə': nuc", "u'ụy' : u'uj', #thay để hạn chế trùng âm u'uy'", "u'ế' : 24, u'ề' : 32, u'ể' : 312, u'ễ'", ": u'z', u'h' : u'h', u'p' : u'p', u'qu' :", ": u'iu', u'uyù' : u'iu', u'uyủ' : u'iu', u'uyũ' :", "u'oáo' : u'aw', u'oào' : u'aw', u'oảo' : u'aw', u'oão'", "cOffset = 2 elif word[l-1] in codas: # if one-character", "u'ướu' : u'ɯəw', u'ườu' : u'ɯəw', u'ưởu' : u'ɯəw', 'ưỡu'", "312, u'ữ' : u'35g', u'ự' : u'21g', # u'y' :", "if dialect == 'n': tones_p = N_tones_p if dialect ==", "u'oéo' : u'ew', u'oèo' : u'ew', u'oẻo' : u'ew', u'oẽo'", ": u'21g', u'ó' : 24, u'ò' : 32, u'ỏ' :", "to all start o and u as in wiki #", "#Now #+Thêm kí tự IPA của tiếng ANH #+Thêm xử", "u's', u'd' : u'z', u'h' : u'h', u'p' : u'p',", "nuc = onglides[nucl] # modify the nuc accordingly if ons:", "tones_p = C_tones_p if dialect == 's': tones_p = S_tones_p", "u'e', u'ể' : u'e', u'ễ' : u'e', u'ệ' : u'e',", "r def T2IPA_split(text,delimit): sys.path.append('./Rules') # make sure we can find", "u'35g', u'ẹ' : u'21g', # u'ê' : 33, u'ế' :", "u'uj', u'ũy' : u'uj', u'ụy' : u'uj', #thay để hạn", "C_tones_p if dialect == 's': tones_p = S_tones_p #Custom tones_p", ": u'zi', u'gì' : u'zi', u'gĩ' : u'zi', u'gị' :", "can find the Rules files #Setup option glottal = 0", "\" IPA=re.sub(delimit+'+', delimit, IPA) IPA=re.sub(' +', ' ', IPA) print(\"IPA", "u'qùy' : u'kwi', u'qủy' : u'kwi', u'qũy' : u'kwi', u'qụy'", ": u'ʷă', u'oặ' : u'ʷă', u'oe' : u'ʷɛ', u'oé' :", ": u'kwi', u'qụy' : u'kwi'} ####################################################### #central.py #coding: utf-8 C_onsets", "32, u'ổ' : 214, u'ỗ' : 214, u'ộ' : 212,", "u'i', u'ỹ' : u'i', u'ỵ' : u'i', u'eo' : u'eo',", "# if there is no onset... ons = u'w' #", "if dialect == 's': if cod in [u'm', u'p']: if", "and Central only) if ((dialect == 'n' and ton ==", "u'í' : 45, u'ì' : 32, u'ỉ' : 214, u'ĩ'", "\"ngh\",\"ng\",\"gh\",\"g\",\"k\",\"c\"] #coding: utf-8 #Custom phoneme follow the https://vi.wikipedia.org/wiki/%C3%82m_v%E1%BB%8B_h%E1%BB%8Dc_ti%E1%BA%BFng_Vi%E1%BB%87t #Improve pronoune", "u'uyạ' : u'ʷiə', u'uyê' : u'ʷiə', u'uyế' : u'ʷiə', u'uyề'", ": u'ɯə', u'ượ' : u'ɯə', u'yê' : u'iɛ', u'yế' :", "u'ò' : 32, u'ỏ' : 214, u'õ' : 214, u'ọ'", "u'ʂ', u'gi': u'j'} Cus_nuclei = { u'a' : u'a', u'á'", "#u'uy' : u'uj', u'úy' : u'uj', u'ùy' : u'uj', u'ủy'", "u'ẽ' : 4, u'ẹ' : 6, u'ế' : 5, u'ề'", ": u'i', u'uỹ' : u'i', u'uỵ' : u'i', u'uya' :", ":\"+ char+\":\") output+=delimit+undefine_symbol return output.rstrip()+delimit #print(\"Parsing\",Parsing(\"default\",\"iu iu\",\"|\")) def getSymbol(): for", "oOffset == 0: if glottal == 1: if word[0] not", "<= len(text[ic:]) and l == text[ic:ic+len(l)]: output+=delimit+l check =1 skip=len(l)-1", "u'ew', u'òeo' : u'ew', u'ỏeo' : u'ew', u'õeo' : u'ew',", "symbols = list(set(symbols)) symbols.sort(reverse = True,key=len) return symbols def vi2IPA_pitrain(text):", "u'uéo' : u'ew', u'uèo' : u'ew', u'uẻo' : u'ew', u'uẽo'", ": u'iə', u'iệ' : u'iə', u'oo' : u'ɔ', u'óo' :", "u'ị' : 212, u'ó' : 45, u'ò' : 32, u'ỏ'", "# u'ŋ' elif palatals != 1 and nuc in [u'i',", "u'ji', u'gí': u'ji', u'gì' : u'ji', u'gì' : u'ji', u'gĩ'", "u'ɔ', u'ó' : u'ɔ', u'ò' : u'ɔ', u'ỏ' : u'ɔ',", "u'oẻ' : u'e', u'oẽ' : u'e', u'oẹ' : u'e', u'oe'", ": u'ɔ', u'ó' : u'ɔ', u'ò' : u'ɔ', u'ỏ' :", "'u:', 'uj', 'aʊ', 'uə', 'aj', 'iə', 'iw', 'əʊ', 'ɑ:', 'tʃ',", "'' cod = '' ton = 0 seq = ''", "ŋɛt5 ngễu <-> nghễu : ŋɛu3 nghía <-> ngía :", "0: if glottal == 1: if word[0] not in onsets:", "(pham or cao): if dialect == 'c': ton = str('35')", "+ Special symbols = list(set(symbols)) symbols.sort(reverse = True,key=len) return symbols", "u'yễ' : u'iɛ', u'yệ' : u'iɛ', u'uơ' : u'uə', u'uở'", "[u'iə', u'ɯə', u'uə', u'u', u'ɯ', u'ɤ', u'o', u'ɔ', u'ă', u'ɤ̆']:", ": 2, u'ẻ' : 4, u'ẽ' : 3, u'ẹ' :", "!= u'kw': # if there is an onglide... nuc =", "u'ủi' : u'uj', u'ũi' : u'uj', u'ụi' : u'uj', u'uy'", "u'ẹ' : u'21g', u'ế' : 13, u'ề' : 42, u'ể'", ": u'iə', u'uyu' : u'iu', u'uyú' : u'iu', u'uyù' :", ">1: for tok in token_under: if tok not in content", ": u'ʐ', u's' : u'ʂ', u'gi' : u'j' } S_nuclei", "BoOK\",\"'\")) #check các ipa của tiếng anh #print(vi2IPA_split(\"Another table was", "u'ew', u'ỏeo' : u'ew', u'õeo' : u'ew', u'ọeo' : u'ew',", "####################################################### # North # #coding: utf-8 N_onsets = { u'b'", "u'iə', u'ia' : u'iə', u'iá' : u'iə', u'ià' : u'iə',", "u'ở' : 312, u'ỡ' : u'35g', u'ợ' : u'21g', u'ú'", "+ lin2 +\"\\t\\t:\\t\\t\"+T2IPA(line)) print(\"Same pair:\" , cout_same) #Các trường hợp", "print(\" ..................Out of domain word: \" ,ipa) else: IPA+=ipa+\" \"", "u'iəw', u'iểu' : u'iəw', u'iễu' : u'iəw', u'iệu' : u'iəw',", "1965:94 ff. elif nuc in [u'iə', u'ɯə', u'uə', u'u', u'ɯ',", ": u'j' } C_nuclei = { u'a' : u'a', u'á'", ": u'en', u'oèn' : u'en', u'oẻn' : u'en', u'oẽn' :", "files #Setup option glottal = 0 pham = 0 cao", "for line in content: if T2IPA(line) in Pair: lin2 =Pair[T2IPA(line)]", "word[l-2:l] in codas: # if two-character coda cod = codas[word[l-2:l]]", "'iw', 'aj', 'ɜ:', 'kw', 'nw', 't∫', 'ɲw', 'eo', 'sw', 'tw',", ": u'ɤ̆j' } N_codas = { u'p' : u'p', u't'", "u'l', u'm' : u'm', u'n': u'n', u'ngh': u'ŋ', u'nh' :", "212, u'ố' : 45, u'ồ' : 32, u'ổ' : 214,", "if single onset ons = onsets[word[0]] oOffset = 1 if", "2, u'ở' : 4, u'ỡ' : 4, u'ợ' : 6,", "char+\":\") output+=delimit+undefine_symbol return output.rstrip()+delimit #print(\"Parsing\",Parsing(\"default\",\"iu iu\",\"|\")) def getSymbol(): for s", "u'ượ' : u'ɯə', u'yê' : u'iɛ', u'yế' : u'iɛ', u'yề'", "'ăw', 'zi', 'kw', 'aɪ', 'iɛ', 'ɤ̆', 'ɔ:', 'ăj', 'ʷa', 'eə',", "#144 in total syms=['ɯəj', 'ɤ̆j', 'ʷiə', 'ɤ̆w', 'ɯəw', 'ʷet', 'iəw',", "theo nam -> custom k vì nó giảm trùng nhiều", "#Vinorm #Underthesea #For each Convert to phoneme #Nếu không được", "print(len(List_token)) ################################ #Looking for pair Pair = {} for lt", ": u'35g', u'ỵ' : u'21g', # } N_tones = {", "u'ỉ' : 4, u'ĩ' : 3, u'ị' : 6, u'ó'", "chữ qu cũng ra w) #Try to add ʷ to", "u'gí': u'ji', u'gì' : u'ji', u'gì' : u'ji', u'gĩ' :", "<-> nghét : ŋɛt5 ngễu <-> nghễu : ŋɛu3 nghía", ": u'ă', u'e' : u'ɛ', u'é' : u'ɛ', u'è' :", ": u'ɯw', u'ừu' : u'ɯw', u'ửu' : u'ɯw', u'ữu' :", ": 13, u'ằ' : 42, u'ẳ' : 312, u'ẵ' :", "u'ũa' : u'uə', u'ụa' : u'uə', u'uô' : u'uə', u'uố'", "u'uờ' : u'ʷɤ', u'uở' : u'ʷɤ', u'uỡ' : u'ʷɤ', u'uợ'", "u'ữ' : 4, u'ự' : 6, u'ý' : 5, u'ỳ'", ": u'iu', u'uýu' : u'iu', u'uỳu' : u'iu', u'uỷu' :", "open(\"Popular.txt\", encoding=\"utf-8\") as f: content=f.read().splitlines() for line in content: if", ": 312, u'ẵ' : u'35g', u'ặ' : u'21g', # u'e'", "nuc = u'ɯ' # Tones # Modified 20 Sep 2008", "punctuation = [\".\",\",\",\"!\",\":\",\"?\",\";\",\"'\"] #\" ' ( ) Have been removed", "glottal, pham, cao, palatals) if None in (ons, nuc, cod,", ": 6, u'ó' : 5, u'ò' : 2, u'ỏ' :", "chang không vòm: không có w ở trước như: \"oa,ua,a\"", "âm được => ý tưởng mượn \"tʃ\" trong teach and", "and len(word) == 3: # if you just have 'gi'", "<-> khuắng : xwʷăŋ5 khỏe <-> khoẻ : xwʷɛ4 khua", "u'uồ' : u'uə', u'uổ' : u'uə', u'uỗ' : u'uə', u'uộ'", "cod == u'ɲ': cod = u'ɲ'#u'ŋ' if palatals == 1:", ": u'ʷi', u'uỹ' : u'ʷi', u'uỵ' : u'ʷi', u'uya' :", "== u'ŋ': cod = u'n' # There is also this", "offglides, onoffglides, qu, gi = S_onsets, S_nuclei, S_codas, S_tones, S_onglides,", "u'ể' : 312, u'ễ' : u'35g', u'ệ' : u'21g', u'í'", "'3', 'θ', 'v', 'ʊ', 'ʤ', 'ɔ', '1', 'ʧ', 'ʈ', '", "in [u'm', u'p']: if nuc == u'iə': nuc = u'i'", ": u'ʷet' } Cus_onoffglides = { u'oe' : u'ɛj', u'oé'", "'ʂw', 'aʊ', 'fw', 'ɛu', 'tʰ', 'tʃ', 'ɔɪ', 'xw', 'ʷɤ', 'ɤ̆',", ": 24, u'ề' : 32, u'ể' : 312, u'ễ' :", "u'qủy' : u'kwi', u'qũy' : u'kwi', u'qụy' : u'kwi'} #######################################################", "N_qu = {u'quy' : u'kwi', u'qúy' : u'kwi', u'qùy' :", "u'iə', u'uyã' : u'iə', u'uyạ' : u'iə', u'uyê' : u'iə',", "4, u'ệ' : 6, u'í' : 5, u'ì' : 2,", "u'ɣ', u'r' : u'z', u's' : u's', u'gi': u'z'} N_nuclei", ": u'zi', u'gĩ' : u'zi', u'gị' : u'zi'} Cus_qu =", ": u'ɣ', u'r' : u'ʐ', u's' : u'ʂ', u'gi': u'j'}", "'aw', '3', 'θ', 'v', 'ʊ', 'ʤ', 'ɔ', '1', 'ʧ', 'ʈ',", ": u'ɯj', u'ưu' : u'ɯw', u'ứu' : u'ɯw', u'ừu' :", "a single orthographic string to IPA.\"\"\" ons = '' nuc", "kí tự #Now #+Thêm kí tự IPA của tiếng ANH", "C_onglides = { u'oa' : u'a', u'oá' : u'a', u'oà'", "to another by\",\"/\").replace(\"/\",\"\")) #Case need to be deal: # NIYE", "5, u'ề' : 2, u'ể' : 4, u'ễ' : 3,", "u'uạy' : u'ăj', u'uây' : u'ɤ̆j', u'uấy' : u'ɤ̆j', u'uầy'", "f: content=f.read().splitlines() for line in content: if T2IPA(line) in Pair:", "or (dialect == 'c' and ton == u'13')) and cod", "C_codas#, C_tones , C_onglides, C_offglides, C_onoffglides, C_qu, C_gi, N_onsets, N_nuclei,", "u'ườu' : u'ɯəw', u'ưởu' : u'ɯəw', 'ưỡu' : u'ɯəw', u'ượu'", "u'ý' : 24, u'ỳ' : 32, u'ỷ' : 312, u'ỹ'", "#Input text line = text if line =='\\n': return \"\"", ": u'ɤ̆j', u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j' } N_codas", ": u'ɤj', u'ưi' : u'ɯj', u'ứi' : u'ɯj', u'ừi' :", "= [word for word in words if len(word)>0] ## hack", ": 32, u'ỷ' : 214, u'ỹ' : 214, u'ỵ' :", "u'ʷiə', u'uyả' : u'ʷiə', u'uyã' : u'ʷiə', u'uyạ' : u'ʷiə',", "listParse=['ʷiə', 'uəj', 'iəw', 'k͡p', 'ʷɤ̆', 'ɤ̆j', 'ŋ͡m', 'kwi', 'ɤ̆w', 'ɯəj',", "312, u'ự' : u'21g', u'ý' : 13, u'ỳ' : 42,", "List_token: print(line + \" -> \"+nor) trung +=1 List_pair.append(line) List_token.append(nor)", "values] seq = ''.join(v+d for v,d in zip(ipa, delimiters)) else:", "u'ẫ' : 214, u'ậ' : 212, u'ắ' : 45, u'ằ'", "is an onset... ons = ons+u'w' # labialize it, but...", "42, u'ẩ' : 312, u'ẫ' : 312, u'ậ' : u'21g',", ": u'35g', u'ợ' : u'21g', u'ú' : 24, u'ù' :", "= words[i].strip() ortho += word word = word.strip(punctuation).lower() ## 29.03.16:", "u'ả' : u'a', u'ã' : u'a', u'ạ' : u'a', u'â'", "= S_tones_p #Custom tones_p = Cus_tones_p tones = tones_p ons", "u'' ortho = u'' words = line.split() ## toss len==0", "u'ʂ', u'gi' : u'j' } C_nuclei = { u'a' :", "u'uə', u'uô' : u'uə', u'uố' : u'uə', u'uồ' : u'uə',", "u'oo' : u'ɔ', u'óo' : u'ɔ', u'òo' : u'ɔ', u'ỏo'", ": u'ɤ̆w', u'ấu' : u'ɤ̆w', u'ầu': u'ɤ̆w', u'ẩu' : u'ɤ̆w',", "u'ɯə', u'ượ' : u'ɯə', u'yê' : u'iɛ', u'yế' : u'iɛ',", "u'uyề' : u'iə', u'uyể' : u'iə', u'uyễ' : u'iə', u'uyệ'", "u'k', u'gh' : u'ɣ', u'r' : u'ʐ', u's' : u'ʂ',", "OptionParser from string import punctuation def trans(word, dialect, glottal, pham,", "<-> gích : ɣitʃ5 ia <-> iê : iə1 iêu", "\") checkinvalid=0 print(token_under) if len(token_under) >1: for tok in token_under:", "'ɪ', 'l', '.', 'j', ':', 't', 'ʒ', 'ə', 'ʌ', 'm',", "u'j', u'x' : u's', u'd' : u'j', u'h' : u'h',", "u'ʐ', u's' : u'ʂ', u'gi' : u'j' } S_nuclei =", "much memory ''' check_sym=\"ɯəjɤ̆jʷiəɤ̆wɯəwʷetiəwuəjʷentʰwʷɤ̆ʷiukwiŋ͡mk͡pcwjwuəeəbwojʷivwăwʈwʂwaʊfwɛutʰtʃɔɪxwʷɤɤ̆ŋwʊəziʷădweɪaɪewiəɣwzwɯjʷɛɯwɤjɔ:əʊʷamwɑ:hwɔjujlwɪəăju:awɛjiwajɜ:kwnwt∫ɲweoswtwʐwiɛʷei:ɯədʒɲθʌlw1ɪɯd∫pəuo3ɣ!ðʧ6ʒʐzvgă_æɤ2ʤi.ɒbhnʂɔɛkm5cjxʈ,4ʊsŋaʃ?r:ηf;et'\" for ine,res in enumerate(Results): if res", "u'ɯə', u'ườ' : u'ɯə', u'ưở' : u'ɯə', u'ưỡ' : u'ɯə',", ": u'o', u'ố' : u'o', u'ồ' : u'o', u'ổ' :", "u'uộ' : u'uə', u'ưa' : u'ɯə', u'ứa' : u'ɯə', u'ừa'", "u'ễu': u'ɛu', u'ệu' : u'ɛu', u'ia' : u'iə', u'ía' :", "các ipa của tiếng anh #print(vi2IPA_split(\"Another table was prepared to", "u'uə', u'uợ' : u'uə', } N_offglides = { u'ai' :", "print(\"Vietnamese Tokenize: \",TK) for iuv,under_valid in enumerate(TK): token_under=under_valid.split(\" \") checkinvalid=0", "u'ò' : 2, u'ỏ' : 4, u'õ' : 4, u'ọ'", "u'uể' : u'e', u'uễ' : u'e', u'uệ' : u'e', u'uơ'", ": u'uə', u'uỡ' : u'uə', u'uợ' : u'uə', } C_offglides", ": u'ej', u'oé' : u'ej', u'oè' : u'ej', u'oẻ' :", "u'oẹt' : u'ʷet' } Cus_onoffglides = { u'oe' : u'ɛj',", "u'et', u'oẹt' : u'et' } N_onoffglides = { u'oe' :", "tokenize = 0 dialect='n' #\"c\"\"s\" tone_type=0 if tone_type==0: pham=1 else:", "else: nucl = word[oOffset:l-cOffset] if nucl in nuclei: if oOffset", "onsets[word[0]] oOffset = 1 if word[l-2:l] in codas: # if", "cod = offglides[nucl][-1] nuc = offglides[nucl][:-1] elif word in gi:", "if check == 0: #Case symbol not in list if", "u'qụy' : u'wi'} ################################################3 import sys, codecs, re from io", ": u'uj', u'úi' : u'uj', u'ùi' : u'uj', u'ủi' :", ": u'uj', u'ùi' : u'uj', u'ủi' : u'uj', u'ũi' :", ": 312, u'ị' : u'21g', u'ó' : 13, u'ò' :", ": u'ʷiə', u'uyả' : u'ʷiə', u'uyã' : u'ʷiə', u'uyạ' :", ": u'ʐ', u's' : u'ʂ', u'gi' : u'j' } C_nuclei", ": u'iə', u'iã' : u'iə', u'iạ' : u'iə', u'iê' :", "IPA=re.sub(' +', ' ', IPA) print(\"IPA Vietnamese: \",IPA) print(\"------------------------------------------------------\") Results+=", ": u'ă', u'oằ' : u'ă', u'oẳ' : u'ă', u'oẵ' :", "đại học là IUYE gì khôngtontaij NIYE BoOK\",\"'\")) #check các", "2, u'ử' : 4, u'ữ' : 4, u'ự' : 6,", "u'ɯəw', u'ượu' : u'ɯəw' } S_onglides = { u'oa' :", "words if word!=u'_'] for i in range(0,len(words)): word = words[i].strip()", "trường hợp có cách bỏ dấu khác nhau đều gộp", "# Phương ngữ khác nhau đã thống nhất ở list", "u'ạy' : u'ăj', u'ao' : u'aw', u'áo' : u'aw', u'ào'", ": u'ʷɛ', u'òe' : u'ʷɛ', u'ỏe' : u'ʷɛ', u'õe' :", "4, u'ỹ' : 4, u'ỵ' : 6, } S_gi =", "u'ɯ', u'ữ' : u'ɯ', u'ự' : u'ɯ', u'y' : u'i',", "palatals, delimit).strip() for x in values] seq = ''.join(v+d for", "\",TK) for iuv,under_valid in enumerate(TK): token_under=under_valid.split(\" \") checkinvalid=0 print(token_under) if", "'oj', 'ʷi', 'vw', 'ăw', 'ʈw', 'ʂw', 'aʊ', 'fw', 'ɛu', 'tʰ',", ": u'iə', u'uyế' : u'iə', u'uyề' : u'iə', u'uyể' :", "u'm', u'n': u'n', u'ngh': u'ŋ', u'nh' : u'ɲ', u'ng' :", ": u'ɔ', u'ỏ' : u'ɔ', u'õ' : u'ɔ', u'ọ' :", ": 5, u'ì' : 2, u'ỉ' : 4, u'ĩ' :", "u'à' : 42, u'ả' : 312, u'ã' : 312, u'ạ'", "u'ờ' : 32, u'ở' : 214, u'ỡ' : 214, u'ợ'", "tones = tones_p ons = '' nuc = '' cod", ": u'ɔ', u'õ' : u'ɔ', u'ọ' : u'ɔ', u'ô' :", "u'ự' : u'21g', u'ý' : 13, u'ỳ' : 42, u'ỷ'", "(TypeError): pass return seq ########################333 from vinorm import * from", "one letter \",\"/\")) #Lọc bỏ dấu nhấn của tiếng anh", "một > must consider (nhưng nếu thêm vào ảnh hưởng", "#thay để hạn chế trùng âm u'uy' : u'ʷi', u'uý'", "def vi2IPA_pitrain(text): epi = epitran.Epitran('vie-Latn') r=epi.transliterate(text) return r def T2IPA_split(text,delimit):", "u'ấy' : u'ɤ̆j', u'ầy' : u'ɤ̆j', u'ẩy' : u'ɤ̆j', u'ẫy'", "zip(ipa, delimiters)) else: seq = convert(word, dialect, glottal, pham, cao,", ": u'ʷiu', u'uỷu' : u'ʷiu', u'uỹu' : u'ʷiu', u'uỵu' :", "trùng âm u'uy' : u'ʷi', u'uý' : u'ʷi', u'uỳ' :", "#print(len(getSymbol())) #print(getSymbol()) ''' test=\"t\" if test in syms: print(test) else:", "u'ỏa' : u'ʷa', u'õa' : u'ʷa', u'ọa' : u'ʷa', u'oă'", "<-> ươ : ɯə1 xõa <-> xoã : swʷa3 '''", "u'uằ' : u'ă', u'uẳ' : u'ă', u'uẵ' : u'ă', u'uặ'", "3, u'ặ' : 6, u'é' : 5, u'è' : 2,", ": u'aj', u'oãi' : u'aj', u'oại' : u'aj', u'oay' :", "#+Thêm xử lí case không có cũng như case Tiếng", "3, u'ụ' : 6, u'ứ' : 5, u'ừ' : 2,", "total syms=['ɯəj', 'ɤ̆j', 'ʷiə', 'ɤ̆w', 'ɯəw', 'ʷet', 'iəw', 'uəj', 'ʷen',", "= list_phoneme + space+word_pad + English_phoneme + punctuation + tone", "u'uyụ' : u'iu', u'uyu' : u'iu', u'uýu' : u'iu', u'uỳu'", "try: (ons, nuc, cod, ton) = trans(word, dialect, glottal, pham,", "'eə', 'u:', 'uj', 'aʊ', 'uə', 'aj', 'iə', 'iw', 'əʊ', 'ɑ:',", ": u'i', u'ị' : u'i', u'o' : u'ɔ', u'ó' :", ": u'ɤ', u'ỡ' : u'ɤ', u'ợ' : u'ɤ', u'u' :", ": u'ji' } C_qu = {u'quy' : u'wi', u'qúy' :", "ons == u'kw': nuc = onglides[nucl] elif nucl in onoffglides:", ": u'k' } # See Alves 2007 (SEALS XII), Vũ", "u'21g', # u'o' : 33, u'ó' : 24, u'ò' :", ": u'uə', u'ũa' : u'uə', u'ụa' : u'uə', u'uô' :", "u'ʷiə', u'uyề' : u'ʷiə', u'uyể' : u'ʷiə', u'uyễ' : u'ʷiə',", "u'ô' : 33, u'ố' : 24, u'ồ' : 32, u'ổ'", "u'ỏe' : u'e', u'õe' : u'e', u'ọe' : u'e', u'ua'", ": 42, u'ỷ' : 312, u'ỹ' : 312, u'ỵ' :", "u'ɯəw', u'ướu' : u'ɯəw', u'ườu' : u'ɯəw', u'ưởu' : u'ɯəw',", "N_gi = { u'gi' : u'zi', u'gí': u'zi', u'gì' :", "u'uỷu' : u'iu', u'uỹu' : u'iu', u'uỵu' : u'iu', u'oen'", "[word for word in words if word!=u'-'] words = [word", ": u'ɯ', u'ứ' : u'ɯ', u'ừ' : u'ɯ', u'ử' :", "IPA) IPA=re.sub(' +', ' ', IPA) print(\"IPA Vietnamese: \",IPA) print(\"------------------------------------------------------\")", "ia <-> iê : iə1 iêu <-> yêu : iəw1", "45, u'ằ' : 32, u'ẳ' : 214, u'ẵ' : 214,", "u'ử' : 4, u'ữ' : 4, u'ự' : 6, u'ý'", "u'á' : 5, u'à' : 2, u'ả' : 4, u'ã'", "u'uy' : u'ʷi', u'uý' : u'ʷi', u'uỳ' : u'ʷi', u'uỷ'", "for c , t for t, tʃ for ch #Thay", "42, u'ở' : 312, u'ỡ' : 312, u'ợ' : u'21g',", ": 214, u'ẫ' : 214, u'ậ' : 212, u'ắ' :", "C_onoffglides, C_qu, C_gi elif dialect == 's': onsets, nuclei, codas,", "là IUYE gì khôngtontaij NIYE BoOK\",\"'\")) #check các ipa của", "'ɲ' to 'ɲ'' in north #Các âm vòng ở đây", "#hook \"oả\", \"oẻ\",\"ỏo\", \"uỷ\", \"ã\",\"ẵ\",\"ẫ\",\"ẽ\",\"ễ\",\"ĩ\",\"õ\",\"ỗ\",\"ỡ\",\"ũ\",\"ữ\",\"ỹ\",\"iễ\",\"õa\",\"oẵ\",\"õe\",\"oõ\",\"uẫ\",\"uễ\",\"uỗ\",\"ưỡ\",\"ũy\",\"ưỡ\",\"uyễ\",\"yễ\", #tilde \"oã\", \"oẽ\",\"õo\", \"uỹ\", \"ạ\",\"ặ\",\"ậ\",\"ẹ\",\"ệ\",\"ị\",\"ọ\",\"ộ\",\"ợ\",\"ụ\",\"ự\",\"ỵ\",\"iệ\",\"ọa\",\"oặ\",\"ọe\",\"oọ\",\"uậ\",\"uệ\",\"uệ\",\"ượ\",\"ụy\",\"ượ\",\"uyệ\",\"yệ\",", "u'oão' : u'aw', u'oạo' : u'aw', u'oeo' : u'ew', u'oéo'", "u'uəj', u'ươi' : u'ɯəj', u'ưới' : u'ɯəj', u'ười' : u'ɯəj',", "u'uẽo' : u'ew', u'uẹo' : u'ew', u'uai' : u'aj', u'uái'", ": u'ʷiə', u'uyà' : u'ʷiə', u'uyả' : u'ʷiə', u'uyã' :", "3 types. Type 1 are onsets which has one letter", "qu[word][:-1] nuc = qu[word][-1] else: # Something is non-Viet return", "u'ắ' : u'ă', u'ằ' : u'ă', u'ẳ' : u'ă', u'ẵ'", ": u'ɯj', u'ữi' : u'ɯj', u'ựi' : u'ɯj', u'ưu' :", ": u'j', u'x' : u's', u'd' : u'j', u'h' :", "u'ue' : u'ʷɛ', u'ué' : u'ʷɛ', u'uè' : u'ʷɛ', u'uẻ'", ": 2, u'ổ' : 4, u'ỗ' : 4, u'ộ' :", "in words if len(word)>0] ## hack to get rid of", "u'a' : 33, u'á' : 24, u'à' : 32, u'ả'", "ton == u'6' and cod in ['p', 't', 'k']: ton", "u'eo' : u'ew', u'éo' : u'ew', u'èo' : u'ew', u'ẻo'", ": u'ʷɛ', u'óe' : u'ʷɛ', u'òe' : u'ʷɛ', u'ỏe' :", ": 5, u'ò' : 2, u'ỏ' : 4, u'õ' :", "'iɛ', 'ʷe', 'i:', 'ɯə', 'dʒ', 'ɲ', 'θ', 'ʌ', 'l', 'w',", "5, u'ì' : 2, u'ỉ' : 4, u'ĩ' : 4,", "see Thompson 1965:94 ff. elif nuc in [u'iə', u'ɯə', u'uə',", "tưởng mượn \"tʃ\" trong teach and watch để thay thế", "u'ʷiu', u'uyú' : u'ʷiu', u'uyù' : u'ʷiu', u'uyủ' : u'ʷiu',", "u'òe' : u'ʷɛ', u'ỏe' : u'ʷɛ', u'õe' : u'ʷɛ', u'ọe'", "u'ỏ' : 312, u'õ' : u'35g', u'ọ' : u'21g', #", "len(word) if l > 0: if word[0:3] in onsets: #", "33, u'ó' : 24, u'ò' : 32, u'ỏ' : 312,", "'d', '∫', 'p', 'ə', 'u', 'o', '3', 'ɣ', '!', 'ð',", ": 3, u'ộ' : 6, u'ớ' : 5, u'ờ' :", "u'ã' : 3, u'ạ' : 6, u'ấ' : 5, u'ầ'", "u'ɤ̆', u'ẩ' : u'ɤ̆', u'ẫ' : u'ɤ̆', u'ậ' : u'ɤ̆',", "S_tones_p #Custom tones_p = Cus_tones_p tones = tones_p ons =", "6, u'ố' : 5, u'ồ' : 2, u'ổ' : 4,", ": 4, u'ỵ' : 6, } S_gi = { u'gi'", "u'ảo' : u'aw', u'ão' : u'aw', u'ạo' : u'aw', u'au'", "u'ng' : u'ŋ', u'ph' : u'f', u'v' : u'j', u'x'", "6, u'ý' : 5, u'ỳ' : 2, u'ỷ' : 4,", "#print(\"Parsing\",Parsing(\"default\",\"iu iu\",\"|\")) def getSymbol(): for s in SET: DICT.update(s) list_phoneme=DICT.values()", "u'uãy' : u'ăj', u'uạy' : u'ăj', u'uây' : u'ɤ̆j', u'uấy'", "[\" \"] tone=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"] punctuation = [\".\",\",\",\"!\",\":\",\"?\",\";\",\"'\"] #\" ' ( )", "45, u'ỳ' : 32, u'ỷ' : 214, u'ỹ' : 214,", "Fronting (Southern and Central dialects) else: if nuc in [u'i',", "u'ej', u'oẹ' : u'ej', u'oai' : u'aj', u'oái' : u'aj',", "tk in TK: ipa = T2IPA_split(tk,delimit).replace(\" \",\"_\") if ipa ==\"\":", "u't', u'c' : u'k', u'm' : u'm', u'n' : u'n',", "u'ɔ', u'õo' : u'ɔ', u'ọo' : u'ɔ', u'oo' : u'ɔ',", ": 312, u'ệ' : u'21g', u'í' : 13, u'ì' :", "open(\"Popular.txt\",encoding=\"utf-8\") as f: content=f.read().splitlines() tess = texts.split(\".\") Results =\"\" for", "in ['p', 't', 'k']: # fixed 8 Nov 2016 ton", "u'áy' : u'ăj', u'ày' : u'ăj', u'ảy' : u'ăj', u'ãy'", "'əʊ', 'ʷa', 'mw', 'ɑ:', 'hw', 'ɔj', 'uj', 'lw', 'ɪə', 'ăj',", ": u'ăj', u'uãy' : u'ăj', u'uạy' : u'ăj', u'uây' :", "nhiều hơn 241->153 case #Tuy nhiên cuối cùng \"ch\" \"c\"", ": 2, u'ỷ' : 4, u'ỹ' : 4, u'ỵ' :", "u'iɛ', u'yễ' : u'iɛ', u'yệ' : u'iɛ', u'uơ' : u'uə',", ": u'p', u't' : u'k', u'c' : u'k', u'm' :", "# u'ô' : 33, u'ố' : 24, u'ồ' : 32,", "u'et', u'oẽt' : u'et', u'oẹt' : u'et' } C_onoffglides =", "nucleus elif nucl in onglides and ons != u'kw': #", "<-> loé : lwʷɛ5 ngét <-> nghét : ŋɛt5 ngễu", "u'ʷa', u'oá' : u'ʷa', u'oà' : u'ʷa', u'oả' : u'ʷa',", "and ton == u'13')) and cod in ['p', 't', 'k']:", "u'kw', u'gi' : u'z', u'tr' : u'c', u'k' : u'k',", "' ', IPA) print(\"IPA Vietnamese: \",IPA) print(\"------------------------------------------------------\") return IPA def", "if eng[-1] == \"*\": if tk.lower().upper() == tk: #print(\"ENGLISH\",tk) #Đọc", "u'ɤj', u'ợi' : u'ɤj', u'ưi' : u'ɯj', u'ứi' : u'ɯj',", "3, u'ợ' : 6, u'ú' : 5, u'ù' : 2,", "from underthesea import word_tokenize import eng_to_ipa SET=[S_onsets, S_nuclei, S_codas#, S_tones", "in [\"ˈ\",\"ˌ\",\"*\"]: continue print(\"this is not in symbol :\"+ char+\":\")", "cod == u't': cod = u'k' if cod == u'n':", ": 45, u'ồ' : 32, u'ổ' : 214, u'ỗ' :", "u'21g', } # used to use \\u02C0 for the unicode", "cod in ['p', 't', 'k']: # fixed 8 Nov 2016", "phoneme tiếng anh #Nếu không có trong từ tiếng anh", ": u'kwi'} ####################################################### #central.py #coding: utf-8 C_onsets = { u'b'", ": 5, u'ằ' : 2, u'ẳ' : 4, u'ẵ' :", ": u'aj', u'ải' : u'aj', u'ãi' : u'aj', u'ại' :", "u'oẳ' : u'ʷă', u'oẵ' : u'ʷă', u'oặ' : u'ʷă', u'oe'", "deal: # NIYE BoOK #print(len(getSymbol())) #print(getSymbol()) ''' test=\"t\" if test", "thống nhất ở list custom # Các trường hợp có", "'lw', 'ɪə', 'ăj', 'u:', 'aw', 'ɛj', 'iw', 'aj', 'ɜ:', 'kw',", "== 'n': tones_p = N_tones_p if dialect == 'c': tones_p", "is true ## if true, call this routine for each", "# u'o' : 33, u'ó' : 24, u'ò' : 32,", ": u'uj', u'ũi' : u'uj', u'ụi' : u'uj', u'uy' :", "u'et', u'oẽt' : u'et', u'oẹt' : u'et' } S_onoffglides =", "5, u'ầ' : 2, u'ẩ' : 4, u'ẫ' : 4,", "u'o', u'ố' : u'o', u'ồ' : u'o', u'ổ' : u'o',", "listParse: if len(l) <= len(text[ic:]) and l == text[ic:ic+len(l)]: output+=delimit+l", "241->153 case #Tuy nhiên cuối cùng \"ch\" \"c\" \"t\" không", "u'ừ' : u'ɯ', u'ử' : u'ɯ', u'ữ' : u'ɯ', u'ự'", "u'oo' : u'ɔ', u'oó' : u'ɔ', u'oò' : u'ɔ', u'oỏ'", "u'p' : u'p', u't' : u't', u'c' : u'k', u'm'", "u'uẻo' : u'ew', u'uẽo' : u'ew', u'uẹo' : u'ew', u'uai'", "def T2IPA(text): sys.path.append('./Rules') # make sure we can find the", "u'i', u'ý' : u'i', u'ỳ' : u'i', u'ỷ' : u'i',", "u'n', u'ch' : u't' } S_tones = { u'á' :", ": 42, u'ẻ' : 312, u'ẽ' : 312, u'ẹ' :", ": u'c', u'k' : u'k', u'c' : u'k', u'gh' :", "khong, check co nguyen am #Neu co de nguyen #Neu", "or cao: if dialect == 'n': tones_p = N_tones_p if", "u'e', u'oẹ' : u'e', u'oe' : u'e', u'óe' : u'e',", ") Have been removed due to none sound modifi =", "seq = u'['+word+u']' else: seq = delimit+delimit.join(filter(None, (ons, nuc, cod,", ": 312, u'ũ' : u'35g', u'ụ' : u'21g', # u'ư'", ": u'ɤ', u'ợ' : u'ɤ', u'u' : u'u', u'ú' :", "u'p' : u'p', u't' : u'k', u'c' : u'k', u'm'", "u'õ' : 214, u'ọ' : 212, u'ố' : 45, u'ồ'", "u'ji', u'gì' : u'ji', u'gì' : u'ji', u'gĩ' : u'ji',", "o and u as in wiki # *** Problem with", "u'w', u'gi' : u'j', u'tr' : u'ʈ', u'k' : u'k',", ": u'ăj', u'oạy' : u'ăj', u'oao' : u'aw', u'oáo' :", "'n', 'ʂ', 'ɔ', 'ɛ', 'k', 'm', '5', ' ', 'c',", ": u'ʷen', u'oèn' : u'ʷen', u'oẻn' : u'ʷen', u'oẽn' :", "'n': if nuc == u'a': if cod == u'k' and", "u'ỏ' : 214, u'õ' : 214, u'ọ' : 212, u'ố'", "if ((dialect == 'n' and ton == u'24') or (dialect", "= vi2IPA_pitrain(line) #nor = vi2IPA(line) nor = T2IPA(line) if nor", "u'iə', u'uyu' : u'iu', u'uyú' : u'iu', u'uyù' : u'iu',", "u'ɯəw', u'ượu' : u'ɯəw' } N_onglides = { u'oa' :", "u'ʷet', u'oèt' : u'ʷet', u'oẻt' : u'ʷet', u'oẽt' : u'ʷet',", "# if two-character coda cod = codas[word[l-2:l]] cOffset = 2", "C_onsets, C_nuclei, C_codas, C_tones, C_onglides, C_offglides, C_onoffglides, C_qu, C_gi elif", "= u'ɛ' if cod == u'ɲ' and nuc == u'a':", ": u'35g', u'ự' : u'21g', # u'y' : 33, u'ý'", "u'ɤ', u'uy' : u'i', u'uý' : u'i', u'uỳ' : u'i',", "u'ʷɛ', u'oẻ' : u'ʷɛ', u'oẽ' : u'ʷɛ', u'oẹ' : u'ʷɛ',", "C_gi elif dialect == 's': onsets, nuclei, codas, tones, onglides,", "'ɒ', 'b', 'h', 'n', 'ʂ', 'ɔ', 'ɛ', 'k', 'm', '5',", "u'uj', u'úy' : u'uj', u'ùy' : u'uj', u'ủy' : u'uj',", "4, u'ỡ' : 3, u'ợ' : 6, u'ú' : 5,", "u'21g', u'ú' : 13, u'ù' : 42, u'ủ' : 312,", "skip>0: skip=skip-1 continue for l in listParse: if len(l) <=", "vi2IPA_pitrain(text): epi = epitran.Epitran('vie-Latn') r=epi.transliterate(text) return r def T2IPA_split(text,delimit): sys.path.append('./Rules')", "u'iə', u'ịa' : u'iə', u'ia' : u'iə', u'iá' : u'iə',", ": u'iɛ', u'yệ' : u'iɛ', u'uơ' : u'uə', u'uở' :", "# if one-character coda cod = codas[word[l-1]] cOffset = 1", "# used to use \\u02C0 for raised glottal instead of", "312, u'ẽ' : u'35g', u'ẹ' : u'21g', u'ế' : 24,", "u'ew', u'oẻo' : u'ew', u'oẽo' : u'ew', u'oẹo' : u'ew',", ": u'e', u'oè' : u'e', u'oẻ' : u'e', u'oẽ' :", ": 42, u'ẩ' : 312, u'ẫ' : 312, u'ậ' :", "seq+u' ' compound = compound + seq return compound def", "S_offglides = { u'ai' : u'aj', u'ái' : u'aj', u'ài'", "= onsets[word[0]] oOffset = 1 if word[l-2:l] in codas: #", "mapping:\",trung) List_token = list(set(List_token)) #print(List_token) print(len(List_token)) ################################ #Looking for pair", "u'ɔj', u'òi' : u'ɔj', u'ỏi' : u'ɔj', u'õi' : u'ɔj',", "s in SET: DICT.update(s) list_phoneme=DICT.values() list_phoneme=list(list_phoneme) English_phoneme=[\"p\",\"b\",\"t\",\"d\",\"t∫\",\"dʒ\",\"k\",\"g\",\"f\",\"v\",\"ð\",\"θ\",\"s\",\"z\",\"∫\",\"ʒ\",\"m\",\"n\",\"η\",\"l\",\"r\",\"w\",\"j\",\"ɪ\",\"i:\",\"ʊ\",\"u:\",\"e\",\"ə\",\"ɜ:\",\"ɒ\",\"ɔ:\",\"æ\",\"ʌ\",\"ɑ:\",\"ɪə\",\"ʊə\",\"eə\",\"eɪ\",\"ɔɪ\",\"aɪ\",\"əʊ\",\"aʊ\",'ʃ',\"ʤ\",\"ʧ\"] Special=['jw', 'ŋw', 'bw',", "u'k͡p' return (ons, nuc, cod, ton) def convert(word, dialect, glottal,", "dừng từ 1->6 #học ác cho kết quả \"c\" khác", "2, u'ẻ' : 4, u'ẽ' : 4, u'ẹ' : 6,", "Central dialects) else: if nuc in [u'i', u'e']: if cod", "u'ặ' : u'21g', u'é' : 13, u'è' : 42, u'ẻ'", "u'ề' : 2, u'ể' : 4, u'ễ' : 3, u'ệ'", "u'a', u'oá' : u'a', u'oà' : u'a', u'oả' : u'a',", "u'kwi', u'qủy' : u'kwi', u'qũy' : u'kwi', u'qụy' : u'kwi'}", "uə1 ưa <-> ươ : ɯə1 xõa <-> xoã :", "offglides, onoffglides, qu, gi = Cus_onsets, Cus_nuclei, Cus_codas, Cus_onglides, Cus_offglides,", "u'iəw', u'iễu' : u'iəw', u'iệu' : u'iəw', u'yêu' : u'iəw',", "u'ʷɤ', u'uớ' : u'ʷɤ', u'uờ' : u'ʷɤ', u'uở' : u'ʷɤ',", "'ʷiu', 'kwi', 'ŋ͡m', 'k͡p', 'cw', 'jw', 'uə', 'eə', 'bw', 'oj',", "u'et', u'oẹt' : u'et' } C_onoffglides = { u'oe' :", "u'uyu' : u'iu', u'uýu' : u'iu', u'uỳu' : u'iu', u'uỷu'", "u'ji', u'gĩ' : u'ji', u'gị' : u'ji' } C_qu =", "== 'n': onsets, nuclei, codas, tones, onglides, offglides, onoffglides, qu,", "import word_tokenize import eng_to_ipa SET=[S_onsets, S_nuclei, S_codas#, S_tones , S_onglides,", "u'21g', u'ó' : 13, u'ò' : 42, u'ỏ' : 312,", "to phoneme #Nếu không được check phoneme tiếng anh #Nếu", ": 312, u'ậ' : u'21g', u'ắ' : 13, u'ằ' :", ": 312, u'ẵ' : u'35g', u'ặ' : u'21g', u'é' :", "u'ỗ' : u'35g', u'ộ' : u'21g', # u'ơ' : 33,", "u'tr' : u'ʈ', u'k' : u'k', u'c' : u'k', u'gh'", "thêm vào ảnh hưởng chữ qu cũng ra w) #Try", "to ɛ #âm cuối: ch : k theo bắc :", "\" elif ipa[0]==\"[\" and ipa[-1]==\"]\": eng = eng_to_ipa.convert(tk) if eng[-1]", "ons = onsets[word[0:2]] oOffset = 2 elif word[0] in onsets:", "there is an onglide... nuc = onglides[nucl] # modify the", "'ə', 'u', 'o', '3', 'ɣ', '!', 'ð', 'ʧ', '6', 'ʒ',", "u'ɔ', u'oõ' : u'ɔ', u'oọ' : u'ɔ', u'ôô' : u'o',", "anh từng chữ letter2sound=\"\" for char in tk: CHAR =", ": 214, u'ệ' : 212, u'í' : 45, u'ì' :", "'!', 'ð', 'ʧ', '6', 'ʒ', 'ʐ', 'z', 'v', 'g', 'ă',", "word: \" ,ipa) else: IPA+=ipa+\" \" IPA=re.sub(delimit+'+', delimit, IPA) IPA=re.sub('", ": 214, u'ỵ' : 212, } S_tones_p = { u'á'", "'b', 'h', 'n', 'ʂ', 'ɔ', 'ɛ', 'k', 'm', '5', '", "u'è' : 2, u'ẻ' : 4, u'ẽ' : 3, u'ẹ'", "<-> \" + lin2 +\"\\t\\t:\\t\\t\"+T2IPA(line)) print(\"Same pair:\" , cout_same) #Các", ": 45, u'ằ' : 32, u'ẳ' : 214, u'ẵ' :", "u'qủy' : u'wi', u'qũy' : u'wi', u'qụy' : u'wi'} ############################################", "cho tiếng anh #+Deal case thống nhất âm vực phoneme", "u'uố' : u'uə', u'uồ' : u'uə', u'uổ' : u'uə', u'uỗ'", "follow the https://vi.wikipedia.org/wiki/%C3%82m_v%E1%BB%8B_h%E1%BB%8Dc_ti%E1%BA%BFng_Vi%E1%BB%87t #Improve pronoune between N C S Cus_onsets", ": u'uj', u'ụi' : u'uj', #u'uy' : u'uj', u'úy' :", ": ŋiw6 nghoèo <-> ngoèo : ŋwew2 quít <-> quýt", "u'ọ' : 212, u'ố' : 45, u'ồ' : 32, u'ổ'", ": 312, u'ỵ' : u'21g', } # used to use", "https://vi.wikipedia.org/wiki/%C3%82m_v%E1%BB%8B_h%E1%BB%8Dc_ti%E1%BA%BFng_Vi%E1%BB%87t #Improve pronoune between N C S Cus_onsets = {", ": u'iəw', u'yệu' : u'iəw', u'uôi' : u'uəj', u'uối' :", ": u'wi', u'qủy' : u'wi', u'qũy' : u'wi', u'qụy' :", "} S_onoffglides = { u'oe' : u'ej', u'oé' : u'ej',", "List_pair = [] with open(\"Popular.txt\", encoding=\"utf-8\") as f: content=f.read().splitlines() for", "u'ɯə', u'yê' : u'iɛ', u'yế' : u'iɛ', u'yề' : u'iɛ',", "u'ă', u'ắ' : u'ă', u'ằ' : u'ă', u'ẳ' : u'ă',", "u'aw', u'áo' : u'aw', u'ào' : u'aw', u'ảo' : u'aw',", "of token in the same mapping:\",trung) List_token = list(set(List_token)) #print(List_token)", "u'ú' : 5, u'ù' : 2, u'ủ' : 4, u'ũ'", "u'ă', u'oe' : u'e', u'oé' : u'e', u'oè' : u'e',", "enumerate(TK): token_under=under_valid.split(\" \") checkinvalid=0 print(token_under) if len(token_under) >1: for tok", "palatals = 0 tokenize = 0 dialect='n' #\"c\"\"s\" tone_type=0 if", "5, u'ù' : 2, u'ủ' : 4, u'ũ' : 3,", "u'5b' if ton == u'6' and cod in ['p', 't',", "chỉ dừng từ 1->6 #học ác cho kết quả \"c\"", "'ɔ', 'ɛ', 'k', 'm', '5', ' ', 'c', 'j', 'x',", "used to use \\u02C0 for the unicode raised glottal character", "'t', 'k']: ton = u'5b' if ton == u'6' and", "cod in ['p', 't', 'k']: ton = u'5b' if ton", "nuc = u'ɛ' if cod == u'ɲ' and nuc ==", "wi để phân biệt với úi #Remain ''' di <->", "u'iw', u'ìu' : u'iw', u'ỉu' : u'iw', u'ĩu' : u'iw',", "u'ẵ' : u'ă', u'ặ' : u'ă', u'e' : u'ɛ', u'é'", "u'ʷɤ̆', u'uầ' : u'ʷɤ̆', u'uẩ' : u'ʷɤ̆', u'uẫ' : u'ʷɤ̆',", "= onsets[word[0:2]] oOffset = 2 elif word[0] in onsets: #", ": u'ɣ', u'l' : u'l', u'm' : u'm', u'n': u'n',", "5, u'ằ' : 2, u'ẳ' : 4, u'ẵ' : 3,", "u'ɤ', u'uớ' : u'ɤ', u'uờ' : u'ɤ', u'uở' : u'ɤ',", "45, u'ầ' : 32, u'ẩ' : 214, u'ẫ' : 214,", "u't': cod = u'k' if cod == u'n': cod =", "u'uə', } Cus_offglides = { u'ai' : u'aj', u'ái' :", "u'et', u'oẽt' : u'et', u'oẹt' : u'et' } N_onoffglides =", ": u'iɛ', u'yễ' : u'iɛ', u'yệ' : u'iɛ', u'uơ' :", "u'ậu' : u'ɤ̆w', u'eo' : u'ew', u'éo' : u'ew', u'èo'", "and cod in ['p', 't', 'k']: ton = u'5b' if", "u'iəw', u'uôi' : u'uəj', u'uối' : u'uəj', u'uồi' : u'uəj',", "u'ʷi', u'uỹ' : u'ʷi', u'uỵ' : u'ʷi', u'ơi' : u'ɤj',", "u'uəj', u'uổi' : u'uəj', u'uỗi' : u'uəj', u'uội' : u'uəj',", "u'o', u'ôộ' : u'o', u'ua' : u'uə', u'úa' : u'uə',", "212, u'ú' : 45, u'ù' : 32, u'ủ' : 214,", "Nov 2016 ton = u'21' # Modification for sắc in", "in onsets: # if onset is 'ngh' ons = onsets[word[0:3]]", "u'iə', u'iã' : u'iə', u'iạ' : u'iə', u'iê' : u'iə',", "214, u'ự' : 212, u'ý' : 45, u'ỳ' : 32,", "that e language to another by\",\"/\").replace(\"/\",\"\")) #Case need to be", "anh: => dùng etrain cho tiếng anh #+Deal case thống", "'ɛj', 'iw', 'aj', 'ɜ:', 'kw', 'nw', 't∫', 'ɲw', 'eo', 'sw',", "ipa = T2IPA_split(tk,delimit).replace(\" \",\"_\") if ipa ==\"\": IPA+=delimit+tk+delimit+\" \" elif", "\",\"/\")) #Lọc bỏ dấu nhấn của tiếng anh \"'\" #print(vi2IPA_split(\"speech?", "Thompson 1965:94 ff. elif nuc in [u'iə', u'ɯə', u'uə', u'u',", "} C_onglides = { u'oa' : u'a', u'oá' : u'a',", "ton = str('33') else: ton = str('1') # Modifications for", ": u'ji' } S_qu = {u'quy' : u'wi', u'qúy' :", "delimit+delimit.join(filter(None, (ons, nuc, cod, ton)))+delimit except (TypeError): pass return seq", ": u'ɔ', u'oõ' : u'ɔ', u'oọ' : u'ɔ', u'ôô' :", "u'ễ' : 312, u'ệ' : u'21g', u'í' : 13, u'ì'", "dialect, glottal, pham, cao, palatals, delimit).strip() for x in values]", "{ u'p' : u'p', u't' : u'k', u'c' : u'k',", ": 212, u'ứ' : 45, u'ừ' : 32, u'ử' :", "u'uãi' : u'aj', u'uại' : u'aj', u'uay' : u'ăj', u'uáy'", "'o', 'k', '5', 'g', '4', 'n', ';', 'r', 'b', 'ɯ',", ": 24, u'ừ' : 32, u'ử' : 312, u'ữ' :", ": u'p', u'qu' : u'kw', u'gi' : u'z', u'tr' :", "u'á' : 24, u'à' : 32, u'ả' : 312, u'ã'", "y #Same negative / need to fix #oe <-> uê", "13, u'ù' : 42, u'ủ' : 312, u'ũ' : 312,", "312, u'ĩ' : 312, u'ị' : u'21g', u'ó' : 13,", "letter2sound=\"\" for char in tk: CHAR = str(char).lower() if CHAR", "domain word: \" ,ipa) else: IPA+=ipa+\" \" IPA=re.sub(' +', '", "u'ɯə', u'ưở' : u'ɯə', u'ưỡ' : u'ɯə', u'ượ' : u'ɯə',", "onglides and ons != u'kw': # if there is an", "4, u'ẫ' : 3, u'ậ' : 6, u'ắ' : 5,", "6, u'ấ' : 5, u'ầ' : 2, u'ẩ' : 4,", "4, u'ẹ' : 6, u'ế' : 5, u'ề' : 2,", ">= 2: ortho += ' ' if i < len(words)-1:", "#Setup option glottal = 0 pham = 0 cao =", "codas, tones, onglides, offglides, onoffglides, qu, gi = N_onsets, N_nuclei,", "u'ẽ' : 312, u'ẹ' : u'21g', u'ế' : 13, u'ề'", "word: \" ,ipa) else: IPA+=ipa+\" \" IPA=re.sub(' +', ' ',", "'ʐ', 'η', 'ŋ', 'ɒ', 'ʂ', '_', 'f', ',', 'ɛ', 'z',", "'η', 'ŋ', 'ɒ', 'ʂ', '_', 'f', ',', 'ɛ', 'z', '6',", "ton = 0 seq = '' try: (ons, nuc, cod,", ": 42, u'ử' : 312, u'ữ' : 312, u'ự' :", "# add a labiovelar onset elif nucl in onglides and", "20 Sep 2008 to fix aberrant 33 error tonelist =", "(SEALS XII), Vũ 1982 C_tones = { u'á' : 13,", "need to be deal: # NIYE BoOK #print(len(getSymbol())) #print(getSymbol()) '''", "'h', 'o', 'k', '5', 'g', '4', 'n', ';', 'r', 'b',", "iəw1 khoắng <-> khuắng : xwʷăŋ5 khỏe <-> khoẻ :", "u'uə', u'uờ': u'uə', u'uở' : u'uə', u'uỡ' : u'uə', u'uợ'", "palatals, delimit).strip() # concatenate if len(words) >= 2: ortho +=", "u'ʷɛ', u'oe' : u'ʷɛ', u'óe' : u'ʷɛ', u'òe' : u'ʷɛ',", "u'zi', u'gĩ' : u'zi', u'gị' : u'zi'} Cus_qu = {u'quy'", "u'uỵ' : u'ʷi', u'ơi' : u'ɤj', u'ới' : u'ɤj', u'ời'", ": u'ʷɛ', u'uẽ' : u'ʷɛ', u'uẹ' : u'ʷɛ', u'uê' :", ": u'aw', u'au' : u'ăw', u'áu' : u'ăw', u'àu' :", "u'ă', u'ằ' : u'ă', u'ẳ' : u'ă', u'ẵ' : u'ă',", "#Giữ nguyên IPA+=Parsing(\"default\",tk.lower(),delimit)+\" \" else: IPA+=Parsing(\"default\",eng,delimit)+\" \" #Check tu dien", "u'ươi' : u'ɯəj', u'ưới' : u'ɯəj', u'ười' : u'ɯəj', u'ưởi'", "u'ă', u'uâ' : u'ɤ̆', u'uấ' : u'ɤ̆', u'uầ' : u'ɤ̆',", "\"'\" if listParse == \"default\": listParse=['ʷiə', 'uəj', 'iəw', 'k͡p', 'ʷɤ̆',", "u'f', u'v' : u'j', u'x' : u's', u'd' : u'j',", ": u'uj', u'uy' : u'ʷi', u'úy' : u'uj', u'ùy' :", "u'oe' : u'ɛj', u'oé' : u'ɛj', u'oè' : u'ɛj', u'oẻ'", "u'35g', u'ệ' : u'21g', # u'i' : 33, u'í' :", "u'ỵ' : u'i', u'eo' : u'eo', u'éo' : u'eo', u'èo'", "reverse fronting, see Thompson 1965:94 ff. elif nuc in [u'iə',", "TTSnorm(text) print(\"------------------------------------------------------\") print(\"Text normalize: \",TN) TK= word_tokenize(TN) print(\"Vietnamese Tokenize: \",TK)", "u'uyù' : u'iu', u'uyủ' : u'iu', u'uyũ' : u'iu', u'uyụ'", "212, u'ứ' : 45, u'ừ' : 32, u'ử' : 214,", "SET: DICT.update(s) list_phoneme=DICT.values() list_phoneme=list(list_phoneme) English_phoneme=[\"p\",\"b\",\"t\",\"d\",\"t∫\",\"dʒ\",\"k\",\"g\",\"f\",\"v\",\"ð\",\"θ\",\"s\",\"z\",\"∫\",\"ʒ\",\"m\",\"n\",\"η\",\"l\",\"r\",\"w\",\"j\",\"ɪ\",\"i:\",\"ʊ\",\"u:\",\"e\",\"ə\",\"ɜ:\",\"ɒ\",\"ɔ:\",\"æ\",\"ʌ\",\"ɑ:\",\"ɪə\",\"ʊə\",\"eə\",\"eɪ\",\"ɔɪ\",\"aɪ\",\"əʊ\",\"aʊ\",'ʃ',\"ʤ\",\"ʧ\"] Special=['jw', 'ŋw', 'bw', 'vw', 'dw',", ": 4, u'ỡ' : 3, u'ợ' : 6, u'ú' :", ": u'iə', u'ía' : u'iə', u'ìa' : u'iə', u'ỉa' :", "u'ổ' : 312, u'ỗ' : u'35g', u'ộ' : u'21g', u'ớ'", ": zin1 díp <-> gíp : zip5 gen <-> ghen", ": u'uə', u'uô' : u'uə', u'uố' : u'uə', u'uồ' :", "u'ɤ̆', u'uẩ' : u'ɤ̆', u'uẫ' : u'ɤ̆', u'uậ' : u'ɤ̆',", "u'uyủ' : u'ʷiu', u'uyũ' : u'ʷiu', u'uyụ' : u'ʷiu', u'uyu'", "S_codas = { u'p' : u'p', u't' : u't', u'c'", "#Case symbol not in list if str(char) in [\"ˈ\",\"ˌ\",\"*\"]: continue", "u'gi' : u'j' } S_nuclei = { u'a' : u'a',", "khác nhau đều gộp chung làm một #Disable convert from", "to be deal: # NIYE BoOK #print(len(getSymbol())) #print(getSymbol()) ''' test=\"t\"", "u'x' : u's', u'd' : u'z', u'h' : u'h', u'p'", "u'ụy' : u'uj', u'uy' : u'ʷi', u'úy' : u'uj', u'ùy'", "u'ăj', u'ảy' : u'ăj', u'ãy' : u'ăj', u'ạy' : u'ăj',", "u'a', u'oà' : u'a', u'oả' : u'a', u'oã' : u'a',", "gen <-> ghen : ɣɛn1 ghì <-> gì : ɣi2", "u'uə', u'uộ' : u'uə', u'ưa' : u'ɯə', u'ứa' : u'ɯə',", "if one-character coda cod = codas[word[l-1]] cOffset = 1 #if", "u'ɤ̆w', u'ậu' : u'ɤ̆w', u'eo' : u'ew', u'éo' : u'ew',", "# Final palatals (Northern dialect) if nuc not in [u'i',", "quít <-> quýt : kwit5 thủa <-> thuở : tʰuə4", "u'uà' : u'a', u'uả' : u'a', u'uã' : u'a', u'uạ'", "# if single onset ons = onsets[word[0]] oOffset = 1", "u'ẩ' : 4, u'ẫ' : 3, u'ậ' : 6, u'ắ'", "hack to get rid of single hyphens or underscores words", "u'm' : u'm', u'n' : u'n', u'ng' : u'ŋ', u'nh'", "words[i].strip() ortho += word word = word.strip(punctuation).lower() ## 29.03.16: check", "= codas[word[l-1]] cOffset = 1 #if word[0:2] == u'gi' and", "in content or \"[\" in T2IPA(tok): checkinvalid=1 if checkinvalid==1: TK", "không có trong từ tiếng anh -> đọc từng kí", "iê : iə1 iêu <-> yêu : iəw1 khoắng <->", "'ʈ', ' ', 'd', 'i', 'ɣ', 'ɲ', 'ɤ', '?', 'ɪ',", "text line = text if line =='\\n': return \"\" else:", "\" IPA=re.sub(' +', ' ', IPA) print(\"IPA Vietnamese: \",IPA) print(\"------------------------------------------------------\")", "u'uẳ' : u'ʷă', u'uẵ' : u'ʷă', u'uặ' : u'ʷă', u'uâ'", "pair Pair = {} for lt in List_pair: Pair[T2IPA(lt)] =", "u'ậ' : 6, u'ắ' : 5, u'ằ' : 2, u'ẳ'", "big problem #Same positive #k <-> c #g <-> gh", ": u'ʷa', u'ọa' : u'ʷa', u'oă' : u'ʷă', u'oắ' :", "u'ếu' : u'ɛu', u'ều' : u'ɛu', u'ểu' : u'ɛu', u'ễu':", ": 5, u'à' : 2, u'ả' : 4, u'ã' :", ": 6, u'ắ' : 5, u'ằ' : 2, u'ẳ' :", "u'wi', u'qũy' : u'wi', u'qụy' : u'wi'} ############################################ #south.py #coding:", "offglides[nucl][:-1] elif word in gi: # if word == 'gi',", "\"\"\"Convert a single orthographic string to IPA.\"\"\" ons = ''", "vì nó giảm trùng nhiều hơn 241->153 case #Tuy nhiên", "u'ưởi' : u'ɯəj', u'ưỡi' : u'ɯəj', u'ượi' : u'ɯəj', u'ươu'", ": u'ă', u'oặ' : u'ă', u'oe' : u'e', u'oé' :", "Tokenize: \",TK) IPA=\"\" for tk in TK: ipa = T2IPA(tk).replace(\"", "ảnh hưởng chữ qu cũng ra w) #Try to add", "u'ẻ' : 312, u'ẽ' : 312, u'ẹ' : u'21g', u'ế'", "u'p' : u'p', u'qu' : u'kw', u'gi' : u'z', u'tr'", "u'iə', u'iá' : u'iə', u'ià' : u'iə', u'iả' : u'iə',", ": u'ɛ', u'ẹ' : u'ɛ', u'ê' : u'e', u'ế' :", "u'm' : u'm', u'n' : u'ŋ', u'ng' : u'ŋ', u'nh'", "return symbols def vi2IPA_pitrain(text): epi = epitran.Epitran('vie-Latn') r=epi.transliterate(text) return r", "u'ỏ' : 4, u'õ' : 3, u'ọ' : 6, u'ố'", ": u'21g', u'ế' : 24, u'ề' : 32, u'ể' :", ": u'ɯə', u'ừa' : u'ɯə', u'ửa' : u'ɯə', u'ữa' :", "''' return Results.rstrip() def vi2IPA(text): print(\"------------------------------------------------------\") TN= TTSnorm(text) print(\"------------------------------------------------------\") print(\"Text", "= nuclei[nucl] # there's your nucleus else: nuc = nuclei[nucl]", ": u'uə', u'uợ' : u'uə', } Cus_offglides = { u'ai'", "u'ɯ', u'ự' : u'ɯ', u'y' : u'i', u'ý' : u'i',", "'s', 'ʐ', 'η', 'ŋ', 'ɒ', 'ʂ', '_', 'f', ',', 'ɛ',", "32, u'ỏ' : 214, u'õ' : 214, u'ọ' : 212,", "if not (pham or cao): if dialect == 'c': ton", "u'uá' : u'a', u'uà' : u'a', u'uả' : u'a', u'uã'", "u'ɯəj', u'ưới' : u'ɯəj', u'ười' : u'ɯəj', u'ưởi' : u'ɯəj',", ": u'ʷi', u'uỵ' : u'ʷi', u'ơi' : u'ɤj', u'ới' :", ": u'ŋ', u'ph' : u'f', u'v' : u'j', u'x' :", "ton = str('1') # Modifications for closed syllables if cOffset", "33, u'ế' : 24, u'ề' : 32, u'ể' : 312,", "nam -> custom k vì nó giảm trùng nhiều hơn", "u'uə', u'uổ' : u'uə', u'uỗ' : u'uə', u'uộ' : u'uə',", "= seq+u' ' compound = compound + seq return compound", ": 312, u'ặ' : u'21g', u'é' : 13, u'è' :", "\"tr\", \"th\", \"ch\", \"ph\",\"nh\",\"kh\",\"gi\",\"qu\", \"ngh\",\"ng\",\"gh\",\"g\",\"k\",\"c\"] #coding: utf-8 #Custom phoneme follow", "ton == u'5' and cod in ['p', 't', 'k']: ton", ": 6, } Cus_gi = { u'gi' : u'zi', u'gí':", "word in gi: # if word == 'gi', 'gì',... ons", "u'eo', u'êu' : u'ɛu', u'ếu' : u'ɛu', u'ều' : u'ɛu',", "w) #Try to add ʷ to all start o and", "<-> iê : iə1 iêu <-> yêu : iəw1 khoắng", "else: letter2sound+=char+\" \" IPA+=T2IPA_split(letter2sound,delimit)+\" \" else: #Giữ nguyên IPA+=Parsing(\"default\",tk.lower(),delimit)+\" \"", "u's' : u'ʂ', u'gi' : u'j' } C_nuclei = {", "u'iə', u'ìa' : u'iə', u'ỉa' : u'iə', u'ĩa' : u'iə',", "use \\u02C0 for the unicode raised glottal character N_tones_p =", "= { u'oe' : u'ɛj', u'oé' : u'ɛj', u'oè' :", "\" + lin2 +\"\\t\\t:\\t\\t\"+T2IPA(line)) print(\"Same pair:\" , cout_same) #Các trường", "u'ôố' : u'o', u'ôồ' : u'o', u'ôổ' : u'o', u'ôỗ'", ": u'aw', u'oảo' : u'aw', u'oão' : u'aw', u'oạo' :", "u'oeo' : u'ew', u'oéo' : u'ew', u'oèo' : u'ew', u'oẻo'", "EN={\"a\":\"ây\",\"ă\":\"á\",\"â\":\"ớ\",\"b\":\"bi\",\"c\":\"si\",\"d\":\"đi\",\"đ\":\"đê\",\"e\":\"i\",\"ê\":\"ê\",\"f\":\"ép\",\"g\":\"giy\",\"h\":\"ếch\",\"i\":\"ai\",\"j\":\"giây\",\"k\":\"cây\",\"l\":\"eo\",\"m\":\"em\",\"n\":\"en\",\"o\":\"âu\",\"ô\":\"ô\",\"ơ\":\"ơ\",\"p\":\"pi\",\"q\":\"kiu\",\"r\":\"a\",\"s\":\"ét\",\"t\":\"ti\",\"u\":\"diu\",\"ư\":\"ư\",\"v\":\"vi\",\"w\":\"đắp liu\",\"x\":\"ít\",\"y\":\"quai\",\"z\":\"giét\"} import re def vi2IPA_split(texts,delimit): content=[] with open(\"Popular.txt\",encoding=\"utf-8\") as", "', IPA) print(\"IPA Vietnamese: \",IPA) print(\"------------------------------------------------------\") Results+= IPA.rstrip()+\" \"+delimit+\".\"+delimit+\" \"", "['p', 't', 'k']: ton = u'5b' if ton == u'6'", "u'uày' : u'ăj', u'uảy' : u'ăj', u'uãy' : u'ăj', u'uạy'", ": 214, u'ợ' : 212, u'ú' : 45, u'ù' :", ": 2, u'ử' : 4, u'ữ' : 4, u'ự' :", "print(line+ \" <-> \" + lin2 +\"\\t\\t:\\t\\t\"+T2IPA(line)) print(\"Same pair:\" ,", "print(\"Same pair:\" , cout_same) #Các trường hợp dẫn đến trùng", "u'h' : u'h', u'p' : u'p', u'qu' : u'kw', u'gi'", "get rid of single hyphens or underscores words = [word", "u'ɤ̆j', u'ẫy' : u'ɤ̆j', u'ậy' : u'ɤ̆j', u'âu' : u'ɤ̆w',", "== 'c': tones_p = C_tones_p if dialect == 's': tones_p", "42, u'ủ' : 312, u'ũ' : 312, u'ụ' : u'21g',", "u'oạ' : u'ʷa', u'óa' : u'ʷa', u'òa' : u'ʷa', u'ỏa'", "} # used to use \\u02C0 for the unicode raised", "\" else: letter2sound+=char+\" \" IPA+=T2IPA_split(letter2sound,\"\")+\" \" else: #Giữ nguyên IPA+=Parsing(\"default\",tk,\"\")+\"", ": u'a', u'óa' : u'a', u'òa' : u'a', u'ỏa' :", "etc ons = onsets[word[0:2]] oOffset = 2 elif word[0] in", "6, u'ó' : 5, u'ò' : 2, u'ỏ' : 4,", "word) values = substrings[::2] delimiters = substrings[1::2] + [''] ipa", "i chang không vòm: không có w ở trước =>", ": u'ɤ̆j', u'ẫy' : u'ɤ̆j', u'ậy' : u'ɤ̆j', u'âu' :", "is no onset... ons = u'w' # add a labiovelar", "+= ' ' if i < len(words)-1: seq = seq+u'", "u'ệ' : u'e', u'i' : u'i', u'í' : u'i', u'ì'", "u'õ' : 3, u'ọ' : 6, u'ố' : 5, u'ồ'", "test in syms: print(test) else: print(\"none\") ''' ################################################### #Step #Vinorm", "u'gi' : u'j', u'tr' : u'ʈ', u'k' : u'k', u'c'", "u'õo' : u'ɔ', u'ọo' : u'ɔ', u'oo' : u'ɔ', u'oó'", "str(char).lower() if CHAR in list(EN.keys()): letter2sound+=EN[CHAR]+\" \" else: letter2sound+=char+\" \"", ": 312, u'õ' : 312, u'ọ' : u'21g', u'ố' :", "5, u'ờ' : 2, u'ở' : 4, u'ỡ' : 3,", "6, u'ớ' : 5, u'ờ' : 2, u'ở' : 4,", "if onset is 'ngh' ons = onsets[word[0:3]] oOffset = 3", "từng kí tự #Now #+Thêm kí tự IPA của tiếng", "u'z', u'h' : u'h', u'p' : u'p', u'qu' : u'kw',", ": u'ʷɛ', u'õe' : u'ʷɛ', u'ọe' : u'ʷɛ', u'ua' :", "u'ử' : 312, u'ữ' : u'35g', u'ự' : u'21g', #", "'s': tones_p = S_tones_p #Custom tones_p = Cus_tones_p tones =", "T2IPA(tok): checkinvalid=1 if checkinvalid==1: TK = TK[:iuv] + TK[iuv+1 :]", "u'ĩu' : u'iw', u'ịu' : u'iw', u'oi' : u'ɔj', u'ói'", "CHAR = str(char).lower() if CHAR in list(EN.keys()): letter2sound+=EN[CHAR]+\" \" else:", "#+Deal case thống nhất âm vực phoneme -> ok #+Get", "' ' if i < len(words)-1: seq = seq+u' '", "'ɒ', 'ʂ', '_', 'f', ',', 'ɛ', 'z', '6', '2', 'x',", "tone + modifi + Special symbols = list(set(symbols)) symbols.sort(reverse =", "IPA+=T2IPA_split(letter2sound,\"\")+\" \" else: #Giữ nguyên IPA+=Parsing(\"default\",tk,\"\")+\" \" else: IPA+=eng+\" \"", ": u'iə', u'uyá' : u'iə', u'uyà' : u'iə', u'uyả' :", ": 32, u'ỉ' : 312, u'ĩ' : u'35g', u'ị' :", ": u'ɯəj', u'ười' : u'ɯəj', u'ưởi' : u'ɯəj', u'ưỡi' :", "45, u'ù' : 32, u'ủ' : 214, u'ũ' : 214,", ": u'ăj', u'ãy' : u'ăj', u'ạy' : u'ăj', u'ao' :", "u'ɛj', u'oẹ' : u'ɛj', u'oai' : u'aj', u'oái' : u'aj',", "u'ượu' : u'ɯəw' } #Các âm vòng ở đây i", "loé : lwʷɛ5 ngét <-> nghét : ŋɛt5 ngễu <->", "u'ɔj', u'ọi' : u'ɔj', u'ôi' : u'oj', u'ối' : u'oj',", "u'ổ' : 312, u'ỗ' : u'35g', u'ộ' : u'21g', #", "u'ãy' : u'ăj', u'ạy' : u'ăj', u'ao' : u'aw', u'áo'", "u'oj', u'ỗi' : u'oj', u'ội' : u'oj', u'ui' : u'uj',", "u'gĩ' : u'zi', u'gị' : u'zi'} Cus_qu = {u'quy' :", ": u'ɤ̆', u'ậ' : u'ɤ̆', u'ă' : u'ă', u'ắ' :", ": 2, u'ỏ' : 4, u'õ' : 4, u'ọ' :", "u'ɔ', u'oọ' : u'ɔ', u'ôô' : u'o', u'ốô' : u'o',", "#học ác cho kết quả \"c\" khác nhau ################################################### checkDict()", "u'ị' : 6, u'ó' : 5, u'ò' : 2, u'ỏ'", "u'ɤ̆', u'uẫ' : u'ɤ̆', u'uậ' : u'ɤ̆', u'ue' : u'ɛ',", "u'uj', u'uy' : u'uj', u'úy' : u'uj', u'ùy' : u'uj',", ": 6, u'ấ' : 5, u'ầ' : 2, u'ẩ' :", "u'ằ' : 32, u'ẳ' : 312, u'ẵ' : u'35g', u'ặ'", ": u'ăj', u'oãy' : u'ăj', u'oạy' : u'ăj', u'oao' :", ": u'a', u'ỏa' : u'a', u'õa' : u'a', u'ọa' :", "biệt với úi #Remain ''' di <-> gi : zi1", "u'ội' : u'oj', u'ui' : u'uj', u'úi' : u'uj', u'ùi'", "token_under: if tok not in content or \"[\" in T2IPA(tok):", "u'ơ' : 33, u'ớ' : 24, u'ờ' : 32, u'ở'", "C_codas, C_tones, C_onglides, C_offglides, C_onoffglides, C_qu, C_gi elif dialect ==", "u'ốô' : u'o', u'ồô' : u'o', u'ổô' : u'o', u'ỗô'", "u'ươu' : u'ɯəw', u'ướu' : u'ɯəw', u'ườu' : u'ɯəw', u'ưởu'", "enumerate(text): #print(char,skip) check = 0 if skip>0: skip=skip-1 continue for", "\"ả\",\"ẳ\",\"ẩ\",\"ẻ\",\"ể\",\"ỉ\",\"ỏ\",\"ổ\",\"ở\",\"ủ\",\"ử\",\"ỷ\",\"iể\",\"ỏa\",\"oẳ\",\"ỏe\",\"oỏ\",\"uẩ\",\"uể\",\"uổ\",\"ưở\",\"ủy\",\"ưở\",\"uyể\",\"yể\", #hook \"oả\", \"oẻ\",\"ỏo\", \"uỷ\", \"ã\",\"ẵ\",\"ẫ\",\"ẽ\",\"ễ\",\"ĩ\",\"õ\",\"ỗ\",\"ỡ\",\"ũ\",\"ữ\",\"ỹ\",\"iễ\",\"õa\",\"oẵ\",\"õe\",\"oõ\",\"uẫ\",\"uễ\",\"uỗ\",\"ưỡ\",\"ũy\",\"ưỡ\",\"uyễ\",\"yễ\", #tilde \"oã\", \"oẽ\",\"õo\", \"uỹ\",", ": u'ɤ̆w', u'ậu' : u'ɤ̆w', u'eo' : u'ew', u'éo' :", "u'ố' : 24, u'ồ' : 32, u'ổ' : 312, u'ỗ'", "'n': onsets, nuclei, codas, tones, onglides, offglides, onoffglides, qu, gi", "u'o', u'ôỗ' : u'o', u'ôộ' : u'o', u'ua' : u'uə',", ": u'aw', u'oào' : u'aw', u'oảo' : u'aw', u'oão' :", "dấu nhấn của tiếng anh \"'\" #print(vi2IPA_split(\"speech? Secondly, we paper,", "\" <-> \" + lin2 +\"\\t\\t:\\t\\t\"+T2IPA(line)) print(\"Same pair:\" , cout_same)", "u'ɔ', u'oó' : u'ɔ', u'oò' : u'ɔ', u'oỏ' : u'ɔ',", "# #coding: utf-8 N_onsets = { u'b' : u'b', u't'", "' ', 'd', 'i', 'ɣ', 'ɲ', 'ɤ', '?', 'ɪ', 'l',", ": 42, u'ủ' : 312, u'ũ' : 312, u'ụ' :", "u'ãu' : u'ăw', u'ạu' : u'ăw', u'ây' : u'ɤ̆j', u'ấy'", "2, u'ẳ' : 4, u'ẵ' : 4, u'ặ' : 6,", "u's' : u'ʂ', u'gi' : u'j' } S_nuclei = {", "'ɯəj', 'ʷen', 'ʷiu', 'ʷet', 'ɯəw', 'ʷɛ', 'ʷɤ', 'ɯj', 'oj', 'ăw',", "dialect == 's': onsets, nuclei, codas, tones, onglides, offglides, onoffglides,", "as f: content=f.read().splitlines() for line in content: #nor_tr = vi2IPA_pitrain(line)", ": 4, u'õ' : 3, u'ọ' : 6, u'ố' :", "u'ỷ' : u'i', u'ỹ' : u'i', u'ỵ' : u'i', u'eo'", "312, u'ỹ' : u'35g', u'ỵ' : u'21g', } # used", "u'ề' : 32, u'ể' : 214, u'ễ' : 214, u'ệ'", "if ipa ==\"\": IPA+=tk+\" \" elif ipa[0]==\"[\" and ipa[-1]==\"]\": eng", "'ŋ', 'ɒ', 'ʂ', '_', 'f', ',', 'ɛ', 'z', '6', '2',", "[\"k͡p\",\"ŋ͡m\"] symbols = list_phoneme + space+word_pad + English_phoneme + punctuation", "and watch để thay thế => k for c ,", "u'ỏ' : 4, u'õ' : 4, u'ọ' : 6, u'ố'", "u'ú' : u'u', u'ù' : u'u', u'ủ' : u'u', u'ũ'", "'6', 'ʒ', 'ʐ', 'z', 'v', 'g', 'ă', '_', 'æ', 'ɤ',", "if len(token_under) >1: for tok in token_under: if tok not", "chế trùng âm u'uy' : u'ʷi', u'uý' : u'ʷi', u'uỳ'", ": u'aj', u'uái' : u'aj', u'uài' : u'aj', u'uải' :", "T2IPA(text): sys.path.append('./Rules') # make sure we can find the Rules", "u'à' : u'a', u'ả' : u'a', u'ã' : u'a', u'ạ'", ": u'uə', u'uỡ' : u'uə', u'uợ' : u'uə', } S_offglides", "32, u'ở' : 214, u'ỡ' : 214, u'ợ' : 212,", "syms: print(test) else: print(\"none\") ''' ################################################### #Step #Vinorm #Underthesea #For", "cod in [u'm', u'p']: if nuc == u'iə': nuc =", "2, u'ể' : 4, u'ễ' : 4, u'ệ' : 6,", "'eɪ', 'ɤj', 'ɯw', 'ɛj', 'ɔj', 'i:', 't∫', 'ɪə', 'ʷă', 'ɜ:',", "dialect == 'c': ton = str('35') else: ton = str('33')", ": u'ʷiu', u'uỹu' : u'ʷiu', u'uỵu' : u'ʷiu', u'oen' :", "ipa = T2IPA(tk).replace(\" \",\"_\") if ipa ==\"\": IPA+=tk+\" \" elif", "u'ã' : u'a', u'ạ' : u'a', u'â' : u'ɤ̆', u'ấ'", "= 0 l = len(word) if l > 0: if", "= { u'a' : 33, u'á' : 24, u'à' :", ": 2, u'ẩ' : 4, u'ẫ' : 3, u'ậ' :", "dialect == 's') and ton == u'21g' and cod in", "'æ', 'ɤ', '2', 'ʤ', 'i', '.', 'ɒ', 'b', 'h', 'n',", "# make sure we can find the Rules files #Setup", "u'e', u'ề' : u'e', u'ể' : u'e', u'ễ' : u'e',", "được check phoneme tiếng anh #Nếu không có trong từ", "u'uə', u'ủa' : u'uə', u'ũa' : u'uə', u'ụa' : u'uə',", ": u'e', u'uề' : u'e', u'uể' : u'e', u'uễ' :", "de nguyen #Neu khong danh van print(\" ..................Out of domain", "u'ẳ' : 214, u'ẵ' : 214, u'ặ' : 212, u'é'", "codas[word[l-2:l]] cOffset = 2 elif word[l-1] in codas: # if", "u'ú' : 13, u'ù' : 42, u'ủ' : 312, u'ũ'", "u'uẻ' : u'ɛ', u'uẽ' : u'ɛ', u'uẹ' : u'ɛ', u'uê'", ": u'e', u'uệ' : u'e', u'uơ' : u'ɤ', u'uớ' :", "u'i', u'ĩ' : u'i', u'ị' : u'i', u'o' : u'ɔ',", "skip=skip-1 continue for l in listParse: if len(l) <= len(text[ic:])", "u'uỡ' : u'ɤ', u'uợ' : u'ɤ', u'uy' : u'i', u'uý'", "u'iêu' : u'iəw', u'iếu' : u'iəw', u'iều' : u'iəw', u'iểu'", "'d', 'i', 'ɣ', 'ɲ', 'ɤ', '?', 'ɪ', 'l', '.', 'j',", ": u'en', u'oẹn' : u'en', u'oet' : u'et', u'oét' :", ": 6, u'ý' : 5, u'ỳ' : 2, u'ỷ' :", "u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j' } C_codas = {", ":] for tok in reversed(token_under): TK.insert(iuv, tok) IPA=\"\" for tk", "u'uầ' : u'ɤ̆', u'uẩ' : u'ɤ̆', u'uẫ' : u'ɤ̆', u'uậ'", "C_onsets = { u'b' : u'b', u't' : u't', u'th'", ": u'ɛ', u'ẻ' : u'ɛ', u'ẽ' : u'ɛ', u'ẹ' :", "214, u'ã' : 214, u'ạ' : 212, u'ấ' : 45,", "u'uə', u'u', u'ɯ', u'ɤ', u'o', u'ɔ', u'ă', u'ɤ̆']: if cod", "u'ẽ' : 3, u'ẹ' : 6, u'ế' : 5, u'ề'", "u'a', u'oạ' : u'a', u'óa' : u'a', u'òa' : u'a',", ": 4, u'ũ' : 4, u'ụ' : 6, u'ứ' :", "din <-> gin : zin1 díp <-> gíp : zip5", "was prepared to show available onsets. Onsets are splitted into", "# fixed 8 Nov 2016 ton = u'21' # Modification", "u'ué' : u'ɛ', u'uè' : u'ɛ', u'uẻ' : u'ɛ', u'uẽ'", ": u'wi'} ############################################ #south.py #coding: utf-8 S_onsets = { u'b'", "'ʷiə', 'ɤ̆w', 'ɯəw', 'ʷet', 'iəw', 'uəj', 'ʷen', 'tʰw', 'ʷɤ̆', 'ʷiu',", "nuc in [u'i', u'e']: if cod == u'k': cod =", "'ʂw', 'ɣw', 'ʐw', 'xw', 'lw', 'hw', 'nw', 'sw', 'c'] word_pad", "{ u'b' : u'b', u't' : u't', u'th' : u'tʰ',", "u'ự' : 6, u'ý' : 5, u'ỳ' : 2, u'ỷ'", "u'ưỡi' : u'ɯəj', u'ượi' : u'ɯəj', u'ươu' : u'ɯəw', u'ướu'", "214, u'ĩ' : 214, u'ị' : 212, u'ó' : 45,", "#+Thêm kí tự IPA của tiếng ANH #+Thêm xử lí", "or (tokenize and '_' in word): substrings = re.split(r'(_|-)', word)", ": 312, u'ỹ' : u'35g', u'ỵ' : u'21g', # }", "true, call this routine for each substring ## and re-concatenate", "words = line.split() ## toss len==0 junk words = [word", "u'gi' : u'ji', u'gí': u'ji', u'gì' : u'ji', u'gì' :", "#Thay offglide: úy -> wi để phân biệt với úi", "#Các trường hợp dẫn đến trùng âm là: # Phương", "u'iã' : u'iə', u'iạ' : u'iə', u'iê' : u'iə', u'iế'", "u'ì' : 2, u'ỉ' : 4, u'ĩ' : 4, u'ị'", "S_codas, S_tones, S_onglides, S_offglides, S_onoffglides, S_qu, S_gi #Custom onsets, nuclei,", "'ɲw', 'eo', 'sw', 'tw', 'ʐw', 'iɛ', 'ʷe', 'i:', 'ɯə', 'dʒ',", "letter2sound+=char+\" \" IPA+=T2IPA_split(letter2sound,delimit)+\" \" else: #Giữ nguyên IPA+=Parsing(\"default\",tk.lower(),delimit)+\" \" else:", "Cus_codas = { u'p' : u'p', u't' : u't', u'c'", "check phoneme tiếng anh #Nếu không có trong từ tiếng", "'ʐ', 'z', 'v', 'g', 'ă', '_', 'æ', 'ɤ', '2', 'ʤ',", "ở list custom # Các trường hợp có cách bỏ", "if ton == u'6' and cod in ['p', 't', 'k']:", ": u'iəw', u'yễu' : u'iəw', u'yệu' : u'iəw', u'uôi' :", ": u'k' } #tones = { u'a' : 33, u'á'", "u'ợ' : u'21g', u'ú' : 24, u'ù' : 32, u'ủ'", "u'ẩ' : 312, u'ẫ' : u'35g', u'ậ' : u'21g', #", "= 0 if skip>0: skip=skip-1 continue for l in listParse:", ": u'ʷɤ', u'uy' : u'ʷi', u'uý' : u'ʷi', u'uỳ' :", "\" else: #Giữ nguyên IPA+=Parsing(\"default\",tk.lower(),delimit)+\" \" else: IPA+=Parsing(\"default\",eng,delimit)+\" \" #Check", "S Cus_onsets = { u'b' : u'b', u't' : u't',", "for ine,res in enumerate(Results): if res not in check_sym: Results[ine]=\"'\"", "#âm cuối: ch : k theo bắc : t theo", ": u'm', u'n' : u'ŋ', u'ng' : u'ŋ', u'nh' :", "u'ɛ', u'uê' : u'e', u'uế' : u'e', u'uề' : u'e',", "gh #i <-> y #Same negative / need to fix", "u'ớ' : 13, u'ờ' : 42, u'ở' : 312, u'ỡ'", "'ew', 'iə', 'ɣw', 'zw', 'ɯj', 'ʷɛ', 'ɯw', 'ɤj', 'ɔ:', 'əʊ',", "'k', '5', 'g', '4', 'n', ';', 'r', 'b', 'ɯ', 'a',", "312, u'ũ' : u'35g', u'ụ' : u'21g', # u'ư' :", "u'ôổ' : u'o', u'ôỗ' : u'o', u'ôộ' : u'o', u'ua'", ": u'ɤ̆w', u'ầu': u'ɤ̆w', u'ẩu' : u'ɤ̆w', u'ẫu' : u'ɤ̆w',", "u'nh' : u'ɲ', u'ng' : u'ŋ', u'ph' : u'f', u'v'", "sys.path.append('./Rules') # make sure we can find the Rules files", "'ʊ', 'ʤ', 'ɔ', '1', 'ʧ', 'ʈ', ' ', 'd', 'i',", "vòng ở đây i chang không vòm: không có w", ": u'ăj', u'oảy' : u'ăj', u'oãy' : u'ăj', u'oạy' :", ": u'ew', u'ỏeo' : u'ew', u'õeo' : u'ew', u'ọeo' :", "if test in syms: print(test) else: print(\"none\") ''' ################################################### #Step", "in range(0,l) if word[i] in tones] if tonelist: ton =", "'u', 'e', 'w', 'p', 'ʃ', 'æ', \"'\", 'h', 'o', 'k',", "and ons != u'kw': # if there is an onglide...", ": u'uəj', u'uối' : u'uəj', u'uồi' : u'uəj', u'uổi' :", "u'kw': # if there is an onglide... nuc = onglides[nucl]", "nuclei: if oOffset == 0: if glottal == 1: if", "k vì nó giảm trùng nhiều hơn 241->153 case #Tuy", "u'oén' : u'ʷen', u'oèn' : u'ʷen', u'oẻn' : u'ʷen', u'oẽn'", "u'ʷă', u'uẳ' : u'ʷă', u'uẵ' : u'ʷă', u'uặ' : u'ʷă',", "if line =='\\n': return \"\" else: compound = u'' ortho", ": 212, u'ấ' : 45, u'ầ' : 32, u'ẩ' :", "u'iə', u'uyê' : u'iə', u'uyế' : u'iə', u'uyề' : u'iə',", "\"ph\",\"nh\",\"kh\",\"gi\",\"qu\", \"ngh\",\"ng\",\"gh\",\"g\",\"k\",\"c\"] #coding: utf-8 #Custom phoneme follow the https://vi.wikipedia.org/wiki/%C3%82m_v%E1%BB%8B_h%E1%BB%8Dc_ti%E1%BA%BFng_Vi%E1%BB%87t #Improve", "ons: ons = ons+u'w' else: ons = u'w' elif nucl", "# u'ư' : 33, u'ứ' : 24, u'ừ' : 32,", "+= word word = word.strip(punctuation).lower() ## 29.03.16: check if tokenize", ": u'ɛj', u'oẻ' : u'ɛj', u'oẽ' : u'ɛj', u'oẹ' :", "u'n' # There is also this reverse fronting, see Thompson", "= u'z' else: nucl = word[oOffset:l-cOffset] if nucl in nuclei:", ": u'e', u'ề' : u'e', u'ể' : u'e', u'ễ' :", "' compound = compound + seq return compound EN={\"a\":\"ây\",\"ă\":\"á\",\"â\":\"ớ\",\"b\":\"bi\",\"c\":\"si\",\"d\":\"đi\",\"đ\":\"đê\",\"e\":\"i\",\"ê\":\"ê\",\"f\":\"ép\",\"g\":\"giy\",\"h\":\"ếch\",\"i\":\"ai\",\"j\":\"giây\",\"k\":\"cây\",\"l\":\"eo\",\"m\":\"em\",\"n\":\"en\",\"o\":\"âu\",\"ô\":\"ô\",\"ơ\":\"ơ\",\"p\":\"pi\",\"q\":\"kiu\",\"r\":\"a\",\"s\":\"ét\",\"t\":\"ti\",\"u\":\"diu\",\"ư\":\"ư\",\"v\":\"vi\",\"w\":\"đắp liu\",\"x\":\"ít\",\"y\":\"quai\",\"z\":\"giét\"}", ": u'uj', u'ơi' : u'ɤj', u'ới' : u'ɤj', u'ời' :", "list_phoneme=DICT.values() list_phoneme=list(list_phoneme) English_phoneme=[\"p\",\"b\",\"t\",\"d\",\"t∫\",\"dʒ\",\"k\",\"g\",\"f\",\"v\",\"ð\",\"θ\",\"s\",\"z\",\"∫\",\"ʒ\",\"m\",\"n\",\"η\",\"l\",\"r\",\"w\",\"j\",\"ɪ\",\"i:\",\"ʊ\",\"u:\",\"e\",\"ə\",\"ɜ:\",\"ɒ\",\"ɔ:\",\"æ\",\"ʌ\",\"ɑ:\",\"ɪə\",\"ʊə\",\"eə\",\"eɪ\",\"ɔɪ\",\"aɪ\",\"əʊ\",\"aʊ\",'ʃ',\"ʤ\",\"ʧ\"] Special=['jw', 'ŋw', 'bw', 'vw', 'dw', 'eo', 'ʈw',", "u'õe' : u'e', u'ọe' : u'e', u'ua' : u'a', u'uá'", "\\u02C0 for the unicode raised glottal character N_tones_p = {", "Velar Fronting (Northern dialect) if dialect == 'n': if nuc", ": u'i', u'uý' : u'i', u'uỳ' : u'i', u'uỷ' :", "onsets, nuclei, codas, tones, onglides, offglides, onoffglides, qu, gi =", "4, u'ậ' : 6, u'ắ' : 5, u'ằ' : 2,", "u'uə', u'uợ' : u'uə', } S_offglides = { u'ai' :", "continue for l in listParse: if len(l) <= len(text[ic:]) and", "nuc = u'ɛ' # Final palatals (Northern dialect) if nuc", "u'ng' : u'ŋ', u'nh' : u'n', u'ch' : u'k' }", "u'õ' : u'ɔ', u'ọ' : u'ɔ', u'ô' : u'o', u'ố'", "co nguyen am #Neu co de nguyen #Neu khong danh", "u'ăj', u'áy' : u'ăj', u'ày' : u'ăj', u'ảy' : u'ăj',", "u'ũ' : 3, u'ụ' : 6, u'ứ' : 5, u'ừ'", "u'gị' : u'ji' } C_qu = {u'quy' : u'wi', u'qúy'", "onsets, nuclei, codas, onglides, offglides, onoffglides, qu, gi = Cus_onsets,", ": u'iə', u'ĩa' : u'iə', u'ịa' : u'iə', u'ia' :", "trung +=1 List_pair.append(line) List_token.append(nor) if nor==\"\": cout+=1 print(line) print(\"Number of", "u'21g', u'í' : 24, u'ì' : 32, u'ỉ' : 312,", ": u'ăj', u'uạy' : u'ăj', u'uây' : u'ɤ̆j', u'uấy' :", "u'óa' : u'ʷa', u'òa' : u'ʷa', u'ỏa' : u'ʷa', u'õa'", "coda cod = codas[word[l-1]] cOffset = 1 #if word[0:2] ==", "glottal = 0 pham = 0 cao = 0 palatals", "312, u'õ' : u'35g', u'ọ' : u'21g', # u'ô' :", "'uj', 'lw', 'ɪə', 'ăj', 'u:', 'aw', 'ɛj', 'iw', 'aj', 'ɜ:',", ": u'iəw', u'yều' : u'iəw', u'yểu' : u'iəw', u'yễu' :", "phí chạy máy không normal phoneme về cường độ âm", "u'ấ' : 24, u'ầ' : 32, u'ẩ' : 312, u'ẫ'", "u'ủ' : u'u', u'ũ' : u'u', u'ụ' : u'u', u'ư'", "u'ẽo' : u'ew', u'ẹo' : u'ew', u'iu' : u'iw', u'íu'", "space+word_pad + English_phoneme + punctuation + tone + modifi +", "u'ỉu' : u'iw', u'ĩu' : u'iw', u'ịu' : u'iw', u'oi'", "IPA+=ipa+\" \" IPA=re.sub(delimit+'+', delimit, IPA) IPA=re.sub(' +', ' ', IPA)", "== 's': if cod in [u'm', u'p']: if nuc ==", "u'e', u'oe' : u'e', u'óe' : u'e', u'òe' : u'e',", "u'ẩ' : 312, u'ẫ' : 312, u'ậ' : u'21g', u'ắ'", "u'ʷiu', u'uyù' : u'ʷiu', u'uyủ' : u'ʷiu', u'uyũ' : u'ʷiu',", "u'oà' : u'a', u'oả' : u'a', u'oã' : u'a', u'oạ'", "u'ưi' : u'ɯj', u'ứi' : u'ɯj', u'ừi' : u'ɯj', u'ửi'", "line.split() ## toss len==0 junk words = [word for word", "xuə1 lóe <-> loé : lwʷɛ5 ngét <-> nghét :", "u'oj', u'ổi' : u'oj', u'ỗi' : u'oj', u'ội' : u'oj',", "u'ờ' : 32, u'ở' : 312, u'ỡ' : u'35g', u'ợ'", "nuc = nuclei[nucl] # there's your nucleus elif nucl in", "\"a\",\"ă\",\"â\",\"e\",\"ê\",\"i\",\"o\",\"ô\",\"ơ\",\"u\",\"ư\",\"y\",\"iê\",\"oa\",\"oă\",\"oe\",\"oo\",\"uâ\",\"uê\",\"uô\",\"uơ\",\"uy\",\"ươ\",\"uyê\",\"yê\", #blank \"á\",\"ắ\",\"ấ\",\"é\",\"ế\",\"í\",\"ó\",\"ố\",\"ớ\",\"ú\",\"ứ\",\"ý\",\"iế\",\"óa\",\"oắ\",\"óe\",\"oó\",\"uấ\",\"uế\",\"uố\",\"ướ\",\"úy\",\"ướ\",\"uyế\",\"yế\", #grave \"oá\", \"oé\",\"óo\", \"uý\", \"à\",\"ằ\",\"ầ\",\"è\",\"ề\",\"ì\",\"ò\",\"ồ\",\"ờ\",\"ù\",\"ừ\",\"ỳ\",\"iề\",\"òa\",\"oằ\",\"òe\",\"oò\",\"uầ\",\"uề\",\"uồ\",\"ườ\",\"ùy\",\"ườ\",\"uyề\",\"yề\", #acute \"oà\",", "the Rules files #Setup option glottal = 0 pham =", "content or \"[\" in T2IPA(tok): checkinvalid=1 if checkinvalid==1: TK =", "u'oèt' : u'ʷet', u'oẻt' : u'ʷet', u'oẽt' : u'ʷet', u'oẹt'", "u'uyụ' : u'ʷiu', u'uyu' : u'ʷiu', u'uýu' : u'ʷiu', u'uỳu'", "u'ɯəw' } S_onglides = { u'oa' : u'a', u'oá' :", "u'ũ' : 214, u'ụ' : 212, u'ứ' : 45, u'ừ'", "= { u'oa' : u'a', u'oá' : u'a', u'oà' :", ": u'en', u'oẻn' : u'en', u'oẽn' : u'en', u'oẹn' :", "nucl in onglides and ons != u'kw': # if there", "convert: \",cout) print(\"Number of token in the same mapping:\",trung) List_token", "oOffset = 2 elif word[0] in onsets: # if single", ": 24, u'à' : 32, u'ả' : 312, u'ã' :", "nhau đều gộp chung làm một #Disable convert from 'ɲ'", "C_tones, C_onglides, C_offglides, C_onoffglides, C_qu, C_gi elif dialect == 's':", "u'ỗ' : u'o', u'ộ' : u'o', u'ơ' : u'ɤ', u'ớ'", "u'ồ' : 42, u'ổ' : 312, u'ỗ' : 312, u'ộ'", "u'ăj', u'uây' : u'ɤ̆j', u'uấy' : u'ɤ̆j', u'uầy' : u'ɤ̆j',", "u'e', u'òe' : u'e', u'ỏe' : u'e', u'õe' : u'e',", "u'a', u'á' : u'a', u'à' : u'a', u'ả' : u'a',", "elif nuc in [u'iə', u'ɯə', u'uə', u'u', u'ɯ', u'ɤ', u'o',", ": u'uj', u'ũy' : u'uj', u'ụy' : u'uj', u'uy' :", "oOffset = 3 elif word[0:2] in onsets: # if onset", ": 33, u'é' : 24, u'è' : 32, u'ẻ' :", "đến trùng âm là: # Phương ngữ khác nhau đã", ": 13, u'è' : 42, u'ẻ' : 312, u'ẽ' :", "u'é' : 45, u'è' : 32, u'ẻ' : 214, u'ẽ'", "= u'i' ons = u'z' else: nucl = word[oOffset:l-cOffset] if", ": u'ɔ', u'ô' : u'o', u'ố' : u'o', u'ồ' :", ": 5, u'è' : 2, u'ẻ' : 4, u'ẽ' :", "u'ỷ' : 214, u'ỹ' : 214, u'ỵ' : 212, }", ": u'h', u'p' : u'p', u'qu' : u'w', u'gi' :", "u'oày' : u'ăj', u'oảy' : u'ăj', u'oãy' : u'ăj', u'oạy'", "N_gi, Cus_onsets, Cus_nuclei, Cus_codas#, N_tones , Cus_onglides, Cus_offglides, Cus_onoffglides, Cus_qu,", "ác cho kết quả \"c\" khác nhau ################################################### checkDict() #print(vi2IPA_split(\"!Singapo", "= trans(word, dialect, glottal, pham, cao, palatals) if None in", "u'ú' : 24, u'ù' : 32, u'ủ' : 312, u'ũ'", "C_tones , C_onglides, C_offglides, C_onoffglides, C_qu, C_gi, N_onsets, N_nuclei, N_codas#,", "u'n' : u'ŋ', u'ng' : u'ŋ', u'nh' : u'n', u'ch'", "if (dialect == 'n' or dialect == 's') and ton", "u'oẹo' : u'ew', u'oeo' : u'ew', u'óeo' : u'ew', u'òeo'", ": u'kwi'} ####################################################### # North # #coding: utf-8 N_onsets =", ": 312, u'ã' : 312, u'ạ' : u'21g', u'ấ' :", ": u'iɛ', u'yể' : u'iɛ', u'yễ' : u'iɛ', u'yệ' :", "u't', u'th' : u'tʰ', u'đ' : u'd', u'ch' : u'c',", "(added 17.09.08) if nuc in [u'u', u'o', u'ɔ']: if cod", "if cod == u't': cod = u'k' if cod ==", "2, u'ả' : 4, u'ã' : 3, u'ạ' : 6,", ": u'ɯj', u'ứi' : u'ɯj', u'ừi' : u'ɯj', u'ửi' :", "cOffset = 1 #if word[0:2] == u'gi' and cod and", ": 32, u'ẩ' : 214, u'ẫ' : 214, u'ậ' :", "212, u'í' : 45, u'ì' : 32, u'ỉ' : 214,", ": 214, u'ĩ' : 214, u'ị' : 212, u'ó' :", "45, u'ừ' : 32, u'ử' : 214, u'ữ' : 214,", "\"oả\", \"oẻ\",\"ỏo\", \"uỷ\", \"ã\",\"ẵ\",\"ẫ\",\"ẽ\",\"ễ\",\"ĩ\",\"õ\",\"ỗ\",\"ỡ\",\"ũ\",\"ữ\",\"ỹ\",\"iễ\",\"õa\",\"oẵ\",\"õe\",\"oõ\",\"uẫ\",\"uễ\",\"uỗ\",\"ưỡ\",\"ũy\",\"ưỡ\",\"uyễ\",\"yễ\", #tilde \"oã\", \"oẽ\",\"õo\", \"uỹ\", \"ạ\",\"ặ\",\"ậ\",\"ẹ\",\"ệ\",\"ị\",\"ọ\",\"ộ\",\"ợ\",\"ụ\",\"ự\",\"ỵ\",\"iệ\",\"ọa\",\"oặ\",\"ọe\",\"oọ\",\"uậ\",\"uệ\",\"uệ\",\"ượ\",\"ụy\",\"ượ\",\"uyệ\",\"yệ\", #dot", "if tone_type==0: pham=1 else: cao=1 #Input text line = text", ": 3, u'ệ' : 6, u'í' : 5, u'ì' :", "{ u'gi' : u'zi', u'gí': u'zi', u'gì' : u'zi', u'gì'", "output=\"\" skip=0 for ic,char in enumerate(text): #print(char,skip) check = 0", "lin2 =Pair[T2IPA(line)] if line != lin2: if (lin2[0]==\"k\" and line[0]==\"c\")", "u'ăw', u'ảu' : u'ăw', u'ãu' : u'ăw', u'ạu' : u'ăw',", ": u'ʷɛ', u'oè' : u'ʷɛ', u'oẻ' : u'ʷɛ', u'oẽ' :", "'h', 'n', 'ʂ', 'ɔ', 'ɛ', 'k', 'm', '5', ' ',", "\",\"_\") if ipa ==\"\": IPA+=delimit+tk+delimit+\" \" elif ipa[0]==\"[\" and ipa[-1]==\"]\":", "u'ɲ' and nuc == u'a': nuc = u'ɛ' # Final", "'gi' and a coda... if word[0:2] in gi and cod", ": 3, u'ọ' : 6, u'ố' : 5, u'ồ' :", "u'ử' : 214, u'ữ' : 214, u'ự' : 212, u'ý'", "= '' nuc = '' cod = '' ton =", "if oOffset == 0: if glottal == 1: if word[0]", ": u'ɲ', u'ng' : u'ŋ', u'ph' : u'f', u'v' :", ": u'35g', u'ẹ' : u'21g', u'ế' : 24, u'ề' :", ": u'c', u'kh' : u'x', u'g' : u'ɣ', u'l' :", ": 33, u'ó' : 24, u'ò' : 32, u'ỏ' :", "l = len(word) if l > 0: if word[0:3] in", "u'uj', u'ụy' : u'uj', #thay để hạn chế trùng âm", "+ TK[iuv+1 :] for tok in reversed(token_under): TK.insert(iuv, tok) IPA=\"\"", "lt cout_same=0 with open(\"Popular.txt\", encoding=\"utf-8\") as f: content=f.read().splitlines() for line", "u'ũi' : u'uj', u'ụi' : u'uj', #u'uy' : u'uj', u'úy'", "214, u'ũ' : 214, u'ụ' : 212, u'ứ' : 45,", ": 312, u'ẫ' : u'35g', u'ậ' : u'21g', u'ắ' :", "delimit): undefine_symbol = \"'\" if listParse == \"default\": listParse=['ʷiə', 'uəj',", "language to another by\",\"/\").replace(\"/\",\"\")) #Case need to be deal: #", "u'õeo' : u'ew', u'ọeo' : u'ew', u'ueo' : u'ew', u'uéo'", ": u'ɯəj', u'ượi' : u'ɯəj', u'ươu' : u'ɯəw', u'ướu' :", "'ɛu', 'tʰ', 'tʃ', 'ɔɪ', 'xw', 'ʷɤ', 'ɤ̆', 'ŋw', 'ʊə', 'zi',", "4, u'ễ' : 4, u'ệ' : 6, u'í' : 5,", "u'ỡ' : 4, u'ợ' : 6, u'ú' : 5, u'ù'", "ngễu <-> nghễu : ŋɛu3 nghía <-> ngía : ŋiə5", "u'e', u'ua' : u'a', u'uá' : u'a', u'uà' : u'a',", "# there's your nucleus elif nucl in onglides and ons", "u'ỏi' : u'ɔj', u'õi' : u'ɔj', u'ọi' : u'ɔj', u'ôi'", "Vietnamese: \",IPA) print(\"------------------------------------------------------\") Results+= IPA.rstrip()+\" \"+delimit+\".\"+delimit+\" \" #For checking: need", "4, u'ộ' : 6, u'ớ' : 5, u'ờ' : 2,", "'eɪ', 'aɪ', 'ew', 'iə', 'ɣw', 'zw', 'ɯj', 'ʷɛ', 'ɯw', 'ɤj',", "<-> ngía : ŋiə5 nghịu <-> ngịu : ŋiw6 nghoèo", "u'ùa' : u'uə', u'ủa' : u'uə', u'ũa' : u'uə', u'ụa'", "u'ỉa' : u'iə', u'ĩa' : u'iə', u'ịa' : u'iə', u'ia'", "u'oại' : u'aj', u'oay' : u'ăj', u'oáy' : u'ăj', u'oày'", "u'wi', u'qủy' : u'wi', u'qũy' : u'wi', u'qụy' : u'wi'}", "32, u'ử' : 214, u'ữ' : 214, u'ự' : 212,", "Cus_gi] DICT={} #144 in total syms=['ɯəj', 'ɤ̆j', 'ʷiə', 'ɤ̆w', 'ɯəw',", "is 'ngh' ons = onsets[word[0:3]] oOffset = 3 elif word[0:2]", "+=1 List_pair.append(line) List_token.append(nor) if nor==\"\": cout+=1 print(line) print(\"Number of token", "u'aw', u'ảo' : u'aw', u'ão' : u'aw', u'ạo' : u'aw',", "u'ỉ' : 312, u'ĩ' : 312, u'ị' : u'21g', u'ó'", "u'ʷen', u'oẽn' : u'ʷen', u'oẹn' : u'ʷen', u'oet' : u'ʷet',", "Cus_tones_p tones = tones_p ons = '' nuc = ''", "u'oãy' : u'ăj', u'oạy' : u'ăj', u'oao' : u'aw', u'oáo'", ": u'iu', u'uỹu' : u'iu', u'uỵu' : u'iu', u'oen' :", ": u'ʷa', u'òa' : u'ʷa', u'ỏa' : u'ʷa', u'õa' :", "u'ươ' : u'ɯə', u'ướ' : u'ɯə', u'ườ' : u'ɯə', u'ưở'", ": u'aj', u'ái' : u'aj', u'ài' : u'aj', u'ải' :", "khác nhau đã thống nhất ở list custom # Các", ": u'ej', u'oẹ' : u'ej', u'oai' : u'aj', u'oái' :", "u'35g', u'ợ' : u'21g', # u'u' : 33, u'ú' :", ": u'ʷi', u'uỳ' : u'ʷi', u'uỷ' : u'ʷi', u'uỹ' :", "u'35g', u'ộ' : u'21g', # u'ơ' : 33, u'ớ' :", "u'ŋ' # Monophthongization (Southern dialects: Thompson 1965: 86; Hoàng 1985:", "English_phoneme + punctuation + tone + modifi + Special symbols", "u'ao' : u'aw', u'áo' : u'aw', u'ào' : u'aw', u'ảo'", "==\"\": IPA+=tk+\" \" elif ipa[0]==\"[\" and ipa[-1]==\"]\": eng = eng_to_ipa.convert(tk)", "isn't an onset.... ons = u'ʔ'+nuclei[nucl] # add a glottal", "def trans(word, dialect, glottal, pham, cao, palatals): # This looks", "BoOK #print(len(getSymbol())) #print(getSymbol()) ''' test=\"t\" if test in syms: print(test)", ": u'ɯj', u'ửi' : u'ɯj', u'ữi' : u'ɯj', u'ựi' :", "2 elif word[l-1] in codas: # if one-character coda cod", "for raised glottal instead of g C_tones_p = { u'á'", "'1', 'ɪ', 'ɯ', 'd', '∫', 'p', 'ə', 'u', 'o', '3',", "cout_same+=1 print(line+ \" <-> \" + lin2 +\"\\t\\t:\\t\\t\"+T2IPA(line)) print(\"Same pair:\"", "'?', 'r', ':', 'η', 'f', ';', 'e', 't', \"'\"] def", "looks ugly, but newer versions of python complain about \"from", "u'n', u'ng' : u'ŋ', u'nh' : u'ɲ', u'ch' : u'tʃ'", ": 214, u'ặ' : 212, u'é' : 45, u'è' :", "nucl in offglides: cod = offglides[nucl][-1] nuc = offglides[nucl][:-1] elif", "u'gị' : u'zi'} N_qu = {u'quy' : u'kwi', u'qúy' :", "pham or cao: if dialect == 'n': tones_p = N_tones_p", "'ɯəw', 'ʷet', 'iəw', 'uəj', 'ʷen', 'tʰw', 'ʷɤ̆', 'ʷiu', 'kwi', 'ŋ͡m',", ": 214, u'ã' : 214, u'ạ' : 212, u'ấ' :", ": u'iə', u'iê' : u'iə', u'iế' : u'iə', u'iề' :", "u'ụ' : 6, u'ứ' : 5, u'ừ' : 2, u'ử'", "u'óo' : u'ɔ', u'òo' : u'ɔ', u'ỏo' : u'ɔ', u'õo'", "khôngtontaij NIYE BoOK\",\"'\")) #check các ipa của tiếng anh #print(vi2IPA_split(\"Another", "u'ai' : u'aj', u'ái' : u'aj', u'ài' : u'aj', u'ải'", "u'ầ' : u'ɤ̆', u'ẩ' : u'ɤ̆', u'ẫ' : u'ɤ̆', u'ậ'", "u'oẻ' : u'ej', u'oẽ' : u'ej', u'oẹ' : u'ej', u'oai'", "} C_onoffglides = { u'oe' : u'ej', u'oé' : u'ej',", ": u'ʷen', u'oẻn' : u'ʷen', u'oẽn' : u'ʷen', u'oẹn' :", "u'ʷiu', u'uyu' : u'ʷiu', u'uýu' : u'ʷiu', u'uỳu' : u'ʷiu',", "'kwi', 'ŋ͡m', 'k͡p', 'cw', 'jw', 'uə', 'eə', 'bw', 'oj', 'ʷi',", ": 2, u'ả' : 4, u'ã' : 3, u'ạ' :", ": 24, u'ù' : 32, u'ủ' : 312, u'ũ' :", "onoffglides: cod = onoffglides[nucl][-1] nuc = onoffglides[nucl][0:-1] if ons !=", "if ton == u'5' and cod in ['p', 't', 'k']:", ": u'uj', u'úy' : u'uj', u'ùy' : u'uj', u'ủy' :", "print(\"this is not in symbol :\"+ char+\":\") output+=delimit+undefine_symbol return output.rstrip()+delimit", "cách bỏ dấu khác nhau đều gộp chung làm một", "312, u'ẫ' : 312, u'ậ' : u'21g', u'ắ' : 13,", ": u'ʷa', u'õa' : u'ʷa', u'ọa' : u'ʷa', u'oă' :", "ons = onsets[word[0]] oOffset = 1 if word[l-2:l] in codas:", "= nuclei[nucl] # there's your nucleus else: # otherwise... nuc", "u'ẹ' : u'21g', # u'ê' : 33, u'ế' : 24,", "return (None, None, None, None) # Velar Fronting (Northern dialect)", "5, u'ồ' : 2, u'ổ' : 4, u'ỗ' : 4,", "'ɛu', 'ɔɪ', 'ʷi', 'eɪ', 'ɤj', 'ɯw', 'ɛj', 'ɔj', 'i:', 't∫',", "13, u'ằ' : 42, u'ẳ' : 312, u'ẵ' : 312,", ": u'ʈ', u'k' : u'k', u'c' : u'k', u'gh' :", "<-> khoẻ : xwʷɛ4 khua <-> khuơ : xuə1 lóe", "làm một #Disable convert from 'ɲ' to 'ɲ'' in north", "',', '4', 'ʊ', 's', 'ŋ', 'a', 'ʃ', '?', 'r', ':',", ": 4, u'ữ' : 3, u'ự' : 6, u'ý' :", "u'ọ' : 6, u'ố' : 5, u'ồ' : 2, u'ổ'", "u'iu', u'uỹu' : u'iu', u'uỵu' : u'iu', u'oen' : u'en',", ": ŋɛt5 ngễu <-> nghễu : ŋɛu3 nghía <-> ngía", "u'ʷa', u'uả' : u'ʷa', u'uã' : u'ʷa', u'uạ' : u'ʷa',", "with ủy onglide and off-glide is a big problem #Same", "u'ɔj', u'õi' : u'ɔj', u'ọi' : u'ɔj', u'ôi' : u'oj',", "Tiếng anh: => dùng etrain cho tiếng anh #+Deal case", "u'ủ' : 312, u'ũ' : 312, u'ụ' : u'21g', u'ứ'", "u'ɔ']: if cod == u'ŋ': cod = u'ŋ͡m' if cod", "0 if skip>0: skip=skip-1 continue for l in listParse: if", "for l in listParse: if len(l) <= len(text[ic:]) and l", "u'uə', } S_offglides = { u'ai' : u'aj', u'ái' :", "None, None) # Velar Fronting (Northern dialect) if dialect ==", "u'òi' : u'ɔj', u'ỏi' : u'ɔj', u'õi' : u'ɔj', u'ọi'", "nhau ################################################### checkDict() #print(vi2IPA_split(\"!Singapo english? đại học là IUYE gì", ": 33, u'ế' : 24, u'ề' : 32, u'ể' :", "check = 0 if skip>0: skip=skip-1 continue for l in", "symbols.sort(reverse = True,key=len) return symbols def vi2IPA_pitrain(text): epi = epitran.Epitran('vie-Latn')", "214, u'ỹ' : 214, u'ỵ' : 212, } S_tones_p =", "181) if dialect == 's': if cod in [u'm', u'p']:", "u'21g', u'ý' : 24, u'ỳ' : 32, u'ỷ' : 312,", "onoffglides, qu, gi = S_onsets, S_nuclei, S_codas, S_tones, S_onglides, S_offglides,", "# Các trường hợp có cách bỏ dấu khác nhau", "ipa của tiếng anh #print(vi2IPA_split(\"Another table was prepared to show", ": u'i', u'ý' : u'i', u'ỳ' : u'i', u'ỷ' :", "u'oẻo' : u'ew', u'oẽo' : u'ew', u'oẹo' : u'ew', u'oeo'", "u'21g', # u'i' : 33, u'í' : 24, u'ì' :", "cod = u'c' # Velar Fronting (Southern and Central dialects)", "u'ứ' : 45, u'ừ' : 32, u'ử' : 214, u'ữ'", ": u'ʷa', u'oà' : u'ʷa', u'oả' : u'ʷa', u'oã' :", ": 45, u'ề' : 32, u'ể' : 214, u'ễ' :", "u'uai' : u'aj', u'uái' : u'aj', u'uài' : u'aj', u'uải'", "== u'k' and cOffset == 2: nuc = u'ɛ' if", "} N_onglides = { u'oa' : u'a', u'oá' : u'a',", ": u'35g', u'ự' : u'21g', u'ý' : 24, u'ỳ' :", "'x', 'ʈ', ',', '4', 'ʊ', 's', 'ŋ', 'a', 'ʃ', '?',", "u'uyu' : u'ʷiu', u'uýu' : u'ʷiu', u'uỳu' : u'ʷiu', u'uỷu'", ": u'aj', u'uài' : u'aj', u'uải' : u'aj', u'uãi' :", "u'ứ' : 13, u'ừ' : 42, u'ử' : 312, u'ữ'", "u'uâ' : u'ʷɤ̆', u'uấ' : u'ʷɤ̆', u'uầ' : u'ʷɤ̆', u'uẩ'", ": u'j', u'h' : u'h', u'p' : u'p', u'qu' :", ": 24, u'ầ' : 32, u'ẩ' : 312, u'ẫ' :", "u'ăj', u'ao' : u'aw', u'áo' : u'aw', u'ào' : u'aw',", "u'ứ' : 5, u'ừ' : 2, u'ử' : 4, u'ữ'", "u'6b' # labialized allophony (added 17.09.08) if nuc in [u'u',", "u'iu', u'uyụ' : u'iu', u'uyu' : u'iu', u'uýu' : u'iu',", "u'ý' : 13, u'ỳ' : 42, u'ỷ' : 312, u'ỹ'", "if listParse == \"default\": listParse=['ʷiə', 'uəj', 'iəw', 'k͡p', 'ʷɤ̆', 'ɤ̆j',", "for text in tess: print(\"------------------------------------------------------\") TN= TTSnorm(text) print(\"------------------------------------------------------\") print(\"Text normalize:", "u'õ' : 4, u'ọ' : 6, u'ố' : 5, u'ồ'", "Monophthongization (Southern dialects: Thompson 1965: 86; Hoàng 1985: 181) if", "convert(word, dialect, glottal, pham, cao, palatals, delimit).strip() # concatenate if", ": u'uə', u'uợ' : u'uə', } N_offglides = { u'ai'", "[u'i', u'e', u'ɛ']: if cod == u'ɲ': cod = u'ɲ'", "u'21g', u'ắ' : 24, u'ằ' : 32, u'ẳ' : 312,", "u'i', u'ỳ' : u'i', u'ỷ' : u'i', u'ỹ' : u'i',", "32, u'ẳ' : 214, u'ẵ' : 214, u'ặ' : 212,", "delimit).strip() for x in values] seq = ''.join(v+d for v,d", "= S_onsets, S_nuclei, S_codas, S_tones, S_onglides, S_offglides, S_onoffglides, S_qu, S_gi", "<-> quýt : kwit5 thủa <-> thuở : tʰuə4 tòe", "fix #oe <-> uê -> fix oe from e to", "u'ằ' : 42, u'ẳ' : 312, u'ẵ' : 312, u'ặ'", ": iəw1 khoắng <-> khuắng : xwʷăŋ5 khỏe <-> khoẻ", "trans(word, dialect, glottal, pham, cao, palatals) if None in (ons,", "u'ỡ' : u'35g', u'ợ' : u'21g', # u'u' : 33,", "2, u'ỷ' : 4, u'ỹ' : 3, u'ỵ' : 6,", "in onsets: # if onset is 'nh', 'gh', 'kʷ' etc", "+', ' ', IPA) print(\"IPA Vietnamese: \",IPA) print(\"------------------------------------------------------\") Results+= IPA.rstrip()+\"", "'ʃ', 'æ', \"'\", 'h', 'o', 'k', '5', 'g', '4', 'n',", "u'ɤj', u'ưi' : u'ɯj', u'ứi' : u'ɯj', u'ừi' : u'ɯj',", ": u'ʐ', u's' : u'ʂ', u'gi': u'j'} Cus_nuclei = {", "\"oa,ua,a\" đều như một > must consider (nhưng nếu thêm", "'ʷe', 'i:', 'ɯə', 'dʒ', 'ɲ', 'θ', 'ʌ', 'l', 'w', '1',", "= { u'oe' : u'ej', u'oé' : u'ej', u'oè' :", "cod in ['p', 't', 'k']: ton = u'6b' # labialized", "u'ầu': u'ɤ̆w', u'ẩu' : u'ɤ̆w', u'ẫu' : u'ɤ̆w', u'ậu' :", "['y','ý','ỳ','ỷ','ỹ','ỵ']) or (lin2[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ'] and line[-1] in ['i','í','ì','ĩ','ỉ','ị']): continue", "u'ã' : u'35g', u'ạ' : u'21g', u'ấ' : 24, u'ầ'", ", C_onglides, C_offglides, C_onoffglides, C_qu, C_gi, N_onsets, N_nuclei, N_codas#, N_tones", "'ɲ', 'ɤ', '?', 'ɪ', 'l', '.', 'j', ':', 't', 'ʒ',", "tʃ for ch #Thay offglide: úy -> wi để phân", "u'oao' : u'aw', u'oáo' : u'aw', u'oào' : u'aw', u'oảo'", "#Custom tones_p = Cus_tones_p tones = tones_p ons = ''", "45, u'à' : 32, u'ả' : 214, u'ã' : 214,", ": u'a', u'ả' : u'a', u'ã' : u'a', u'ạ' :", "u'ɯəw', 'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw' } S_onglides =", "# otherwise... nuc = nuclei[nucl] # there's your nucleus else:", "in syms: print(test) else: print(\"none\") ''' ################################################### #Step #Vinorm #Underthesea", "u'21g', u'ứ' : 13, u'ừ' : 42, u'ử' : 312,", "\",TN) TK= word_tokenize(TN) print(\"Vietnamese Tokenize: \",TK) IPA=\"\" for tk in", "vi2IPA_split(texts,delimit): content=[] with open(\"Popular.txt\",encoding=\"utf-8\") as f: content=f.read().splitlines() tess = texts.split(\".\")", "u'ăj', u'ạy' : u'ăj', u'ao' : u'aw', u'áo' : u'aw',", "= { u'b' : u'b', u't' : u't', u'th' :", ": u'ɯəw', 'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw' } C_onglides", "nuc == u'uə': nuc = u'u' if nuc == u'ɯə':", ": u'ʷa', u'óa' : u'ʷa', u'òa' : u'ʷa', u'ỏa' :", ": u'aj', u'oay' : u'ăj', u'oáy' : u'ăj', u'oày' :", "Tones # Modified 20 Sep 2008 to fix aberrant 33", "312, u'ễ' : u'35g', u'ệ' : u'21g', u'í' : 24,", "u'uỡ' : u'uə', u'uợ' : u'uə', } S_offglides = {", "def checkDict(): cout=0 trung=0 List_token=[] List_pair = [] with open(\"Popular.txt\",", "gi and cod and len(word) == 3: # if you", "tự IPA của tiếng ANH #+Thêm xử lí case không", "nhất âm vực phoneme -> ok #+Get lại bộ symbol", ": u'a', u'uà' : u'a', u'uả' : u'a', u'uã' :", ": u'ăj', u'uáy' : u'ăj', u'uày' : u'ăj', u'uảy' :", "u'ồ' : u'o', u'ổ' : u'o', u'ỗ' : u'o', u'ộ'", ": u'iəw', u'yểu' : u'iəw', u'yễu' : u'iəw', u'yệu' :", "Mapping #Neu khong, check co nguyen am #Neu co de", ": 312, u'õ' : u'35g', u'ọ' : u'21g', # u'ô'", "u'ɤ̆j' } S_codas = { u'p' : u'p', u't' :", "'bw', 'oj', 'ʷi', 'vw', 'ăw', 'ʈw', 'ʂw', 'aʊ', 'fw', 'ɛu',", "u'ɤ̆j' } N_codas = { u'p' : u'p', u't' :", "'ɯəw', 'ʷɛ', 'ʷɤ', 'ɯj', 'oj', 'ăw', 'zi', 'kw', 'aɪ', 'iɛ',", "#south.py #coding: utf-8 S_onsets = { u'b' : u'b', u't'", ": u'ʷă', u'uẵ' : u'ʷă', u'uặ' : u'ʷă', u'uâ' :", "#Custom phoneme follow the https://vi.wikipedia.org/wiki/%C3%82m_v%E1%BB%8B_h%E1%BB%8Dc_ti%E1%BA%BFng_Vi%E1%BB%87t #Improve pronoune between N C", ": u'i', u'uya' : u'iə', u'uyá' : u'iə', u'uyà' :", "= u'5b' if ton == u'6' and cod in ['p',", "u'uợ' : u'uə', } C_offglides = { u'ai' : u'aj',", ": u'p', u't' : u't', u'c' : u'k', u'm' :", "text in tess: print(\"------------------------------------------------------\") TN= TTSnorm(text) print(\"------------------------------------------------------\") print(\"Text normalize: \",TN)", "u'au' : u'ăw', u'áu' : u'ăw', u'àu' : u'ăw', u'ảu'", "u'iə', u'oo' : u'ɔ', u'óo' : u'ɔ', u'òo' : u'ɔ',", "u'21g', u'ó' : 24, u'ò' : 32, u'ỏ' : 312,", ": u'wi', u'qùy' : u'wi', u'qủy' : u'wi', u'qũy' :", "[''] ipa = [convert(x, dialect, glottal, pham, cao, palatals, delimit).strip()", "u'ɯəw', u'ượu' : u'ɯəw' } #Các âm vòng ở đây", "f: content=f.read().splitlines() tess = texts.split(\".\") Results =\"\" for text in", "u'ɯəw' } C_onglides = { u'oa' : u'a', u'oá' :", ": 33, u'ố' : 24, u'ồ' : 32, u'ổ' :", "'ɲ', 'θ', 'ʌ', 'l', 'w', '1', 'ɪ', 'ɯ', 'd', '∫',", "u'ɛ', u'ẹ' : u'ɛ', u'ê' : u'e', u'ế' : u'e',", "add a labiovelar onset elif nucl in onglides and ons", "u'ʷiə', u'uyể' : u'ʷiə', u'uyễ' : u'ʷiə', u'uyệ' : u'ʷiə',", "codas: # if one-character coda cod = codas[word[l-1]] cOffset =", "tʰuə4 tòe <-> toè : twʷɛ2 ua <-> uơ :", "u'ʷi', u'ơi' : u'ɤj', u'ới' : u'ɤj', u'ời' : u'ɤj',", "'ʷet', 'ɯəw', 'ʷɛ', 'ʷɤ', 'ɯj', 'oj', 'ăw', 'zi', 'kw', 'aɪ',", "u'e', u'ỏe' : u'e', u'õe' : u'e', u'ọe' : u'e',", "u'ụ' : u'21g', # u'ư' : 33, u'ứ' : 24,", "=='\\n': return \"\" else: compound = u'' ortho = u''", "\"'\", 'h', 'o', 'k', '5', 'g', '4', 'n', ';', 'r',", "u'tr' : u'c', u'k' : u'k', u'c' : u'k', u'gh'", "u'ay' : u'ăj', u'áy' : u'ăj', u'ày' : u'ăj', u'ảy'", "u'e', u'ɛ']: if cod == u'ɲ': cod = u'ɲ' #", "'gì',... ons = gi[word][0] nuc = gi[word][1] elif word in", "nucleus else: nuc = nuclei[nucl] # there's your nucleus else:", "in qu: # if word == 'quy', 'qúy',... ons =", "u'uại' : u'aj', u'uay' : u'ăj', u'uáy' : u'ăj', u'uày'", "} S_offglides = { u'ai' : u'aj', u'ái' : u'aj',", "#Tuy nhiên cuối cùng \"ch\" \"c\" \"t\" không phân âm", "nuc, cod, ton) = trans(word, dialect, glottal, pham, cao, palatals)", "it, but... else: # if there is no onset... ons", ": u'ʷi', u'ơi' : u'ɤj', u'ới' : u'ɤj', u'ời' :", "= delimit+delimit.join(filter(None, (ons, nuc, cod, ton)))+delimit except (TypeError): pass return", ": u'ɲ', u'ch' : u'tʃ' } Cus_tones_p = { u'á'", "in ['i','í','ì','ĩ','ỉ','ị'] and line[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ']) or (lin2[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ']", "pham=1 else: cao=1 #Input text line = text if line", "if cod == u'ŋ': cod = u'n' # There is", "u'ew', u'ẹo' : u'ew', u'iu' : u'iw', u'íu' : u'iw',", ": 214, u'ỡ' : 214, u'ợ' : 212, u'ú' :", "u'iu', u'uyù' : u'iu', u'uyủ' : u'iu', u'uyũ' : u'iu',", "vinorm import * from underthesea import word_tokenize import eng_to_ipa SET=[S_onsets,", ": iə1 iêu <-> yêu : iəw1 khoắng <-> khuắng", "'u:', 'aw', 'ɛj', 'iw', 'aj', 'ɜ:', 'kw', 'nw', 't∫', 'ɲw',", ": u'iə', u'iá' : u'iə', u'ià' : u'iə', u'iả' :", "u'ủ' : 312, u'ũ' : u'35g', u'ụ' : u'21g', #", "3, u'ạ' : 6, u'ấ' : 5, u'ầ' : 2,", ": u'ɤ̆j', u'uầy' : u'ɤ̆j', u'uẩy' : u'ɤ̆j', u'uẫy' :", "ngoèo : ŋwew2 quít <-> quýt : kwit5 thủa <->", ": u'uəj', u'uổi' : u'uəj', u'uỗi' : u'uəj', u'uội' :", "#if word[0:2] == u'gi' and cod and len(word) == 3:", ": u'ʷi', u'uỵ' : u'ʷi', u'uya' : u'ʷiə', u'uyá' :", "u'oẽo' : u'ew', u'oẹo' : u'ew', u'oeo' : u'ew', u'óeo'", "vi2IPA(text): print(\"------------------------------------------------------\") TN= TTSnorm(text) print(\"------------------------------------------------------\") print(\"Text normalize: \",TN) TK= word_tokenize(TN)", ": u'35g', u'ọ' : u'21g', u'ố' : 24, u'ồ' :", "continue cout_same+=1 print(line+ \" <-> \" + lin2 +\"\\t\\t:\\t\\t\"+T2IPA(line)) print(\"Same", "def vi2IPA_split(texts,delimit): content=[] with open(\"Popular.txt\",encoding=\"utf-8\") as f: content=f.read().splitlines() tess =", "312, u'ẫ' : u'35g', u'ậ' : u'21g', # u'ă' :", "u'35g', u'ụ' : u'21g', u'ứ' : 24, u'ừ' : 32,", "u'ɔ', u'ô' : u'o', u'ố' : u'o', u'ồ' : u'o',", "u'ʷɤ̆', u'uẩ' : u'ʷɤ̆', u'uẫ' : u'ʷɤ̆', u'uậ' : u'ʷɤ̆',", ": u'aj', u'oái' : u'aj', u'oài' : u'aj', u'oải' :", "u'ặ' : u'21g', # u'e' : 33, u'é' : 24,", "u'ữ' : 312, u'ự' : u'21g', u'ý' : 13, u'ỳ'", ": u'kwi', u'qũy' : u'kwi', u'qụy' : u'kwi'} ####################################################### #central.py", "1->6 #học ác cho kết quả \"c\" khác nhau ###################################################", "u'ɤ̆j', u'ầy' : u'ɤ̆j', u'ẩy' : u'ɤ̆j', u'ẫy' : u'ɤ̆j',", ": 2, u'ể' : 4, u'ễ' : 3, u'ệ' :", "u'ể' : 4, u'ễ' : 3, u'ệ' : 6, u'í'", "you just have 'gi' and a coda... if word[0:2] in", "u'ời' : u'ɤj', u'ởi' : u'ɤj', u'ỡi' : u'ɤj', u'ợi'", ": u'a', u'uả' : u'a', u'uã' : u'a', u'uạ' :", "u'35g', u'ậ' : u'21g', u'ắ' : 24, u'ằ' : 32,", "u'wi', u'qụy' : u'wi'} ################################################3 import sys, codecs, re from", ": 45, u'ì' : 32, u'ỉ' : 214, u'ĩ' :", "nếu thêm vào ảnh hưởng chữ qu cũng ra w)", "onset.... ons = u'ʔ'+nuclei[nucl] # add a glottal stop else:", "u'ụ' : 212, u'ứ' : 45, u'ừ' : 32, u'ử'", "13, u'ề' : 42, u'ể' : 312, u'ễ' : 312,", "<-> uê -> fix oe from e to ɛ #âm", "f: content=f.read().splitlines() for line in content: #nor_tr = vi2IPA_pitrain(line) #nor", ": u'o', u'ộ' : u'o', u'ơ' : u'ɤ', u'ớ' :", "'iə', 'ɣw', 'zw', 'ɯj', 'ʷɛ', 'ɯw', 'ɤj', 'ɔ:', 'əʊ', 'ʷa',", "TN= TTSnorm(text) print(\"------------------------------------------------------\") print(\"Text normalize: \",TN) TK= word_tokenize(TN) print(\"Vietnamese Tokenize:", "qu, gi = S_onsets, S_nuclei, S_codas, S_tones, S_onglides, S_offglides, S_onoffglides,", "all start o and u as in wiki # ***", "ra w) #Try to add ʷ to all start o", "24, u'ờ' : 32, u'ở' : 312, u'ỡ' : u'35g',", "u'đ' : u'd', u'ch' : u'c', u'kh' : u'x', u'g'", "32, u'ẩ' : 312, u'ẫ' : u'35g', u'ậ' : u'21g',", "u'ɛj', u'oẽ' : u'ɛj', u'oẹ' : u'ɛj', u'oai' : u'aj',", "u'k', u'm' : u'm', u'n' : u'ŋ', u'ng' : u'ŋ',", "if ons: # if there is an onset... ons =", "u'ew', u'uèo' : u'ew', u'uẻo' : u'ew', u'uẽo' : u'ew',", ": u'ʷă', u'oe' : u'ʷɛ', u'oé' : u'ʷɛ', u'oè' :", "Obstruent-final nang tones are modal voice if (dialect == 'n'", "################################################3 import sys, codecs, re from io import StringIO from", "= 1 if word[l-2:l] in codas: # if two-character coda", "'sw', 'tw', 'ʐw', 'iɛ', 'ʷe', 'i:', 'ɯə', 'dʒ', 'ɲ', 'θ',", ": u'o', u'ôộ' : u'o', u'ua' : u'uə', u'úa' :", ": u'aw', u'ão' : u'aw', u'ạo' : u'aw', u'au' :", "word) or (tokenize and '_' in word): substrings = re.split(r'(_|-)',", "#Looking for pair Pair = {} for lt in List_pair:", "u'ʷiu', u'uýu' : u'ʷiu', u'uỳu' : u'ʷiu', u'uỷu' : u'ʷiu',", "u'ĩ' : u'35g', u'ị' : u'21g', u'ó' : 24, u'ò'", "return compound def T2IPA(text): sys.path.append('./Rules') # make sure we can", ": u'wi', u'qũy' : u'wi', u'qụy' : u'wi'} ############################################ #south.py", "if ons != u'kw': if ons: ons = ons+u'w' else:", "u'qúy' : u'kwi', u'qùy' : u'kwi', u'qủy' : u'kwi', u'qũy'", "compound EN={\"a\":\"ây\",\"ă\":\"á\",\"â\":\"ớ\",\"b\":\"bi\",\"c\":\"si\",\"d\":\"đi\",\"đ\":\"đê\",\"e\":\"i\",\"ê\":\"ê\",\"f\":\"ép\",\"g\":\"giy\",\"h\":\"ếch\",\"i\":\"ai\",\"j\":\"giây\",\"k\":\"cây\",\"l\":\"eo\",\"m\":\"em\",\"n\":\"en\",\"o\":\"âu\",\"ô\":\"ô\",\"ơ\":\"ơ\",\"p\":\"pi\",\"q\":\"kiu\",\"r\":\"a\",\"s\":\"ét\",\"t\":\"ti\",\"u\":\"diu\",\"ư\":\"ư\",\"v\":\"vi\",\"w\":\"đắp liu\",\"x\":\"ít\",\"y\":\"quai\",\"z\":\"giét\"} import re def vi2IPA_split(texts,delimit): content=[] with open(\"Popular.txt\",encoding=\"utf-8\")", "u'gi' and cod and len(word) == 3: # if you", "u'uờ' : u'ɤ', u'uở' : u'ɤ', u'uỡ' : u'ɤ', u'uợ'", "def Parsing(listParse, text, delimit): undefine_symbol = \"'\" if listParse ==", "u'ɯw', u'iêu' : u'iəw', u'iếu' : u'iəw', u'iều' : u'iəw',", "312, u'ẵ' : 312, u'ặ' : u'21g', u'é' : 13,", ": u'ʷa', u'oă' : u'ʷă', u'oắ' : u'ʷă', u'oằ' :", "(Southern dialects: Thompson 1965: 86; Hoàng 1985: 181) if dialect", "u'ằ' : 2, u'ẳ' : 4, u'ẵ' : 3, u'ặ'", "u'ìa' : u'iə', u'ỉa' : u'iə', u'ĩa' : u'iə', u'ịa'", "onglides and ons == u'kw': nuc = onglides[nucl] elif nucl", "u'u' if nuc == u'ɯə': nuc = u'ɯ' # Tones", "word in words if word!=u'-'] words = [word for word", "eng_to_ipa SET=[S_onsets, S_nuclei, S_codas#, S_tones , S_onglides, S_offglides, S_onoffglides, S_qu,", "u'ʷɛ', u'ỏe' : u'ʷɛ', u'õe' : u'ʷɛ', u'ọe' : u'ʷɛ',", "= u'w' # add a labiovelar onset elif nucl in", "ons != u'kw': if ons: ons = ons+u'w' else: ons", "u'qụy' : u'wi'} ############################################ #south.py #coding: utf-8 S_onsets = {", "chi phí chạy máy không normal phoneme về cường độ", "cod and len(word) == 3: # if you just have", "là: # Phương ngữ khác nhau đã thống nhất ở", "u'ʷiə', u'uyế' : u'ʷiə', u'uyề' : u'ʷiə', u'uyể' : u'ʷiə',", "u'iə', u'ía' : u'iə', u'ìa' : u'iə', u'ỉa' : u'iə',", "u'ạu' : u'ăw', u'ây' : u'ɤ̆j', u'ấy' : u'ɤ̆j', u'ầy'", "delimit): \"\"\"Convert a single orthographic string to IPA.\"\"\" ons =", "anh \"'\" #print(vi2IPA_split(\"speech? Secondly, we paper, we investigate work! One", "as f: content=f.read().splitlines() for line in content: if T2IPA(line) in", "u'iə', u'uyể' : u'iə', u'uyễ' : u'iə', u'uyệ' : u'iə',", "u'ʷɤ', u'uờ' : u'ʷɤ', u'uở' : u'ʷɤ', u'uỡ' : u'ʷɤ',", ": 4, u'ỵ' : 6, } C_gi = { u'gi'", "u'ʷa', u'uà' : u'ʷa', u'uả' : u'ʷa', u'uã' : u'ʷa',", "u'a', u'à' : u'a', u'ả' : u'a', u'ã' : u'a',", "24, u'ề' : 32, u'ể' : 312, u'ễ' : u'35g',", "u'ộ' : u'21g', u'ớ' : 13, u'ờ' : 42, u'ở'", "and cod in ['p', 't', 'k']: # fixed 8 Nov", ": u'ji', u'gí': u'ji', u'gì' : u'ji', u'gì' : u'ji',", "u'a', u'uả' : u'a', u'uã' : u'a', u'uạ' : u'a',", "u'ɤ̆', u'ue' : u'ɛ', u'ué' : u'ɛ', u'uè' : u'ɛ',", ": 6, u'ố' : 5, u'ồ' : 2, u'ổ' :", "palatals, delimit): \"\"\"Convert a single orthographic string to IPA.\"\"\" ons", "'θ', 'ʌ', 'l', 'w', '1', 'ɪ', 'ɯ', 'd', '∫', 'p',", "for 8-tone system if cao == 1: if ton ==", "u'uỳu' : u'iu', u'uỷu' : u'iu', u'uỹu' : u'iu', u'uỵu'", "u'ằ' : 2, u'ẳ' : 4, u'ẵ' : 4, u'ặ'", "{ u'oe' : u'ej', u'oé' : u'ej', u'oè' : u'ej',", ": u'ej', u'oẻ' : u'ej', u'oẽ' : u'ej', u'oẹ' :", "word == 'gi', 'gì',... ons = gi[word][0] nuc = gi[word][1]", "# Monophthongization (Southern dialects: Thompson 1965: 86; Hoàng 1985: 181)", "u'ự' : u'ɯ', u'y' : u'i', u'ý' : u'i', u'ỳ'", "else: compound = u'' ortho = u'' words = line.split()", "N_onglides, N_offglides, N_onoffglides, N_qu, N_gi elif dialect == 'c': onsets,", ": u'kwi', u'qủy' : u'kwi', u'qũy' : u'kwi', u'qụy' :", "312, u'ễ' : u'35g', u'ệ' : u'21g', # u'i' :", ": u'ʷet', u'oét' : u'ʷet', u'oèt' : u'ʷet', u'oẻt' :", "0 tokenize = 0 dialect='n' #\"c\"\"s\" tone_type=0 if tone_type==0: pham=1", "u'ŋ', u'nh' : u'ɲ', u'ng' : u'ŋ', u'ph' : u'f',", "for s in SET: DICT.update(s) list_phoneme=DICT.values() list_phoneme=list(list_phoneme) English_phoneme=[\"p\",\"b\",\"t\",\"d\",\"t∫\",\"dʒ\",\"k\",\"g\",\"f\",\"v\",\"ð\",\"θ\",\"s\",\"z\",\"∫\",\"ʒ\",\"m\",\"n\",\"η\",\"l\",\"r\",\"w\",\"j\",\"ɪ\",\"i:\",\"ʊ\",\"u:\",\"e\",\"ə\",\"ɜ:\",\"ɒ\",\"ɔ:\",\"æ\",\"ʌ\",\"ɑ:\",\"ɪə\",\"ʊə\",\"eə\",\"eɪ\",\"ɔɪ\",\"aɪ\",\"əʊ\",\"aʊ\",'ʃ',\"ʤ\",\"ʧ\"] Special=['jw', 'ŋw',", "C_offglides, C_onoffglides, C_qu, C_gi, N_onsets, N_nuclei, N_codas#, N_tones , N_onglides,", "u'21g', # u'y' : 33, u'ý' : 24, u'ỳ' :", "else: IPA+=eng+\" \" #Check tu dien tieng anh Etrain bưc", ": u'iw', u'oi' : u'ɔj', u'ói' : u'ɔj', u'òi' :", "u'ử' : 312, u'ữ' : u'35g', u'ự' : u'21g', u'ý'", "không normal phoneme về cường độ âm sắc chỉ dừng", ": u'35g', u'ộ' : u'21g', # u'ơ' : 33, u'ớ'", ": u'iu', u'oen' : u'en', u'oén' : u'en', u'oèn' :", "u'uyà' : u'ʷiə', u'uyả' : u'ʷiə', u'uyã' : u'ʷiə', u'uyạ'", "for sắc in closed syllables (Northern and Central only) if", "u'ɔ', u'ôô' : u'o', u'ốô' : u'o', u'ồô' : u'o',", "4, u'ẵ' : 3, u'ặ' : 6, u'é' : 5,", "['p', 't', 'k']: ton = u'45' # Modification for 8-tone", "u'p' : u'p', u'qu' : u'w', u'gi' : u'j', u'tr'", "if there isn't an onset.... ons = u'ʔ'+nuclei[nucl] # add", "the https://vi.wikipedia.org/wiki/%C3%82m_v%E1%BB%8B_h%E1%BB%8Dc_ti%E1%BA%BFng_Vi%E1%BB%87t #Improve pronoune between N C S Cus_onsets =", ": u'ʷɛ', u'oẻ' : u'ʷɛ', u'oẽ' : u'ʷɛ', u'oẹ' :", "words = [word for word in words if word!=u'-'] words", "'s': if cod in [u'm', u'p']: if nuc == u'iə':", "gi = S_onsets, S_nuclei, S_codas, S_tones, S_onglides, S_offglides, S_onoffglides, S_qu,", ": u'ɔ', u'oó' : u'ɔ', u'oò' : u'ɔ', u'oỏ' :", ": u'ʷiu', u'uyụ' : u'ʷiu', u'uyu' : u'ʷiu', u'uýu' :", "line =='\\n': return \"\" else: compound = u'' ortho =", ": u'21g', u'ấ' : 24, u'ầ' : 32, u'ẩ' :", ": u'iu', u'uyủ' : u'iu', u'uyũ' : u'iu', u'uyụ' :", "Cus_onsets, Cus_nuclei, Cus_codas, Cus_onglides, Cus_offglides, Cus_onoffglides, Cus_qu, Cus_gi if pham", "to show available onsets. Onsets are splitted into 3 types.", "u'uə', u'uợ' : u'uə', } Cus_offglides = { u'ai' :", "u'ù' : 2, u'ủ' : 4, u'ũ' : 3, u'ụ'", "danh van print(\" ..................Out of domain word: \" ,ipa) else:", "u'uỵu' : u'iu', u'oen' : u'en', u'oén' : u'en', u'oèn'", ": 212, u'ớ' : 45, u'ờ' : 32, u'ở' :", "return output.rstrip()+delimit #print(\"Parsing\",Parsing(\"default\",\"iu iu\",\"|\")) def getSymbol(): for s in SET:", "u'ɯəw', 'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw' } #Các âm", ": u'21g', # u'ă' : 33, u'ắ' : 24, u'ằ'", ": u'o', u'ôổ' : u'o', u'ôỗ' : u'o', u'ôộ' :", ": 4, u'ệ' : 6, u'í' : 5, u'ì' :", "u'iả' : u'iə', u'iã' : u'iə', u'iạ' : u'iə', u'iê'", "anh -> đọc từng kí tự #Now #+Thêm kí tự", "u'a', u'uạ' : u'a', u'uă' : u'ă', u'uắ' : u'ă',", "5, u'à' : 2, u'ả' : 4, u'ã' : 3,", "ch : k theo bắc : t theo nam ->", "add ʷ to all start o and u as in", ": u'u', u'ủ' : u'u', u'ũ' : u'u', u'ụ' :", "== u'21\\u02C0' and cod in ['p', 't', 'k']: # fixed", "u'oé' : u'ʷɛ', u'oè' : u'ʷɛ', u'oẻ' : u'ʷɛ', u'oẽ'", "u'ọa' : u'a', u'oă' : u'ă', u'oắ' : u'ă', u'oằ'", "u'ử' : 4, u'ữ' : 3, u'ự' : 6, u'ý'", "u'ɯ', u'ứ' : u'ɯ', u'ừ' : u'ɯ', u'ử' : u'ɯ',", ": u'ɛ', u'é' : u'ɛ', u'è' : u'ɛ', u'ẻ' :", "tones, onglides, offglides, onoffglides, qu, gi = N_onsets, N_nuclei, N_codas,", "u'['+word+u']' else: seq = delimit+delimit.join(filter(None, (ons, nuc, cod, ton)))+delimit except", "u'm', u'n' : u'ŋ', u'ng' : u'ŋ', u'nh' : u'n',", "'ʷă', 'ɜ:', 'tʰ', 'dʒ', 'ew', 'ʊə', 'ɯə', 'aw', '3', 'θ',", "nguyên IPA+=Parsing(\"default\",tk,\"\")+\" \" else: IPA+=eng+\" \" #Check tu dien tieng", "'ew', 'ʊə', 'ɯə', 'aw', '3', 'θ', 'v', 'ʊ', 'ʤ', 'ɔ',", ": u'ɤ', u'ờ' : u'ɤ', u'ở' : u'ɤ', u'ỡ' :", "{ u'a' : 33, u'á' : 24, u'à' : 32,", ": 214, u'õ' : 214, u'ọ' : 212, u'ố' :", "5, u'ỳ' : 2, u'ỷ' : 4, u'ỹ' : 4,", "u'ể' : 214, u'ễ' : 214, u'ệ' : 212, u'í'", "and re-concatenate if (tokenize and '-' in word) or (tokenize", "u'ɯw', u'ừu' : u'ɯw', u'ửu' : u'ɯw', u'ữu' : u'ɯw',", "wiki # *** Problem with ủy onglide and off-glide is", "u'ɛ', u'ẻ' : u'ɛ', u'ẽ' : u'ɛ', u'ẹ' : u'ɛ',", "text, delimit): undefine_symbol = \"'\" if listParse == \"default\": listParse=['ʷiə',", "u'ỏ' : u'ɔ', u'õ' : u'ɔ', u'ọ' : u'ɔ', u'ô'", "214, u'ệ' : 212, u'í' : 45, u'ì' : 32,", "nuc = '' cod = '' ton = 0 seq", "u'ʷɛ', u'ua' : u'ʷa', u'uá' : u'ʷa', u'uà' : u'ʷa',", "north #Các âm vòng ở đây i chang không vòm:", ": 13, u'ồ' : 42, u'ổ' : 312, u'ỗ' :", "ons = onsets[word[0:3]] oOffset = 3 elif word[0:2] in onsets:", "(dialect == 'n' or dialect == 's') and ton ==", "Pair: lin2 =Pair[T2IPA(line)] if line != lin2: if (lin2[0]==\"k\" and", "# u'â' : 33, u'ấ' : 24, u'ầ' : 32,", ": 312, u'ỗ' : u'35g', u'ộ' : u'21g', # u'ơ'", "u'uề' : u'ʷe', u'uể' : u'ʷe', u'uễ' : u'ʷe', u'uệ'", "\"uỳ\", \"ả\",\"ẳ\",\"ẩ\",\"ẻ\",\"ể\",\"ỉ\",\"ỏ\",\"ổ\",\"ở\",\"ủ\",\"ử\",\"ỷ\",\"iể\",\"ỏa\",\"oẳ\",\"ỏe\",\"oỏ\",\"uẩ\",\"uể\",\"uổ\",\"ưở\",\"ủy\",\"ưở\",\"uyể\",\"yể\", #hook \"oả\", \"oẻ\",\"ỏo\", \"uỷ\", \"ã\",\"ẵ\",\"ẫ\",\"ẽ\",\"ễ\",\"ĩ\",\"õ\",\"ỗ\",\"ỡ\",\"ũ\",\"ữ\",\"ỹ\",\"iễ\",\"õa\",\"oẵ\",\"õe\",\"oõ\",\"uẫ\",\"uễ\",\"uỗ\",\"ưỡ\",\"ũy\",\"ưỡ\",\"uyễ\",\"yễ\", #tilde \"oã\", \"oẽ\",\"õo\",", "and line[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ']) or (lin2[-1] in ['y','ý','ỳ','ỷ','ỹ','ỵ'] and line[-1]", "= u'21' # Modification for sắc in closed syllables (Northern", "= { u'á' : 13, u'à' : 42, u'ả' :", "5, u'ò' : 2, u'ỏ' : 4, u'õ' : 4,", "u'yê' : u'iɛ', u'yế' : u'iɛ', u'yề' : u'iɛ', u'yể'", "len(words)-1: seq = seq+u' ' compound = compound + seq", "u'ỳ' : u'i', u'ỷ' : u'i', u'ỹ' : u'i', u'ỵ'", "u'a', u'õa' : u'a', u'ọa' : u'a', u'oă' : u'ă',", ": lwʷɛ5 ngét <-> nghét : ŋɛt5 ngễu <-> nghễu", "u'ɯəj', u'ươu' : u'ɯəw', u'ướu' : u'ɯəw', u'ườu' : u'ɯəw',", "\",TN) TK= word_tokenize(TN) print(\"Vietnamese Tokenize: \",TK) for iuv,under_valid in enumerate(TK):", "'vw', 'dw', 'eo', 'ʈw', 'mw', 'zw', 'fw', 'tw', 'tʰw', 'ɲw',", "u'ʷen', u'oén' : u'ʷen', u'oèn' : u'ʷen', u'oẻn' : u'ʷen',", "u'c' # Velar Fronting (Southern and Central dialects) else: if", "u'tʰ', u'đ' : u'd', u'ch' : u'c', u'kh' : u'x',", "u'ê' : 33, u'ế' : 24, u'ề' : 32, u'ể'", "Modification for sắc in closed syllables (Northern and Central only)", "in T2IPA(tok): checkinvalid=1 if checkinvalid==1: TK = TK[:iuv] + TK[iuv+1", "'ʷɤ', 'ɯj', 'oj', 'ăw', 'zi', 'kw', 'aɪ', 'iɛ', 'ɤ̆', 'ɔ:',", "u'uỹu' : u'iu', u'uỵu' : u'iu', u'oen' : u'en', u'oén'", ": u'ă', u'ắ' : u'ă', u'ằ' : u'ă', u'ẳ' :", "= u'n' # There is also this reverse fronting, see", "u'uyà' : u'iə', u'uyả' : u'iə', u'uyã' : u'iə', u'uyạ'", ": u'35g', u'ọ' : u'21g', # u'ô' : 33, u'ố'", "u'uý' : u'i', u'uỳ' : u'i', u'uỷ' : u'i', u'uỹ'", "u'iəw', u'iều' : u'iəw', u'iểu' : u'iəw', u'iễu' : u'iəw',", "khong danh van print(\" ..................Out of domain word: \" ,ipa)", ": u'ʷɤ', u'uờ' : u'ʷɤ', u'uở' : u'ʷɤ', u'uỡ' :", "u't' : u't', u'th' : u'tʰ', u'đ' : u'd', u'ch'", "u'a', u'â' : u'ɤ̆', u'ấ' : u'ɤ̆', u'ầ' : u'ɤ̆',", "u'uấy' : u'ɤ̆j', u'uầy' : u'ɤ̆j', u'uẩy' : u'ɤ̆j', u'uẫy'", ": u'u', u'ư' : u'ɯ', u'ứ' : u'ɯ', u'ừ' :", "u'ệ' : u'21g', u'í' : 24, u'ì' : 32, u'ỉ'", ": 214, u'ị' : 212, u'ó' : 45, u'ò' :", "else: IPA+=ipa+\" \" IPA=re.sub(delimit+'+', delimit, IPA) IPA=re.sub(' +', ' ',", "in tk: CHAR = str(char).lower() if CHAR in list(EN.keys()): letter2sound+=EN[CHAR]+\"", "312, u'ỗ' : u'35g', u'ộ' : u'21g', u'ớ' : 24,", "space = [\" \"] tone=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"] punctuation = [\".\",\",\",\"!\",\":\",\"?\",\";\",\"'\"] #\" '", "khuắng : xwʷăŋ5 khỏe <-> khoẻ : xwʷɛ4 khua <->", "312, u'ũ' : 312, u'ụ' : u'21g', u'ứ' : 13,", "Secondly, we paper, we investigate work! One is that e", "u'h', u'p' : u'p', u'qu' : u'w', u'gi' : u'j',", "u'uyũ' : u'iu', u'uyụ' : u'iu', u'uyu' : u'iu', u'uýu'", "32, u'ể' : 312, u'ễ' : u'35g', u'ệ' : u'21g',", "u'ɛu', u'ệu' : u'ɛu', u'ia' : u'iə', u'ía' : u'iə',", "u'iều' : u'iəw', u'iểu' : u'iəw', u'iễu' : u'iəw', u'iệu'", ": u'21g', u'ố' : 24, u'ồ' : 32, u'ổ' :", "pham, cao, palatals): # This looks ugly, but newer versions", "u'uə', } C_offglides = { u'ai' : u'aj', u'ái' :", "[] with open(\"Popular.txt\", encoding=\"utf-8\") as f: content=f.read().splitlines() for line in", "u'iə', u'uyạ' : u'iə', u'uyê' : u'iə', u'uyế' : u'iə',", "'w', 'p', 'ʃ', 'æ', \"'\", 'h', 'o', 'k', '5', 'g',", "= u'' ortho = u'' words = line.split() ## toss", "u'uə', u'ũa' : u'uə', u'ụa' : u'uə', u'uô' : u'uə',", "u'ẵ' : u'35g', u'ặ' : u'21g', # u'e' : 33,", "u'ệ' : 6, u'í' : 5, u'ì' : 2, u'ỉ'", ": u'aj', u'ài' : u'aj', u'ải' : u'aj', u'ãi' :", ": u'a', u'ạ' : u'a', u'â' : u'ɤ̆', u'ấ' :", "gích : ɣitʃ5 ia <-> iê : iə1 iêu <->", "42, u'ả' : 312, u'ã' : 312, u'ạ' : u'21g',", "312, u'ọ' : u'21g', u'ố' : 13, u'ồ' : 42,", "u'yể' : u'iɛ', u'yễ' : u'iɛ', u'yệ' : u'iɛ', u'uơ'", "palatals) if None in (ons, nuc, cod, ton): seq =", "214, u'ặ' : 212, u'é' : 45, u'è' : 32,", "punctuation def trans(word, dialect, glottal, pham, cao, palatals): # This", "################################################### checkDict() #print(vi2IPA_split(\"!Singapo english? đại học là IUYE gì khôngtontaij", "There is also this reverse fronting, see Thompson 1965:94 ff.", "u'iə', u'iể' : u'iə', u'iễ' : u'iə', u'iệ' : u'iə',", "u'21g', u'é' : 24, u'è' : 32, u'ẻ' : 312,", "is not in symbol :\"+ char+\":\") output+=delimit+undefine_symbol return output.rstrip()+delimit #print(\"Parsing\",Parsing(\"default\",\"iu", ": u'v', u'x' : u's', u'd' : u'z', u'h' :", "= 0 palatals = 0 tokenize = 0 delimit =", ": u'aj', u'uải' : u'aj', u'uãi' : u'aj', u'uại' :", "else: seq = convert(word, dialect, glottal, pham, cao, palatals, delimit).strip()", "u'gh' : u'ɣ', u'r' : u'ʐ', u's' : u'ʂ', u'gi'", "str(tonelist[len(tonelist)-1]) else: if not (pham or cao): if dialect ==", ": u'ew', u'ẽo' : u'ew', u'ẹo' : u'ew', u'iu' :", "for tok in token_under: if tok not in content or", "N_gi elif dialect == 'c': onsets, nuclei, codas, tones, onglides,", "6, u'ứ' : 5, u'ừ' : 2, u'ử' : 4,", ": u'iw', u'ìu' : u'iw', u'ỉu' : u'iw', u'ĩu' :", "u'oẳ' : u'ă', u'oẵ' : u'ă', u'oặ' : u'ă', u'oe'", "'kwi', 'ɤ̆w', 'ɯəj', 'ʷen', 'ʷiu', 'ʷet', 'ɯəw', 'ʷɛ', 'ʷɤ', 'ɯj',", "in ['y','ý','ỳ','ỷ','ỹ','ỵ'] and line[-1] in ['i','í','ì','ĩ','ỉ','ị']): continue cout_same+=1 print(line+ \"", ": 214, u'ữ' : 214, u'ự' : 212, u'ý' :", "u'kh' : u'x', u'g' : u'ɣ', u'l' : u'l', u'm'", "u'yề' : u'iɛ', u'yể' : u'iɛ', u'yễ' : u'iɛ', u'yệ'", "} #Các âm vòng ở đây i chang không vòm:", "u'ẵ' : 214, u'ặ' : 212, u'é' : 45, u'è'", ": u'e', u'uế' : u'e', u'uề' : u'e', u'uể' :", ": 312, u'ũ' : 312, u'ụ' : u'21g', u'ứ' :", "which has one letter \",\"/\")) #Lọc bỏ dấu nhấn của", ": u'ăj', u'ảy' : u'ăj', u'ãy' : u'ăj', u'ạy' :", "= str('33') else: ton = str('1') # Modifications for closed", "u'ɤ̆', u'uầ' : u'ɤ̆', u'uẩ' : u'ɤ̆', u'uẫ' : u'ɤ̆',", "u'ʷă', u'uắ' : u'ʷă', u'uằ' : u'ʷă', u'uẳ' : u'ʷă',", "u'ôộ' : u'o', u'ua' : u'uə', u'úa' : u'uə', u'ùa'", "u'e', u'ọe' : u'e', u'ua' : u'a', u'uá' : u'a',", "'zw', 'ɯj', 'ʷɛ', 'ɯw', 'ɤj', 'ɔ:', 'əʊ', 'ʷa', 'mw', 'ɑ:',", ": u'ɯw', u'iêu' : u'iəw', u'iếu' : u'iəw', u'iều' :", "u'ủy' : u'uj', u'ũy' : u'uj', u'ụy' : u'uj', u'ơi'", "str(char) in [\"ˈ\",\"ˌ\",\"*\"]: continue print(\"this is not in symbol :\"+", "None) # Velar Fronting (Northern dialect) if dialect == 'n':", "\"\" else: compound = u'' ortho = u'' words =", "u'k' : u'k', u'c' : u'k', u'gh' : u'ɣ', u'r'", "u'uyể' : u'iə', u'uyễ' : u'iə', u'uyệ' : u'iə', u'uyu'", "312, u'ẽ' : u'35g', u'ẹ' : u'21g', # u'ê' :", "print(\"Vietnamese Tokenize: \",TK) IPA=\"\" for tk in TK: ipa =", "u'ɤ̆j', u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j' } Cus_codas =", "u'b' : u'b', u't' : u't', u'th' : u'tʰ', u'đ'", "32, u'ủ' : 312, u'ũ' : u'35g', u'ụ' : u'21g',", ": u'ɔ', u'òo' : u'ɔ', u'ỏo' : u'ɔ', u'õo' :", "u'e', u'óe' : u'e', u'òe' : u'e', u'ỏe' : u'e',", "'gi' and a coda... nucl = u'i' ons = u'z'", "'ʷet', 'iəw', 'uəj', 'ʷen', 'tʰw', 'ʷɤ̆', 'ʷiu', 'kwi', 'ŋ͡m', 'k͡p',", "-> đọc từng kí tự #Now #+Thêm kí tự IPA", "# if there is an onglide... nuc = onglides[nucl] #", "glottal, pham, cao, palatals): # This looks ugly, but newer", "u'aj', u'oài' : u'aj', u'oải' : u'aj', u'oãi' : u'aj',", "tones, onglides, offglides, onoffglides, qu, gi = C_onsets, C_nuclei, C_codas,", "u'k' and cOffset == 2: nuc = u'ɛ' if cod", "TK = TK[:iuv] + TK[iuv+1 :] for tok in reversed(token_under):", "if tk.lower().upper() == tk: #Đọc tiếng anh từng chữ letter2sound=\"\"", "u'âu' : u'ɤ̆w', u'ấu' : u'ɤ̆w', u'ầu': u'ɤ̆w', u'ẩu' :", "S_onsets, S_nuclei, S_codas, S_tones, S_onglides, S_offglides, S_onoffglides, S_qu, S_gi #Custom", "bỏ dấu nhấn của tiếng anh \"'\" #print(vi2IPA_split(\"speech? Secondly, we", "# See Alves 2007 (SEALS XII), Vũ 1982 C_tones =", "u'ɤ', u'uờ' : u'ɤ', u'uở' : u'ɤ', u'uỡ' : u'ɤ',", "'k͡p', 'ʷɤ̆', 'ɤ̆j', 'ŋ͡m', 'kwi', 'ɤ̆w', 'ɯəj', 'ʷen', 'ʷiu', 'ʷet',", "# if you just have 'gi' and a coda... nucl", ": u'ɯə', u'ưở' : u'ɯə', u'ưỡ' : u'ɯə', u'ượ' :", "{ u'p' : u'p', u't' : u't', u'c' : u'k',", ": twʷɛ2 ua <-> uơ : uə1 ưa <-> ươ", "u'ôồ' : u'o', u'ôổ' : u'o', u'ôỗ' : u'o', u'ôộ'", "else: ons = u'w' elif nucl in offglides: cod =", "u'á' : u'a', u'à' : u'a', u'ả' : u'a', u'ã'", "#nor_tr = vi2IPA_pitrain(line) #nor = vi2IPA(line) nor = T2IPA(line) if", "'iə', 'iw', 'əʊ', 'ɑ:', 'tʃ', 'ʷe', 'ɛu', 'ɔɪ', 'ʷi', 'eɪ',", "u'c' : u'k', u'gh' : u'ɣ', u'r' : u'ʐ', u's'", "seq = convert(word, dialect, glottal, pham, cao, palatals, delimit).strip() #", "u'oe' : u'e', u'óe' : u'e', u'òe' : u'e', u'ỏe'", "u'ỉ' : 312, u'ĩ' : u'35g', u'ị' : u'21g', u'ó'", "## and re-concatenate if (tokenize and '-' in word) or", "u'ưở' : u'ɯə', u'ưỡ' : u'ɯə', u'ượ' : u'ɯə', u'yê'", "Cus_gi = { u'gi' : u'zi', u'gí': u'zi', u'gì' :", "'iw', 'əʊ', 'ɑ:', 'tʃ', 'ʷe', 'ɛu', 'ɔɪ', 'ʷi', 'eɪ', 'ɤj',", "u'uə', u'uở' : u'uə', u'uỡ' : u'uə', u'uợ' : u'uə',", "elif ipa[0]==\"[\" and ipa[-1]==\"]\": eng = eng_to_ipa.convert(tk) if eng[-1] ==", "u'ẫ' : 3, u'ậ' : 6, u'ắ' : 5, u'ằ'", "u'õi' : u'ɔj', u'ọi' : u'ɔj', u'ôi' : u'oj', u'ối'", "TK: ipa = T2IPA(tk).replace(\" \",\"_\") if ipa ==\"\": IPA+=tk+\" \"", "u'i' : u'i', u'í' : u'i', u'ì' : u'i', u'ỉ'", "u'ớ' : u'ɤ', u'ờ' : u'ɤ', u'ở' : u'ɤ', u'ỡ'", "u'oẹ' : u'ej', u'oai' : u'aj', u'oái' : u'aj', u'oài'", ": 42, u'ả' : 312, u'ã' : 312, u'ạ' :", "u'ià' : u'iə', u'iả' : u'iə', u'iã' : u'iə', u'iạ'", "dien tieng anh Etrain bưc #Neu co Mapping #Neu khong,", "u'zi', u'gị' : u'zi'} Cus_qu = {u'quy' : u'kwi', u'qúy'", "u'iə', u'uyá' : u'iə', u'uyà' : u'iə', u'uyả' : u'iə',", "u'35g', u'ẹ' : u'21g', u'ế' : 24, u'ề' : 32,", "gì khôngtontaij NIYE BoOK\",\"'\")) #check các ipa của tiếng anh", "or dialect == 's') and ton == u'21g' and cod", "u'nh' : u'n', u'ch' : u'k' } # See Alves", "'5', 'g', '4', 'n', ';', 'r', 'b', 'ɯ', 'a', 's',", "u'ỹ' : 214, u'ỵ' : 212, } S_tones_p = {", "eng_to_ipa.convert(tk) if eng[-1] == \"*\": if tk.lower().upper() == tk: #Đọc", "4, u'ỹ' : 4, u'ỵ' : 6, } C_gi =", ": u'iə', u'oo' : u'ɔ', u'óo' : u'ɔ', u'òo' :", ": u'ʷa', u'uã' : u'ʷa', u'uạ' : u'ʷa', u'uă' :", "u'õ' : 312, u'ọ' : u'21g', u'ố' : 13, u'ồ'", "#tones = { u'a' : 33, u'á' : 24, u'à'", "one-character coda cod = codas[word[l-1]] cOffset = 1 #if word[0:2]", "'u', 'o', '3', 'ɣ', '!', 'ð', 'ʧ', '6', 'ʒ', 'ʐ',", "'vw', 'ăw', 'ʈw', 'ʂw', 'aʊ', 'fw', 'ɛu', 'tʰ', 'tʃ', 'ɔɪ',", "words = [word for word in words if word!=u'_'] for", "aberrant 33 error tonelist = [tones[word[i]] for i in range(0,l)", "u'ej', u'oé' : u'ej', u'oè' : u'ej', u'oẻ' : u'ej',", ": u'iu', u'uyú' : u'iu', u'uyù' : u'iu', u'uyủ' :", "u'iəw', u'iếu' : u'iəw', u'iều' : u'iəw', u'iểu' : u'iəw',", ": u'ʷɤ̆', u'ue' : u'ʷɛ', u'ué' : u'ʷɛ', u'uè' :", "u'ʔ'+nuclei[nucl] # add a glottal stop else: # otherwise... nuc", ": 32, u'ỏ' : 214, u'õ' : 214, u'ọ' :", "u'ɲ': cod = u'ɲ'#u'ŋ' if palatals == 1: if cod", "u'uậy' : u'ɤ̆j' } S_codas = { u'p' : u'p',", "u'ụy' : u'uj', u'ơi' : u'ɤj', u'ới' : u'ɤj', u'ời'", "Cus_onsets, Cus_nuclei, Cus_codas#, N_tones , Cus_onglides, Cus_offglides, Cus_onoffglides, Cus_qu, Cus_gi]", "test=\"t\" if test in syms: print(test) else: print(\"none\") ''' ###################################################", "u'i' if nuc == u'uə': nuc = u'u' if nuc", "u'oẹn' : u'ʷen', u'oet' : u'ʷet', u'oét' : u'ʷet', u'oèt'", "u'ễ' : 214, u'ệ' : 212, u'í' : 45, u'ì'", "offglides: cod = offglides[nucl][-1] nuc = offglides[nucl][:-1] elif word in", "45, u'è' : 32, u'ẻ' : 214, u'ẽ' : 214,", "'æ', \"'\", 'h', 'o', 'k', '5', 'g', '4', 'n', ';',", "4, u'ỡ' : 4, u'ợ' : 6, u'ú' : 5,", ": u'e', u'oẹ' : u'e', u'oe' : u'e', u'óe' :", "nuc in [u'i', u'e', u'ɛ']: cod = u'c' # Velar", "u'ù' : 2, u'ủ' : 4, u'ũ' : 4, u'ụ'", "'iəw', 'k͡p', 'ʷɤ̆', 'ɤ̆j', 'ŋ͡m', 'kwi', 'ɤ̆w', 'ɯəj', 'ʷen', 'ʷiu',", ": 3, u'ị' : 6, u'ó' : 5, u'ò' :", "32, u'ả' : 312, u'ã' : u'35g', u'ạ' : u'21g',", "elif word[l-1] in codas: # if one-character coda cod =", "ipa[0]==\"[\" and ipa[-1]==\"]\": eng = eng_to_ipa.convert(tk) if eng[-1] == \"*\":", "xoã : swʷa3 ''' #Ở đây tiết kiệm chi phí", ": u'wi', u'qúy' : u'wi', u'qùy' : u'wi', u'qủy' :", "u'ɯw', u'ửu' : u'ɯw', u'ữu' : u'ɯw', u'ựu' : u'ɯw',", "u'ữ' : u'ɯ', u'ự' : u'ɯ', u'y' : u'i', u'ý'", "4, u'ễ' : 3, u'ệ' : 6, u'í' : 5,", ": ɣi2 ghích <-> gích : ɣitʃ5 ia <-> iê", "anh #print(vi2IPA_split(\"Another table was prepared to show available onsets. Onsets", "u'g' : u'ɣ', u'l' : u'l', u'm' : u'm', u'n':", "} N_onoffglides = { u'oe' : u'ej', u'oé' : u'ej',", "Cus_onoffglides, Cus_qu, Cus_gi] DICT={} #144 in total syms=['ɯəj', 'ɤ̆j', 'ʷiə',", "fix oe from e to ɛ #âm cuối: ch :", ": u'ă', u'ẳ' : u'ă', u'ẵ' : u'ă', u'ặ' :", "onsets: # if onset is 'ngh' ons = onsets[word[0:3]] oOffset", "u'ʷiu', u'uyũ' : u'ʷiu', u'uyụ' : u'ʷiu', u'uyu' : u'ʷiu',", ": u'k', u'm' : u'm', u'n' : u'n', u'ng' :", "dùng etrain cho tiếng anh #+Deal case thống nhất âm", "== \"default\": listParse=['ʷiə', 'uəj', 'iəw', 'k͡p', 'ʷɤ̆', 'ɤ̆j', 'ŋ͡m', 'kwi',", "u'uảy' : u'ăj', u'uãy' : u'ăj', u'uạy' : u'ăj', u'uây'", "42, u'ỏ' : 312, u'õ' : 312, u'ọ' : u'21g',", "cod in ['p', 't', 'k']: ton = u'45' # Modification", "== 'n' or dialect == 's') and ton == u'21g'", "onglide... nuc = onglides[nucl] # modify the nuc accordingly if", "u'uớ' : u'ɤ', u'uờ' : u'ɤ', u'uở' : u'ɤ', u'uỡ'", "u'iu', u'uyu' : u'iu', u'uýu' : u'iu', u'uỳu' : u'iu',", "trùng nhiều hơn 241->153 case #Tuy nhiên cuối cùng \"ch\"", "u'p' : u'p', u'qu' : u'kw', u'gi' : u'j', u'tr'", "== 'c': onsets, nuclei, codas, tones, onglides, offglides, onoffglides, qu,", ": u'aw', u'oeo' : u'ew', u'oéo' : u'ew', u'oèo' :", ": u'aw', u'ạo' : u'aw', u'au' : u'ăw', u'áu' :", "swʷa3 ''' #Ở đây tiết kiệm chi phí chạy máy", "u'ɤ̆j', u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j' } S_codas =", "# there's your nucleus else: nuc = nuclei[nucl] # there's", "in range(0,len(words)): word = words[i].strip() ortho += word word =", ": u'e', u'uể' : u'e', u'uễ' : u'e', u'uệ' :", ": 32, u'ủ' : 214, u'ũ' : 214, u'ụ' :", "listParse.sort(reverse = True,key=len) output=\"\" skip=0 for ic,char in enumerate(text): #print(char,skip)", "u'iə', u'iê' : u'iə', u'iế' : u'iə', u'iề' : u'iə',", "32, u'ỉ' : 312, u'ĩ' : u'35g', u'ị' : u'21g',", "in word): substrings = re.split(r'(_|-)', word) values = substrings[::2] delimiters", "compound = u'' ortho = u'' words = line.split() ##", "'c', 'j', 'x', 'ʈ', ',', '4', 'ʊ', 's', 'ŋ', 'a',", ": u'uə', } C_offglides = { u'ai' : u'aj', u'ái'", "13, u'ỳ' : 42, u'ỷ' : 312, u'ỹ' : 312,", "u'iɛ', u'yế' : u'iɛ', u'yề' : u'iɛ', u'yể' : u'iɛ',", "'b', 'ɯ', 'a', 's', 'ʐ', 'η', 'ŋ', 'ɒ', 'ʂ', '_',", "1: if cod == u'k' and nuc in [u'i', u'e',", "u'e', u'uễ' : u'e', u'uệ' : u'e', u'uơ' : u'ɤ',", ": u'o', u'ôồ' : u'o', u'ôổ' : u'o', u'ôỗ' :", ": u'ej', u'oai' : u'aj', u'oái' : u'aj', u'oài' :", "u'ử' : 312, u'ữ' : 312, u'ự' : u'21g', u'ý'", "u'ò' : 42, u'ỏ' : 312, u'õ' : 312, u'ọ'", "u'nh' : u'n', u'ch' : u't' } S_tones = {", "u'uẵ' : u'ă', u'uặ' : u'ă', u'uâ' : u'ɤ̆', u'uấ'", "['p', 't', 'k']: #if ton == u'21\\u02C0' and cod in", "#Case need to be deal: # NIYE BoOK #print(len(getSymbol())) #print(getSymbol())", ": u'ɤ̆', u'uẫ' : u'ɤ̆', u'uậ' : u'ɤ̆', u'ue' :", "used to use \\u02C0 for raised glottal instead of g", "print(\"Text normalize: \",TN) TK= word_tokenize(TN) print(\"Vietnamese Tokenize: \",TK) IPA=\"\" for", "of domain word: \" ,ipa) else: IPA+=ipa+\" \" IPA=re.sub(' +',", "['i','í','ì','ĩ','ỉ','ị']): continue cout_same+=1 print(line+ \" <-> \" + lin2 +\"\\t\\t:\\t\\t\"+T2IPA(line))", "onoffglides, qu, gi = C_onsets, C_nuclei, C_codas, C_tones, C_onglides, C_offglides,", ",ipa) else: IPA+=ipa+\" \" IPA=re.sub(' +', ' ', IPA) print(\"IPA", "u'h', u'p' : u'p', u'qu' : u'kw', u'gi' : u'z',", "<-> thuở : tʰuə4 tòe <-> toè : twʷɛ2 ua", "13, u'è' : 42, u'ẻ' : 312, u'ẽ' : 312,", "tones_p = Cus_tones_p tones = tones_p ons = '' nuc", "of python complain about \"from x import *\" syntax if", "u'oj', u'ui' : u'uj', u'úi' : u'uj', u'ùi' : u'uj',", ": u'ɛu', u'ều' : u'ɛu', u'ểu' : u'ɛu', u'ễu': u'ɛu',", ": u'ɤ', u'ở' : u'ɤ', u'ỡ' : u'ɤ', u'ợ' :", "= T2IPA(tk).replace(\" \",\"_\") if ipa ==\"\": IPA+=tk+\" \" elif ipa[0]==\"[\"", ": u'uəj', u'uỗi' : u'uəj', u'uội' : u'uəj', u'ươi' :", "u'aw', u'au' : u'ăw', u'áu' : u'ăw', u'àu' : u'ăw',", "u'e' : u'ɛ', u'é' : u'ɛ', u'è' : u'ɛ', u'ẻ'", "Onsets are splitted into 3 types. Type 1 are onsets", "has one letter \",\"/\")) #Lọc bỏ dấu nhấn của tiếng", "u'ɯəw', u'ườu' : u'ɯəw', u'ưởu' : u'ɯəw', 'ưỡu' : u'ɯəw',", ": u'iɛ', u'yế' : u'iɛ', u'yề' : u'iɛ', u'yể' :", ": u'21g', } # used to use \\u02C0 for raised", ": u'ʷi', u'uya' : u'ʷiə', u'uyá' : u'ʷiə', u'uyà' :", "u'ăw', u'ạu' : u'ăw', u'ây' : u'ɤ̆j', u'ấy' : u'ɤ̆j',", "u'u', u'ú' : u'u', u'ù' : u'u', u'ủ' : u'u',", "u'iəw', u'iệu' : u'iəw', u'yêu' : u'iəw', u'yếu' : u'iəw',", "u'ɛu', u'ễu': u'ɛu', u'ệu' : u'ɛu', u'ia' : u'iə', u'ía'", "TK[:iuv] + TK[iuv+1 :] for tok in reversed(token_under): TK.insert(iuv, tok)", ": u'ɯw', u'ửu' : u'ɯw', u'ữu' : u'ɯw', u'ựu' :", "tones_p = N_tones_p if dialect == 'c': tones_p = C_tones_p", "[convert(x, dialect, glottal, pham, cao, palatals, delimit).strip() for x in", "u'ỗ' : 4, u'ộ' : 6, u'ớ' : 5, u'ờ'", "'ɔj', 'i:', 't∫', 'ɪə', 'ʷă', 'ɜ:', 'tʰ', 'dʒ', 'ew', 'ʊə',", "Hoàng 1985: 181) if dialect == 's': if cod in", "'ɛj', 'ɔj', 'i:', 't∫', 'ɪə', 'ʷă', 'ɜ:', 'tʰ', 'dʒ', 'ew',", "u'ŋ', u'ph' : u'f', u'v' : u'j', u'x' : u's',", "\",IPA) print(\"------------------------------------------------------\") return IPA def checkDict(): cout=0 trung=0 List_token=[] List_pair", "((dialect == 'n' and ton == u'24') or (dialect ==", "tiếng anh #+Deal case thống nhất âm vực phoneme ->", "u'aj', u'oái' : u'aj', u'oài' : u'aj', u'oải' : u'aj',", "u'ứi' : u'ɯj', u'ừi' : u'ɯj', u'ửi' : u'ɯj', u'ữi'", "u'iəw', u'yêu' : u'iəw', u'yếu' : u'iəw', u'yều' : u'iəw',", "import OptionParser from string import punctuation def trans(word, dialect, glottal,", ": u'ʷɤ', u'uớ' : u'ʷɤ', u'uờ' : u'ʷɤ', u'uở' :", "u'ɯəw' } #Các âm vòng ở đây i chang không", "u'oẻt' : u'ʷet', u'oẽt' : u'ʷet', u'oẹt' : u'ʷet' }", ": u'ɯəj', u'ưỡi' : u'ɯəj', u'ượi' : u'ɯəj', u'ươu' :", "u'uj', #thay để hạn chế trùng âm u'uy' : u'ʷi',", "u'yệ' : u'iɛ', u'uơ' : u'uə', u'uở' : u'uə', u'uờ':", ": u'et', u'oẽt' : u'et', u'oẹt' : u'et' } S_onoffglides", "'t', 'k']: ton = u'6b' # labialized allophony (added 17.09.08)", "u'uâ' : u'ɤ̆', u'uấ' : u'ɤ̆', u'uầ' : u'ɤ̆', u'uẩ'", ": u'j' } S_nuclei = { u'a' : u'a', u'á'", "214, u'ị' : 212, u'ó' : 45, u'ò' : 32,", "option glottal = 0 pham = 0 cao = 0", "\",cout) print(\"Number of token in the same mapping:\",trung) List_token =", "= [tones[word[i]] for i in range(0,l) if word[i] in tones]", "u'gĩ' : u'ji', u'gị' : u'ji' } C_qu = {u'quy'", ": u'ɤj', u'ợi' : u'ɤj', u'ưi' : u'ɯj', u'ứi' :", "u'uə', u'uỡ' : u'uə', u'uợ' : u'uə', } S_offglides =", "u'ɯə', u'ưỡ' : u'ɯə', u'ượ' : u'ɯə', u'yê' : u'iɛ',", "u'ẫ' : u'35g', u'ậ' : u'21g', u'ắ' : 24, u'ằ'", "sắc in closed syllables (Northern and Central only) if ((dialect", ": u'21g', u'ý' : 13, u'ỳ' : 42, u'ỷ' :", "32, u'ỉ' : 214, u'ĩ' : 214, u'ị' : 212,", "từng chữ letter2sound=\"\" for char in tk: CHAR = str(char).lower()", ": 4, u'ẵ' : 3, u'ặ' : 6, u'é' :", "for i in range(0,l) if word[i] in tones] if tonelist:", "ɣi2 ghích <-> gích : ɣitʃ5 ia <-> iê :", "u'eo', u'èo' : u'eo', u'ẻo' : u'eo', u'ẽo': u'eo', u'ẹo'", ": u'ɛ', u'uê' : u'e', u'uế' : u'e', u'uề' :", "u'ʷă', u'uặ' : u'ʷă', u'uâ' : u'ʷɤ̆', u'uấ' : u'ʷɤ̆',", "[u'u', u'o', u'ɔ']: if cod == u'ŋ': cod = u'ŋ͡m'", "#Neu khong, check co nguyen am #Neu co de nguyen", "u'ệ' : u'21g', # u'i' : 33, u'í' : 24,", "IPA+=delimit+tk+delimit+\" \" elif ipa[0]==\"[\" and ipa[-1]==\"]\": eng = eng_to_ipa.convert(tk) if", "u'ʷă', u'uâ' : u'ʷɤ̆', u'uấ' : u'ʷɤ̆', u'uầ' : u'ʷɤ̆',", "u'ầ' : 2, u'ẩ' : 4, u'ẫ' : 3, u'ậ'", "u'ợi' : u'ɤj', u'ưi' : u'ɯj', u'ứi' : u'ɯj', u'ừi'", "= u'ɯ' # Tones # Modified 20 Sep 2008 to", "u'ố' : 45, u'ồ' : 32, u'ổ' : 214, u'ỗ'", "u'zi', u'gí': u'zi', u'gì' : u'zi', u'gì' : u'zi', u'gĩ'", ": 24, u'ồ' : 32, u'ổ' : 312, u'ỗ' :", "== 'quy', 'qúy',... ons = qu[word][:-1] nuc = qu[word][-1] else:", "5, u'ầ' : 2, u'ẩ' : 4, u'ẫ' : 3,", "and ton == u'24') or (dialect == 'c' and ton", "u'uỷu' : u'ʷiu', u'uỹu' : u'ʷiu', u'uỵu' : u'ʷiu', u'oen'", "u'ué' : u'ʷɛ', u'uè' : u'ʷɛ', u'uẻ' : u'ʷɛ', u'uẽ'", "u'21g', # u'u' : 33, u'ú' : 24, u'ù' :", "có w ở trước => Try to add ʷ Cus_onglides", "{ u'á' : 45, u'à' : 32, u'ả' : 214,", "k for c , t for t, tʃ for ch", "C_tones_p = { u'á' : 5, u'à' : 2, u'ả'", "content: if T2IPA(line) in Pair: lin2 =Pair[T2IPA(line)] if line !=", ": u'ʷa', u'uá' : u'ʷa', u'uà' : u'ʷa', u'uả' :", ": u'p', u'qu' : u'w', u'gi' : u'j', u'tr' :", "u'ạ' : u'21g', # u'â' : 33, u'ấ' : 24,", "u'ɛj', u'oẻ' : u'ɛj', u'oẽ' : u'ɛj', u'oẹ' : u'ɛj',", "for ic,char in enumerate(text): #print(char,skip) check = 0 if skip>0:", "not in list if str(char) in [\"ˈ\",\"ˌ\",\"*\"]: continue print(\"this is", "6, u'é' : 5, u'è' : 2, u'ẻ' : 4,", "cao: if dialect == 'n': tones_p = N_tones_p if dialect", "C_qu, C_gi elif dialect == 's': onsets, nuclei, codas, tones,", "custom # Các trường hợp có cách bỏ dấu khác", "am #Neu co de nguyen #Neu khong danh van print(\"", "không có w ở trước như: \"oa,ua,a\" đều như một", "else: seq = delimit+delimit.join(filter(None, (ons, nuc, cod, ton)))+delimit except (TypeError):", "2, u'ỷ' : 4, u'ỹ' : 4, u'ỵ' : 6,", ": u'uə', u'uỡ' : u'uə', u'uợ' : u'uə', } Cus_offglides", "{} for lt in List_pair: Pair[T2IPA(lt)] = lt cout_same=0 with", "True,key=len) return symbols def vi2IPA_pitrain(text): epi = epitran.Epitran('vie-Latn') r=epi.transliterate(text) return", "u'oj', u'ối' : u'oj', u'ồi' : u'oj', u'ổi' : u'oj',", "u'ɤ', u'uở' : u'ɤ', u'uỡ' : u'ɤ', u'uợ' : u'ɤ',", ": u'ʷa', u'uạ' : u'ʷa', u'uă' : u'ʷă', u'uắ' :", "u'gi' : u'j' } C_nuclei = { u'a' : u'a',", "u'ậ' : u'ɤ̆', u'ă' : u'ă', u'ắ' : u'ă', u'ằ'", "otherwise... nuc = nuclei[nucl] # there's your nucleus else: nuc", "'ŋ', 'a', 'ʃ', '?', 'r', ':', 'η', 'f', ';', 'e',", "5, u'à' : 2, u'ả' : 4, u'ã' : 4,", "42, u'ỷ' : 312, u'ỹ' : 312, u'ỵ' : u'21g',", "'ɯ', 'a', 's', 'ʐ', 'η', 'ŋ', 'ɒ', 'ʂ', '_', 'f',", ": u'ɤ', u'uợ' : u'ɤ', u'uy' : u'i', u'uý' :", ": u'ʷe', u'uế' : u'ʷe', u'uề' : u'ʷe', u'uể' :", "( ) Have been removed due to none sound modifi", "trường hợp dẫn đến trùng âm là: # Phương ngữ", "u'uj', u'ụy' : u'uj', u'ơi' : u'ɤj', u'ới' : u'ɤj',", "u'wi', u'qùy' : u'wi', u'qủy' : u'wi', u'qũy' : u'wi',", "ons: # if there is an onset... ons = ons+u'w'", "(ons, nuc, cod, ton) def convert(word, dialect, glottal, pham, cao,", "u'ɛ']: if cod == u'ɲ': cod = u'ɲ'#u'ŋ' if palatals", "u'y' : 33, u'ý' : 24, u'ỳ' : 32, u'ỷ'", "'z', 'v', 'g', 'ă', '_', 'æ', 'ɤ', '2', 'ʤ', 'i',", "u'e', u'uơ' : u'ɤ', u'uớ' : u'ɤ', u'uờ' : u'ɤ',", ": u'35g', u'ạ' : u'21g', # u'â' : 33, u'ấ'", "2, u'ở' : 4, u'ỡ' : 3, u'ợ' : 6,", "ugly, but newer versions of python complain about \"from x", "u'uớ' : u'ʷɤ', u'uờ' : u'ʷɤ', u'uở' : u'ʷɤ', u'uỡ'", "u'úa' : u'uə', u'ùa' : u'uə', u'ủa' : u'uə', u'ũa'", "'ʂ', 'ɔ', 'ɛ', 'k', 'm', '5', ' ', 'c', 'j',", "if word[0:3] in onsets: # if onset is 'ngh' ons", ": u'ʷet', u'oẹt' : u'ʷet' } Cus_onoffglides = { u'oe'", ": u'j', u'tr' : u'ʈ', u'k' : u'k', u'c' :", ": u'ew', u'oèo' : u'ew', u'oẻo' : u'ew', u'oẽo' :", "u'ữa' : u'ɯə', u'ựa' : u'ɯə', u'ươ' : u'ɯə', u'ướ'", ": u'ɤ̆j', u'uậy' : u'ɤ̆j' } C_codas = { u'p'", "u'ɛ', u'è' : u'ɛ', u'ẻ' : u'ɛ', u'ẽ' : u'ɛ',", "'mw', 'ɑ:', 'hw', 'ɔj', 'uj', 'lw', 'ɪə', 'ăj', 'u:', 'aw',", "nuclei[nucl] # there's your nucleus else: nuc = nuclei[nucl] #", "are splitted into 3 types. Type 1 are onsets which", "u'ɣ', u'r' : u'ʐ', u's' : u'ʂ', u'gi': u'j'} Cus_nuclei", "u'áu' : u'ăw', u'àu' : u'ăw', u'ảu' : u'ăw', u'ãu'", ": u'zi', u'gí': u'zi', u'gì' : u'zi', u'gì' : u'zi',", "u'ở' : 4, u'ỡ' : 3, u'ợ' : 6, u'ú'", ": u'21g', # u'o' : 33, u'ó' : 24, u'ò'", "text if line =='\\n': return \"\" else: compound = u''", ": 42, u'ể' : 312, u'ễ' : 312, u'ệ' :", "u'21g', u'ấ' : 24, u'ầ' : 32, u'ẩ' : 312,", "{ u'á' : 5, u'à' : 2, u'ả' : 4,", "312, u'õ' : 312, u'ọ' : u'21g', u'ố' : 13,", "in reversed(token_under): TK.insert(iuv, tok) IPA=\"\" for tk in TK: ipa", "ghì <-> gì : ɣi2 ghích <-> gích : ɣitʃ5", "custom k vì nó giảm trùng nhiều hơn 241->153 case", "u'gì' : u'zi', u'gì' : u'zi', u'gĩ' : u'zi', u'gị'", "u'ỳ' : 2, u'ỷ' : 4, u'ỹ' : 4, u'ỵ'", "u'ổô' : u'o', u'ỗô' : u'o', u'ộô' : u'o', u'ôô'", "u'e', u'uể' : u'e', u'uễ' : u'e', u'uệ' : u'e',", "range(0,len(words)): word = words[i].strip() ortho += word word = word.strip(punctuation).lower()", "u'oè' : u'ʷɛ', u'oẻ' : u'ʷɛ', u'oẽ' : u'ʷɛ', u'oẹ'", ": u'35g', u'ỵ' : u'21g', } # used to use", "nguyen am #Neu co de nguyen #Neu khong danh van", "u'ɛ' if cod == u'ɲ' and nuc == u'a': nuc", "'ɯw', 'ɛj', 'ɔj', 'i:', 't∫', 'ɪə', 'ʷă', 'ɜ:', 'tʰ', 'dʒ',", "chạy máy không normal phoneme về cường độ âm sắc", ": u'ew', u'uai' : u'aj', u'uái' : u'aj', u'uài' :", "\" else: letter2sound+=char+\" \" IPA+=T2IPA_split(letter2sound,delimit)+\" \" else: #Giữ nguyên IPA+=Parsing(\"default\",tk.lower(),delimit)+\"", "\"*\": if tk.lower().upper() == tk: #Đọc tiếng anh từng chữ", "tones] if tonelist: ton = str(tonelist[len(tonelist)-1]) else: if not (pham", "labialized allophony (added 17.09.08) if nuc in [u'u', u'o', u'ɔ']:", "S_onglides, S_offglides, S_onoffglides, S_qu, S_gi, C_onsets, C_nuclei, C_codas#, C_tones ,", ": u'wi', u'qụy' : u'wi'} ############################################ #south.py #coding: utf-8 S_onsets", "312, u'ũ' : u'35g', u'ụ' : u'21g', u'ứ' : 24,", "312, u'ợ' : u'21g', u'ú' : 13, u'ù' : 42,", "nuclei, codas, tones, onglides, offglides, onoffglides, qu, gi = N_onsets,", "trước như: \"oa,ua,a\" đều như một > must consider (nhưng", ": 312, u'ễ' : u'35g', u'ệ' : u'21g', # u'i'", "IPA+=Parsing(\"default\",eng,delimit)+\" \" #Check tu dien tieng anh Etrain bưc #Neu", "u'ỷ' : 312, u'ỹ' : u'35g', u'ỵ' : u'21g', #", "u'uyá' : u'ʷiə', u'uyà' : u'ʷiə', u'uyả' : u'ʷiə', u'uyã'", "substring ## and re-concatenate if (tokenize and '-' in word)", "cao, palatals, delimit).strip() for x in values] seq = ''.join(v+d", "u'uyể' : u'ʷiə', u'uyễ' : u'ʷiə', u'uyệ' : u'ʷiə', u'uyu'", "gi = N_onsets, N_nuclei, N_codas, N_tones, N_onglides, N_offglides, N_onoffglides, N_qu,", ": u'iəw', u'yếu' : u'iəw', u'yều' : u'iəw', u'yểu' :", "'ŋw', 'bw', 'vw', 'dw', 'eo', 'ʈw', 'mw', 'zw', 'fw', 'tw',", "Special symbols = list(set(symbols)) symbols.sort(reverse = True,key=len) return symbols def", "= str('35') else: ton = str('33') else: ton = str('1')", ": 2, u'ẩ' : 4, u'ẫ' : 4, u'ậ' :", "rid of single hyphens or underscores words = [word for", ": k theo bắc : t theo nam -> custom", ", t for t, tʃ for ch #Thay offglide: úy", "if cod == u'k' and cOffset == 2: nuc =", "{ u'oa' : u'a', u'oá' : u'a', u'oà' : u'a',", "u'iəw', u'yều' : u'iəw', u'yểu' : u'iəw', u'yễu' : u'iəw',", "u'ɲ', u'ch' : u'tʃ' } Cus_tones_p = { u'á' :", "u'uệ' : u'ʷe', u'uơ' : u'ʷɤ', u'uớ' : u'ʷɤ', u'uờ'", "u'ʷiə', u'uyạ' : u'ʷiə', u'uyê' : u'ʷiə', u'uyế' : u'ʷiə',", "can not convert: \",cout) print(\"Number of token in the same", "#Step #Vinorm #Underthesea #For each Convert to phoneme #Nếu không", "u'ượi' : u'ɯəj', u'ươu' : u'ɯəw', u'ướu' : u'ɯəw', u'ườu'", "seq return compound EN={\"a\":\"ây\",\"ă\":\"á\",\"â\":\"ớ\",\"b\":\"bi\",\"c\":\"si\",\"d\":\"đi\",\"đ\":\"đê\",\"e\":\"i\",\"ê\":\"ê\",\"f\":\"ép\",\"g\":\"giy\",\"h\":\"ếch\",\"i\":\"ai\",\"j\":\"giây\",\"k\":\"cây\",\"l\":\"eo\",\"m\":\"em\",\"n\":\"en\",\"o\":\"âu\",\"ô\":\"ô\",\"ơ\":\"ơ\",\"p\":\"pi\",\"q\":\"kiu\",\"r\":\"a\",\"s\":\"ét\",\"t\":\"ti\",\"u\":\"diu\",\"ư\":\"ư\",\"v\":\"vi\",\"w\":\"đắp liu\",\"x\":\"ít\",\"y\":\"quai\",\"z\":\"giét\"} import re def vi2IPA_split(texts,delimit): content=[]", ": u'oj', u'ỗi' : u'oj', u'ội' : u'oj', u'ui' :", "86; Hoàng 1985: 181) if dialect == 's': if cod", "đọc từng kí tự #Now #+Thêm kí tự IPA của", ": u'21g', # u'i' : 33, u'í' : 24, u'ì'", "each substring ## and re-concatenate if (tokenize and '-' in", ": u'ăj', u'oày' : u'ăj', u'oảy' : u'ăj', u'oãy' :", "u'ộ' : 6, u'ớ' : 5, u'ờ' : 2, u'ở'", "u'ả' : 312, u'ã' : u'35g', u'ạ' : u'21g', #", "if nucl in nuclei: if oOffset == 0: if glottal", "214, u'ộ' : 212, u'ớ' : 45, u'ờ' : 32,", "u'ng' : u'ŋ', u'ph' : u'f', u'v' : u'v', u'x'", "return \"\" else: compound = u'' ortho = u'' words", "0 tokenize = 0 delimit = '' dialect='n' #\"c\"\"s\" tone_type=0", "khỏe <-> khoẻ : xwʷɛ4 khua <-> khuơ : xuə1", "32, u'ỷ' : 312, u'ỹ' : u'35g', u'ỵ' : u'21g',", "'ŋ͡m', 'kwi', 'ɤ̆w', 'ɯəj', 'ʷen', 'ʷiu', 'ʷet', 'ɯəw', 'ʷɛ', 'ʷɤ',", "u'ɔ', u'ọ' : u'ɔ', u'ô' : u'o', u'ố' : u'o',", "=\"\" for text in tess: print(\"------------------------------------------------------\") TN= TTSnorm(text) print(\"------------------------------------------------------\") print(\"Text", "char in tk: CHAR = str(char).lower() if CHAR in list(EN.keys()):", "'ɔɪ', 'ʷi', 'eɪ', 'ɤj', 'ɯw', 'ɛj', 'ɔj', 'i:', 't∫', 'ɪə',", "'ăj', 'u:', 'aw', 'ɛj', 'iw', 'aj', 'ɜ:', 'kw', 'nw', 't∫',", ": u'i', u'ì' : u'i', u'ỉ' : u'i', u'ĩ' :", "u'ử' : u'ɯ', u'ữ' : u'ɯ', u'ự' : u'ɯ', u'y'", "tonelist = [tones[word[i]] for i in range(0,l) if word[i] in", "u'uyế' : u'ʷiə', u'uyề' : u'ʷiə', u'uyể' : u'ʷiə', u'uyễ'", "''' check_sym=\"ɯəjɤ̆jʷiəɤ̆wɯəwʷetiəwuəjʷentʰwʷɤ̆ʷiukwiŋ͡mk͡pcwjwuəeəbwojʷivwăwʈwʂwaʊfwɛutʰtʃɔɪxwʷɤɤ̆ŋwʊəziʷădweɪaɪewiəɣwzwɯjʷɛɯwɤjɔ:əʊʷamwɑ:hwɔjujlwɪəăju:awɛjiwajɜ:kwnwt∫ɲweoswtwʐwiɛʷei:ɯədʒɲθʌlw1ɪɯd∫pəuo3ɣ!ðʧ6ʒʐzvgă_æɤ2ʤi.ɒbhnʂɔɛkm5cjxʈ,4ʊsŋaʃ?r:ηf;et'\" for ine,res in enumerate(Results): if res not in", "paper, we investigate work! One is that e language to", "for each substring ## and re-concatenate if (tokenize and '-'", "u'ạ' : u'a', u'â' : u'ɤ̆', u'ấ' : u'ɤ̆', u'ầ'", ": 312, u'ạ' : u'21g', u'ấ' : 13, u'ầ' :", ": 13, u'à' : 42, u'ả' : 312, u'ã' :", "u'aj', u'ại' : u'aj', u'ay' : u'ăj', u'áy' : u'ăj',", "N_tones_p = { u'á' : 5, u'à' : 2, u'ả'", ": 33, u'á' : 24, u'à' : 32, u'ả' :", "u'ù' : 42, u'ủ' : 312, u'ũ' : 312, u'ụ'", "'ɯə', 'dʒ', 'ɲ', 'θ', 'ʌ', 'l', 'w', '1', 'ɪ', 'ɯ',", ": u'a', u'á' : u'a', u'à' : u'a', u'ả' :", ": u'ɯəw' } S_onglides = { u'oa' : u'a', u'oá'", ": 32, u'ỉ' : 214, u'ĩ' : 214, u'ị' :", "'i:', 'ɯə', 'dʒ', 'ɲ', 'θ', 'ʌ', 'l', 'w', '1', 'ɪ',", "..................Out of domain word: \" ,ipa) else: IPA+=ipa+\" \" IPA=re.sub(delimit+'+',", "u'uj', u'ơi' : u'ɤj', u'ới' : u'ɤj', u'ời' : u'ɤj',", ": u'uəj', u'uội' : u'uəj', u'ươi' : u'ɯəj', u'ưới' :", "u'ứ' : u'ɯ', u'ừ' : u'ɯ', u'ử' : u'ɯ', u'ữ'", ": u'b', u't' : u't', u'th' : u'tʰ', u'đ' :", "\" IPA+=T2IPA_split(letter2sound,delimit)+\" \" else: #Giữ nguyên IPA+=Parsing(\"default\",tk.lower(),delimit)+\" \" else: IPA+=Parsing(\"default\",eng,delimit)+\"", "== u'uə': nuc = u'u' if nuc == u'ɯə': nuc", "'j', ':', 't', 'ʒ', 'ə', 'ʌ', 'm', '!', '∫', 'ð',", "if nuc == u'uə': nuc = u'u' if nuc ==", "312, u'ẹ' : u'21g', u'ế' : 13, u'ề' : 42,", "= gi[word][0] nuc = gi[word][1] elif word in qu: #", "u'uè' : u'ʷɛ', u'uẻ' : u'ʷɛ', u'uẽ' : u'ʷɛ', u'uẹ'", "'ʷiu', 'ʷet', 'ɯəw', 'ʷɛ', 'ʷɤ', 'ɯj', 'oj', 'ăw', 'zi', 'kw',", "{ u'gi' : u'ji', u'gí': u'ji', u'gì' : u'ji', u'gì'", "u'uổ' : u'uə', u'uỗ' : u'uə', u'uộ' : u'uə', u'ưa'", ": u'iɛ', u'yề' : u'iɛ', u'yể' : u'iɛ', u'yễ' :", "if cod == u'ŋ': cod = u'ŋ͡m' if cod ==", "in closed syllables (Northern and Central only) if ((dialect ==", "u'iəw', u'yệu' : u'iəw', u'uôi' : u'uəj', u'uối' : u'uəj',", "u'ũ' : u'u', u'ụ' : u'u', u'ư' : u'ɯ', u'ứ'", "Cus_tones_p = { u'á' : 5, u'à' : 2, u'ả'", "dialect) if nuc not in [u'i', u'e', u'ɛ']: if cod", "content=f.read().splitlines() for line in content: #nor_tr = vi2IPA_pitrain(line) #nor =", "u'uə', } N_offglides = { u'ai' : u'aj', u'ái' :", ", N_onglides, N_offglides, N_onoffglides, N_qu, N_gi, Cus_onsets, Cus_nuclei, Cus_codas#, N_tones", "between N C S Cus_onsets = { u'b' : u'b',", "gi[word][1] elif word in qu: # if word == 'quy',", "u'ji' } C_qu = {u'quy' : u'wi', u'qúy' : u'wi',", "S_onoffglides, S_qu, S_gi #Custom onsets, nuclei, codas, onglides, offglides, onoffglides,", "u'wi'} ################################################3 import sys, codecs, re from io import StringIO", "} C_codas = { u'p' : u'p', u't' : u'k',", ": u'e', u'ỏe' : u'e', u'õe' : u'e', u'ọe' :", ": u'ɔ', u'oọ' : u'ɔ', u'ôô' : u'o', u'ốô' :", "cod == u'ŋ': cod = u'n' # There is also", "tok in reversed(token_under): TK.insert(iuv, tok) IPA=\"\" for tk in TK:", "word_tokenize(TN) print(\"Vietnamese Tokenize: \",TK) IPA=\"\" for tk in TK: ipa", "3, u'ộ' : 6, u'ớ' : 5, u'ờ' : 2,", "a labiovelar onset elif nucl in onglides and ons ==", "= u'['+word+u']' else: seq = delimit+delimit.join(filter(None, (ons, nuc, cod, ton)))+delimit", ": u'ʷiə', u'uyề' : u'ʷiə', u'uyể' : u'ʷiə', u'uyễ' :", "4, u'ụ' : 6, u'ứ' : 5, u'ừ' : 2,", "u'v', u'x' : u's', u'd' : u'z', u'h' : u'h',", "# North # #coding: utf-8 N_onsets = { u'b' :", "use \\u02C0 for raised glottal instead of g C_tones_p =", "u'oa' : u'a', u'oá' : u'a', u'oà' : u'a', u'oả'", "u'óeo' : u'ew', u'òeo' : u'ew', u'ỏeo' : u'ew', u'õeo'", ": 214, u'ỗ' : 214, u'ộ' : 212, u'ớ' :", "u'oèo' : u'ew', u'oẻo' : u'ew', u'oẽo' : u'ew', u'oẹo'", "word!=u'_'] for i in range(0,len(words)): word = words[i].strip() ortho +=", "u'uái' : u'aj', u'uài' : u'aj', u'uải' : u'aj', u'uãi'", "'m', '5', ' ', 'c', 'j', 'x', 'ʈ', ',', '4',", "'ʊə', 'ɯə', 'aw', '3', 'θ', 'v', 'ʊ', 'ʤ', 'ɔ', '1',", "encoding=\"utf-8\") as f: content=f.read().splitlines() for line in content: #nor_tr =", ": 214, u'ự' : 212, u'ý' : 45, u'ỳ' :", "coda... if word[0:2] in gi and cod and len(word) ==", "cOffset == 2: nuc = u'ɛ' if cod == u'ɲ'", "S_gi, C_onsets, C_nuclei, C_codas#, C_tones , C_onglides, C_offglides, C_onoffglides, C_qu,", "u'21g', # u'ơ' : 33, u'ớ' : 24, u'ờ' :", "214, u'ẽ' : 214, u'ẹ' : 212, u'ế' : 45,", ": u'35g', u'ụ' : u'21g', u'ứ' : 24, u'ừ' :", "u'ngh': u'ŋ', u'nh' : u'ɲ', u'ng' : u'ŋ', u'ph' :", "seq = seq+u' ' compound = compound + seq return", "u'ŋ', u'nh' : u'ɲ', u'ch' : u'tʃ' } Cus_tones_p =", ": u'ʷiu', u'oen' : u'ʷen', u'oén' : u'ʷen', u'oèn' :", "u'ỷ' : 4, u'ỹ' : 3, u'ỵ' : 6, }", ": u'21g', u'é' : 24, u'è' : 32, u'ẻ' :", "u'ʷɛ', u'uê' : u'ʷe', u'uế' : u'ʷe', u'uề' : u'ʷe',", "uê -> fix oe from e to ɛ #âm cuối:", ": u'z', u's' : u's', u'gi': u'z'} N_nuclei = {", ": u'o', u'ộô' : u'o', u'ôô' : u'o', u'ôố' :", "-> custom k vì nó giảm trùng nhiều hơn 241->153", ": u'ʷă', u'uằ' : u'ʷă', u'uẳ' : u'ʷă', u'uẵ' :", ": u'ɤ̆', u'ấ' : u'ɤ̆', u'ầ' : u'ɤ̆', u'ẩ' :", "1965: 86; Hoàng 1985: 181) if dialect == 's': if", "\"uỹ\", \"ạ\",\"ặ\",\"ậ\",\"ẹ\",\"ệ\",\"ị\",\"ọ\",\"ộ\",\"ợ\",\"ụ\",\"ự\",\"ỵ\",\"iệ\",\"ọa\",\"oặ\",\"ọe\",\"oọ\",\"uậ\",\"uệ\",\"uệ\",\"ượ\",\"ụy\",\"ượ\",\"uyệ\",\"yệ\", #dot \"oạ\", \"oẹ\",\"ọo\", \"uỵ\"] Onset=[\"b\",\"d\",\"h\",\"l\",\"m\",\"n\",\"p\",\"r\",\"s\",\"t\",\"v\",\"x\",\"đ\",\"p\", \"tr\", \"th\", \"ch\",", "\"c\" \"t\" không phân âm được => ý tưởng mượn", "is also this reverse fronting, see Thompson 1965:94 ff. elif", ": u'uj', u'ũy' : u'uj', u'ụy' : u'uj', u'ơi' :", "} C_qu = {u'quy' : u'wi', u'qúy' : u'wi', u'qùy'", "Etrain bưc #Neu co Mapping #Neu khong, check co nguyen", "u'ụ' : u'21g', u'ứ' : 13, u'ừ' : 42, u'ử'", ": 4, u'õ' : 4, u'ọ' : 6, u'ố' :", "u'ẻ' : 312, u'ẽ' : u'35g', u'ẹ' : u'21g', #", ": u'aw', u'oáo' : u'aw', u'oào' : u'aw', u'oảo' :", "otherwise... nuc = nuclei[nucl] # there's your nucleus elif nucl", ": u'21g', u'ú' : 24, u'ù' : 32, u'ủ' :", "cao, palatals, delimit).strip() # concatenate if len(words) >= 2: ortho", "T2IPA(line) if nor in List_token: print(line + \" -> \"+nor)", "u'ậ' : u'21g', u'ắ' : 13, u'ằ' : 42, u'ẳ'", "N_qu, N_gi elif dialect == 'c': onsets, nuclei, codas, tones,", "= '' cod = '' ton = 0 oOffset =", "u'ở' : 4, u'ỡ' : 4, u'ợ' : 6, u'ú'", "and a coda... if word[0:2] in gi and cod and", ": u'ɤ̆j', u'uậy' : u'ɤ̆j' } N_codas = { u'p'", "u'uẩ' : u'ɤ̆', u'uẫ' : u'ɤ̆', u'uậ' : u'ɤ̆', u'ue'", ": u'wi'} ################################################3 import sys, codecs, re from io import", "skip=0 for ic,char in enumerate(text): #print(char,skip) check = 0 if", "in content: if T2IPA(line) in Pair: lin2 =Pair[T2IPA(line)] if line", "print(\"Text normalize: \",TN) TK= word_tokenize(TN) print(\"Vietnamese Tokenize: \",TK) for iuv,under_valid", "Cus_nuclei = { u'a' : u'a', u'á' : u'a', u'à'", "none sound modifi = [\"k͡p\",\"ŋ͡m\"] symbols = list_phoneme + space+word_pad", "u'uj', u'ũi' : u'uj', u'ụi' : u'uj', #u'uy' : u'uj',", "24, u'ò' : 32, u'ỏ' : 312, u'õ' : u'35g',", "ch #Thay offglide: úy -> wi để phân biệt với", "u'ʷă', u'oẵ' : u'ʷă', u'oặ' : u'ʷă', u'oe' : u'ʷɛ',", "ons+u'w' # labialize it, but... else: # if there is", "u'ɯə', u'ướ' : u'ɯə', u'ườ' : u'ɯə', u'ưở' : u'ɯə',", "u'gĩ' : u'zi', u'gị' : u'zi'} N_qu = {u'quy' :", "check =1 skip=len(l)-1 break if check == 0: #Case symbol", "312, u'ẽ' : 312, u'ẹ' : u'21g', u'ế' : 13,", ": u'ew', u'oẻo' : u'ew', u'oẽo' : u'ew', u'oẹo' :", "u'àu' : u'ăw', u'ảu' : u'ăw', u'ãu' : u'ăw', u'ạu'", "u'm', u'n' : u'n', u'ng' : u'ŋ', u'nh' : u'ɲ',", "u'uỳ' : u'i', u'uỷ' : u'i', u'uỹ' : u'i', u'uỵ'", ": u'ɯw', u'ứu' : u'ɯw', u'ừu' : u'ɯw', u'ửu' :", ": u'ɛ', u'ué' : u'ɛ', u'uè' : u'ɛ', u'uẻ' :", "của tiếng anh \"'\" #print(vi2IPA_split(\"speech? Secondly, we paper, we investigate", "u'ɔ', u'ò' : u'ɔ', u'ỏ' : u'ɔ', u'õ' : u'ɔ',", "u'i', u'ị' : u'i', u'o' : u'ɔ', u'ó' : u'ɔ',", "for ch #Thay offglide: úy -> wi để phân biệt", "line[-1] in ['i','í','ì','ĩ','ỉ','ị']): continue cout_same+=1 print(line+ \" <-> \" +", ": u'iu', u'uyụ' : u'iu', u'uyu' : u'iu', u'uýu' :", "về cường độ âm sắc chỉ dừng từ 1->6 #học", "u'ʷet' } Cus_onoffglides = { u'oe' : u'ɛj', u'oé' :", "u'ỏeo' : u'ew', u'õeo' : u'ew', u'ọeo' : u'ew', u'ueo'", "in onglides and ons != u'kw': # if there is", "u'uýu' : u'iu', u'uỳu' : u'iu', u'uỷu' : u'iu', u'uỹu'", "13, u'à' : 42, u'ả' : 312, u'ã' : 312,", "1 #if word[0:2] == u'gi' and cod and len(word) ==", "onoffglides, qu, gi = N_onsets, N_nuclei, N_codas, N_tones, N_onglides, N_offglides,", "u'ệ' : 212, u'í' : 45, u'ì' : 32, u'ỉ'", "u'oá' : u'a', u'oà' : u'a', u'oả' : u'a', u'oã'", "u'ãi' : u'aj', u'ại' : u'aj', u'ay' : u'ăj', u'áy'", ": u'ɣ', u'r' : u'z', u's' : u's', u'gi': u'z'}", ": u'ɯ', u'ử' : u'ɯ', u'ữ' : u'ɯ', u'ự' :", "= { u'á' : 5, u'à' : 2, u'ả' :", "in zip(ipa, delimiters)) else: seq = convert(word, dialect, glottal, pham,", "*** Problem with ủy onglide and off-glide is a big", "u'à' : 2, u'ả' : 4, u'ã' : 4, u'ạ'", "coda cod = codas[word[l-2:l]] cOffset = 2 elif word[l-1] in", "'ɯj', 'oj', 'ăw', 'zi', 'kw', 'aɪ', 'iɛ', 'ɤ̆', 'ɔ:', 'ăj',", "word[0] not in onsets: # if there isn't an onset....", "ở trước như: \"oa,ua,a\" đều như một > must consider", "c #g <-> gh #i <-> y #Same negative /", "u'ủi' : u'uj', u'ũi' : u'uj', u'ụi' : u'uj', #u'uy'", ": u'ʷen', u'oẽn' : u'ʷen', u'oẹn' : u'ʷen', u'oet' :", "if checkinvalid==1: TK = TK[:iuv] + TK[iuv+1 :] for tok", "312, u'ã' : u'35g', u'ạ' : u'21g', u'ấ' : 24,", "u'ji', u'gị' : u'ji' } C_qu = {u'quy' : u'wi',", "u'ɤ', u'uợ' : u'ɤ', u'uy' : u'i', u'uý' : u'i',", "ɣitʃ5 ia <-> iê : iə1 iêu <-> yêu :", ": u'iə', u'ịa' : u'iə', u'ia' : u'iə', u'iá' :", "u'uyê' : u'iə', u'uyế' : u'iə', u'uyề' : u'iə', u'uyể'", "\" ,ipa) else: IPA+=ipa+\" \" IPA=re.sub(delimit+'+', delimit, IPA) IPA=re.sub(' +',", "case Tiếng anh: => dùng etrain cho tiếng anh #+Deal", "u'iu' : u'iw', u'íu' : u'iw', u'ìu' : u'iw', u'ỉu'", "u'uậy' : u'ɤ̆j' } C_codas = { u'p' : u'p',", ": u'eo', u'ẻo' : u'eo', u'ẽo': u'eo', u'ẹo' : u'eo',", "u'n' : u'n', u'ng' : u'ŋ', u'nh' : u'ɲ', u'ch'", ": u'iu', u'uyũ' : u'iu', u'uyụ' : u'iu', u'uyu' :", "u'ư' : u'ɯ', u'ứ' : u'ɯ', u'ừ' : u'ɯ', u'ử'", ": u'ʂ', u'gi' : u'j' } S_nuclei = { u'a'", "Cus_offglides = { u'ai' : u'aj', u'ái' : u'aj', u'ài'", ": u'ʷiə', u'uyễ' : u'ʷiə', u'uyệ' : u'ʷiə', u'uyu' :", "= 2 elif word[l-1] in codas: # if one-character coda", "must consider (nhưng nếu thêm vào ảnh hưởng chữ qu", "u'ng' : u'ŋ', u'nh' : u'ɲ', u'ch' : u'k' }", "u'ẵ' : 312, u'ặ' : u'21g', u'é' : 13, u'è'", "#print(getSymbol()) ''' test=\"t\" if test in syms: print(test) else: print(\"none\")", "u'zi'} Cus_qu = {u'quy' : u'kwi', u'qúy' : u'kwi', u'qùy'", "u'ɯəj', u'ưởi' : u'ɯəj', u'ưỡi' : u'ɯəj', u'ượi' : u'ɯəj',", "u'ʷiə', u'uyà' : u'ʷiə', u'uyả' : u'ʷiə', u'uyã' : u'ʷiə',", ": u'ʷiə', u'uyá' : u'ʷiə', u'uyà' : u'ʷiə', u'uyả' :", "u'21g', u'ấ' : 13, u'ầ' : 42, u'ẩ' : 312,", "'cw', 'ʂw', 'ɣw', 'ʐw', 'xw', 'lw', 'hw', 'nw', 'sw', 'c']", "u'ầy' : u'ɤ̆j', u'ẩy' : u'ɤ̆j', u'ẫy' : u'ɤ̆j', u'ậy'", "4, u'ẽ' : 3, u'ẹ' : 6, u'ế' : 5,", "\" else: IPA+=eng+\" \" #Check tu dien tieng anh Etrain", "into 3 types. Type 1 are onsets which has one", "nghễu : ŋɛu3 nghía <-> ngía : ŋiə5 nghịu <->", "lt in List_pair: Pair[T2IPA(lt)] = lt cout_same=0 with open(\"Popular.txt\", encoding=\"utf-8\")", "'v', 'ʊ', 'ʤ', 'ɔ', '1', 'ʧ', 'ʈ', ' ', 'd',", "phân âm được => ý tưởng mượn \"tʃ\" trong teach", ": u'ʷă', u'oẵ' : u'ʷă', u'oặ' : u'ʷă', u'oe' :", "elif nucl in onglides and ons == u'kw': nuc =", "312, u'ã' : u'35g', u'ạ' : u'21g', # u'â' :", "u'ưỡ' : u'ɯə', u'ượ' : u'ɯə', u'yê' : u'iɛ', u'yế'", ": u'iw', u'ỉu' : u'iw', u'ĩu' : u'iw', u'ịu' :", "= compound + seq return compound def T2IPA(text): sys.path.append('./Rules') #", "312, u'ậ' : u'21g', u'ắ' : 13, u'ằ' : 42,", "u'oẽt' : u'et', u'oẹt' : u'et' } S_onoffglides = {", "u'ʷɤ̆', u'ue' : u'ʷɛ', u'ué' : u'ʷɛ', u'uè' : u'ʷɛ',", "} Cus_onoffglides = { u'oe' : u'ɛj', u'oé' : u'ɛj',", "u'ẻ' : 4, u'ẽ' : 3, u'ẹ' : 6, u'ế'", "} S_tones = { u'á' : 45, u'à' : 32,", ": 312, u'ĩ' : u'35g', u'ị' : u'21g', u'ó' :", ": u'ɯəw', 'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw' } #Các", ": u'ʷɛ', u'ua' : u'ʷa', u'uá' : u'ʷa', u'uà' :", "elif word[0] in onsets: # if single onset ons =", "# concatenate if len(words) >= 2: ortho += ' '", "u'uəj', u'uối' : u'uəj', u'uồi' : u'uəj', u'uổi' : u'uəj',", "u'ăj', u'oao' : u'aw', u'oáo' : u'aw', u'oào' : u'aw',", ": 212, u'ố' : 45, u'ồ' : 32, u'ổ' :", ": u'n', u'ch' : u'k' } # See Alves 2007", "u'ư' : 33, u'ứ' : 24, u'ừ' : 32, u'ử'", "reversed(token_under): TK.insert(iuv, tok) IPA=\"\" for tk in TK: ipa =", ": u'ɯə', u'ươ' : u'ɯə', u'ướ' : u'ɯə', u'ườ' :", "u'oả' : u'a', u'oã' : u'a', u'oạ' : u'a', u'óa'", ": 214, u'ọ' : 212, u'ố' : 45, u'ồ' :", "u'35g', u'ự' : u'21g', # u'y' : 33, u'ý' :", "u'ăw', u'ãu' : u'ăw', u'ạu' : u'ăw', u'ây' : u'ɤ̆j',", "'nw', 'sw', 'c'] word_pad = [\"_\"] space = [\" \"]", "u'uə', u'ụa' : u'uə', u'uô' : u'uə', u'uố' : u'uə',", ": u'ɔj', u'ôi' : u'oj', u'ối' : u'oj', u'ồi' :", ": u'ăw', u'áu' : u'ăw', u'àu' : u'ăw', u'ảu' :", "#Grapheme Rime_tone=[ \"a\",\"ă\",\"â\",\"e\",\"ê\",\"i\",\"o\",\"ô\",\"ơ\",\"u\",\"ư\",\"y\",\"iê\",\"oa\",\"oă\",\"oe\",\"oo\",\"uâ\",\"uê\",\"uô\",\"uơ\",\"uy\",\"ươ\",\"uyê\",\"yê\", #blank \"á\",\"ắ\",\"ấ\",\"é\",\"ế\",\"í\",\"ó\",\"ố\",\"ớ\",\"ú\",\"ứ\",\"ý\",\"iế\",\"óa\",\"oắ\",\"óe\",\"oó\",\"uấ\",\"uế\",\"uố\",\"ướ\",\"úy\",\"ướ\",\"uyế\",\"yế\", #grave \"oá\", \"oé\",\"óo\", \"uý\", \"à\",\"ằ\",\"ầ\",\"è\",\"ề\",\"ì\",\"ò\",\"ồ\",\"ờ\",\"ù\",\"ừ\",\"ỳ\",\"iề\",\"òa\",\"oằ\",\"òe\",\"oò\",\"uầ\",\"uề\",\"uồ\",\"ườ\",\"ùy\",\"ườ\",\"uyề\",\"yề\",", "u'ăj', u'oảy' : u'ăj', u'oãy' : u'ăj', u'oạy' : u'ăj',", "u'e', u'oè' : u'e', u'oẻ' : u'e', u'oẽ' : u'e',", "tones_p ons = '' nuc = '' cod = ''", "33 error tonelist = [tones[word[i]] for i in range(0,l) if", "} #tones = { u'a' : 33, u'á' : 24,", "tu dien tieng anh Etrain bưc #Neu co Mapping #Neu", ": u'ʷɤ̆', u'uẫ' : u'ʷɤ̆', u'uậ' : u'ʷɤ̆', u'ue' :", "ons = u'z' else: nucl = word[oOffset:l-cOffset] if nucl in", "'p', 'ə', 'u', 'o', '3', 'ɣ', '!', 'ð', 'ʧ', '6',", "u'i', u'ỷ' : u'i', u'ỹ' : u'i', u'ỵ' : u'i',", "ton = u'6b' # labialized allophony (added 17.09.08) if nuc", "if true, call this routine for each substring ## and", "u'ʷa', u'õa' : u'ʷa', u'ọa' : u'ʷa', u'oă' : u'ʷă',", "214, u'ữ' : 214, u'ự' : 212, u'ý' : 45,", "substrings[::2] delimiters = substrings[1::2] + [''] ipa = [convert(x, dialect,", "2, u'ẩ' : 4, u'ẫ' : 4, u'ậ' : 6,", "u'21g', # u'â' : 33, u'ấ' : 24, u'ầ' :", "42, u'ể' : 312, u'ễ' : 312, u'ệ' : u'21g',", "l > 0: if word[0:3] in onsets: # if onset", ": 24, u'è' : 32, u'ẻ' : 312, u'ẽ' :", "if word == 'quy', 'qúy',... ons = qu[word][:-1] nuc =", "u'ew', u'uai' : u'aj', u'uái' : u'aj', u'uài' : u'aj',", "IPA) print(\"IPA Vietnamese: \",IPA) print(\"------------------------------------------------------\") return IPA def checkDict(): cout=0", "ons = ons+u'w' # labialize it, but... else: # if", "u'i', u'uỹ' : u'i', u'uỵ' : u'i', u'uya' : u'iə',", "u'j' } C_nuclei = { u'a' : u'a', u'á' :", "'uj', 'aʊ', 'uə', 'aj', 'iə', 'iw', 'əʊ', 'ɑ:', 'tʃ', 'ʷe',", "u'wi', u'qũy' : u'wi', u'qụy' : u'wi'} ################################################3 import sys,", "đây tiết kiệm chi phí chạy máy không normal phoneme", ": 312, u'ự' : u'21g', u'ý' : 13, u'ỳ' :", "u'uài' : u'aj', u'uải' : u'aj', u'uãi' : u'aj', u'uại'", ": u'21g', u'í' : 24, u'ì' : 32, u'ỉ' :", ": 2, u'ỉ' : 4, u'ĩ' : 4, u'ị' :", "u'ĩ' : 312, u'ị' : u'21g', u'ó' : 13, u'ò'", ": u'ă', u'ặ' : u'ă', u'e' : u'ɛ', u'é' :", "your nucleus else: # otherwise... nuc = nuclei[nucl] # there's", ": u'ji', u'gĩ' : u'ji', u'gị' : u'ji' } C_qu", ": u'm', u'n': u'n', u'ngh': u'ŋ', u'nh' : u'ɲ', u'ng'", "T2IPA_split(tk,delimit).replace(\" \",\"_\") if ipa ==\"\": IPA+=delimit+tk+delimit+\" \" elif ipa[0]==\"[\" and", "# if word == 'quy', 'qúy',... ons = qu[word][:-1] nuc", ": 212, } S_tones_p = { u'á' : 5, u'à'", "IPA+=T2IPA_split(letter2sound,delimit)+\" \" else: #Giữ nguyên IPA+=Parsing(\"default\",tk.lower(),delimit)+\" \" else: IPA+=Parsing(\"default\",eng,delimit)+\" \"", "u'ɤ̆w', u'eo' : u'ew', u'éo' : u'ew', u'èo' : u'ew',", "u'ʷɤ', u'uở' : u'ʷɤ', u'uỡ' : u'ʷɤ', u'uợ' : u'ʷɤ',", "u'ỹ' : 3, u'ỵ' : 6, } Cus_gi = {", "'aʊ', 'uə', 'aj', 'iə', 'iw', 'əʊ', 'ɑ:', 'tʃ', 'ʷe', 'ɛu',", "nhiên cuối cùng \"ch\" \"c\" \"t\" không phân âm được", "'e', 't', \"'\"] def Parsing(listParse, text, delimit): undefine_symbol = \"'\"", "cod = u'ɲ'#u'ŋ' if palatals == 1: if cod ==", "u'uəj', u'uỗi' : u'uəj', u'uội' : u'uəj', u'ươi' : u'ɯəj',", "u'ắ' : 45, u'ằ' : 32, u'ẳ' : 214, u'ẵ'", "IPA+=ipa+\" \" IPA=re.sub(' +', ' ', IPA) print(\"IPA Vietnamese: \",IPA)", "onsets[word[0:3]] oOffset = 3 elif word[0:2] in onsets: # if", "u'ẳ' : 312, u'ẵ' : 312, u'ặ' : u'21g', u'é'", ": u't', u'c' : u'k', u'm' : u'm', u'n' :", "r=epi.transliterate(text) return r def T2IPA_split(text,delimit): sys.path.append('./Rules') # make sure we", "u'uy' : u'i', u'uý' : u'i', u'uỳ' : u'i', u'uỷ'", "print(\"Number of token can not convert: \",cout) print(\"Number of token", "u'ồ' : 32, u'ổ' : 214, u'ỗ' : 214, u'ộ'", "u'oè' : u'ej', u'oẻ' : u'ej', u'oẽ' : u'ej', u'oẹ'", "''.join(v+d for v,d in zip(ipa, delimiters)) else: seq = convert(word,", "u'ɛu', u'ia' : u'iə', u'ía' : u'iə', u'ìa' : u'iə',", "312, u'ộ' : u'21g', u'ớ' : 13, u'ờ' : 42,", "u'ɣ', u'l' : u'l', u'm' : u'm', u'n': u'n', u'ngh':", "\" IPA+=T2IPA_split(letter2sound,\"\")+\" \" else: #Giữ nguyên IPA+=Parsing(\"default\",tk,\"\")+\" \" else: IPA+=eng+\"", "memory ''' check_sym=\"ɯəjɤ̆jʷiəɤ̆wɯəwʷetiəwuəjʷentʰwʷɤ̆ʷiukwiŋ͡mk͡pcwjwuəeəbwojʷivwăwʈwʂwaʊfwɛutʰtʃɔɪxwʷɤɤ̆ŋwʊəziʷădweɪaɪewiəɣwzwɯjʷɛɯwɤjɔ:əʊʷamwɑ:hwɔjujlwɪəăju:awɛjiwajɜ:kwnwt∫ɲweoswtwʐwiɛʷei:ɯədʒɲθʌlw1ɪɯd∫pəuo3ɣ!ðʧ6ʒʐzvgă_æɤ2ʤi.ɒbhnʂɔɛkm5cjxʈ,4ʊsŋaʃ?r:ηf;et'\" for ine,res in enumerate(Results): if res not", "cod = u'k' if cod == u'n': cod = u'ŋ'", "ton = str(tonelist[len(tonelist)-1]) else: if not (pham or cao): if", "{u'quy' : u'wi', u'qúy' : u'wi', u'qùy' : u'wi', u'qủy'", "u'ắ' : 13, u'ằ' : 42, u'ẳ' : 312, u'ẵ'", ": u'u', u'ụ' : u'u', u'ư' : u'ɯ', u'ứ' :", "is an onglide... nuc = onglides[nucl] # modify the nuc", ": u'uə', u'uờ': u'uə', u'uở' : u'uə', u'uỡ' : u'uə',", "u'áo' : u'aw', u'ào' : u'aw', u'ảo' : u'aw', u'ão'", "u'ì' : 32, u'ỉ' : 312, u'ĩ' : u'35g', u'ị'", "stop else: # otherwise... nuc = nuclei[nucl] # there's your", "have 'gi' and a coda... nucl = u'i' ons =", "u'ʷɤ̆', u'uẫ' : u'ʷɤ̆', u'uậ' : u'ʷɤ̆', u'ue' : u'ʷɛ',", "u'uạ' : u'ʷa', u'uă' : u'ʷă', u'uắ' : u'ʷă', u'uằ'", ": u'e', u'ễ' : u'e', u'ệ' : u'e', u'i' :", "'lw', 'hw', 'nw', 'sw', 'c'] word_pad = [\"_\"] space =", "như: \"oa,ua,a\" đều như một > must consider (nhưng nếu", ": u'ʷa', u'uà' : u'ʷa', u'uả' : u'ʷa', u'uã' :", "u'ʷă', u'oe' : u'ʷɛ', u'oé' : u'ʷɛ', u'oè' : u'ʷɛ',", "c , t for t, tʃ for ch #Thay offglide:", "u'uə', u'uố' : u'uə', u'uồ' : u'uə', u'uổ' : u'uə',", "u'oă' : u'ă', u'oắ' : u'ă', u'oằ' : u'ă', u'oẳ'", "else: if nuc in [u'i', u'e']: if cod == u'k':", "word_pad = [\"_\"] space = [\" \"] tone=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"] punctuation =", "#g <-> gh #i <-> y #Same negative / need", "dialects: Thompson 1965: 86; Hoàng 1985: 181) if dialect ==", "u'ờ' : 2, u'ở' : 4, u'ỡ' : 4, u'ợ'", "u'ể' : 312, u'ễ' : 312, u'ệ' : u'21g', u'í'", "u'ʷe', u'uề' : u'ʷe', u'uể' : u'ʷe', u'uễ' : u'ʷe',", "u'kwi', u'qũy' : u'kwi', u'qụy' : u'kwi'} ####################################################### # North", "32, u'ủ' : 214, u'ũ' : 214, u'ụ' : 212,", "IPA+=eng+\" \" #Check tu dien tieng anh Etrain bưc #Neu", "List_pair: Pair[T2IPA(lt)] = lt cout_same=0 with open(\"Popular.txt\", encoding=\"utf-8\") as f:", "'ă'] listParse.sort(reverse = True,key=len) output=\"\" skip=0 for ic,char in enumerate(text):", "Rime_tone=[ \"a\",\"ă\",\"â\",\"e\",\"ê\",\"i\",\"o\",\"ô\",\"ơ\",\"u\",\"ư\",\"y\",\"iê\",\"oa\",\"oă\",\"oe\",\"oo\",\"uâ\",\"uê\",\"uô\",\"uơ\",\"uy\",\"ươ\",\"uyê\",\"yê\", #blank \"á\",\"ắ\",\"ấ\",\"é\",\"ế\",\"í\",\"ó\",\"ố\",\"ớ\",\"ú\",\"ứ\",\"ý\",\"iế\",\"óa\",\"oắ\",\"óe\",\"oó\",\"uấ\",\"uế\",\"uố\",\"ướ\",\"úy\",\"ướ\",\"uyế\",\"yế\", #grave \"oá\", \"oé\",\"óo\", \"uý\", \"à\",\"ằ\",\"ầ\",\"è\",\"ề\",\"ì\",\"ò\",\"ồ\",\"ờ\",\"ù\",\"ừ\",\"ỳ\",\"iề\",\"òa\",\"oằ\",\"òe\",\"oò\",\"uầ\",\"uề\",\"uồ\",\"ườ\",\"ùy\",\"ườ\",\"uyề\",\"yề\", #acute", "else: cao=1 #Input text line = text if line =='\\n':", ": u'21g', u'ó' : 13, u'ò' : 42, u'ỏ' :", "This looks ugly, but newer versions of python complain about", "u'ớ' : 45, u'ờ' : 32, u'ở' : 214, u'ỡ'", ": u'ʷɤ̆', u'uấ' : u'ʷɤ̆', u'uầ' : u'ʷɤ̆', u'uẩ' :", "u'ɔ', u'ỏ' : u'ɔ', u'õ' : u'ɔ', u'ọ' : u'ɔ',", "u'o' : 33, u'ó' : 24, u'ò' : 32, u'ỏ'", ": u'ji', u'gĩ' : u'ji', u'gị' : u'ji' } S_qu", "u'ậ' : u'21g', u'ắ' : 24, u'ằ' : 32, u'ẳ'", ": 33, u'ấ' : 24, u'ầ' : 32, u'ẩ' :", "= str(char).lower() if CHAR in list(EN.keys()): letter2sound+=EN[CHAR]+\" \" else: letter2sound+=char+\"", "u'ó' : 45, u'ò' : 32, u'ỏ' : 214, u'õ'", "cout=0 trung=0 List_token=[] List_pair = [] with open(\"Popular.txt\", encoding=\"utf-8\") as", ": u'ʷɛ', u'oé' : u'ʷɛ', u'oè' : u'ʷɛ', u'oẻ' :", "u'iəw', u'yếu' : u'iəw', u'yều' : u'iəw', u'yểu' : u'iəw',", ": u'ɯəw', u'ườu' : u'ɯəw', u'ưởu' : u'ɯəw', 'ưỡu' :", "u'ề' : 2, u'ể' : 4, u'ễ' : 4, u'ệ'", ": u'wi', u'qụy' : u'wi'} ################################################3 import sys, codecs, re", "u'ăw', u'ây' : u'ɤ̆j', u'ấy' : u'ɤ̆j', u'ầy' : u'ɤ̆j',", ": u'ʷɛ', u'ọe' : u'ʷɛ', u'ua' : u'ʷa', u'uá' :", "= ''.join(v+d for v,d in zip(ipa, delimiters)) else: seq =", "như case Tiếng anh: => dùng etrain cho tiếng anh", "list(set(List_token)) #print(List_token) print(len(List_token)) ################################ #Looking for pair Pair = {}", "u'ă' : u'ă', u'ắ' : u'ă', u'ằ' : u'ă', u'ẳ'", "there's your nucleus else: # otherwise... nuc = nuclei[nucl] #", "u'oet' : u'et', u'oét' : u'et', u'oèt' : u'et', u'oẻt'", "dialect == 'n': if nuc == u'a': if cod ==", "print(\"------------------------------------------------------\") print(\"Text normalize: \",TN) TK= word_tokenize(TN) print(\"Vietnamese Tokenize: \",TK) for", "u'o', u'ộô' : u'o', u'ôô' : u'o', u'ôố' : u'o',", "compound = compound + seq return compound EN={\"a\":\"ây\",\"ă\":\"á\",\"â\":\"ớ\",\"b\":\"bi\",\"c\":\"si\",\"d\":\"đi\",\"đ\":\"đê\",\"e\":\"i\",\"ê\":\"ê\",\"f\":\"ép\",\"g\":\"giy\",\"h\":\"ếch\",\"i\":\"ai\",\"j\":\"giây\",\"k\":\"cây\",\"l\":\"eo\",\"m\":\"em\",\"n\":\"en\",\"o\":\"âu\",\"ô\":\"ô\",\"ơ\":\"ơ\",\"p\":\"pi\",\"q\":\"kiu\",\"r\":\"a\",\"s\":\"ét\",\"t\":\"ti\",\"u\":\"diu\",\"ư\":\"ư\",\"v\":\"vi\",\"w\":\"đắp liu\",\"x\":\"ít\",\"y\":\"quai\",\"z\":\"giét\"} import", "\"ch\" \"c\" \"t\" không phân âm được => ý tưởng", "and nuc in [u'i', u'e', u'ɛ']: cod = u'c' #", "= 0 seq = '' try: (ons, nuc, cod, ton)", "\"tʃ\" trong teach and watch để thay thế => k", "'ð', 'u', 'e', 'w', 'p', 'ʃ', 'æ', \"'\", 'h', 'o',", "có cách bỏ dấu khác nhau đều gộp chung làm", "TK= word_tokenize(TN) print(\"Vietnamese Tokenize: \",TK) IPA=\"\" for tk in TK:", ": 4, u'ã' : 4, u'ạ' : 6, u'ấ' :", "u'ʷa', u'óa' : u'ʷa', u'òa' : u'ʷa', u'ỏa' : u'ʷa',", "= [\" \"] tone=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"] punctuation = [\".\",\",\",\"!\",\":\",\"?\",\";\",\"'\"] #\" ' (", "u'n', u'ngh': u'ŋ', u'nh' : u'ɲ', u'ng' : u'ŋ', u'ph'", "english? đại học là IUYE gì khôngtontaij NIYE BoOK\",\"'\")) #check", "u'ɯə', u'ươ' : u'ɯə', u'ướ' : u'ɯə', u'ườ' : u'ɯə',", "u'ề' : u'e', u'ể' : u'e', u'ễ' : u'e', u'ệ'", ": 2, u'ổ' : 4, u'ỗ' : 3, u'ộ' :", "'dʒ', 'ew', 'ʊə', 'ɯə', 'aw', '3', 'θ', 'v', 'ʊ', 'ʤ',", ": u'oj', u'ối' : u'oj', u'ồi' : u'oj', u'ổi' :", "u'aj', u'uài' : u'aj', u'uải' : u'aj', u'uãi' : u'aj',", "u'ượu' : u'ɯəw' } N_onglides = { u'oa' : u'a',", "không có cũng như case Tiếng anh: => dùng etrain", "u'ă', u'oẳ' : u'ă', u'oẵ' : u'ă', u'oặ' : u'ă',", "# Velar Fronting (Northern dialect) if dialect == 'n': if", "ŋiw6 nghoèo <-> ngoèo : ŋwew2 quít <-> quýt :", "u'c', u'k' : u'k', u'c' : u'k', u'gh' : u'ɣ',", "Central only) if ((dialect == 'n' and ton == u'24')", "work! One is that e language to another by\",\"/\").replace(\"/\",\"\")) #Case", ": u'uə', u'ưa' : u'ɯə', u'ứa' : u'ɯə', u'ừa' :", "u'ă', u'ặ' : u'ă', u'e' : u'ɛ', u'é' : u'ɛ',", "'ɤj', 'ɔ:', 'əʊ', 'ʷa', 'mw', 'ɑ:', 'hw', 'ɔj', 'uj', 'lw',", "for iuv,under_valid in enumerate(TK): token_under=under_valid.split(\" \") checkinvalid=0 print(token_under) if len(token_under)", "u'uýu' : u'ʷiu', u'uỳu' : u'ʷiu', u'uỷu' : u'ʷiu', u'uỹu'", ": u'uj', u'ụy' : u'uj', #thay để hạn chế trùng", "312, u'ỹ' : u'35g', u'ỵ' : u'21g', # } N_tones", "delimiters = substrings[1::2] + [''] ipa = [convert(x, dialect, glottal,", "\" -> \"+nor) trung +=1 List_pair.append(line) List_token.append(nor) if nor==\"\": cout+=1", "qu cũng ra w) #Try to add ʷ to all", "u'oả' : u'ʷa', u'oã' : u'ʷa', u'oạ' : u'ʷa', u'óa'", "\"+nor) trung +=1 List_pair.append(line) List_token.append(nor) if nor==\"\": cout+=1 print(line) print(\"Number", "u'ch' : u't' } S_tones = { u'á' : 45,", "C_gi = { u'gi' : u'ji', u'gí': u'ji', u'gì' :", ": u'ăw', u'àu' : u'ăw', u'ảu' : u'ăw', u'ãu' :", "u'óa' : u'a', u'òa' : u'a', u'ỏa' : u'a', u'õa'", ": u'a', u'õa' : u'a', u'ọa' : u'a', u'oă' :", ": u'a', u'â' : u'ɤ̆', u'ấ' : u'ɤ̆', u'ầ' :", ": u's', u'd' : u'z', u'h' : u'h', u'p' :", ": u'ɤ̆j', u'uậy' : u'ɤ̆j' } S_codas = { u'p'", "u'ɤ̆w', u'ấu' : u'ɤ̆w', u'ầu': u'ɤ̆w', u'ẩu' : u'ɤ̆w', u'ẫu'", "+ [''] ipa = [convert(x, dialect, glottal, pham, cao, palatals,", "} Cus_tones_p = { u'á' : 5, u'à' : 2,", "'t', 'ʒ', 'ə', 'ʌ', 'm', '!', '∫', 'ð', 'u', 'e',", "True,key=len) output=\"\" skip=0 for ic,char in enumerate(text): #print(char,skip) check =", "u'ue' : u'ɛ', u'ué' : u'ɛ', u'uè' : u'ɛ', u'uẻ'", "u'uả' : u'a', u'uã' : u'a', u'uạ' : u'a', u'uă'", "'mw', 'zw', 'fw', 'tw', 'tʰw', 'ɲw', 'cw', 'ʂw', 'ɣw', 'ʐw',", "and nuc in [u'i', u'e', u'ɛ']: if cod == u'ɲ':", "i < len(words)-1: seq = seq+u' ' compound = compound", "IUYE gì khôngtontaij NIYE BoOK\",\"'\")) #check các ipa của tiếng", "nuc == u'iə': nuc = u'i' if nuc == u'uə':", "u'ăj', u'uãy' : u'ăj', u'uạy' : u'ăj', u'uây' : u'ɤ̆j',", "u'21g', u'ứ' : 24, u'ừ' : 32, u'ử' : 312,", ": u'uə', u'uở' : u'uə', u'uờ': u'uə', u'uở' : u'uə',", "iu\",\"|\")) def getSymbol(): for s in SET: DICT.update(s) list_phoneme=DICT.values() list_phoneme=list(list_phoneme)", "cod, ton) def convert(word, dialect, glottal, pham, cao, palatals, delimit):", "u'ɤ̆', u'ấ' : u'ɤ̆', u'ầ' : u'ɤ̆', u'ẩ' : u'ɤ̆',", ": u'ɯəw', u'ượu' : u'ɯəw' } C_onglides = { u'oa'", ": 4, u'ỗ' : 4, u'ộ' : 6, u'ớ' :", "u'r' : u'ʐ', u's' : u'ʂ', u'gi' : u'j' }", "u'ʷiə', u'uyê' : u'ʷiə', u'uyế' : u'ʷiə', u'uyề' : u'ʷiə',", "312, u'ỡ' : u'35g', u'ợ' : u'21g', u'ú' : 24,", "and cOffset == 2: nuc = u'ɛ' if cod ==", "'-' in word) or (tokenize and '_' in word): substrings", "qu, gi = Cus_onsets, Cus_nuclei, Cus_codas, Cus_onglides, Cus_offglides, Cus_onoffglides, Cus_qu,", "214, u'ỗ' : 214, u'ộ' : 212, u'ớ' : 45,", "u'ɤ̆j', u'uẩy' : u'ɤ̆j', u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j'", "13, u'ò' : 42, u'ỏ' : 312, u'õ' : 312,", "u'ôô' : u'o', u'ôố' : u'o', u'ôồ' : u'o', u'ôổ'", "u'aj', u'uãi' : u'aj', u'uại' : u'aj', u'uay' : u'ăj',", "u'ũ' : u'35g', u'ụ' : u'21g', # u'ư' : 33,", "nucl in nuclei: if oOffset == 0: if glottal ==", "2, u'ỉ' : 4, u'ĩ' : 3, u'ị' : 6,", ": 2, u'ẻ' : 4, u'ẽ' : 4, u'ẹ' :", "seq+u' ' compound = compound + seq return compound EN={\"a\":\"ây\",\"ă\":\"á\",\"â\":\"ớ\",\"b\":\"bi\",\"c\":\"si\",\"d\":\"đi\",\"đ\":\"đê\",\"e\":\"i\",\"ê\":\"ê\",\"f\":\"ép\",\"g\":\"giy\",\"h\":\"ếch\",\"i\":\"ai\",\"j\":\"giây\",\"k\":\"cây\",\"l\":\"eo\",\"m\":\"em\",\"n\":\"en\",\"o\":\"âu\",\"ô\":\"ô\",\"ơ\":\"ơ\",\"p\":\"pi\",\"q\":\"kiu\",\"r\":\"a\",\"s\":\"ét\",\"t\":\"ti\",\"u\":\"diu\",\"ư\":\"ư\",\"v\":\"vi\",\"w\":\"đắp", "312, u'ỡ' : u'35g', u'ợ' : u'21g', # u'u' :", "nuc, cod, ton): seq = u'['+word+u']' else: seq = delimit+delimit.join(filter(None,", "ŋɛu3 nghía <-> ngía : ŋiə5 nghịu <-> ngịu :", "onglides[nucl] # modify the nuc accordingly if ons: # if", "positive #k <-> c #g <-> gh #i <-> y", "u'iəw', u'yểu' : u'iəw', u'yễu' : u'iəw', u'yệu' : u'iəw',", "and nuc == u'a': nuc = u'ɛ' # Final palatals", ": 33, u'í' : 24, u'ì' : 32, u'ỉ' :", "u'uəj', u'uội' : u'uəj', u'ươi' : u'ɯəj', u'ưới' : u'ɯəj',", "u'ẳ' : u'ă', u'ẵ' : u'ă', u'ặ' : u'ă', u'e'", "u'k' and nuc in [u'i', u'e', u'ɛ']: cod = u'c'", "2, u'ẳ' : 4, u'ẵ' : 3, u'ặ' : 6,", "u'wi', u'qúy' : u'wi', u'qùy' : u'wi', u'qủy' : u'wi',", "u'ɯə': nuc = u'ɯ' # Tones # Modified 20 Sep", ": u'35g', u'ặ' : u'21g', # u'e' : 33, u'é'", "io import StringIO from optparse import OptionParser from string import", "u'ɯj', u'ữi' : u'ɯj', u'ựi' : u'ɯj', u'ưu' : u'ɯw',", "u'ɤ̆j', u'uậy' : u'ɤ̆j' } C_codas = { u'p' :", "'dw', 'eo', 'ʈw', 'mw', 'zw', 'fw', 'tw', 'tʰw', 'ɲw', 'cw',", "tiếng anh \"'\" #print(vi2IPA_split(\"speech? Secondly, we paper, we investigate work!", "#\" ' ( ) Have been removed due to none", "content=f.read().splitlines() tess = texts.split(\".\") Results =\"\" for text in tess:", "2, u'ổ' : 4, u'ỗ' : 4, u'ộ' : 6,", "= True,key=len) return symbols def vi2IPA_pitrain(text): epi = epitran.Epitran('vie-Latn') r=epi.transliterate(text)", "u'kw': if ons: ons = ons+u'w' else: ons = u'w'", "5, u'ừ' : 2, u'ử' : 4, u'ữ' : 3,", ": u'i', u'uỷ' : u'i', u'uỹ' : u'i', u'uỵ' :", "== u'ɯə': nuc = u'ɯ' # Tones # Modified 20", "214, u'ỵ' : 212, } S_tones_p = { u'á' :", "u'uỷ' : u'i', u'uỹ' : u'i', u'uỵ' : u'i', u'uya'", ": 4, u'ỹ' : 3, u'ỵ' : 6, } Cus_gi", "32, u'ẻ' : 214, u'ẽ' : 214, u'ẹ' : 212,", "2, u'ỉ' : 4, u'ĩ' : 4, u'ị' : 6,", "u'ɲ', u'ng' : u'ŋ', u'ph' : u'f', u'v' : u'j',", "32, u'ẩ' : 214, u'ẫ' : 214, u'ậ' : 212,", "u'oẽ' : u'e', u'oẹ' : u'e', u'oe' : u'e', u'óe'", "u'ʷiə', u'uyá' : u'ʷiə', u'uyà' : u'ʷiə', u'uyả' : u'ʷiə',", "u'ɯj', u'ửi' : u'ɯj', u'ữi' : u'ɯj', u'ựi' : u'ɯj',", "có w ở trước như: \"oa,ua,a\" đều như một >", ": u'ɤ̆', u'uẩ' : u'ɤ̆', u'uẫ' : u'ɤ̆', u'uậ' :", "Vũ 1982 C_tones = { u'á' : 13, u'à' :", "u'ỹ' : 3, u'ỵ' : 6, } N_gi = {", "u'ộ' : 212, u'ớ' : 45, u'ờ' : 32, u'ở'", "'c'] word_pad = [\"_\"] space = [\" \"] tone=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"] punctuation", "C_onsets, C_nuclei, C_codas#, C_tones , C_onglides, C_offglides, C_onoffglides, C_qu, C_gi,", "re from io import StringIO from optparse import OptionParser from", "g C_tones_p = { u'á' : 5, u'à' : 2,", "'ɪə', 'ăj', 'u:', 'aw', 'ɛj', 'iw', 'aj', 'ɜ:', 'kw', 'nw',", "nuc in [u'iə', u'ɯə', u'uə', u'u', u'ɯ', u'ɤ', u'o', u'ɔ',", "to get rid of single hyphens or underscores words =", "cod = u'n' # There is also this reverse fronting,", "24, u'è' : 32, u'ẻ' : 312, u'ẽ' : u'35g',", "5, u'ằ' : 2, u'ẳ' : 4, u'ẵ' : 4,", "u'ì' : 42, u'ỉ' : 312, u'ĩ' : 312, u'ị'", ": u'35g', u'ẹ' : u'21g', # u'ê' : 33, u'ế'", "in codas: # if one-character coda cod = codas[word[l-1]] cOffset", "u's' : u's', u'gi': u'z'} N_nuclei = { u'a' :", "cod == u'k': cod = u't' if cod == u'ŋ':", "u'o', u'ơ' : u'ɤ', u'ớ' : u'ɤ', u'ờ' : u'ɤ',", "#k <-> c #g <-> gh #i <-> y #Same", ": ŋwew2 quít <-> quýt : kwit5 thủa <-> thuở", ": 4, u'ẽ' : 4, u'ẹ' : 6, u'ế' :", "32, u'ả' : 214, u'ã' : 214, u'ạ' : 212,", "StringIO from optparse import OptionParser from string import punctuation def", "u'ậ' : u'21g', # u'ă' : 33, u'ắ' : 24,", "seq = '' try: (ons, nuc, cod, ton) = trans(word,", "u'oen' : u'en', u'oén' : u'en', u'oèn' : u'en', u'oẻn'", "u'uở' : u'ʷɤ', u'uỡ' : u'ʷɤ', u'uợ' : u'ʷɤ', u'uy'", ": u'ɔ', u'ỏo' : u'ɔ', u'õo' : u'ɔ', u'ọo' :", "pham, cao, palatals) if None in (ons, nuc, cod, ton):", "u'ày' : u'ăj', u'ảy' : u'ăj', u'ãy' : u'ăj', u'ạy'", "u'ượu' : u'ɯəw' } S_onglides = { u'oa' : u'a',", "S_gi = { u'gi' : u'ji', u'gí': u'ji', u'gì' :", ": 3, u'ụ' : 6, u'ứ' : 5, u'ừ' :", "instead of g C_tones_p = { u'á' : 5, u'à'", ": u'i', u'uỳ' : u'i', u'uỷ' : u'i', u'uỹ' :", ": u'ʷiə', u'uyê' : u'ʷiə', u'uyế' : u'ʷiə', u'uyề' :", "u'iạ' : u'iə', u'iê' : u'iə', u'iế' : u'iə', u'iề'", ": u'ă', u'oe' : u'e', u'oé' : u'e', u'oè' :", "sure we can find the Rules files #Setup option glottal", ": u'ʷɤ', u'uợ' : u'ʷɤ', u'uy' : u'ʷi', u'uý' :", "3, u'ỵ' : 6, } N_gi = { u'gi' :", "ton = str('35') else: ton = str('33') else: ton =", ": u'e', u'ua' : u'a', u'uá' : u'a', u'uà' :", "ŋwew2 quít <-> quýt : kwit5 thủa <-> thuở :", "u'uẩy' : u'ɤ̆j', u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j' }", "u'uà' : u'ʷa', u'uả' : u'ʷa', u'uã' : u'ʷa', u'uạ'", "== 'c': ton = str('35') else: ton = str('33') else:", "except (TypeError): pass return seq ########################333 from vinorm import *", ": u'o', u'ỗô' : u'o', u'ộô' : u'o', u'ôô' :", "North # #coding: utf-8 N_onsets = { u'b' : u'b',", "u'ʷi', u'uỹ' : u'ʷi', u'uỵ' : u'ʷi', u'uya' : u'ʷiə',", "= { u'á' : 45, u'à' : 32, u'ả' :", "u'h', u'p' : u'p', u'qu' : u'kw', u'gi' : u'j',", "u'aj', u'uay' : u'ăj', u'uáy' : u'ăj', u'uày' : u'ăj',", "else: # otherwise... nuc = nuclei[nucl] # there's your nucleus", "42, u'ỉ' : 312, u'ĩ' : 312, u'ị' : u'21g',", "seq = ''.join(v+d for v,d in zip(ipa, delimiters)) else: seq", "u'ɲ': cod = u'ɲ' # u'ŋ' elif palatals != 1", "gi = Cus_onsets, Cus_nuclei, Cus_codas, Cus_onglides, Cus_offglides, Cus_onoffglides, Cus_qu, Cus_gi", "onoffglides[nucl][-1] nuc = onoffglides[nucl][0:-1] if ons != u'kw': if ons:", "u'uyú' : u'iu', u'uyù' : u'iu', u'uyủ' : u'iu', u'uyũ'", "x import *\" syntax if dialect == 'n': onsets, nuclei,", "i in range(0,len(words)): word = words[i].strip() ortho += word word", "u'u' : 33, u'ú' : 24, u'ù' : 32, u'ủ'", "dẫn đến trùng âm là: # Phương ngữ khác nhau", "âm là: # Phương ngữ khác nhau đã thống nhất", "u'ew', u'oẹo' : u'ew', u'oeo' : u'ew', u'óeo' : u'ew',", "33, u'ý' : 24, u'ỳ' : 32, u'ỷ' : 312,", "u'oẻn' : u'en', u'oẽn' : u'en', u'oẹn' : u'en', u'oet'", ": u'ʷiə', u'uyu' : u'ʷiu', u'uyú' : u'ʷiu', u'uyù' :", "== 1: if word[0] not in onsets: # if there", "u'oài' : u'aj', u'oải' : u'aj', u'oãi' : u'aj', u'oại'", "cod == u'ɲ' and nuc == u'a': nuc = u'ɛ'", "u'i', u'uỷ' : u'i', u'uỹ' : u'i', u'uỵ' : u'i',", ": u'uə', u'uố' : u'uə', u'uồ' : u'uə', u'uổ' :", "onglides, offglides, onoffglides, qu, gi = N_onsets, N_nuclei, N_codas, N_tones,", "u'ợ' : 212, u'ú' : 45, u'ù' : 32, u'ủ'", "\"oá\", \"oé\",\"óo\", \"uý\", \"à\",\"ằ\",\"ầ\",\"è\",\"ề\",\"ì\",\"ò\",\"ồ\",\"ờ\",\"ù\",\"ừ\",\"ỳ\",\"iề\",\"òa\",\"oằ\",\"òe\",\"oò\",\"uầ\",\"uề\",\"uồ\",\"ườ\",\"ùy\",\"ườ\",\"uyề\",\"yề\", #acute \"oà\", \"oè\",\"òo\", \"uỳ\", \"ả\",\"ẳ\",\"ẩ\",\"ẻ\",\"ể\",\"ỉ\",\"ỏ\",\"ổ\",\"ở\",\"ủ\",\"ử\",\"ỷ\",\"iể\",\"ỏa\",\"oẳ\",\"ỏe\",\"oỏ\",\"uẩ\",\"uể\",\"uổ\",\"ưở\",\"ủy\",\"ưở\",\"uyể\",\"yể\", #hook", ": u'e', u'òe' : u'e', u'ỏe' : u'e', u'õe' :", "if nuc in [u'u', u'o', u'ɔ']: if cod == u'ŋ':", "word in qu: # if word == 'quy', 'qúy',... ons", "== \"*\": if tk.lower().upper() == tk: #Đọc tiếng anh từng", "closed syllables (Northern and Central only) if ((dialect == 'n'", "u'uơ' : u'ʷɤ', u'uớ' : u'ʷɤ', u'uờ' : u'ʷɤ', u'uở'", "u'ấ' : 45, u'ầ' : 32, u'ẩ' : 214, u'ẫ'", "to 'ɲ'' in north #Các âm vòng ở đây i", "'cw', 'jw', 'uə', 'eə', 'bw', 'oj', 'ʷi', 'vw', 'ăw', 'ʈw',", "print(line + \" -> \"+nor) trung +=1 List_pair.append(line) List_token.append(nor) if", "u'uằ' : u'ʷă', u'uẳ' : u'ʷă', u'uẵ' : u'ʷă', u'uặ'", "u'uyã' : u'iə', u'uyạ' : u'iə', u'uyê' : u'iə', u'uyế'", "else: # if there is no onset... ons = u'w'", ": u'ɤ̆', u'ẩ' : u'ɤ̆', u'ẫ' : u'ɤ̆', u'ậ' :", "\"uý\", \"à\",\"ằ\",\"ầ\",\"è\",\"ề\",\"ì\",\"ò\",\"ồ\",\"ờ\",\"ù\",\"ừ\",\"ỳ\",\"iề\",\"òa\",\"oằ\",\"òe\",\"oò\",\"uầ\",\"uề\",\"uồ\",\"ườ\",\"ùy\",\"ườ\",\"uyề\",\"yề\", #acute \"oà\", \"oè\",\"òo\", \"uỳ\", \"ả\",\"ẳ\",\"ẩ\",\"ẻ\",\"ể\",\"ỉ\",\"ỏ\",\"ổ\",\"ở\",\"ủ\",\"ử\",\"ỷ\",\"iể\",\"ỏa\",\"oẳ\",\"ỏe\",\"oỏ\",\"uẩ\",\"uể\",\"uổ\",\"ưở\",\"ủy\",\"ưở\",\"uyể\",\"yể\", #hook \"oả\", \"oẻ\",\"ỏo\",", "eng = eng_to_ipa.convert(tk) if eng[-1] == \"*\": if tk.lower().upper() ==", "continue print(\"this is not in symbol :\"+ char+\":\") output+=delimit+undefine_symbol return", "{ u'oa' : u'ʷa', u'oá' : u'ʷa', u'oà' : u'ʷa',", "thủa <-> thuở : tʰuə4 tòe <-> toè : twʷɛ2", "u'ụ' : u'u', u'ư' : u'ɯ', u'ứ' : u'ɯ', u'ừ'", "u'e', u'uề' : u'e', u'uể' : u'e', u'uễ' : u'e',", "Cus_qu, Cus_gi] DICT={} #144 in total syms=['ɯəj', 'ɤ̆j', 'ʷiə', 'ɤ̆w',", "không được check phoneme tiếng anh #Nếu không có trong", "5, u'è' : 2, u'ẻ' : 4, u'ẽ' : 4,", "#Underthesea #For each Convert to phoneme #Nếu không được check", "u'ăw', u'áu' : u'ăw', u'àu' : u'ăw', u'ảu' : u'ăw',", "nuclei[nucl] # there's your nucleus elif nucl in onglides and", "C_codas = { u'p' : u'p', u't' : u'k', u'c'", "'t', \"'\"] def Parsing(listParse, text, delimit): undefine_symbol = \"'\" if", "true ## if true, call this routine for each substring", "'eo', 'ʈw', 'mw', 'zw', 'fw', 'tw', 'tʰw', 'ɲw', 'cw', 'ʂw',", "English_phoneme=[\"p\",\"b\",\"t\",\"d\",\"t∫\",\"dʒ\",\"k\",\"g\",\"f\",\"v\",\"ð\",\"θ\",\"s\",\"z\",\"∫\",\"ʒ\",\"m\",\"n\",\"η\",\"l\",\"r\",\"w\",\"j\",\"ɪ\",\"i:\",\"ʊ\",\"u:\",\"e\",\"ə\",\"ɜ:\",\"ɒ\",\"ɔ:\",\"æ\",\"ʌ\",\"ɑ:\",\"ɪə\",\"ʊə\",\"eə\",\"eɪ\",\"ɔɪ\",\"aɪ\",\"əʊ\",\"aʊ\",'ʃ',\"ʤ\",\"ʧ\"] Special=['jw', 'ŋw', 'bw', 'vw', 'dw', 'eo', 'ʈw', 'mw', 'zw',", "u'ɯ', u'ừ' : u'ɯ', u'ử' : u'ɯ', u'ữ' : u'ɯ',", ": u'uj', u'uy' : u'uj', u'úy' : u'uj', u'ùy' :", "'kw', 'nw', 't∫', 'ɲw', 'eo', 'sw', 'tw', 'ʐw', 'iɛ', 'ʷe',", "dialect, glottal, pham, cao, palatals, delimit).strip() # concatenate if len(words)", "Type 1 are onsets which has one letter \",\"/\")) #Lọc", ": u'ɔ', u'ò' : u'ɔ', u'ỏ' : u'ɔ', u'õ' :", "# u'y' : 33, u'ý' : 24, u'ỳ' : 32,", "u'oằ' : u'ʷă', u'oẳ' : u'ʷă', u'oẵ' : u'ʷă', u'oặ'", "{ u'á' : 24, u'à' : 32, u'ả' : 312,", "qu: # if word == 'quy', 'qúy',... ons = qu[word][:-1]", "'ʷɛ', 'ʷɤ', 'ɯj', 'oj', 'ăw', 'zi', 'kw', 'aɪ', 'iɛ', 'ɤ̆',", "u'uỹ' : u'ʷi', u'uỵ' : u'ʷi', u'ơi' : u'ɤj', u'ới'", "u'ó' : 24, u'ò' : 32, u'ỏ' : 312, u'õ'", "'m', '!', '∫', 'ð', 'u', 'e', 'w', 'p', 'ʃ', 'æ',", "'ɤj', 'ɯw', 'ɛj', 'ɔj', 'i:', 't∫', 'ɪə', 'ʷă', 'ɜ:', 'tʰ',", "u'ăj', u'oãy' : u'ăj', u'oạy' : u'ăj', u'oao' : u'aw',", "u'ọi' : u'ɔj', u'ôi' : u'oj', u'ối' : u'oj', u'ồi'", "6, } C_gi = { u'gi' : u'ji', u'gí': u'ji',", "u'ua' : u'a', u'uá' : u'a', u'uà' : u'a', u'uả'", "normalize: \",TN) TK= word_tokenize(TN) print(\"Vietnamese Tokenize: \",TK) for iuv,under_valid in", "trans(word, dialect, glottal, pham, cao, palatals): # This looks ugly,", "u'ă', u'e' : u'ɛ', u'é' : u'ɛ', u'è' : u'ɛ',", "toss len==0 junk words = [word for word in words", "thuở : tʰuə4 tòe <-> toè : twʷɛ2 ua <->", ": 45, u'ừ' : 32, u'ử' : 214, u'ữ' :", "= str('1') # Modifications for closed syllables if cOffset !=0:", "'ŋ͡m', 'k͡p', 'cw', 'jw', 'uə', 'eə', 'bw', 'oj', 'ʷi', 'vw',", "== 0: if glottal == 1: if word[0] not in", ": u'a', u'à' : u'a', u'ả' : u'a', u'ã' :", "u'ch' : u'k' } # See Alves 2007 (SEALS XII),", "<-> gin : zin1 díp <-> gíp : zip5 gen", "to use \\u02C0 for the unicode raised glottal character N_tones_p", "u'ẻ' : u'ɛ', u'ẽ' : u'ɛ', u'ẹ' : u'ɛ', u'ê'", "error tonelist = [tones[word[i]] for i in range(0,l) if word[i]", "= list(set(List_token)) #print(List_token) print(len(List_token)) ################################ #Looking for pair Pair =", ": 4, u'ợ' : 6, u'ú' : 5, u'ù' :", "if cod == u'ɲ' and nuc == u'a': nuc =", "= u'45' # Modification for 8-tone system if cao ==", "u'n': u'n', u'ngh': u'ŋ', u'nh' : u'ɲ', u'ng' : u'ŋ',", "u'i', u'í' : u'i', u'ì' : u'i', u'ỉ' : u'i',", "onset ons = onsets[word[0]] oOffset = 1 if word[l-2:l] in", "u'uờ': u'uə', u'uở' : u'uə', u'uỡ' : u'uə', u'uợ' :", "letter2sound+=EN[CHAR]+\" \" else: letter2sound+=char+\" \" IPA+=T2IPA_split(letter2sound,delimit)+\" \" else: #Giữ nguyên", "u'i', u'ỉ' : u'i', u'ĩ' : u'i', u'ị' : u'i',", "u'ạ' : 6, u'ấ' : 5, u'ầ' : 2, u'ẩ'", ": u'tʰ', u'đ' : u'd', u'ch' : u'c', u'kh' :", "như một > must consider (nhưng nếu thêm vào ảnh", "ons+u'w' else: ons = u'w' elif nucl in offglides: cod", "(ons, nuc, cod, ton)))+delimit except (TypeError): pass return seq ########################333", "tiếng anh #Nếu không có trong từ tiếng anh ->", "u'ej', u'oẻ' : u'ej', u'oẽ' : u'ej', u'oẹ' : u'ej',", "u'35g', u'ạ' : u'21g', u'ấ' : 24, u'ầ' : 32,", ": u'ăj', u'uày' : u'ăj', u'uảy' : u'ăj', u'uãy' :", ": u'ă', u'oẵ' : u'ă', u'oặ' : u'ă', u'oe' :", "#Remain ''' di <-> gi : zi1 dìm <-> gìm", "#Improve pronoune between N C S Cus_onsets = { u'b'", "u'iá' : u'iə', u'ià' : u'iə', u'iả' : u'iə', u'iã'", ": 5, u'ù' : 2, u'ủ' : 4, u'ũ' :", ": u'21g', # } N_tones = { u'á' : 24,", "dialect == 'c': tones_p = C_tones_p if dialect == 's':", "dialect, glottal, pham, cao, palatals, delimit): \"\"\"Convert a single orthographic", "\",\"_\") if ipa ==\"\": IPA+=tk+\" \" elif ipa[0]==\"[\" and ipa[-1]==\"]\":", "tone=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"] punctuation = [\".\",\",\",\"!\",\":\",\"?\",\";\",\"'\"] #\" ' ( ) Have been", "u'uj', u'úi' : u'uj', u'ùi' : u'uj', u'ủi' : u'uj',", "u'a' : u'a', u'á' : u'a', u'à' : u'a', u'ả'", "u'ậy' : u'ɤ̆j', u'âu' : u'ɤ̆w', u'ấu' : u'ɤ̆w', u'ầu':", ": u'ɔ', u'õo' : u'ɔ', u'ọo' : u'ɔ', u'oo' :", "re def vi2IPA_split(texts,delimit): content=[] with open(\"Popular.txt\",encoding=\"utf-8\") as f: content=f.read().splitlines() tess", ": 13, u'ầ' : 42, u'ẩ' : 312, u'ẫ' :", "u'oi' : u'ɔj', u'ói' : u'ɔj', u'òi' : u'ɔj', u'ỏi'", "u'ʷet', u'oẻt' : u'ʷet', u'oẽt' : u'ʷet', u'oẹt' : u'ʷet'", ": u'ʷet', u'oẽt' : u'ʷet', u'oẹt' : u'ʷet' } Cus_onoffglides", "Pair[T2IPA(lt)] = lt cout_same=0 with open(\"Popular.txt\", encoding=\"utf-8\") as f: content=f.read().splitlines()", "DICT.update(s) list_phoneme=DICT.values() list_phoneme=list(list_phoneme) English_phoneme=[\"p\",\"b\",\"t\",\"d\",\"t∫\",\"dʒ\",\"k\",\"g\",\"f\",\"v\",\"ð\",\"θ\",\"s\",\"z\",\"∫\",\"ʒ\",\"m\",\"n\",\"η\",\"l\",\"r\",\"w\",\"j\",\"ɪ\",\"i:\",\"ʊ\",\"u:\",\"e\",\"ə\",\"ɜ:\",\"ɒ\",\"ɔ:\",\"æ\",\"ʌ\",\"ɑ:\",\"ɪə\",\"ʊə\",\"eə\",\"eɪ\",\"ɔɪ\",\"aɪ\",\"əʊ\",\"aʊ\",'ʃ',\"ʤ\",\"ʧ\"] Special=['jw', 'ŋw', 'bw', 'vw', 'dw', 'eo',", "'ưỡu' : u'ɯəw', u'ượu' : u'ɯəw' } #Các âm vòng", "u'ê' : u'e', u'ế' : u'e', u'ề' : u'e', u'ể'", "= onoffglides[nucl][0:-1] if ons != u'kw': if ons: ons =", ": t theo nam -> custom k vì nó giảm", "gìm : zim2 din <-> gin : zin1 díp <->", "str('33') else: ton = str('1') # Modifications for closed syllables", "== u'ɲ' and nuc == u'a': nuc = u'ɛ' #", "= '' dialect='n' #\"c\"\"s\" tone_type=0 if tone_type==0: pham=1 else: cao=1", ": 6, u'ú' : 5, u'ù' : 2, u'ủ' :", ": u'21g', u'ớ' : 13, u'ờ' : 42, u'ở' :", "312, u'ữ' : 312, u'ự' : u'21g', u'ý' : 13,", "u'ɲ'#u'ŋ' if palatals == 1: if cod == u'k' and", "u'ɤ̆', u'ă' : u'ă', u'ắ' : u'ă', u'ằ' : u'ă',", "u'ɤ̆j', u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j' } N_codas =", "= { u'p' : u'p', u't' : u't', u'c' :", "############################################ #south.py #coding: utf-8 S_onsets = { u'b' : u'b',", "u'ch' : u'tʃ' } Cus_tones_p = { u'á' : 5,", "u'ấ' : u'ɤ̆', u'ầ' : u'ɤ̆', u'ẩ' : u'ɤ̆', u'ẫ'", "and a coda... nucl = u'i' ons = u'z' else:", ": u'ʷɤ', u'uở' : u'ʷɤ', u'uỡ' : u'ʷɤ', u'uợ' :", ": 5, u'ồ' : 2, u'ổ' : 4, u'ỗ' :", "if cod == u'k': cod = u'k͡p' return (ons, nuc,", ": u'iw', u'ịu' : u'iw', u'oi' : u'ɔj', u'ói' :", "Results[ine]=\"'\" ''' return Results.rstrip() def vi2IPA(text): print(\"------------------------------------------------------\") TN= TTSnorm(text) print(\"------------------------------------------------------\")", "texts.split(\".\") Results =\"\" for text in tess: print(\"------------------------------------------------------\") TN= TTSnorm(text)", ": u'ʷi', u'uỷ' : u'ʷi', u'uỹ' : u'ʷi', u'uỵ' :", "negative / need to fix #oe <-> uê -> fix", "u'iə', u'uyệ' : u'iə', u'uyu' : u'iu', u'uyú' : u'iu',", ": u'ɯəj', u'ưới' : u'ɯəj', u'ười' : u'ɯəj', u'ưởi' :", "raised glottal character N_tones_p = { u'á' : 5, u'à'", "#Giữ nguyên IPA+=Parsing(\"default\",tk,\"\")+\" \" else: IPA+=eng+\" \" #Check tu dien", "ưa <-> ươ : ɯə1 xõa <-> xoã : swʷa3", "zip5 gen <-> ghen : ɣɛn1 ghì <-> gì :", "N_onsets = { u'b' : u'b', u't' : u't', u'th'", "ton == u'24') or (dialect == 'c' and ton ==", "32, u'ẳ' : 312, u'ẵ' : u'35g', u'ặ' : u'21g',", "u'ua' : u'uə', u'úa' : u'uə', u'ùa' : u'uə', u'ủa'", "= texts.split(\".\") Results =\"\" for text in tess: print(\"------------------------------------------------------\") TN=", ": u'iu', u'uỷu' : u'iu', u'uỹu' : u'iu', u'uỵu' :", "u'oẹ' : u'e', u'oe' : u'e', u'óe' : u'e', u'òe'", "eng_to_ipa.convert(tk) if eng[-1] == \"*\": if tk.lower().upper() == tk: #print(\"ENGLISH\",tk)", "== u'21g' and cod in ['p', 't', 'k']: #if ton", ": u'aw', u'oão' : u'aw', u'oạo' : u'aw', u'oeo' :", ": u'21g', u'ớ' : 24, u'ờ' : 32, u'ở' :", "'ɛ', 'k', 'm', '5', ' ', 'c', 'j', 'x', 'ʈ',", "u'oõ' : u'ɔ', u'oọ' : u'ɔ', u'ôô' : u'o', u'ốô'", ": 4, u'ũ' : 3, u'ụ' : 6, u'ứ' :", ": u'e', u'oẽ' : u'e', u'oẹ' : u'e', u'oe' :", "cod == u'ŋ': cod = u'ŋ͡m' if cod == u'k':", "u'ủ' : 4, u'ũ' : 4, u'ụ' : 6, u'ứ'", "and cod in ['p', 't', 'k']: ton = u'45' #", "'ʷɤ̆', 'ʷiu', 'kwi', 'ŋ͡m', 'k͡p', 'cw', 'jw', 'uə', 'eə', 'bw',", ": u'oj', u'ồi' : u'oj', u'ổi' : u'oj', u'ỗi' :", "0: #Case symbol not in list if str(char) in [\"ˈ\",\"ˌ\",\"*\"]:", "C_tones = { u'á' : 13, u'à' : 42, u'ả'", "âm sắc chỉ dừng từ 1->6 #học ác cho kết", "Velar Fronting (Southern and Central dialects) else: if nuc in", "glottal stop else: # otherwise... nuc = nuclei[nucl] # there's", "checkDict() #print(vi2IPA_split(\"!Singapo english? đại học là IUYE gì khôngtontaij NIYE", "u'ɯə', u'ữa' : u'ɯə', u'ựa' : u'ɯə', u'ươ' : u'ɯə',", ": u'ɔj', u'ọi' : u'ɔj', u'ôi' : u'oj', u'ối' :", "u'ồô' : u'o', u'ổô' : u'o', u'ỗô' : u'o', u'ộô'", ": 32, u'ể' : 214, u'ễ' : 214, u'ệ' :", "x in values] seq = ''.join(v+d for v,d in zip(ipa,", ": u'21g', u'ứ' : 24, u'ừ' : 32, u'ử' :", ": 214, u'ũ' : 214, u'ụ' : 212, u'ứ' :", "#Disable convert from 'ɲ' to 'ɲ'' in north #Các âm", "in token_under: if tok not in content or \"[\" in", "u'ỹ' : 312, u'ỵ' : u'21g', } # used to", ": u'a', u'uã' : u'a', u'uạ' : u'a', u'uă' :", "== u'ɲ': cod = u'ɲ'#u'ŋ' if palatals == 1: if", ": u'ɲ', u'ch' : u'k' } #tones = { u'a'", ": u'ɔj', u'ói' : u'ɔj', u'òi' : u'ɔj', u'ỏi' :", "= N_tones_p if dialect == 'c': tones_p = C_tones_p if", "u'ạ' : u'21g', u'ấ' : 24, u'ầ' : 32, u'ẩ'", "u'o', u'ua' : u'uə', u'úa' : u'uə', u'ùa' : u'uə',", ": 2, u'ở' : 4, u'ỡ' : 4, u'ợ' :", ": u'21g', u'ế' : 13, u'ề' : 42, u'ể' :", "syllables (Northern and Central only) if ((dialect == 'n' and", ": ɣitʃ5 ia <-> iê : iə1 iêu <-> yêu", ": u'21g', # u'ô' : 33, u'ố' : 24, u'ồ'", ": u'ʷɛ', u'oẹ' : u'ʷɛ', u'oe' : u'ʷɛ', u'óe' :", "= onglides[nucl] # modify the nuc accordingly if ons: #", "u'u', u'ư' : u'ɯ', u'ứ' : u'ɯ', u'ừ' : u'ɯ',", "single onset ons = onsets[word[0]] oOffset = 1 if word[l-2:l]", "print(\"Number of token in the same mapping:\",trung) List_token = list(set(List_token))", ": 214, u'ễ' : 214, u'ệ' : 212, u'í' :", "u'ỷ' : 312, u'ỹ' : u'35g', u'ỵ' : u'21g', }", "== u'a': if cod == u'k' and cOffset == 2:", "u'uə', u'uỡ' : u'uə', u'uợ' : u'uə', } C_offglides =", "tk in TK: ipa = T2IPA(tk).replace(\" \",\"_\") if ipa ==\"\":", "u'21g', # u'ă' : 33, u'ắ' : 24, u'ằ' :", "print(\"------------------------------------------------------\") return IPA def checkDict(): cout=0 trung=0 List_token=[] List_pair =", "u'uể' : u'ʷe', u'uễ' : u'ʷe', u'uệ' : u'ʷe', u'uơ'", "u'ỹ' : 4, u'ỵ' : 6, } C_gi = {", "u'ộ' : u'o', u'ơ' : u'ɤ', u'ớ' : u'ɤ', u'ờ'", "42, u'ẻ' : 312, u'ẽ' : 312, u'ẹ' : u'21g',", ": u'ʷɤ̆', u'uẩ' : u'ʷɤ̆', u'uẫ' : u'ʷɤ̆', u'uậ' :", ": ɣɛn1 ghì <-> gì : ɣi2 ghích <-> gích", "token in the same mapping:\",trung) List_token = list(set(List_token)) #print(List_token) print(len(List_token))", ": u'a', u'uă' : u'ă', u'uắ' : u'ă', u'uằ' :", "u'ʂ', u'gi' : u'j' } S_nuclei = { u'a' :", "listParse == \"default\": listParse=['ʷiə', 'uəj', 'iəw', 'k͡p', 'ʷɤ̆', 'ɤ̆j', 'ŋ͡m',", "u'ʷe', u'uệ' : u'ʷe', u'uơ' : u'ʷɤ', u'uớ' : u'ʷɤ',", "co de nguyen #Neu khong danh van print(\" ..................Out of", "'aʊ', 'fw', 'ɛu', 'tʰ', 'tʃ', 'ɔɪ', 'xw', 'ʷɤ', 'ɤ̆', 'ŋw',", "u'ụi' : u'uj', #u'uy' : u'uj', u'úy' : u'uj', u'ùy'", ": u'ŋ', u'nh' : u'n', u'ch' : u'k' } #", "'xw', 'lw', 'hw', 'nw', 'sw', 'c'] word_pad = [\"_\"] space", "'aɪ', 'iɛ', 'ɤ̆', 'ɔ:', 'ăj', 'ʷa', 'eə', 'u:', 'uj', 'aʊ',", "u'ằ' : u'ă', u'ẳ' : u'ă', u'ẵ' : u'ă', u'ặ'", "u'ɤ̆j', u'uẫy' : u'ɤ̆j', u'uậy' : u'ɤ̆j' } C_codas =", "' ', IPA) print(\"IPA Vietnamese: \",IPA) print(\"------------------------------------------------------\") Results+= IPA.rstrip()+\" \"+delimit+\".\"+delimit+\"", "gi : zi1 dìm <-> gìm : zim2 din <->", "u'gí': u'zi', u'gì' : u'zi', u'gì' : u'zi', u'gĩ' :", ": u'k', u'c' : u'k', u'm' : u'm', u'n' :", "u'uội' : u'uəj', u'ươi' : u'ɯəj', u'ưới' : u'ɯəj', u'ười'", "# NIYE BoOK #print(len(getSymbol())) #print(getSymbol()) ''' test=\"t\" if test in", "nuc = nuclei[nucl] # there's your nucleus else: # otherwise...", "u'uải' : u'aj', u'uãi' : u'aj', u'uại' : u'aj', u'uay'", "u'uyạ' : u'iə', u'uyê' : u'iə', u'uyế' : u'iə', u'uyề'", "u'uấ' : u'ʷɤ̆', u'uầ' : u'ʷɤ̆', u'uẩ' : u'ʷɤ̆', u'uẫ'", "# Tones # Modified 20 Sep 2008 to fix aberrant", "u'35g', u'ặ' : u'21g', # u'e' : 33, u'é' :", "#dot \"oạ\", \"oẹ\",\"ọo\", \"uỵ\"] Onset=[\"b\",\"d\",\"h\",\"l\",\"m\",\"n\",\"p\",\"r\",\"s\",\"t\",\"v\",\"x\",\"đ\",\"p\", \"tr\", \"th\", \"ch\", \"ph\",\"nh\",\"kh\",\"gi\",\"qu\", \"ngh\",\"ng\",\"gh\",\"g\",\"k\",\"c\"]", ": u'iə', u'uyệ' : u'iə', u'uyu' : u'iu', u'uyú' :", "palatals = 0 tokenize = 0 delimit = '' dialect='n'", ": u'kwi', u'qúy' : u'kwi', u'qùy' : u'kwi', u'qủy' :", "u'iế' : u'iə', u'iề' : u'iə', u'iể' : u'iə', u'iễ'", "13, u'ì' : 42, u'ỉ' : 312, u'ĩ' : 312,", "phoneme về cường độ âm sắc chỉ dừng từ 1->6", "+ English_phoneme + punctuation + tone + modifi + Special", ": u'aj', u'uại' : u'aj', u'uay' : u'ăj', u'uáy' :", "hạn chế trùng âm u'uy' : u'ʷi', u'uý' : u'ʷi',", "u'ễ' : u'35g', u'ệ' : u'21g', # u'i' : 33,", "u'p']: if nuc == u'iə': nuc = u'i' if nuc", "'ɑ:', 'hw', 'ɔj', 'uj', 'lw', 'ɪə', 'ăj', 'u:', 'aw', 'ɛj',", "u'ỡ' : u'35g', u'ợ' : u'21g', u'ú' : 24, u'ù'", "kí tự IPA của tiếng ANH #+Thêm xử lí case", "2, u'ẻ' : 4, u'ẽ' : 3, u'ẹ' : 6,", "4, u'ỗ' : 3, u'ộ' : 6, u'ớ' : 5,", "palatals == 1: if cod == u'k' and nuc in", "oOffset = 1 if word[l-2:l] in codas: # if two-character", "# u'ơ' : 33, u'ớ' : 24, u'ờ' : 32,", ": u'ʷɛ', u'uê' : u'ʷe', u'uế' : u'ʷe', u'uề' :", "\"] tone=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\"] punctuation = [\".\",\",\",\"!\",\":\",\"?\",\";\",\"'\"] #\" ' ( ) Have", ": u'ʷɤ', u'uỡ' : u'ʷɤ', u'uợ' : u'ʷɤ', u'uy' :", "not convert: \",cout) print(\"Number of token in the same mapping:\",trung)", "u'ỉ' : 214, u'ĩ' : 214, u'ị' : 212, u'ó'", "\"c\" khác nhau ################################################### checkDict() #print(vi2IPA_split(\"!Singapo english? đại học là", "# Velar Fronting (Southern and Central dialects) else: if nuc", "cao, palatals) if None in (ons, nuc, cod, ton): seq", "another by\",\"/\").replace(\"/\",\"\")) #Case need to be deal: # NIYE BoOK", "u'ia' : u'iə', u'ía' : u'iə', u'ìa' : u'iə', u'ỉa'", ": u'ʷe', u'uơ' : u'ʷɤ', u'uớ' : u'ʷɤ', u'uờ' :", "u'ŋ': cod = u'ŋ͡m' if cod == u'k': cod =", "'ɤ̆', 'ɔ:', 'ăj', 'ʷa', 'eə', 'u:', 'uj', 'aʊ', 'uə', 'aj',", "u'uẻ' : u'ʷɛ', u'uẽ' : u'ʷɛ', u'uẹ' : u'ʷɛ', u'uê'", "u'ʷa', u'ỏa' : u'ʷa', u'õa' : u'ʷa', u'ọa' : u'ʷa',", "u'yế' : u'iɛ', u'yề' : u'iɛ', u'yể' : u'iɛ', u'yễ'", "u'ẽ' : u'35g', u'ẹ' : u'21g', u'ế' : 24, u'ề'", "u'oa' : u'ʷa', u'oá' : u'ʷa', u'oà' : u'ʷa', u'oả'", "trong teach and watch để thay thế => k for", "u as in wiki # *** Problem with ủy onglide", "u'uyễ' : u'iə', u'uyệ' : u'iə', u'uyu' : u'iu', u'uyú'", "#oe <-> uê -> fix oe from e to ɛ", "u'ợ' : u'21g', # u'u' : 33, u'ú' : 24,", ": xwʷɛ4 khua <-> khuơ : xuə1 lóe <-> loé", "u'ɛ', u'ê' : u'e', u'ế' : u'e', u'ề' : u'e',", ": u'ʷe', u'uể' : u'ʷe', u'uễ' : u'ʷe', u'uệ' :", "table was prepared to show available onsets. Onsets are splitted", "\"uỷ\", \"ã\",\"ẵ\",\"ẫ\",\"ẽ\",\"ễ\",\"ĩ\",\"õ\",\"ỗ\",\"ỡ\",\"ũ\",\"ữ\",\"ỹ\",\"iễ\",\"õa\",\"oẵ\",\"õe\",\"oõ\",\"uẫ\",\"uễ\",\"uỗ\",\"ưỡ\",\"ũy\",\"ưỡ\",\"uyễ\",\"yễ\", #tilde \"oã\", \"oẽ\",\"õo\", \"uỹ\", \"ạ\",\"ặ\",\"ậ\",\"ẹ\",\"ệ\",\"ị\",\"ọ\",\"ộ\",\"ợ\",\"ụ\",\"ự\",\"ỵ\",\"iệ\",\"ọa\",\"oặ\",\"ọe\",\"oọ\",\"uậ\",\"uệ\",\"uệ\",\"ượ\",\"ụy\",\"ượ\",\"uyệ\",\"yệ\", #dot \"oạ\", \"oẹ\",\"ọo\",", "for closed syllables if cOffset !=0: # Obstruent-final nang tones", "= u'ɛ' # Final palatals (Northern dialect) if nuc not", "have 'gi' and a coda... if word[0:2] in gi and", "u'ă', u'uắ' : u'ă', u'uằ' : u'ă', u'uẳ' : u'ă',", "return (ons, nuc, cod, ton) def convert(word, dialect, glottal, pham,", "u'o', u'ổ' : u'o', u'ỗ' : u'o', u'ộ' : u'o',", "đã thống nhất ở list custom # Các trường hợp", ": u'21g', u'í' : 13, u'ì' : 42, u'ỉ' :", "u's', u'gi': u'z'} N_nuclei = { u'a' : u'a', u'á'" ]
[ "def get_session_store_class(cls): return SessionStore class Meta: db_name = 'deft_adcr' db_table", "SessionStore as DBStore class CustomSession(AbstractBaseSession): @classmethod def get_session_store_class(cls): return SessionStore", "'<NAME>' from django.contrib.sessions.base_session import AbstractBaseSession from django.contrib.sessions.backends.db import SessionStore as", "django.contrib.sessions.base_session import AbstractBaseSession from django.contrib.sessions.backends.db import SessionStore as DBStore class", "db_table = '\"ATLAS_DEFT\".\"DJANGO_SESSION\"' class SessionStore(DBStore): @classmethod def get_model_class(cls): return CustomSession", "db_name = 'deft_adcr' db_table = '\"ATLAS_DEFT\".\"DJANGO_SESSION\"' class SessionStore(DBStore): @classmethod def", "AbstractBaseSession from django.contrib.sessions.backends.db import SessionStore as DBStore class CustomSession(AbstractBaseSession): @classmethod", "= 'deft_adcr' db_table = '\"ATLAS_DEFT\".\"DJANGO_SESSION\"' class SessionStore(DBStore): @classmethod def get_model_class(cls):", "django.contrib.sessions.backends.db import SessionStore as DBStore class CustomSession(AbstractBaseSession): @classmethod def get_session_store_class(cls):", "import SessionStore as DBStore class CustomSession(AbstractBaseSession): @classmethod def get_session_store_class(cls): return", "as DBStore class CustomSession(AbstractBaseSession): @classmethod def get_session_store_class(cls): return SessionStore class", "@classmethod def get_session_store_class(cls): return SessionStore class Meta: db_name = 'deft_adcr'", "SessionStore class Meta: db_name = 'deft_adcr' db_table = '\"ATLAS_DEFT\".\"DJANGO_SESSION\"' class", "class Meta: db_name = 'deft_adcr' db_table = '\"ATLAS_DEFT\".\"DJANGO_SESSION\"' class SessionStore(DBStore):", "<filename>taskengine/sessions.py __author__ = '<NAME>' from django.contrib.sessions.base_session import AbstractBaseSession from django.contrib.sessions.backends.db", "return SessionStore class Meta: db_name = 'deft_adcr' db_table = '\"ATLAS_DEFT\".\"DJANGO_SESSION\"'", "import AbstractBaseSession from django.contrib.sessions.backends.db import SessionStore as DBStore class CustomSession(AbstractBaseSession):", "from django.contrib.sessions.backends.db import SessionStore as DBStore class CustomSession(AbstractBaseSession): @classmethod def", "class CustomSession(AbstractBaseSession): @classmethod def get_session_store_class(cls): return SessionStore class Meta: db_name", "get_session_store_class(cls): return SessionStore class Meta: db_name = 'deft_adcr' db_table =", "'deft_adcr' db_table = '\"ATLAS_DEFT\".\"DJANGO_SESSION\"' class SessionStore(DBStore): @classmethod def get_model_class(cls): return", "Meta: db_name = 'deft_adcr' db_table = '\"ATLAS_DEFT\".\"DJANGO_SESSION\"' class SessionStore(DBStore): @classmethod", "__author__ = '<NAME>' from django.contrib.sessions.base_session import AbstractBaseSession from django.contrib.sessions.backends.db import", "from django.contrib.sessions.base_session import AbstractBaseSession from django.contrib.sessions.backends.db import SessionStore as DBStore", "DBStore class CustomSession(AbstractBaseSession): @classmethod def get_session_store_class(cls): return SessionStore class Meta:", "CustomSession(AbstractBaseSession): @classmethod def get_session_store_class(cls): return SessionStore class Meta: db_name =", "= '<NAME>' from django.contrib.sessions.base_session import AbstractBaseSession from django.contrib.sessions.backends.db import SessionStore" ]
[ "elements: # bill 23 16 19 22 def test_sum_w_23_16_19_22(self): test_list", "#write the import for function for assignment7 sum_list_values from src.assignments.assignment7", "assignment7 sum_list_values from src.assignments.assignment7 import sum_list_values class Test_Assign7(unittest.TestCase): def sample_test(self):", "for function for assignment7 sum_list_values from src.assignments.assignment7 import sum_list_values class", "16 19 22 def test_sum_w_23_16_19_22(self): test_list = ['bill', 23, 16,", "19 22 def test_sum_w_23_16_19_22(self): test_list = ['bill', 23, 16, 19,", "the import for function for assignment7 sum_list_values from src.assignments.assignment7 import", "from src.assignments.assignment7 import sum_list_values class Test_Assign7(unittest.TestCase): def sample_test(self): self.assertEqual(1,1) #create", "function for assignment7 sum_list_values from src.assignments.assignment7 import sum_list_values class Test_Assign7(unittest.TestCase):", "test_list = ['bill', 23, 16, 19, 22] self.assertEqual(80, sum_list_values(test_list)) #unittest.main(verbosity=2)", "bill 23 16 19 22 def test_sum_w_23_16_19_22(self): test_list = ['bill',", "sum_list_values from src.assignments.assignment7 import sum_list_values class Test_Assign7(unittest.TestCase): def sample_test(self): self.assertEqual(1,1)", "import unittest #write the import for function for assignment7 sum_list_values", "sample_test(self): self.assertEqual(1,1) #create a test for the sum_list_values function with", "list elements: # bill 23 16 19 22 def test_sum_w_23_16_19_22(self):", "sum_list_values function with list elements: # bill 23 16 19", "Test_Assign7(unittest.TestCase): def sample_test(self): self.assertEqual(1,1) #create a test for the sum_list_values", "for assignment7 sum_list_values from src.assignments.assignment7 import sum_list_values class Test_Assign7(unittest.TestCase): def", "sum_list_values class Test_Assign7(unittest.TestCase): def sample_test(self): self.assertEqual(1,1) #create a test for", "def test_sum_w_23_16_19_22(self): test_list = ['bill', 23, 16, 19, 22] self.assertEqual(80,", "import for function for assignment7 sum_list_values from src.assignments.assignment7 import sum_list_values", "test_sum_w_23_16_19_22(self): test_list = ['bill', 23, 16, 19, 22] self.assertEqual(80, sum_list_values(test_list))", "self.assertEqual(1,1) #create a test for the sum_list_values function with list", "# bill 23 16 19 22 def test_sum_w_23_16_19_22(self): test_list =", "unittest #write the import for function for assignment7 sum_list_values from", "a test for the sum_list_values function with list elements: #", "23 16 19 22 def test_sum_w_23_16_19_22(self): test_list = ['bill', 23,", "for the sum_list_values function with list elements: # bill 23", "with list elements: # bill 23 16 19 22 def", "22 def test_sum_w_23_16_19_22(self): test_list = ['bill', 23, 16, 19, 22]", "#create a test for the sum_list_values function with list elements:", "function with list elements: # bill 23 16 19 22", "the sum_list_values function with list elements: # bill 23 16", "test for the sum_list_values function with list elements: # bill", "def sample_test(self): self.assertEqual(1,1) #create a test for the sum_list_values function", "import sum_list_values class Test_Assign7(unittest.TestCase): def sample_test(self): self.assertEqual(1,1) #create a test", "class Test_Assign7(unittest.TestCase): def sample_test(self): self.assertEqual(1,1) #create a test for the", "src.assignments.assignment7 import sum_list_values class Test_Assign7(unittest.TestCase): def sample_test(self): self.assertEqual(1,1) #create a" ]
[ "= ('_signing_key',) def __init__(self, skey): self._signing_key = nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder) @staticmethod", "\"\"\" ciphertext = b64decode(ciphertext) if verifier: ciphertext = verifier.verifyb(ciphertext) data", "b64decode(ciphertext) if verifier: ciphertext = verifier.verifyb(ciphertext) data = self._box.decrypt(ciphertext) return", "2.0 (the \"License\"); # you may not use this file", "\"\"\" return self._signing_key.sign(message) def pack(self, doc): return b64encode(self.packb(doc)).decode() def packb(self,", "after encryption. (See also: https://pynacl.readthedocs.io/en/stable/signing) Arguments: key (str): Base64-encoded key", "def signb(self, message): \"\"\"Sign a binary message with its signature", "to use in verifying the signed ciphertext. If not provided,", "def keygen(): signing_key = nacl.signing.SigningKey.generate() return ( signing_key.encode(nacl.encoding.Base64Encoder).decode(), signing_key.verify_key.encode(nacl.encoding.Base64Encoder).decode(), )", "nacl.secret import nacl.signing import nacl.utils from .version import __version__ #", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "doc): return b64encode(self.packb(doc)).decode() def packb(self, doc): packed = msgpack.packb(doc, encoding='utf-8',", "packb(self, doc): packed = msgpack.packb(doc, encoding='utf-8', use_bin_type=True) return self.signb(packed) class", "signing_key = nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder) return signing_key.verify_key.encode(nacl.encoding.Base64Encoder) def signb(self, message): \"\"\"Sign", "return self._signing_key.sign(message) def pack(self, doc): return b64encode(self.packb(doc)).decode() def packb(self, doc):", "verifyb(self, message): \"\"\"Verify a signed binary message. Arguments: message(bytes): Data", "demonstrated the ability to create arbitrary valid messages, so messages", "from .version import __version__ # NOQA class Signer: \"\"\"Message signer", "Arguments: signer: An instance of Signer to use in signing", "Signer to use in signing the result. If not provided,", "language governing permissions and # limitations under the License. from", "signer: ciphertext = signer.signb(ciphertext) return b64encode(ciphertext).decode() def decrypt(self, ciphertext, verifier=None):", "use this file except in compliance with the License. #", "return msgpack.unpackb(packed, raw=False, encoding='utf-8') class BlackBox: \"\"\"Encryption engine based on", "def packb(self, doc): packed = msgpack.packb(doc, encoding='utf-8', use_bin_type=True) return self.signb(packed)", "\"\"\" __slots__ = ('_box',) def __init__(self, key): self._box = nacl.secret.SecretBox(b64decode(key))", "packed): packed = self.verifyb(packed) return msgpack.unpackb(packed, raw=False, encoding='utf-8') class BlackBox:", "def encrypt(self, doc, signer=None): \"\"\"Serialize and encrypt a document to", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "import __version__ # NOQA class Signer: \"\"\"Message signer based on", "message): \"\"\"Verify a signed binary message. Arguments: message(bytes): Data to", "License. # You may obtain a copy of the License", "self.verifyb(packed) return msgpack.unpackb(packed, raw=False, encoding='utf-8') class BlackBox: \"\"\"Encryption engine based", "self._verify_key = nacl.signing.VerifyKey(vkey, nacl.encoding.Base64Encoder) def verifyb(self, message): \"\"\"Verify a signed", "nacl.secret.SecretBox(b64decode(key)) @staticmethod def keygen(): return b64encode(nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)).decode() def encrypt(self, doc, signer=None):", "def vkey(skey): signing_key = nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder) return signing_key.verify_key.encode(nacl.encoding.Base64Encoder) def signb(self,", "def __init__(self, vkey): self._verify_key = nacl.signing.VerifyKey(vkey, nacl.encoding.Base64Encoder) def verifyb(self, message):", "under the License is distributed on an \"AS IS\" BASIS,", "License for the specific language governing permissions and # limitations", "self._box.encrypt(data) if signer: ciphertext = signer.signb(ciphertext) return b64encode(ciphertext).decode() def decrypt(self,", "based on Ed25519 and nacl.signing. Arguments: key (str): Base64-encoded key", "SecretBox (Salsa20/Poly1305). Warning per the SecretBox docs: Once you’ve decrypted", "instance of Verifier to use in verifying the signed ciphertext.", "keygen() \"\"\" __slots__ = ('_box',) def __init__(self, key): self._box =", "Arguments: doc: The string, dict, array, or other JSON-compatible object", "repudiable. For non-repudiable messages, sign them after encryption. (See also:", "governing permissions and # limitations under the License. from base64", "document to Base64-encoded ciphertext. Arguments: doc: The string, dict, array,", "import nacl.utils from .version import __version__ # NOQA class Signer:", "obtained from keygen() \"\"\" __slots__ = ('_box',) def __init__(self, key):", "ciphertext = verifier.verifyb(ciphertext) data = self._box.decrypt(ciphertext) return msgpack.unpackb(data, raw=False, encoding='utf-8')", "by <NAME> # # Licensed under the Apache License, Version", "keygen() \"\"\" __slots__ = ('_signing_key',) def __init__(self, skey): self._signing_key =", "the result. If not provided, the ciphertext is not signed.", "valid messages, so messages you send are repudiable. For non-repudiable", "in compliance with the License. # You may obtain a", "software # distributed under the License is distributed on an", "dict, array, or other JSON-compatible object to serialize and encrypt.", "not signed. Returns: str: Ciphertext \"\"\" data = msgpack.packb(doc, encoding='utf-8',", "decrypt(self, ciphertext, verifier=None): \"\"\"Unpack Base64-encoded ciphertext. Arguments: ciphertext (bytes): Ciphertext", "the signed ciphertext. If not provided, the ciphertext is assumed", "from keygen() \"\"\" __slots__ = ('_box',) def __init__(self, key): self._box", "b64encode(self.packb(doc)).decode() def packb(self, doc): packed = msgpack.packb(doc, encoding='utf-8', use_bin_type=True) return", "\"\"\"Verify a signed binary message. Arguments: message(bytes): Data to verify.", "signature attached. Arguments: message(bytes): Data to sign. Returns: bytes: Signed", "result. If not provided, the ciphertext is not signed. Returns:", "msgpack import nacl.encoding import nacl.secret import nacl.signing import nacl.utils from", "arbitrary valid messages, so messages you send are repudiable. For", "msgpack.packb(doc, encoding='utf-8', use_bin_type=True) ciphertext = self._box.encrypt(data) if signer: ciphertext =", "to Base64-encoded ciphertext. Arguments: doc: The string, dict, array, or", "key (str): Base64-encoded key obtained from keygen() \"\"\" __slots__ =", "ciphertext. Arguments: ciphertext (bytes): Ciphertext to decrypt and deserialize. Keyword", "def __init__(self, skey): self._signing_key = nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder) @staticmethod def keygen():", "provided, the ciphertext is assumed to be unsigned. Returns: doc:", "Arguments: key (str): Base64-encoded key obtained from keygen() \"\"\" __slots__", "# Copyright 2018 by <NAME> # # Licensed under the", "ciphertext = signer.signb(ciphertext) return b64encode(ciphertext).decode() def decrypt(self, ciphertext, verifier=None): \"\"\"Unpack", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "Returns: bytes: The orignal message, sans signature. \"\"\" return self._verify_key.verify(message)", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "__init__(self, vkey): self._verify_key = nacl.signing.VerifyKey(vkey, nacl.encoding.Base64Encoder) def verifyb(self, message): \"\"\"Verify", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "Ciphertext \"\"\" data = msgpack.packb(doc, encoding='utf-8', use_bin_type=True) ciphertext = self._box.encrypt(data)", "to in writing, software # distributed under the License is", "# See the License for the specific language governing permissions", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "use_bin_type=True) ciphertext = self._box.encrypt(data) if signer: ciphertext = signer.signb(ciphertext) return", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "with the License. # You may obtain a copy of", "nacl.utils from .version import __version__ # NOQA class Signer: \"\"\"Message", ".version import __version__ # NOQA class Signer: \"\"\"Message signer based", "\"\"\"Signature verifier based on Ed25519 and nacl.signing. Arguments: key (str):", "signed binary message. Arguments: message(bytes): Data to verify. Returns: bytes:", "to serialize and encrypt. Keyword Arguments: signer: An instance of", "ability to create arbitrary valid messages, so messages you send", "message): \"\"\"Sign a binary message with its signature attached. Arguments:", "Arguments: message(bytes): Data to sign. Returns: bytes: Signed message \"\"\"", "Deserialized JSON-compatible object. \"\"\" ciphertext = b64decode(ciphertext) if verifier: ciphertext", "to verify. Returns: bytes: The orignal message, sans signature. \"\"\"", "BlackBox: \"\"\"Encryption engine based on PyNaCl's SecretBox (Salsa20/Poly1305). Warning per", "compliance with the License. # You may obtain a copy", "agreed to in writing, software # distributed under the License", "unpackb(self, packed): packed = self.verifyb(packed) return msgpack.unpackb(packed, raw=False, encoding='utf-8') class", "Returns: doc: Deserialized JSON-compatible object. \"\"\" ciphertext = b64decode(ciphertext) if", "nacl.encoding.Base64Encoder) @staticmethod def keygen(): signing_key = nacl.signing.SigningKey.generate() return ( signing_key.encode(nacl.encoding.Base64Encoder).decode(),", "doc): packed = msgpack.packb(doc, encoding='utf-8', use_bin_type=True) return self.signb(packed) class Verifier:", "distributed under the License is distributed on an \"AS IS\"", "base64 import b64decode, b64encode import msgpack import nacl.encoding import nacl.secret", "Arguments: verifier: An instance of Verifier to use in verifying", "__slots__ = ('_signing_key',) def __init__(self, skey): self._signing_key = nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder)", "bytes: The orignal message, sans signature. \"\"\" return self._verify_key.verify(message) def", "express or implied. # See the License for the specific", "= signer.signb(ciphertext) return b64encode(ciphertext).decode() def decrypt(self, ciphertext, verifier=None): \"\"\"Unpack Base64-encoded", "except in compliance with the License. # You may obtain", "also: https://pynacl.readthedocs.io/en/stable/signing) Arguments: key (str): Base64-encoded key obtained from keygen()", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "and encrypt. Keyword Arguments: signer: An instance of Signer to", "pack(self, doc): return b64encode(self.packb(doc)).decode() def packb(self, doc): packed = msgpack.packb(doc,", "a document to Base64-encoded ciphertext. Arguments: doc: The string, dict,", "not use this file except in compliance with the License.", "skey): self._signing_key = nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder) @staticmethod def keygen(): signing_key =", "signature. \"\"\" return self._verify_key.verify(message) def unpack(self, packed): return self.unpackb(b64decode(packed)) def", "return b64encode(nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)).decode() def encrypt(self, doc, signer=None): \"\"\"Serialize and encrypt a", "message you’ve demonstrated the ability to create arbitrary valid messages,", "def keygen(): return b64encode(nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)).decode() def encrypt(self, doc, signer=None): \"\"\"Serialize and", "writing, software # distributed under the License is distributed on", "unpack(self, packed): return self.unpackb(b64decode(packed)) def unpackb(self, packed): packed = self.verifyb(packed)", "encrypt(self, doc, signer=None): \"\"\"Serialize and encrypt a document to Base64-encoded", "you may not use this file except in compliance with", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "sans signature. \"\"\" return self._verify_key.verify(message) def unpack(self, packed): return self.unpackb(b64decode(packed))", "https://pynacl.readthedocs.io/en/stable/signing) Arguments: key (str): Base64-encoded key obtained from keygen() \"\"\"", "key): self._box = nacl.secret.SecretBox(b64decode(key)) @staticmethod def keygen(): return b64encode(nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)).decode() def", "nacl.encoding.Base64Encoder) def verifyb(self, message): \"\"\"Verify a signed binary message. Arguments:", "signed. Returns: str: Ciphertext \"\"\" data = msgpack.packb(doc, encoding='utf-8', use_bin_type=True)", "decrypted the message you’ve demonstrated the ability to create arbitrary", "on Ed25519 and nacl.signing. Arguments: key (str): Base64-encoded key obtained", "verify key \"\"\" __slots__ = ('_verify_key',) def __init__(self, vkey): self._verify_key", "class BlackBox: \"\"\"Encryption engine based on PyNaCl's SecretBox (Salsa20/Poly1305). Warning", "signing_key.verify_key.encode(nacl.encoding.Base64Encoder).decode(), ) @staticmethod def vkey(skey): signing_key = nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder) return", "CONDITIONS OF ANY KIND, either express or implied. # See", "('_signing_key',) def __init__(self, skey): self._signing_key = nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder) @staticmethod def", "('_verify_key',) def __init__(self, vkey): self._verify_key = nacl.signing.VerifyKey(vkey, nacl.encoding.Base64Encoder) def verifyb(self,", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "is not signed. Returns: str: Ciphertext \"\"\" data = msgpack.packb(doc,", "based on Ed25519 and nacl.signing. Arguments: key (str): Base64-encoded verify", "binary message. Arguments: message(bytes): Data to verify. Returns: bytes: The", "you’ve decrypted the message you’ve demonstrated the ability to create", "import nacl.encoding import nacl.secret import nacl.signing import nacl.utils from .version", "signing_key.verify_key.encode(nacl.encoding.Base64Encoder) def signb(self, message): \"\"\"Sign a binary message with its", "import msgpack import nacl.encoding import nacl.secret import nacl.signing import nacl.utils", "= nacl.secret.SecretBox(b64decode(key)) @staticmethod def keygen(): return b64encode(nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)).decode() def encrypt(self, doc,", "Returns: str: Ciphertext \"\"\" data = msgpack.packb(doc, encoding='utf-8', use_bin_type=True) ciphertext", "self._signing_key = nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder) @staticmethod def keygen(): signing_key = nacl.signing.SigningKey.generate()", "Keyword Arguments: signer: An instance of Signer to use in", "and nacl.signing. Arguments: key (str): Base64-encoded verify key \"\"\" __slots__", "you’ve demonstrated the ability to create arbitrary valid messages, so", "ciphertext is assumed to be unsigned. Returns: doc: Deserialized JSON-compatible", "of Verifier to use in verifying the signed ciphertext. If", "OR CONDITIONS OF ANY KIND, either express or implied. #", "If not provided, the ciphertext is not signed. Returns: str:", "the message you’ve demonstrated the ability to create arbitrary valid", "messages, sign them after encryption. (See also: https://pynacl.readthedocs.io/en/stable/signing) Arguments: key", "Data to verify. Returns: bytes: The orignal message, sans signature.", "the License is distributed on an \"AS IS\" BASIS, #", "__init__(self, skey): self._signing_key = nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder) @staticmethod def keygen(): signing_key", "under the License. from base64 import b64decode, b64encode import msgpack", "For non-repudiable messages, sign them after encryption. (See also: https://pynacl.readthedocs.io/en/stable/signing)", "import b64decode, b64encode import msgpack import nacl.encoding import nacl.secret import", "return b64encode(ciphertext).decode() def decrypt(self, ciphertext, verifier=None): \"\"\"Unpack Base64-encoded ciphertext. Arguments:", "If not provided, the ciphertext is assumed to be unsigned.", "and # limitations under the License. from base64 import b64decode,", "= msgpack.packb(doc, encoding='utf-8', use_bin_type=True) return self.signb(packed) class Verifier: \"\"\"Signature verifier", "key obtained from keygen() \"\"\" __slots__ = ('_box',) def __init__(self,", "doc: The string, dict, array, or other JSON-compatible object to", "Ed25519 and nacl.signing. Arguments: key (str): Base64-encoded verify key \"\"\"", "@staticmethod def vkey(skey): signing_key = nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder) return signing_key.verify_key.encode(nacl.encoding.Base64Encoder) def", "ciphertext (bytes): Ciphertext to decrypt and deserialize. Keyword Arguments: verifier:", "object. \"\"\" ciphertext = b64decode(ciphertext) if verifier: ciphertext = verifier.verifyb(ciphertext)", "law or agreed to in writing, software # distributed under", "the SecretBox docs: Once you’ve decrypted the message you’ve demonstrated", "(See also: https://pynacl.readthedocs.io/en/stable/signing) Arguments: key (str): Base64-encoded key obtained from", "message(bytes): Data to sign. Returns: bytes: Signed message \"\"\" return", "\"\"\"Message signer based on Ed25519 and nacl.signing. Arguments: key (str):", "NOQA class Signer: \"\"\"Message signer based on Ed25519 and nacl.signing.", "doc: Deserialized JSON-compatible object. \"\"\" ciphertext = b64decode(ciphertext) if verifier:", "ciphertext. If not provided, the ciphertext is assumed to be", "Verifier to use in verifying the signed ciphertext. If not", "= nacl.signing.SigningKey.generate() return ( signing_key.encode(nacl.encoding.Base64Encoder).decode(), signing_key.verify_key.encode(nacl.encoding.Base64Encoder).decode(), ) @staticmethod def vkey(skey):", "doc, signer=None): \"\"\"Serialize and encrypt a document to Base64-encoded ciphertext.", "if verifier: ciphertext = verifier.verifyb(ciphertext) data = self._box.decrypt(ciphertext) return msgpack.unpackb(data,", "Verifier: \"\"\"Signature verifier based on Ed25519 and nacl.signing. Arguments: key", "key \"\"\" __slots__ = ('_verify_key',) def __init__(self, vkey): self._verify_key =", "messages you send are repudiable. For non-repudiable messages, sign them", "keygen(): signing_key = nacl.signing.SigningKey.generate() return ( signing_key.encode(nacl.encoding.Base64Encoder).decode(), signing_key.verify_key.encode(nacl.encoding.Base64Encoder).decode(), ) @staticmethod", "permissions and # limitations under the License. from base64 import", "__slots__ = ('_box',) def __init__(self, key): self._box = nacl.secret.SecretBox(b64decode(key)) @staticmethod", "from keygen() \"\"\" __slots__ = ('_signing_key',) def __init__(self, skey): self._signing_key", "(bytes): Ciphertext to decrypt and deserialize. Keyword Arguments: verifier: An", "messages, so messages you send are repudiable. For non-repudiable messages,", "from base64 import b64decode, b64encode import msgpack import nacl.encoding import", "may obtain a copy of the License at # #", "(str): Base64-encoded verify key \"\"\" __slots__ = ('_verify_key',) def __init__(self,", "limitations under the License. from base64 import b64decode, b64encode import", "class Verifier: \"\"\"Signature verifier based on Ed25519 and nacl.signing. Arguments:", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "# NOQA class Signer: \"\"\"Message signer based on Ed25519 and", "may not use this file except in compliance with the", "import nacl.signing import nacl.utils from .version import __version__ # NOQA", "instance of Signer to use in signing the result. If", "msgpack.unpackb(packed, raw=False, encoding='utf-8') class BlackBox: \"\"\"Encryption engine based on PyNaCl's", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "assumed to be unsigned. Returns: doc: Deserialized JSON-compatible object. \"\"\"", "this file except in compliance with the License. # You", "encrypt. Keyword Arguments: signer: An instance of Signer to use", "return b64encode(self.packb(doc)).decode() def packb(self, doc): packed = msgpack.packb(doc, encoding='utf-8', use_bin_type=True)", "or other JSON-compatible object to serialize and encrypt. Keyword Arguments:", "and encrypt a document to Base64-encoded ciphertext. Arguments: doc: The", "the ciphertext is assumed to be unsigned. Returns: doc: Deserialized", "( signing_key.encode(nacl.encoding.Base64Encoder).decode(), signing_key.verify_key.encode(nacl.encoding.Base64Encoder).decode(), ) @staticmethod def vkey(skey): signing_key = nacl.signing.SigningKey(skey,", "key (str): Base64-encoded verify key \"\"\" __slots__ = ('_verify_key',) def", "nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder) @staticmethod def keygen(): signing_key = nacl.signing.SigningKey.generate() return (", "<NAME> # # Licensed under the Apache License, Version 2.0", "message, sans signature. \"\"\" return self._verify_key.verify(message) def unpack(self, packed): return", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "str: Ciphertext \"\"\" data = msgpack.packb(doc, encoding='utf-8', use_bin_type=True) ciphertext =", "# # Licensed under the Apache License, Version 2.0 (the", "2018 by <NAME> # # Licensed under the Apache License,", "engine based on PyNaCl's SecretBox (Salsa20/Poly1305). Warning per the SecretBox", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "The orignal message, sans signature. \"\"\" return self._verify_key.verify(message) def unpack(self,", "Ed25519 and nacl.signing. Arguments: key (str): Base64-encoded key obtained from", "its signature attached. Arguments: message(bytes): Data to sign. Returns: bytes:", "a signed binary message. Arguments: message(bytes): Data to verify. Returns:", "the ciphertext is not signed. Returns: str: Ciphertext \"\"\" data", "unsigned. Returns: doc: Deserialized JSON-compatible object. \"\"\" ciphertext = b64decode(ciphertext)", "encrypt a document to Base64-encoded ciphertext. Arguments: doc: The string,", "a binary message with its signature attached. Arguments: message(bytes): Data", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "binary message with its signature attached. Arguments: message(bytes): Data to", "other JSON-compatible object to serialize and encrypt. Keyword Arguments: signer:", "Returns: bytes: Signed message \"\"\" return self._signing_key.sign(message) def pack(self, doc):", "def decrypt(self, ciphertext, verifier=None): \"\"\"Unpack Base64-encoded ciphertext. Arguments: ciphertext (bytes):", "JSON-compatible object to serialize and encrypt. Keyword Arguments: signer: An", "with its signature attached. Arguments: message(bytes): Data to sign. Returns:", "verifying the signed ciphertext. If not provided, the ciphertext is", "Base64-encoded verify key \"\"\" __slots__ = ('_verify_key',) def __init__(self, vkey):", "nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder) return signing_key.verify_key.encode(nacl.encoding.Base64Encoder) def signb(self, message): \"\"\"Sign a binary", "signer: An instance of Signer to use in signing the", "\"\"\" return self._verify_key.verify(message) def unpack(self, packed): return self.unpackb(b64decode(packed)) def unpackb(self,", "PyNaCl's SecretBox (Salsa20/Poly1305). Warning per the SecretBox docs: Once you’ve", "data = msgpack.packb(doc, encoding='utf-8', use_bin_type=True) ciphertext = self._box.encrypt(data) if signer:", "Base64-encoded ciphertext. Arguments: ciphertext (bytes): Ciphertext to decrypt and deserialize.", "docs: Once you’ve decrypted the message you’ve demonstrated the ability", "encoding='utf-8', use_bin_type=True) return self.signb(packed) class Verifier: \"\"\"Signature verifier based on", "create arbitrary valid messages, so messages you send are repudiable.", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "keygen(): return b64encode(nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)).decode() def encrypt(self, doc, signer=None): \"\"\"Serialize and encrypt", "signing_key.encode(nacl.encoding.Base64Encoder).decode(), signing_key.verify_key.encode(nacl.encoding.Base64Encoder).decode(), ) @staticmethod def vkey(skey): signing_key = nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder)", "The string, dict, array, or other JSON-compatible object to serialize", "__init__(self, key): self._box = nacl.secret.SecretBox(b64decode(key)) @staticmethod def keygen(): return b64encode(nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)).decode()", "or implied. # See the License for the specific language", "you send are repudiable. For non-repudiable messages, sign them after", "@staticmethod def keygen(): return b64encode(nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)).decode() def encrypt(self, doc, signer=None): \"\"\"Serialize", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "\"\"\"Sign a binary message with its signature attached. Arguments: message(bytes):", "Keyword Arguments: verifier: An instance of Verifier to use in", "to be unsigned. Returns: doc: Deserialized JSON-compatible object. \"\"\" ciphertext", "JSON-compatible object. \"\"\" ciphertext = b64decode(ciphertext) if verifier: ciphertext =", "= ('_verify_key',) def __init__(self, vkey): self._verify_key = nacl.signing.VerifyKey(vkey, nacl.encoding.Base64Encoder) def", "encryption. (See also: https://pynacl.readthedocs.io/en/stable/signing) Arguments: key (str): Base64-encoded key obtained", "not provided, the ciphertext is not signed. Returns: str: Ciphertext", "def unpackb(self, packed): packed = self.verifyb(packed) return msgpack.unpackb(packed, raw=False, encoding='utf-8')", "self._verify_key.verify(message) def unpack(self, packed): return self.unpackb(b64decode(packed)) def unpackb(self, packed): packed", "Signed message \"\"\" return self._signing_key.sign(message) def pack(self, doc): return b64encode(self.packb(doc)).decode()", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "('_box',) def __init__(self, key): self._box = nacl.secret.SecretBox(b64decode(key)) @staticmethod def keygen():", "packed = self.verifyb(packed) return msgpack.unpackb(packed, raw=False, encoding='utf-8') class BlackBox: \"\"\"Encryption", "message \"\"\" return self._signing_key.sign(message) def pack(self, doc): return b64encode(self.packb(doc)).decode() def", "(Salsa20/Poly1305). Warning per the SecretBox docs: Once you’ve decrypted the", "packed): return self.unpackb(b64decode(packed)) def unpackb(self, packed): packed = self.verifyb(packed) return", "in signing the result. If not provided, the ciphertext is", "verifier: ciphertext = verifier.verifyb(ciphertext) data = self._box.decrypt(ciphertext) return msgpack.unpackb(data, raw=False,", "(the \"License\"); # you may not use this file except", "attached. Arguments: message(bytes): Data to sign. Returns: bytes: Signed message", "# you may not use this file except in compliance", "verify. Returns: bytes: The orignal message, sans signature. \"\"\" return", "Base64-encoded ciphertext. Arguments: doc: The string, dict, array, or other", "Signer: \"\"\"Message signer based on Ed25519 and nacl.signing. Arguments: key", "\"\"\"Unpack Base64-encoded ciphertext. Arguments: ciphertext (bytes): Ciphertext to decrypt and", "verifier: An instance of Verifier to use in verifying the", "import nacl.secret import nacl.signing import nacl.utils from .version import __version__", "nacl.signing.SigningKey.generate() return ( signing_key.encode(nacl.encoding.Base64Encoder).decode(), signing_key.verify_key.encode(nacl.encoding.Base64Encoder).decode(), ) @staticmethod def vkey(skey): signing_key", "\"\"\" data = msgpack.packb(doc, encoding='utf-8', use_bin_type=True) ciphertext = self._box.encrypt(data) if", "sign. Returns: bytes: Signed message \"\"\" return self._signing_key.sign(message) def pack(self,", "# # Unless required by applicable law or agreed to", "nacl.encoding import nacl.secret import nacl.signing import nacl.utils from .version import", "use_bin_type=True) return self.signb(packed) class Verifier: \"\"\"Signature verifier based on Ed25519", "nacl.signing. Arguments: key (str): Base64-encoded verify key \"\"\" __slots__ =", "nacl.signing.VerifyKey(vkey, nacl.encoding.Base64Encoder) def verifyb(self, message): \"\"\"Verify a signed binary message.", "signing_key = nacl.signing.SigningKey.generate() return ( signing_key.encode(nacl.encoding.Base64Encoder).decode(), signing_key.verify_key.encode(nacl.encoding.Base64Encoder).decode(), ) @staticmethod def", "be unsigned. Returns: doc: Deserialized JSON-compatible object. \"\"\" ciphertext =", "def __init__(self, key): self._box = nacl.secret.SecretBox(b64decode(key)) @staticmethod def keygen(): return", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "return self.signb(packed) class Verifier: \"\"\"Signature verifier based on Ed25519 and", "so messages you send are repudiable. For non-repudiable messages, sign", "encoding='utf-8', use_bin_type=True) ciphertext = self._box.encrypt(data) if signer: ciphertext = signer.signb(ciphertext)", "ciphertext = b64decode(ciphertext) if verifier: ciphertext = verifier.verifyb(ciphertext) data =", "Version 2.0 (the \"License\"); # you may not use this", "serialize and encrypt. Keyword Arguments: signer: An instance of Signer", "Once you’ve decrypted the message you’ve demonstrated the ability to", "self._box = nacl.secret.SecretBox(b64decode(key)) @staticmethod def keygen(): return b64encode(nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)).decode() def encrypt(self,", "b64decode, b64encode import msgpack import nacl.encoding import nacl.secret import nacl.signing", "__slots__ = ('_verify_key',) def __init__(self, vkey): self._verify_key = nacl.signing.VerifyKey(vkey, nacl.encoding.Base64Encoder)", "implied. # See the License for the specific language governing", "Arguments: ciphertext (bytes): Ciphertext to decrypt and deserialize. Keyword Arguments:", "def verifyb(self, message): \"\"\"Verify a signed binary message. Arguments: message(bytes):", "under the Apache License, Version 2.0 (the \"License\"); # you", "self.signb(packed) class Verifier: \"\"\"Signature verifier based on Ed25519 and nacl.signing.", "based on PyNaCl's SecretBox (Salsa20/Poly1305). Warning per the SecretBox docs:", "= nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder) @staticmethod def keygen(): signing_key = nacl.signing.SigningKey.generate() return", "raw=False, encoding='utf-8') class BlackBox: \"\"\"Encryption engine based on PyNaCl's SecretBox", "= self._box.encrypt(data) if signer: ciphertext = signer.signb(ciphertext) return b64encode(ciphertext).decode() def", "by applicable law or agreed to in writing, software #", "self._signing_key.sign(message) def pack(self, doc): return b64encode(self.packb(doc)).decode() def packb(self, doc): packed", "to sign. Returns: bytes: Signed message \"\"\" return self._signing_key.sign(message) def", "use in verifying the signed ciphertext. If not provided, the", "per the SecretBox docs: Once you’ve decrypted the message you’ve", "verifier based on Ed25519 and nacl.signing. Arguments: key (str): Base64-encoded", "= ('_box',) def __init__(self, key): self._box = nacl.secret.SecretBox(b64decode(key)) @staticmethod def", "signed ciphertext. If not provided, the ciphertext is assumed to", "the License. from base64 import b64decode, b64encode import msgpack import", "key obtained from keygen() \"\"\" __slots__ = ('_signing_key',) def __init__(self,", "vkey(skey): signing_key = nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder) return signing_key.verify_key.encode(nacl.encoding.Base64Encoder) def signb(self, message):", "return ( signing_key.encode(nacl.encoding.Base64Encoder).decode(), signing_key.verify_key.encode(nacl.encoding.Base64Encoder).decode(), ) @staticmethod def vkey(skey): signing_key =", "An instance of Verifier to use in verifying the signed", "Copyright 2018 by <NAME> # # Licensed under the Apache", "= b64decode(ciphertext) if verifier: ciphertext = verifier.verifyb(ciphertext) data = self._box.decrypt(ciphertext)", "provided, the ciphertext is not signed. Returns: str: Ciphertext \"\"\"", "class Signer: \"\"\"Message signer based on Ed25519 and nacl.signing. Arguments:", "Data to sign. Returns: bytes: Signed message \"\"\" return self._signing_key.sign(message)", "= nacl.signing.VerifyKey(vkey, nacl.encoding.Base64Encoder) def verifyb(self, message): \"\"\"Verify a signed binary", "deserialize. Keyword Arguments: verifier: An instance of Verifier to use", "message(bytes): Data to verify. Returns: bytes: The orignal message, sans", "b64encode import msgpack import nacl.encoding import nacl.secret import nacl.signing import", "def unpack(self, packed): return self.unpackb(b64decode(packed)) def unpackb(self, packed): packed =", "to use in signing the result. If not provided, the", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "on PyNaCl's SecretBox (Salsa20/Poly1305). Warning per the SecretBox docs: Once", "Unless required by applicable law or agreed to in writing,", "not provided, the ciphertext is assumed to be unsigned. Returns:", ") @staticmethod def vkey(skey): signing_key = nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder) return signing_key.verify_key.encode(nacl.encoding.Base64Encoder)", "nacl.signing import nacl.utils from .version import __version__ # NOQA class", "Arguments: key (str): Base64-encoded verify key \"\"\" __slots__ = ('_verify_key',)", "ciphertext = self._box.encrypt(data) if signer: ciphertext = signer.signb(ciphertext) return b64encode(ciphertext).decode()", "the specific language governing permissions and # limitations under the", "ciphertext, verifier=None): \"\"\"Unpack Base64-encoded ciphertext. Arguments: ciphertext (bytes): Ciphertext to", "verifier=None): \"\"\"Unpack Base64-encoded ciphertext. Arguments: ciphertext (bytes): Ciphertext to decrypt", "Ciphertext to decrypt and deserialize. Keyword Arguments: verifier: An instance", "signer based on Ed25519 and nacl.signing. Arguments: key (str): Base64-encoded", "applicable law or agreed to in writing, software # distributed", "An instance of Signer to use in signing the result.", "__version__ # NOQA class Signer: \"\"\"Message signer based on Ed25519", "in writing, software # distributed under the License is distributed", "= nacl.signing.SigningKey(skey, nacl.encoding.Base64Encoder) return signing_key.verify_key.encode(nacl.encoding.Base64Encoder) def signb(self, message): \"\"\"Sign a", "array, or other JSON-compatible object to serialize and encrypt. Keyword", "if signer: ciphertext = signer.signb(ciphertext) return b64encode(ciphertext).decode() def decrypt(self, ciphertext,", "(str): Base64-encoded key obtained from keygen() \"\"\" __slots__ = ('_box',)", "obtained from keygen() \"\"\" __slots__ = ('_signing_key',) def __init__(self, skey):", "on Ed25519 and nacl.signing. Arguments: key (str): Base64-encoded verify key", "License. from base64 import b64decode, b64encode import msgpack import nacl.encoding", "return signing_key.verify_key.encode(nacl.encoding.Base64Encoder) def signb(self, message): \"\"\"Sign a binary message with", "\"\"\"Serialize and encrypt a document to Base64-encoded ciphertext. Arguments: doc:", "and deserialize. Keyword Arguments: verifier: An instance of Verifier to", "def pack(self, doc): return b64encode(self.packb(doc)).decode() def packb(self, doc): packed =", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "# You may obtain a copy of the License at", "b64encode(ciphertext).decode() def decrypt(self, ciphertext, verifier=None): \"\"\"Unpack Base64-encoded ciphertext. Arguments: ciphertext", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "# limitations under the License. from base64 import b64decode, b64encode", "Base64-encoded key obtained from keygen() \"\"\" __slots__ = ('_signing_key',) def", "(str): Base64-encoded key obtained from keygen() \"\"\" __slots__ = ('_signing_key',)", "nacl.encoding.Base64Encoder) return signing_key.verify_key.encode(nacl.encoding.Base64Encoder) def signb(self, message): \"\"\"Sign a binary message", "sign them after encryption. (See also: https://pynacl.readthedocs.io/en/stable/signing) Arguments: key (str):", "b64encode(nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)).decode() def encrypt(self, doc, signer=None): \"\"\"Serialize and encrypt a document", "encoding='utf-8') class BlackBox: \"\"\"Encryption engine based on PyNaCl's SecretBox (Salsa20/Poly1305).", "the License for the specific language governing permissions and #", "msgpack.packb(doc, encoding='utf-8', use_bin_type=True) return self.signb(packed) class Verifier: \"\"\"Signature verifier based", "Apache License, Version 2.0 (the \"License\"); # you may not", "= msgpack.packb(doc, encoding='utf-8', use_bin_type=True) ciphertext = self._box.encrypt(data) if signer: ciphertext", "either express or implied. # See the License for the", "signb(self, message): \"\"\"Sign a binary message with its signature attached.", "message with its signature attached. Arguments: message(bytes): Data to sign.", "@staticmethod def keygen(): signing_key = nacl.signing.SigningKey.generate() return ( signing_key.encode(nacl.encoding.Base64Encoder).decode(), signing_key.verify_key.encode(nacl.encoding.Base64Encoder).decode(),", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "SecretBox docs: Once you’ve decrypted the message you’ve demonstrated the", "ciphertext is not signed. Returns: str: Ciphertext \"\"\" data =", "orignal message, sans signature. \"\"\" return self._verify_key.verify(message) def unpack(self, packed):", "<filename>setec/__init__.py<gh_stars>0 # Copyright 2018 by <NAME> # # Licensed under", "nacl.signing. Arguments: key (str): Base64-encoded key obtained from keygen() \"\"\"", "message. Arguments: message(bytes): Data to verify. Returns: bytes: The orignal", "signing the result. If not provided, the ciphertext is not", "\"\"\"Encryption engine based on PyNaCl's SecretBox (Salsa20/Poly1305). Warning per the", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "signer=None): \"\"\"Serialize and encrypt a document to Base64-encoded ciphertext. Arguments:", "return self._verify_key.verify(message) def unpack(self, packed): return self.unpackb(b64decode(packed)) def unpackb(self, packed):", "vkey): self._verify_key = nacl.signing.VerifyKey(vkey, nacl.encoding.Base64Encoder) def verifyb(self, message): \"\"\"Verify a", "to create arbitrary valid messages, so messages you send are", "\"License\"); # you may not use this file except in", "non-repudiable messages, sign them after encryption. (See also: https://pynacl.readthedocs.io/en/stable/signing) Arguments:", "send are repudiable. For non-repudiable messages, sign them after encryption.", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "signer.signb(ciphertext) return b64encode(ciphertext).decode() def decrypt(self, ciphertext, verifier=None): \"\"\"Unpack Base64-encoded ciphertext.", "# distributed under the License is distributed on an \"AS", "decrypt and deserialize. Keyword Arguments: verifier: An instance of Verifier", "Arguments: message(bytes): Data to verify. Returns: bytes: The orignal message,", "string, dict, array, or other JSON-compatible object to serialize and", "# Unless required by applicable law or agreed to in", "\"\"\" __slots__ = ('_signing_key',) def __init__(self, skey): self._signing_key = nacl.signing.SigningKey(skey,", "self.unpackb(b64decode(packed)) def unpackb(self, packed): packed = self.verifyb(packed) return msgpack.unpackb(packed, raw=False,", "= self.verifyb(packed) return msgpack.unpackb(packed, raw=False, encoding='utf-8') class BlackBox: \"\"\"Encryption engine", "of Signer to use in signing the result. If not", "are repudiable. For non-repudiable messages, sign them after encryption. (See", "is assumed to be unsigned. Returns: doc: Deserialized JSON-compatible object.", "in verifying the signed ciphertext. If not provided, the ciphertext", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "and nacl.signing. Arguments: key (str): Base64-encoded key obtained from keygen()", "Base64-encoded key obtained from keygen() \"\"\" __slots__ = ('_box',) def", "You may obtain a copy of the License at #", "\"\"\" __slots__ = ('_verify_key',) def __init__(self, vkey): self._verify_key = nacl.signing.VerifyKey(vkey,", "return self.unpackb(b64decode(packed)) def unpackb(self, packed): packed = self.verifyb(packed) return msgpack.unpackb(packed,", "Warning per the SecretBox docs: Once you’ve decrypted the message", "to decrypt and deserialize. Keyword Arguments: verifier: An instance of", "the Apache License, Version 2.0 (the \"License\"); # you may", "bytes: Signed message \"\"\" return self._signing_key.sign(message) def pack(self, doc): return", "object to serialize and encrypt. Keyword Arguments: signer: An instance", "the ability to create arbitrary valid messages, so messages you", "ciphertext. Arguments: doc: The string, dict, array, or other JSON-compatible", "packed = msgpack.packb(doc, encoding='utf-8', use_bin_type=True) return self.signb(packed) class Verifier: \"\"\"Signature", "use in signing the result. If not provided, the ciphertext", "them after encryption. (See also: https://pynacl.readthedocs.io/en/stable/signing) Arguments: key (str): Base64-encoded" ]
[ "(works only for web browsers).\"\"\" bl_idname = 'LNDetectMobileBrowserNode' bl_label =", "only for web browsers).\"\"\" bl_idname = 'LNDetectMobileBrowserNode' bl_label = 'Detect", "'LNDetectMobileBrowserNode' bl_label = 'Detect Mobile Browser' arm_version = 1 def", "web browsers).\"\"\" bl_idname = 'LNDetectMobileBrowserNode' bl_label = 'Detect Mobile Browser'", "class DetectMobileBrowserNode(ArmLogicTreeNode): \"\"\"Determines the mobile browser or not (works only", "bl_label = 'Detect Mobile Browser' arm_version = 1 def init(self,", "= 'LNDetectMobileBrowserNode' bl_label = 'Detect Mobile Browser' arm_version = 1", "not (works only for web browsers).\"\"\" bl_idname = 'LNDetectMobileBrowserNode' bl_label", "'Detect Mobile Browser' arm_version = 1 def init(self, context): super(DetectMobileBrowserNode,", "\"\"\"Determines the mobile browser or not (works only for web", "bl_idname = 'LNDetectMobileBrowserNode' bl_label = 'Detect Mobile Browser' arm_version =", "Mobile Browser' arm_version = 1 def init(self, context): super(DetectMobileBrowserNode, self).init(context)", "browsers).\"\"\" bl_idname = 'LNDetectMobileBrowserNode' bl_label = 'Detect Mobile Browser' arm_version", "* class DetectMobileBrowserNode(ArmLogicTreeNode): \"\"\"Determines the mobile browser or not (works", "browser or not (works only for web browsers).\"\"\" bl_idname =", "from arm.logicnode.arm_nodes import * class DetectMobileBrowserNode(ArmLogicTreeNode): \"\"\"Determines the mobile browser", "Browser' arm_version = 1 def init(self, context): super(DetectMobileBrowserNode, self).init(context) self.add_output('NodeSocketBool',", "DetectMobileBrowserNode(ArmLogicTreeNode): \"\"\"Determines the mobile browser or not (works only for", "import * class DetectMobileBrowserNode(ArmLogicTreeNode): \"\"\"Determines the mobile browser or not", "or not (works only for web browsers).\"\"\" bl_idname = 'LNDetectMobileBrowserNode'", "for web browsers).\"\"\" bl_idname = 'LNDetectMobileBrowserNode' bl_label = 'Detect Mobile", "the mobile browser or not (works only for web browsers).\"\"\"", "arm.logicnode.arm_nodes import * class DetectMobileBrowserNode(ArmLogicTreeNode): \"\"\"Determines the mobile browser or", "arm_version = 1 def init(self, context): super(DetectMobileBrowserNode, self).init(context) self.add_output('NodeSocketBool', 'Mobile')", "= 'Detect Mobile Browser' arm_version = 1 def init(self, context):", "mobile browser or not (works only for web browsers).\"\"\" bl_idname" ]
[ "]), ('Cape Town', [ ('Cape Town City', []), ]) ]),", "from corehq.messaging.scheduling.models import AlertSchedule, SMSContent, AlertEvent from corehq.messaging.scheduling.scheduling_partitioned.dbaccessors import \\", "form_id=uuid.uuid4().hex, ) self._dump_and_load(Counter({ CaseUploadFileMeta: 1, CaseUploadRecord: 1, CaseUploadFormRecord: 1, }))", "= FormAccessors(cls.domain_name) cls.case_accessors = CaseAccessors(cls.domain_name) cls.product = make_product(cls.domain_name, 'A Product',", "[], [])), \"Not all SQL objects deleted\" @sharded class TestSQLDumpLoadShardedModels(BaseDumpLoadTest):", "corehq.apps.locations.tests.test_location_types import make_loc_type from corehq.apps.products.models import SQLProduct from corehq.apps.locations.models import", "the DB objects_remaining = list(get_objects_to_dump(self.domain_name, [], [])) object_classes = [obj.__class__.__name__", "make_loc_type('city', county, domain=self.domain_name) self._dump_and_load(expected_object_counts) hierarchy = LocationType.objects.full_hierarchy(self.domain_name) desired_hierarchy = {", "object is not callable\" ): greasy_spoon['spam'] def _normalize_object_counter(counter, for_loaded=False): \"\"\"Converts", "email='<EMAIL>', uuid=user_id ) self.addCleanup(user.delete, self.domain_name, deleted_by=None) DemoUserRestore( demo_user_id=user_id, restore_blob_id=uuid.uuid4().hex, content_length=1027,", "= FuzzyProperties.objects.filter(domain=self.domain_name) self.assertEqual(set(f.case_type for f in post_fuzzies), {'dog', 'owner'}) def", "keyed counter\"\"\" def _model_class_to_label(model_class): label = '{}.{}'.format(model_class._meta.app_label, model_class.__name__) return label", "event_name=EventTypes.NEW_CASE, url='example.com', user_id='user_id', ) self._dump_and_load(Counter({ZapierSubscription: 1})) @mock.patch(\"corehq.apps.dump_reload.sql.load.ENQUEUE_TIMEOUT\", 1) class TestSqlLoadWithError(BaseDumpLoadTest):", "Domain from corehq.apps.dump_reload.sql import SqlDataDumper, SqlDataLoader from corehq.apps.dump_reload.sql.dump import (", "sharded, ) from corehq.messaging.scheduling.scheduling_partitioned.models import ( AlertScheduleInstance, ) class BaseDumpLoadTest(TestCase):", "name='test3', is_archived=True) self._dump_and_load(expected_object_counts) self.assertEqual(2, SQLProduct.active_objects.filter(domain=self.domain_name).count()) all_active = SQLProduct.active_objects.filter(domain=self.domain_name).all() self.assertTrue(p1 in", "test_sms(self): from corehq.apps.sms.models import PhoneNumber, MessagingEvent, MessagingSubEvent expected_object_counts = Counter({PhoneNumber:", "from corehq.apps.sms.models import ( SQLMobileBackend, SQLMobileBackendMapping, ) domain_backend = SQLMobileBackend.objects.create(", ") self._dump_and_load(expected_object_counts) def test_message_scheduling(self): AlertScheduleInstance( schedule_instance_id=uuid.uuid4(), domain=self.domain_name, recipient_type='CommCareUser', recipient_id=uuid.uuid4().hex, current_event_num=0,", "domain=self.domain_name) city = make_loc_type('city', county, domain=self.domain_name) self._dump_and_load(expected_object_counts) hierarchy = LocationType.objects.full_hierarchy(self.domain_name)", "nottest from casexml.apps.case.mock import CaseFactory, CaseIndex, CaseStructure from corehq.apps.commtrack.helpers import", "}) user = CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>',", "= LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) post_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(post_ledger_values)) self.assertEqual(2, len(post_ledger_transactions)) self.assertEqual(pre_ledger_values[0].ledger_reference,", "LedgerTransaction, LedgerValue, XFormInstanceSQL, ) from corehq.form_processor.tests.utils import ( FormProcessorTestUtils, create_form_for_test,", "from django.contrib.admin.utils import NestedObjects from django.db import transaction, IntegrityError from", "couch_user_id=uuid.uuid4().hex, case_type='person', upload_file_meta=upload_file_meta, ) CaseUploadFormRecord.objects.create( case_upload_record=case_upload_record, form_id=uuid.uuid4().hex, ) self._dump_and_load(Counter({ CaseUploadFileMeta:", "MessagingEvent: 1, MessagingSubEvent: 1}) phone_number = PhoneNumber( domain=self.domain_name, owner_doc_type='CommCareCase', owner_id='fake-owner-id1',", "for f in post_fuzzies), {'dog', 'owner'}) def test_users(self): from corehq.apps.users.models", "XFormInstanceSQL: 2, BlobMeta: 2, CommCareCaseSQL: 2, CaseTransaction: 3, CommCareCaseIndexSQL: 1", "CaseSearchConfig: 1, FuzzyProperties: 2, }) pre_config, created = CaseSearchConfig.objects.get_or_create(pk=self.domain_name) pre_config.enabled", "for model \"{}\" missing raw arg'.format( receiver, model ) self.assertIn('raw',", "casexml.apps.case.mock import CaseFactory, CaseIndex, CaseStructure from corehq.apps.commtrack.helpers import make_product from", "return dump_lines def _parse_dump_output(self, output_stream): dump_output = output_stream.getvalue().split('\\n') dump_lines =", "= sorted(pre_ledger_transactions, key=lambda t: t.pk) post_ledger_transactions = sorted(post_ledger_transactions, key=lambda t:", "}) pre_cases = self.factory.create_or_update_case( CaseStructure( attrs={'case_name': 'child', 'update': {'age': 3,", "from io import StringIO import mock from django.contrib.admin.utils import NestedObjects", "make_loc_type('county', state, domain=self.domain_name) city = make_loc_type('city', county, domain=self.domain_name) self._dump_and_load(expected_object_counts) hierarchy", "Winelands', [ ('Stellenbosch', []), ('Paarl', []), ]), ('Cape Town', [", "', 'Alberton', 'Benoni', 'Springs'] ) def test_sms(self): from corehq.apps.sms.models import", "output_stream = StringIO() if dumper_fn: dumper_fn(output_stream) else: SqlDataDumper(self.domain_name, [], []).dump(output_stream)", "def test_message_scheduling(self): AlertScheduleInstance( schedule_instance_id=uuid.uuid4(), domain=self.domain_name, recipient_type='CommCareUser', recipient_id=uuid.uuid4().hex, current_event_num=0, schedule_iteration_num=1, next_event_due=datetime(2017,", "UserErrorEntry from corehq.apps.users.models import CommCareUser from django.contrib.auth.models import User expected_object_counts", "10) ], self.domain_name) submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id, 5) ], self.domain_name) pre_ledger_values", "delete_sql_data(self): delete_domain_sql_data_for_dump_load_test(self.domain_name) def tearDown(self): self.delete_sql_data() super(BaseDumpLoadTest, self).tearDown() def _dump_and_load(self, expected_dump_counts,", "LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) pre_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(pre_ledger_values)) self.assertEqual(2, len(pre_ledger_transactions)) self._dump_and_load(expected_object_counts) post_ledger_values", "output_stream): dump_output = output_stream.getvalue().split('\\n') dump_lines = [line.strip() for line in", "_model_class_to_label(model_class): label = '{}.{}'.format(model_class._meta.app_label, model_class.__name__) return label if for_loaded else", "SqlDataDumper(self.domain_name, [], []).dump(output_stream) self.delete_sql_data() # resave the product to force", "_parse_dump_output(self, output_stream): dump_output = output_stream.getvalue().split('\\n') dump_lines = [line.strip() for line", "self._dump_and_load(expected_object_counts) names = ['Cape Winelands', 'Paarl', 'Cape Town'] location_ids =", "StringIO() SqlDataDumper(self.domain_name, [], []).dump(output_stream) self.delete_sql_data() # resave the product to", "f.read() submit_form_locally(xml, self.domain_name) self._dump_and_load(expected_object_counts) def test_demo_user_restore(self): from corehq.apps.users.models import CommCareUser", "obj in objects_remaining] counts = Counter(object_classes) self.assertEqual([], objects_remaining, 'Not all", "test_device_logs(self): from corehq.apps.receiverwrapper.util import submit_form_locally from phonelog.models import DeviceReportEntry, ForceCloseEntry,", "import make_product from corehq.apps.commtrack.tests.util import get_single_balance_block from corehq.apps.domain.models import Domain", "test_zapier_subscription(self): ZapierSubscription.objects.create( domain=self.domain_name, case_type='case_type', event_name=EventTypes.NEW_CASE, url='example.com', user_id='user_id', ) self._dump_and_load(Counter({ZapierSubscription: 1}))", "'.' + receiver.__name__ if receiver_path in whitelist_receivers: continue args =", "for form in pre_forms)) for pre_form in pre_forms: post_form =", "SQLProduct.active_objects.filter(domain=self.domain_name).all() self.assertTrue(p1 in all_active) self.assertTrue(p2 in all_active) self.assertTrue(parchived not in", "created_by=None, created_via=None, email='<EMAIL>', ) ccuser_2 = CommCareUser.create( domain=self.domain_name, username='user_2', password='<PASSWORD>',", "make_loc_type('state', domain=self.domain_name) district = make_loc_type('district', state, domain=self.domain_name) section = make_loc_type('section',", "self.products[0].save() actual_model_counts, dump_lines = self._parse_dump_output(output_stream) self.assertEqual(actual_model_counts['products.sqlproduct'], 3) loader = SqlDataLoader()", "XFormInstanceSQL: 3, BlobMeta: 3, CommCareCaseSQL: 1, CaseTransaction: 3, LedgerValue: 1,", "# Load loader = SqlDataLoader(object_filter=load_filter) loaded_model_counts = loader.load_objects(dump_lines) normalized_expected_loaded_counts =", "nose.tools import nottest from casexml.apps.case.mock import CaseFactory, CaseIndex, CaseStructure from", "all_active = SQLProduct.active_objects.filter(domain=self.domain_name).all() self.assertTrue(p1 in all_active) self.assertTrue(p2 in all_active) self.assertTrue(parchived", "normalized_expected_loaded_counts = _normalize_object_counter(expected_load_counts, for_loaded=True) self.assertDictEqual(dict(normalized_expected_loaded_counts), dict(loaded_model_counts)) self.assertEqual(sum(expected_load_counts.values()), sum(loaded_model_counts.values())) return dump_lines", "\"\"\"Ensure that any post_save signal handlers have been updated to", "CommCareCaseSQL: 1, CaseTransaction: 3, LedgerValue: 1, LedgerTransaction: 2 }) case", "post_form.to_json()) def test_sql_dump_load_case(self): expected_object_counts = Counter({ XFormInstanceSQL: 2, BlobMeta: 2,", "1, SQLMobileBackend: 1, }) self.assertEqual(SQLMobileBackend.objects.first().domain, self.domain_name) self.assertEqual(SQLMobileBackendMapping.objects.first().domain, self.domain_name) def test_case_importer(self):", "= Counter({ XFormInstanceSQL: 3, BlobMeta: 3, CommCareCaseSQL: 1, CaseTransaction: 3,", "organization=org, slug='testp1', name='demop1', domain=self.domain_name ) self._dump_and_load(Counter({TransifexOrganization: 1, TransifexProject: 2})) def", "SMSContent()), (AlertEvent(minutes_to_wait=15), SMSContent()), ] ) self.addCleanup(lambda: delete_alert_schedule_instances_for_schedule(AlertScheduleInstance, schedule.schedule_id)) self._dump_and_load(Counter({AlertSchedule: 1,", "'district', 'city'] location_structure = [ ('Western Cape', [ ('Cape Winelands',", "state.id: ( state, { district.id: ( district, { section.id: (section,", "SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1') p2 = SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2') parchived =", "deleted: {}'.format(counts)) # Dump actual_model_counts, dump_lines = self._parse_dump_output(output_stream) expected_model_counts =", "= Counter({ User: 1, DeviceReportEntry: 7, UserEntry: 1, UserErrorEntry: 2,", "= Counter({ XFormInstanceSQL: 2, BlobMeta: 2 }) pre_forms = [", "test_too_many_params(self): def appender(item1, item2): return [item1, item2] greasy_spoon = DefaultDictWithKey(appender)", "= make_loc_type('state', domain=self.domain_name) district = make_loc_type('district', state, domain=self.domain_name) section =", "'update': {'age': 42}, 'create': True})), ] ) ) pre_cases[0] =", "), }, ), } self.assertEqual(hierarchy, desired_hierarchy) def test_location(self): from corehq.apps.locations.models", "with self.assertRaisesRegex( TypeError, \"'NoneType' object is not callable\" ): greasy_spoon['spam']", "3, 'diabetic': False}, 'create': True}, indices=[ CaseIndex(CaseStructure(attrs={'case_name': 'parent', 'update': {'age':", "from corehq.apps.locations.tests.test_location_types import make_loc_type expected_object_counts = Counter({LocationType: 7}) state =", "that there's no data left in the DB objects_remaining =", "county = make_loc_type('county', state, domain=self.domain_name) city = make_loc_type('city', county, domain=self.domain_name)", "model ) self.assertIn('raw', args, message) @nottest def delete_domain_sql_data_for_dump_load_test(domain_name): for model_class,", "pre_config.save() self._dump_and_load(expected_object_counts) post_config = CaseSearchConfig.objects.get(domain=self.domain_name) self.assertTrue(post_config.enabled) self.assertEqual(pre_config.fuzzy_properties, post_config.fuzzy_properties) post_fuzzies =", ") SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=domain_backend, backend_type=SQLMobileBackend.SMS, prefix='123', ) global_backend = SQLMobileBackend.objects.create(", "City'] ) result = SQLLocation.objects.get_locations_and_children([locations['Gauteng'].location_id]) self.assertItemsEqual( [loc.name for loc in", "domain=self.domain_name, backend=global_backend, backend_type=SQLMobileBackend.SMS, prefix='*', ) self._dump_and_load({ SQLMobileBackendMapping: 1, SQLMobileBackend: 1,", "False}, 'create': True}, indices=[ CaseIndex(CaseStructure(attrs={'case_name': 'parent', 'update': {'age': 42}, 'create':", "LocationType.objects.full_hierarchy(self.domain_name) desired_hierarchy = { state.id: ( state, { district.id: (", "json import uuid from collections import Counter from datetime import", "greasy_spoon = DefaultDictWithKey() with self.assertRaisesRegex( TypeError, \"'NoneType' object is not", "] for model in models: for receiver in post_save._live_receivers(model): receiver_path", "from corehq.apps.translations.models import TransifexProject, TransifexOrganization org = TransifexOrganization.objects.create(slug='test', name='demo', api_token='<PASSWORD>')", "cls.form_accessors = FormAccessors(cls.domain_name) cls.case_accessors = CaseAccessors(cls.domain_name) cls.product = make_product(cls.domain_name, 'A", "phonelog.models import DeviceReportEntry, ForceCloseEntry, UserEntry, UserErrorEntry from corehq.apps.users.models import CommCareUser", "import CommCareUser from corehq.apps.ota.models import DemoUserRestore from django.contrib.auth.models import User", "deleted_by=None) self._dump_and_load(expected_object_counts) def test_dump_roles(self): from corehq.apps.users.models import UserRole, Permissions, RoleAssignableBy,", "greasy_spoon['spam'] def test_no_factory(self): greasy_spoon = DefaultDictWithKey() with self.assertRaisesRegex( TypeError, \"'NoneType'", "= SQLMobileBackend.objects.create( domain=None, name='test-global-mobile-backend', display_name='Test Global Mobile Backend', hq_api_id='TGMB', inbound_api_key='test-global-mobile-backend-inbound-api-key',", "in all_active) self.assertTrue(p2 in all_active) self.assertTrue(parchived not in all_active) def", "post_case = self.case_accessors.get_case(pre_case.case_id) self.assertDictEqual(pre_case.to_json(), post_case.to_json()) def test_ledgers(self): expected_object_counts = Counter({", ").save() self._dump_and_load({AlertScheduleInstance: 1}) def test_mobile_backend(self): from corehq.apps.sms.models import ( SQLMobileBackend,", "[role1_loaded.get_id]) def test_device_logs(self): from corehq.apps.receiverwrapper.util import submit_form_locally from phonelog.models import", "domain=self.domain_name, username='webuser_t1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', ) self.addCleanup(ccuser_1.delete, self.domain_name, deleted_by=None)", "1, MessagingEvent: 1, MessagingSubEvent: 1}) phone_number = PhoneNumber( domain=self.domain_name, owner_doc_type='CommCareCase',", "import LocationType from corehq.apps.locations.tests.test_location_types import make_loc_type expected_object_counts = Counter({LocationType: 7})", "TransifexProject.objects.create( organization=org, slug='testp', name='demop', domain=self.domain_name ) TransifexProject.objects.create( organization=org, slug='testp1', name='demop1',", "result], ['Cape Winelands', 'Stellenbosch', 'Paarl', 'Cape Town', 'Cape Town City']", "self.assertEqual(greasy_spoon['spam'], ['spam']) greasy_spoon['spam'].append('spam') self.assertEqual(greasy_spoon['spam'], ['spam', 'spam']) def test_not_enough_params(self): def empty_list():", "get_single_balance_block from corehq.apps.domain.models import Domain from corehq.apps.dump_reload.sql import SqlDataDumper, SqlDataLoader", ") ) pre_cases[0] = self.factory.create_or_update_case(CaseStructure( case_id=pre_cases[0].case_id, attrs={'external_id': 'billie jean', 'update':", "handle 'raw' calls.\"\"\" whitelist_receivers = [ 'django_digest.models._post_save_persist_partial_digests' ] for model", "test_case_importer(self): from corehq.apps.case_importer.tracking.models import ( CaseUploadFileMeta, CaseUploadFormRecord, CaseUploadRecord, ) upload_file_meta", "Counter({ XFormInstanceSQL: 3, BlobMeta: 3, CommCareCaseSQL: 1, CaseTransaction: 3, LedgerValue:", "datetime import datetime from io import StringIO import mock from", "pre_cases: post_case = self.case_accessors.get_case(pre_case.case_id) self.assertDictEqual(pre_case.to_json(), post_case.to_json()) def test_ledgers(self): expected_object_counts =", "arguments but 1 was given' ): greasy_spoon['spam'] def test_too_many_params(self): def", "NestedObjects from django.db import transaction, IntegrityError from django.db.models.signals import post_delete,", ") self.addCleanup(user.delete, self.domain_name, deleted_by=None) with open('corehq/ex-submodules/couchforms/tests/data/devicelogs/devicelog.xml', 'rb') as f: xml", "setup_locations_and_types expected_object_counts = Counter({LocationType: 3, SQLLocation: 11}) location_type_names = ['province',", "(center, {}), }), }, ), county.id: ( county, {city.id: (city,", "as f: xml = f.read() submit_form_locally(xml, self.domain_name) self._dump_and_load(expected_object_counts) def test_demo_user_restore(self):", "name='test2'), SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3'), ] def test_load_error_queue_full(self): \"\"\"Blocks when sending", "self._dump_and_load(expected_object_counts) def test_dump_roles(self): from corehq.apps.users.models import UserRole, Permissions, RoleAssignableBy, RolePermission", "pre_cases)) for pre_case in pre_cases: post_case = self.case_accessors.get_case(pre_case.case_id) self.assertDictEqual(pre_case.to_json(), post_case.to_json())", "SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1'), SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2'), SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3'), ]", "BlobMeta: 2 }) pre_forms = [ create_form_for_test(self.domain_name), create_form_for_test(self.domain_name) ] self._dump_and_load(expected_object_counts)", "= NestedObjects(using=iterator.db) collector.collect(iterator) collector.delete() assert [] == list(get_objects_to_dump(domain_name, [], [])),", "sure that there's no data left in the DB objects_remaining", "label if for_loaded else label.lower() return Counter({ _model_class_to_label(model_class): count for", "'Cape Town City'] ) result = SQLLocation.objects.get_locations_and_children([locations['Gauteng'].location_id]) self.assertItemsEqual( [loc.name for", "dict(loaded_model_counts)) self.assertEqual(sum(expected_load_counts.values()), sum(loaded_model_counts.values())) return dump_lines def _parse_dump_output(self, output_stream): dump_output =", "FuzzyProperties.objects.filter(domain=self.domain_name) self.assertEqual(set(f.case_type for f in post_fuzzies), {'dog', 'owner'}) def test_users(self):", "names = ['Cape Winelands', 'Paarl', 'Cape Town'] location_ids = [locations[name].location_id", "delete_domain_sql_data_for_dump_load_test(self.domain_name) def tearDown(self): self.delete_sql_data() super(BaseDumpLoadTest, self).tearDown() def _dump_and_load(self, expected_dump_counts, load_filter=None,", "= LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(pre_ledger_values)) self.assertEqual(2, len(pre_ledger_transactions)) self._dump_and_load(expected_object_counts) post_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id)", "@classmethod def setUpClass(cls): post_delete.disconnect(zapier_subscription_post_delete, sender=ZapierSubscription) super(BaseDumpLoadTest, cls).setUpClass() cls.domain_name = uuid.uuid4().hex", "corehq.apps.users.models import CommCareUser from corehq.apps.ota.models import DemoUserRestore from django.contrib.auth.models import", "def test_location_type(self): from corehq.apps.locations.models import LocationType from corehq.apps.locations.tests.test_location_types import make_loc_type", "expected_model_counts = _normalize_object_counter(expected_dump_counts) self.assertDictEqual(dict(expected_model_counts), dict(actual_model_counts)) # Load loader = SqlDataLoader(object_filter=load_filter)", "LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(post_ledger_values)) self.assertEqual(2, len(post_ledger_transactions)) self.assertEqual(pre_ledger_values[0].ledger_reference, post_ledger_values[0].ledger_reference) self.assertDictEqual(pre_ledger_values[0].to_json(), post_ledger_values[0].to_json()) pre_ledger_transactions", "[loc.name for loc in result], ['Gauteng', 'Ekurhuleni ', 'Alberton', 'Benoni',", "], self.domain_name) pre_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) pre_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(pre_ledger_values))", "slug='testp1', name='demop1', domain=self.domain_name ) self._dump_and_load(Counter({TransifexOrganization: 1, TransifexProject: 2})) def test_filtered_dump_load(self):", "enlist(item): return [item] greasy_spoon = DefaultDictWithKey(enlist) self.assertEqual(greasy_spoon['spam'], ['spam']) greasy_spoon['spam'].append('spam') self.assertEqual(greasy_spoon['spam'],", "not in all_active) def test_location_type(self): from corehq.apps.locations.models import LocationType from", "district, { section.id: (section, {}), block.id: (block, { center.id: (center,", "greasy_spoon['spam'] def _normalize_object_counter(counter, for_loaded=False): \"\"\"Converts a <Model Class> keyed counter", "self.addCleanup(ccuser_1.delete, self.domain_name, deleted_by=None) self.addCleanup(ccuser_2.delete, self.domain_name, deleted_by=None) self.addCleanup(web_user.delete, self.domain_name, deleted_by=None) self._dump_and_load(expected_object_counts)", "[], []).dump(output_stream) self.delete_sql_data() # make sure that there's no data", "# Dump actual_model_counts, dump_lines = self._parse_dump_output(output_stream) expected_model_counts = _normalize_object_counter(expected_dump_counts) self.assertDictEqual(dict(expected_model_counts),", "to 'terminate' it.\"\"\" self._load_with_errors(chunk_size=2) def _load_with_errors(self, chunk_size): output_stream = StringIO()", "42}, 'create': True})), ] ) ) pre_cases[0] = self.factory.create_or_update_case(CaseStructure( case_id=pre_cases[0].case_id,", "'billie jean', 'update': {'name': '<NAME>'}} ))[0] self._dump_and_load(expected_object_counts) case_ids = self.case_accessors.get_case_ids_in_domain()", "case_type='case_type', event_name=EventTypes.NEW_CASE, url='example.com', user_id='user_id', ) self._dump_and_load(Counter({ZapierSubscription: 1})) @mock.patch(\"corehq.apps.dump_reload.sql.load.ENQUEUE_TIMEOUT\", 1) class", "sending ``None`` into the queue to 'terminate' it.\"\"\" self._load_with_errors(chunk_size=2) def", "\"Not all SQL objects deleted\" @sharded class TestSQLDumpLoadShardedModels(BaseDumpLoadTest): maxDiff =", "[], location_structure, ) self._dump_and_load(expected_object_counts) names = ['Cape Winelands', 'Paarl', 'Cape", "XFormInstanceSQL, ) from corehq.form_processor.tests.utils import ( FormProcessorTestUtils, create_form_for_test, sharded, )", "product_id='test3', name='test3', is_archived=True) self._dump_and_load(expected_object_counts) self.assertEqual(2, SQLProduct.active_objects.filter(domain=self.domain_name).count()) all_active = SQLProduct.active_objects.filter(domain=self.domain_name).all() self.assertTrue(p1", "test_no_factory(self): greasy_spoon = DefaultDictWithKey() with self.assertRaisesRegex( TypeError, \"'NoneType' object is", "SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=domain_backend, backend_type=SQLMobileBackend.SMS, prefix='123', ) global_backend = SQLMobileBackend.objects.create( domain=None,", "3, CommCareCaseIndexSQL: 1 }) pre_cases = self.factory.create_or_update_case( CaseStructure( attrs={'case_name': 'child',", "post_case.to_json()) def test_ledgers(self): expected_object_counts = Counter({ XFormInstanceSQL: 3, BlobMeta: 3,", "User expected_object_counts = Counter({ User: 1, DemoUserRestore: 1 }) user_id", "model \"{}\" missing raw arg'.format( receiver, model ) self.assertIn('raw', args,", "len(pre_ledger_transactions)) self._dump_and_load(expected_object_counts) post_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) post_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(post_ledger_values))", "positional argument: 'item2'\" ): greasy_spoon['spam'] def test_no_factory(self): greasy_spoon = DefaultDictWithKey()", "WebUser from django.contrib.auth.models import User expected_object_counts = Counter({User: 3}) ccuser_1", "expected_load_counts=Counter({SQLProduct: 1})) self.assertEqual(0, LocationType.objects.count()) def test_sms_content(self): from corehq.messaging.scheduling.models import AlertSchedule,", "2, ForceCloseEntry: 1 }) user = CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>',", "zapier_subscription_post_delete, ) from corehq.blobs.models import BlobMeta from corehq.form_processor.backends.sql.dbaccessors import LedgerAccessorSQL", "test_sql_dump_load_case(self): expected_object_counts = Counter({ XFormInstanceSQL: 2, BlobMeta: 2, CommCareCaseSQL: 2,", "pre_cases = self.factory.create_or_update_case( CaseStructure( attrs={'case_name': 'child', 'update': {'age': 3, 'diabetic':", ") self._dump_and_load(Counter({ZapierSubscription: 1})) @mock.patch(\"corehq.apps.dump_reload.sql.load.ENQUEUE_TIMEOUT\", 1) class TestSqlLoadWithError(BaseDumpLoadTest): def setUp(self): self.products", "import PhoneNumber, MessagingEvent, MessagingSubEvent expected_object_counts = Counter({PhoneNumber: 1, MessagingEvent: 1,", "+ receiver.__name__ if receiver_path in whitelist_receivers: continue args = inspect.getargspec(receiver).args", "in pre_forms)) for pre_form in pre_forms: post_form = self.form_accessors.get_form(pre_form.form_id) self.assertDictEqual(pre_form.to_json(),", "import SQLProduct from corehq.apps.locations.models import LocationType make_loc_type('state', domain=self.domain_name) SQLProduct.objects.create(domain=self.domain_name, product_id='test1',", "with open('corehq/ex-submodules/couchforms/tests/data/devicelogs/devicelog.xml', 'rb') as f: xml = f.read() submit_form_locally(xml, self.domain_name)", "p1 = SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1') p2 = SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2')", "self.addCleanup(user.delete, self.domain_name, deleted_by=None) DemoUserRestore( demo_user_id=user_id, restore_blob_id=uuid.uuid4().hex, content_length=1027, restore_comment=\"Test migrate demo", "('Paarl', []), ]), ('Cape Town', [ ('Cape Town City', []),", "for obj in objects_remaining] counts = Counter(object_classes) self.assertEqual([], objects_remaining, 'Not", "True}, indices=[ CaseIndex(CaseStructure(attrs={'case_name': 'parent', 'update': {'age': 42}, 'create': True})), ]", "whitelist_receivers = [ 'django_digest.models._post_save_persist_partial_digests' ] for model in models: for", "( get_model_iterator_builders_to_dump, get_objects_to_dump, ) from corehq.apps.dump_reload.sql.load import ( DefaultDictWithKey, constraint_checks_deferred,", "corehq.apps.dump_reload.sql.load import ( DefaultDictWithKey, constraint_checks_deferred, ) from corehq.apps.hqcase.utils import submit_case_blocks", "models = list(expected_dump_counts) self._check_signals_handle_raw(models) output_stream = StringIO() if dumper_fn: dumper_fn(output_stream)", "password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', uuid=user_id ) self.addCleanup(user.delete, self.domain_name, deleted_by=None) DemoUserRestore(", "password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', uuid='428d454aa9abc74e1964e16d3565d6b6' # match ID in devicelog.xml", "domain=self.domain_name) SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1') expected_object_counts = Counter({LocationType: 1, SQLProduct: 1})", "continue args = inspect.getargspec(receiver).args message = 'Signal handler \"{}\" for", "def setUp(self): self.products = [ SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1'), SQLProduct.objects.create(domain=self.domain_name, product_id='test2',", "dump_lines = self._parse_dump_output(output_stream) expected_model_counts = _normalize_object_counter(expected_dump_counts) self.assertDictEqual(dict(expected_model_counts), dict(actual_model_counts)) # Load", "open('corehq/ex-submodules/couchforms/tests/data/devicelogs/devicelog.xml', 'rb') as f: xml = f.read() submit_form_locally(xml, self.domain_name) self._dump_and_load(expected_object_counts)", "expected_object_counts = Counter({ XFormInstanceSQL: 3, BlobMeta: 3, CommCareCaseSQL: 1, CaseTransaction:", "SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2'), SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3'), ] def test_load_error_queue_full(self): \"\"\"Blocks", "test_location(self): from corehq.apps.locations.models import LocationType, SQLLocation from corehq.apps.locations.tests.util import setup_locations_and_types", "Town', [ ('Cape Town City', []), ]) ]), ('Gauteng', [", "the chunk size so that the queue blocks loader.load_objects(dump_lines) class", "import Domain from corehq.apps.dump_reload.sql import SqlDataDumper, SqlDataLoader from corehq.apps.dump_reload.sql.dump import", "= make_loc_type('city', county, domain=self.domain_name) self._dump_and_load(expected_object_counts) hierarchy = LocationType.objects.full_hierarchy(self.domain_name) desired_hierarchy =", "'Springs'] ) def test_sms(self): from corehq.apps.sms.models import PhoneNumber, MessagingEvent, MessagingSubEvent", "domain=self.domain_name) self._dump_and_load(expected_object_counts) hierarchy = LocationType.objects.full_hierarchy(self.domain_name) desired_hierarchy = { state.id: (", "county.id: ( county, {city.id: (city, {})}, ), }, ), }", "Load loader = SqlDataLoader(object_filter=load_filter) loaded_model_counts = loader.load_objects(dump_lines) normalized_expected_loaded_counts = _normalize_object_counter(expected_load_counts,", "make_product(cls.domain_name, 'A Product', 'prodcode_a') cls.default_objects_counts.update({SQLProduct: 1}) @classmethod def tearDownClass(cls): FormProcessorTestUtils.delete_all_cases_forms_ledgers(cls.domain_name)", "in post_fuzzies), {'dog', 'owner'}) def test_users(self): from corehq.apps.users.models import CommCareUser", "domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', uuid='428d454aa9abc74e1964e16d3565d6b6' # match ID", "None @classmethod def setUpClass(cls): super(TestSQLDumpLoadShardedModels, cls).setUpClass() cls.factory = CaseFactory(domain=cls.domain_name) cls.form_accessors", "from phonelog.models import DeviceReportEntry, ForceCloseEntry, UserEntry, UserErrorEntry from corehq.apps.users.models import", "self.assertEqual(set(case_ids), set(case.case_id for case in pre_cases)) for pre_case in pre_cases:", "SQLProduct from corehq.apps.locations.models import LocationType make_loc_type('state', domain=self.domain_name) SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1')", "pre_forms: post_form = self.form_accessors.get_form(pre_form.form_id) self.assertDictEqual(pre_form.to_json(), post_form.to_json()) def test_sql_dump_load_case(self): expected_object_counts =", "prefix='*', ) self._dump_and_load({ SQLMobileBackendMapping: 1, SQLMobileBackend: 1, }) self.assertEqual(SQLMobileBackend.objects.first().domain, self.domain_name)", "self.assertEqual([], objects_remaining, 'Not all data deleted: {}'.format(counts)) # Dump actual_model_counts,", "Town'] location_ids = [locations[name].location_id for name in names] result =", "deleted\" @sharded class TestSQLDumpLoadShardedModels(BaseDumpLoadTest): maxDiff = None @classmethod def setUpClass(cls):", "(AlertEvent(minutes_to_wait=15), SMSContent()), ] ) self.addCleanup(lambda: delete_alert_schedule_instances_for_schedule(AlertScheduleInstance, schedule.schedule_id)) self._dump_and_load(Counter({AlertSchedule: 1, AlertEvent:", ") self.addCleanup(user.delete, self.domain_name, deleted_by=None) DemoUserRestore( demo_user_id=user_id, restore_blob_id=uuid.uuid4().hex, content_length=1027, restore_comment=\"Test migrate", "domain=self.domain_name, owner_doc_type='CommCareCase', owner_id='fake-owner-id1', phone_number='99912341234', backend_id=None, ivr_backend_id=None, verified=True, is_two_way=True, pending_verification=False, contact_last_modified=datetime.utcnow()", "CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', uuid=user_id ) self.addCleanup(user.delete,", "dump_output if line.strip()] actual_model_counts = Counter([json.loads(line)['model'] for line in dump_lines])", ") upload_file_meta = CaseUploadFileMeta.objects.create( identifier=uuid.uuid4().hex, filename='picture.jpg', length=1024, ) case_upload_record =", "argument: 'item2'\" ): greasy_spoon['spam'] def test_no_factory(self): greasy_spoon = DefaultDictWithKey() with", "Global Mobile Backend', hq_api_id='TGMB', inbound_api_key='test-global-mobile-backend-inbound-api-key', supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS, is_global=True, ) SQLMobileBackendMapping.objects.create(", "3, LedgerValue: 1, LedgerTransaction: 2 }) case = self.factory.create_case() submit_case_blocks([", "import submit_case_blocks from corehq.apps.products.models import SQLProduct from corehq.apps.zapier.consts import EventTypes", "setup_locations_and_types( self.domain_name, location_type_names, [], location_structure, ) self._dump_and_load(expected_object_counts) names = ['Cape", "str(post)) class TestSQLDumpLoad(BaseDumpLoadTest): def test_case_search_config(self): from corehq.apps.case_search.models import CaseSearchConfig, FuzzyProperties", "[ ('Alberton', []), ('Benoni', []), ('Springs', []), ]), ]), ]", "= make_loc_type('section', district, domain=self.domain_name) block = make_loc_type('block', district, domain=self.domain_name) center", "that any post_save signal handlers have been updated to handle", "SQLLocation.objects.get_locations_and_children(location_ids) self.assertItemsEqual( [loc.name for loc in result], ['Cape Winelands', 'Stellenbosch',", "the queue blocks loader.load_objects(dump_lines) class DefaultDictWithKeyTests(SimpleTestCase): def test_intended_use_case(self): def enlist(item):", "dict(actual_model_counts)) # Load loader = SqlDataLoader(object_filter=load_filter) loaded_model_counts = loader.load_objects(dump_lines) normalized_expected_loaded_counts", "@mock.patch(\"corehq.apps.dump_reload.sql.load.ENQUEUE_TIMEOUT\", 1) class TestSqlLoadWithError(BaseDumpLoadTest): def setUp(self): self.products = [ SQLProduct.objects.create(domain=self.domain_name,", "[], [])) object_classes = [obj.__class__.__name__ for obj in objects_remaining] counts", "import Counter from datetime import datetime from io import StringIO", "Dump actual_model_counts, dump_lines = self._parse_dump_output(output_stream) expected_model_counts = _normalize_object_counter(expected_dump_counts) self.assertDictEqual(dict(expected_model_counts), dict(actual_model_counts))", ") from corehq.apps.hqcase.utils import submit_case_blocks from corehq.apps.products.models import SQLProduct from", "def test_sql_dump_load_case(self): expected_object_counts = Counter({ XFormInstanceSQL: 2, BlobMeta: 2, CommCareCaseSQL:", "in post_save._live_receivers(model): receiver_path = receiver.__module__ + '.' + receiver.__name__ if", "FuzzyProperties expected_object_counts = Counter({ CaseSearchConfig: 1, FuzzyProperties: 2, }) pre_config,", "{ state.id: ( state, { district.id: ( district, { section.id:", ") self.addCleanup(ccuser_1.delete, self.domain_name, deleted_by=None) self.addCleanup(ccuser_2.delete, self.domain_name, deleted_by=None) self.addCleanup(web_user.delete, self.domain_name, deleted_by=None)", "))[0] self._dump_and_load(expected_object_counts) case_ids = self.case_accessors.get_case_ids_in_domain() self.assertEqual(set(case_ids), set(case.case_id for case in", "= Counter([json.loads(line)['model'] for line in dump_lines]) return actual_model_counts, dump_lines def", "names] result = SQLLocation.objects.get_locations_and_children(location_ids) self.assertItemsEqual( [loc.name for loc in result],", "AlertEvent from corehq.messaging.scheduling.scheduling_partitioned.dbaccessors import \\ delete_alert_schedule_instances_for_schedule schedule = AlertSchedule.create_simple_alert(self.domain, SMSContent())", "'prodcode_a') cls.default_objects_counts.update({SQLProduct: 1}) @classmethod def tearDownClass(cls): FormProcessorTestUtils.delete_all_cases_forms_ledgers(cls.domain_name) super(TestSQLDumpLoadShardedModels, cls).tearDownClass() def", "expected_object_counts = Counter({ UserRole: 2, RolePermission: 11, RoleAssignableBy: 1 })", "content_length=1027, restore_comment=\"Test migrate demo user restore\" ).save() self._dump_and_load(expected_object_counts) def test_products(self):", "created_via=None, email='<EMAIL>', ) web_user = WebUser.create( domain=self.domain_name, username='webuser_t1', password='<PASSWORD>', created_by=None,", "]), ] location_types, locations = setup_locations_and_types( self.domain_name, location_type_names, [], location_structure,", "all_active) def test_location_type(self): from corehq.apps.locations.models import LocationType from corehq.apps.locations.tests.test_location_types import", "'Ekurhuleni ', 'Alberton', 'Benoni', 'Springs'] ) def test_sms(self): from corehq.apps.sms.models", "role1_loaded = UserRole.objects.get(id=role1.id) role2_loaded = UserRole.objects.get(id=role2.id) self.assertEqual(role1_loaded.permissions.to_list(), Permissions().to_list()) self.assertEqual(role1_loaded.assignable_by, [])", "if for_loaded else label.lower() return Counter({ _model_class_to_label(model_class): count for model_class,", "in whitelist_receivers: continue args = inspect.getargspec(receiver).args message = 'Signal handler", "backend_type=SQLMobileBackend.SMS, is_global=False, ) SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=domain_backend, backend_type=SQLMobileBackend.SMS, prefix='123', ) global_backend", ") CaseUploadFormRecord.objects.create( case_upload_record=case_upload_record, form_id=uuid.uuid4().hex, ) self._dump_and_load(Counter({ CaseUploadFileMeta: 1, CaseUploadRecord: 1,", "username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', ) ccuser_2 = CommCareUser.create( domain=self.domain_name,", "_normalize_object_counter(expected_dump_counts) self.assertDictEqual(dict(expected_model_counts), dict(actual_model_counts)) # Load loader = SqlDataLoader(object_filter=load_filter) loaded_model_counts =", "CommCareCaseSQL, LedgerTransaction, LedgerValue, XFormInstanceSQL, ) from corehq.form_processor.tests.utils import ( FormProcessorTestUtils,", "for pre_form in pre_forms: post_form = self.form_accessors.get_form(pre_form.form_id) self.assertDictEqual(pre_form.to_json(), post_form.to_json()) def", "email='<EMAIL>', ) web_user = WebUser.create( domain=self.domain_name, username='webuser_t1', password='<PASSWORD>', created_by=None, created_via=None,", "{ section.id: (section, {}), block.id: (block, { center.id: (center, {}),", "= expected_load_counts or expected_dump_counts expected_dump_counts.update(self.default_objects_counts) models = list(expected_dump_counts) self._check_signals_handle_raw(models) output_stream", "expected_object_counts = Counter({ XFormInstanceSQL: 2, BlobMeta: 2 }) pre_forms =", "properties=['name']), ] for fuzzy in pre_fuzzies: fuzzy.save() pre_config.fuzzy_properties.set(pre_fuzzies) pre_config.save() self._dump_and_load(expected_object_counts)", "domain=self.domain_name, date=datetime.utcnow(), source=MessagingEvent.SOURCE_REMINDER, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) MessagingSubEvent.objects.create( parent=event, date=datetime.utcnow(), recipient_type=MessagingEvent.RECIPIENT_CASE,", "def test_no_factory(self): greasy_spoon = DefaultDictWithKey() with self.assertRaisesRegex( TypeError, \"'NoneType' object", "return Counter({ _model_class_to_label(model_class): count for model_class, count in counter.items() })", ") self._dump_and_load(expected_object_counts) names = ['Cape Winelands', 'Paarl', 'Cape Town'] location_ids", "= f.read() submit_form_locally(xml, self.domain_name) self._dump_and_load(expected_object_counts) def test_demo_user_restore(self): from corehq.apps.users.models import", "self.assertTrue(p2 in all_active) self.assertTrue(parchived not in all_active) def test_location_type(self): from", "username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', uuid=user_id ) self.addCleanup(user.delete, self.domain_name, deleted_by=None)", "import make_loc_type expected_object_counts = Counter({LocationType: 7}) state = make_loc_type('state', domain=self.domain_name)", "import LedgerAccessorSQL from corehq.form_processor.interfaces.dbaccessors import ( CaseAccessors, FormAccessors, ) from", "name='demo', api_token='<PASSWORD>') TransifexProject.objects.create( organization=org, slug='testp', name='demop', domain=self.domain_name ) TransifexProject.objects.create( organization=org,", "loader = SqlDataLoader(object_filter=load_filter) loaded_model_counts = loader.load_objects(dump_lines) normalized_expected_loaded_counts = _normalize_object_counter(expected_load_counts, for_loaded=True)", "self.product._id, 5) ], self.domain_name) pre_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) pre_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id)", "= MessagingEvent.objects.create( domain=self.domain_name, date=datetime.utcnow(), source=MessagingEvent.SOURCE_REMINDER, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) MessagingSubEvent.objects.create( parent=event,", "Winelands', 'Stellenbosch', 'Paarl', 'Cape Town', 'Cape Town City'] ) result", "desired_hierarchy = { state.id: ( state, { district.id: ( district,", "CommCareUser from django.contrib.auth.models import User expected_object_counts = Counter({ User: 1,", "get_single_balance_block(case.case_id, self.product._id, 5) ], self.domain_name) pre_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) pre_ledger_transactions =", "self._load_with_errors(chunk_size=1) def test_load_error_queue_full_on_terminate(self): \"\"\"Blocks when sending ``None`` into the queue", "for line in dump_output if line.strip()] actual_model_counts = Counter([json.loads(line)['model'] for", "post_save from django.test import SimpleTestCase, TestCase from nose.tools import nottest", "backend_id=None, ivr_backend_id=None, verified=True, is_two_way=True, pending_verification=False, contact_last_modified=datetime.utcnow() ) phone_number.save() event =", "corehq.apps.sms.models import PhoneNumber, MessagingEvent, MessagingSubEvent expected_object_counts = Counter({PhoneNumber: 1, MessagingEvent:", "self.assertEqual(pre_ledger_values[0].ledger_reference, post_ledger_values[0].ledger_reference) self.assertDictEqual(pre_ledger_values[0].to_json(), post_ledger_values[0].to_json()) pre_ledger_transactions = sorted(pre_ledger_transactions, key=lambda t: t.pk)", "SQLMobileBackend, SQLMobileBackendMapping, ) domain_backend = SQLMobileBackend.objects.create( domain=self.domain_name, name='test-domain-mobile-backend', display_name='Test Domain", "11}) location_type_names = ['province', 'district', 'city'] location_structure = [ ('Western", "= SQLLocation.objects.get_locations_and_children([locations['Gauteng'].location_id]) self.assertItemsEqual( [loc.name for loc in result], ['Gauteng', 'Ekurhuleni", "pre_config, created = CaseSearchConfig.objects.get_or_create(pk=self.domain_name) pre_config.enabled = True pre_fuzzies = [", "into the queue to 'terminate' it.\"\"\" self._load_with_errors(chunk_size=2) def _load_with_errors(self, chunk_size):", "[] == list(get_objects_to_dump(domain_name, [], [])), \"Not all SQL objects deleted\"", "Mobile Backend', hq_api_id='TDMB', inbound_api_key='test-domain-mobile-backend-inbound-api-key', supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS, is_global=False, ) SQLMobileBackendMapping.objects.create( domain=self.domain_name,", "}) user_id = uuid.uuid4().hex user = CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>',", "( zapier_subscription_post_delete, ) from corehq.blobs.models import BlobMeta from corehq.form_processor.backends.sql.dbaccessors import", "corehq.apps.locations.models import LocationType from corehq.apps.locations.tests.test_location_types import make_loc_type expected_object_counts = Counter({LocationType:", "CommCareUser from corehq.apps.ota.models import DemoUserRestore from django.contrib.auth.models import User expected_object_counts", "fuzzy.save() pre_config.fuzzy_properties.set(pre_fuzzies) pre_config.save() self._dump_and_load(expected_object_counts) post_config = CaseSearchConfig.objects.get(domain=self.domain_name) self.assertTrue(post_config.enabled) self.assertEqual(pre_config.fuzzy_properties, post_config.fuzzy_properties)", ") from corehq.form_processor.tests.utils import ( FormProcessorTestUtils, create_form_for_test, sharded, ) from", "self.products = [ SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1'), SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2'), SQLProduct.objects.create(domain=self.domain_name,", "1), active=True, alert_schedule_id=uuid.uuid4(), ).save() self._dump_and_load({AlertScheduleInstance: 1}) def test_mobile_backend(self): from corehq.apps.sms.models", "SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1') expected_object_counts = Counter({LocationType: 1, SQLProduct: 1}) self._dump_and_load(expected_object_counts,", "import DemoUserRestore from django.contrib.auth.models import User expected_object_counts = Counter({ User:", "migrate demo user restore\" ).save() self._dump_and_load(expected_object_counts) def test_products(self): from corehq.apps.products.models", "make_loc_type expected_object_counts = Counter({LocationType: 7}) state = make_loc_type('state', domain=self.domain_name) district", "corehq.blobs.models import BlobMeta from corehq.form_processor.backends.sql.dbaccessors import LedgerAccessorSQL from corehq.form_processor.interfaces.dbaccessors import", "self.assertEqual(hierarchy, desired_hierarchy) def test_location(self): from corehq.apps.locations.models import LocationType, SQLLocation from", "self._dump_and_load(Counter({ CaseUploadFileMeta: 1, CaseUploadRecord: 1, CaseUploadFormRecord: 1, })) def test_transifex(self):", "MessagingEvent.objects.create( domain=self.domain_name, date=datetime.utcnow(), source=MessagingEvent.SOURCE_REMINDER, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) MessagingSubEvent.objects.create( parent=event, date=datetime.utcnow(),", "center = make_loc_type('center', block, domain=self.domain_name) county = make_loc_type('county', state, domain=self.domain_name)", "DefaultDictWithKey, constraint_checks_deferred, ) from corehq.apps.hqcase.utils import submit_case_blocks from corehq.apps.products.models import", "TransifexOrganization org = TransifexOrganization.objects.create(slug='test', name='demo', api_token='<PASSWORD>') TransifexProject.objects.create( organization=org, slug='testp', name='demop',", "self.product._id, 10) ], self.domain_name) submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id, 5) ], self.domain_name)", "from corehq.apps.receiverwrapper.util import submit_form_locally from phonelog.models import DeviceReportEntry, ForceCloseEntry, UserEntry,", "\"\"\"Blocks when sending 'test3'\"\"\" self._load_with_errors(chunk_size=1) def test_load_error_queue_full_on_terminate(self): \"\"\"Blocks when sending", "deleted_by=None) with open('corehq/ex-submodules/couchforms/tests/data/devicelogs/devicelog.xml', 'rb') as f: xml = f.read() submit_form_locally(xml,", "= UserRole.create( self.domain_name, 'role1', permissions=Permissions(edit_web_users=True), assignable_by=[role1.id] ) self.addCleanup(role1.delete) self.addCleanup(role2.delete) self._dump_and_load(expected_object_counts)", "jean', 'update': {'name': '<NAME>'}} ))[0] self._dump_and_load(expected_object_counts) case_ids = self.case_accessors.get_case_ids_in_domain() self.assertEqual(set(case_ids),", "counts = Counter(object_classes) self.assertEqual([], objects_remaining, 'Not all data deleted: {}'.format(counts))", "corehq.apps.locations.models import LocationType, SQLLocation from corehq.apps.locations.tests.util import setup_locations_and_types expected_object_counts =", "product_id='test1', name='test1') p2 = SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2') parchived = SQLProduct.objects.create(domain=self.domain_name,", "'diabetic': False}, 'create': True}, indices=[ CaseIndex(CaseStructure(attrs={'case_name': 'parent', 'update': {'age': 42},", "in pre_forms: post_form = self.form_accessors.get_form(pre_form.form_id) self.assertDictEqual(pre_form.to_json(), post_form.to_json()) def test_sql_dump_load_case(self): expected_object_counts", "1, UserErrorEntry: 2, ForceCloseEntry: 1 }) user = CommCareUser.create( domain=self.domain_name,", "receiver.__name__ if receiver_path in whitelist_receivers: continue args = inspect.getargspec(receiver).args message", "xml = f.read() submit_form_locally(xml, self.domain_name) self._dump_and_load(expected_object_counts) def test_demo_user_restore(self): from corehq.apps.users.models", "Backend', hq_api_id='TGMB', inbound_api_key='test-global-mobile-backend-inbound-api-key', supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS, is_global=True, ) SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=global_backend,", ") self.addCleanup(role1.delete) self.addCleanup(role2.delete) self._dump_and_load(expected_object_counts) role1_loaded = UserRole.objects.get(id=role1.id) role2_loaded = UserRole.objects.get(id=role2.id)", "'spam']) def test_not_enough_params(self): def empty_list(): return [] greasy_spoon = DefaultDictWithKey(empty_list)", "self.form_accessors.get_form(pre_form.form_id) self.assertDictEqual(pre_form.to_json(), post_form.to_json()) def test_sql_dump_load_case(self): expected_object_counts = Counter({ XFormInstanceSQL: 2,", "= CaseFactory(domain=cls.domain_name) cls.form_accessors = FormAccessors(cls.domain_name) cls.case_accessors = CaseAccessors(cls.domain_name) cls.product =", "permissions=Permissions(edit_web_users=True), assignable_by=[role1.id] ) self.addCleanup(role1.delete) self.addCleanup(role2.delete) self._dump_and_load(expected_object_counts) role1_loaded = UserRole.objects.get(id=role1.id) role2_loaded", "self.case_accessors.get_case(pre_case.case_id) self.assertDictEqual(pre_case.to_json(), post_case.to_json()) def test_ledgers(self): expected_object_counts = Counter({ XFormInstanceSQL: 3,", "or expected_dump_counts expected_dump_counts.update(self.default_objects_counts) models = list(expected_dump_counts) self._check_signals_handle_raw(models) output_stream = StringIO()", "builder in get_model_iterator_builders_to_dump(domain_name, [], []): for iterator in builder.querysets(): with", "= SQLLocation.objects.get_locations_and_children(location_ids) self.assertItemsEqual( [loc.name for loc in result], ['Cape Winelands',", "from django.contrib.auth.models import User expected_object_counts = Counter({ User: 1, DeviceReportEntry:", "1 was given' ): greasy_spoon['spam'] def test_too_many_params(self): def appender(item1, item2):", "1) class TestSqlLoadWithError(BaseDumpLoadTest): def setUp(self): self.products = [ SQLProduct.objects.create(domain=self.domain_name, product_id='test1',", "import post_delete, post_save from django.test import SimpleTestCase, TestCase from nose.tools", "( CaseAccessors, FormAccessors, ) from corehq.form_processor.models import ( CaseTransaction, CommCareCaseIndexSQL,", ") MessagingSubEvent.objects.create( parent=event, date=datetime.utcnow(), recipient_type=MessagingEvent.RECIPIENT_CASE, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) self._dump_and_load(expected_object_counts) def", "[item] greasy_spoon = DefaultDictWithKey(enlist) self.assertEqual(greasy_spoon['spam'], ['spam']) greasy_spoon['spam'].append('spam') self.assertEqual(greasy_spoon['spam'], ['spam', 'spam'])", "= CaseSearchConfig.objects.get(domain=self.domain_name) self.assertTrue(post_config.enabled) self.assertEqual(pre_config.fuzzy_properties, post_config.fuzzy_properties) post_fuzzies = FuzzyProperties.objects.filter(domain=self.domain_name) self.assertEqual(set(f.case_type for", "CaseUploadFormRecord, CaseUploadRecord, ) upload_file_meta = CaseUploadFileMeta.objects.create( identifier=uuid.uuid4().hex, filename='picture.jpg', length=1024, )", "positional arguments but 1 was given' ): greasy_spoon['spam'] def test_too_many_params(self):", "from corehq.apps.products.models import SQLProduct from corehq.apps.locations.models import LocationType make_loc_type('state', domain=self.domain_name)", "self.addCleanup(user.delete, self.domain_name, deleted_by=None) with open('corehq/ex-submodules/couchforms/tests/data/devicelogs/devicelog.xml', 'rb') as f: xml =", "class TestSQLDumpLoadShardedModels(BaseDumpLoadTest): maxDiff = None @classmethod def setUpClass(cls): super(TestSQLDumpLoadShardedModels, cls).setUpClass()", "= Counter({User: 3}) ccuser_1 = CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None,", "email='<EMAIL>', ) ccuser_2 = CommCareUser.create( domain=self.domain_name, username='user_2', password='<PASSWORD>', created_by=None, created_via=None,", "corehq.apps.users.models import CommCareUser from corehq.apps.users.models import WebUser from django.contrib.auth.models import", "in zip(pre_ledger_transactions, post_ledger_transactions): self.assertEqual(str(pre), str(post)) class TestSQLDumpLoad(BaseDumpLoadTest): def test_case_search_config(self): from", "result = SQLLocation.objects.get_locations_and_children(location_ids) self.assertItemsEqual( [loc.name for loc in result], ['Cape", "cls).setUpClass() cls.factory = CaseFactory(domain=cls.domain_name) cls.form_accessors = FormAccessors(cls.domain_name) cls.case_accessors = CaseAccessors(cls.domain_name)", "SQLLocation.objects.get_locations_and_children([locations['Gauteng'].location_id]) self.assertItemsEqual( [loc.name for loc in result], ['Gauteng', 'Ekurhuleni ',", "self.assertEqual(sum(expected_load_counts.values()), sum(loaded_model_counts.values())) return dump_lines def _parse_dump_output(self, output_stream): dump_output = output_stream.getvalue().split('\\n')", "corehq.apps.translations.models import TransifexProject, TransifexOrganization org = TransifexOrganization.objects.create(slug='test', name='demo', api_token='<PASSWORD>') TransifexProject.objects.create(", "sum(loaded_model_counts.values())) return dump_lines def _parse_dump_output(self, output_stream): dump_output = output_stream.getvalue().split('\\n') dump_lines", "DeviceReportEntry, ForceCloseEntry, UserEntry, UserErrorEntry from corehq.apps.users.models import CommCareUser from django.contrib.auth.models", "role1 = UserRole.create(self.domain_name, 'role1') role2 = UserRole.create( self.domain_name, 'role1', permissions=Permissions(edit_web_users=True),", "actual_model_counts, dump_lines = self._parse_dump_output(output_stream) self.assertEqual(actual_model_counts['products.sqlproduct'], 3) loader = SqlDataLoader() with", "test_message_scheduling(self): AlertScheduleInstance( schedule_instance_id=uuid.uuid4(), domain=self.domain_name, recipient_type='CommCareUser', recipient_id=uuid.uuid4().hex, current_event_num=0, schedule_iteration_num=1, next_event_due=datetime(2017, 3,", "1, FuzzyProperties: 2, }) pre_config, created = CaseSearchConfig.objects.get_or_create(pk=self.domain_name) pre_config.enabled =", "ivr_backend_id=None, verified=True, is_two_way=True, pending_verification=False, contact_last_modified=datetime.utcnow() ) phone_number.save() event = MessagingEvent.objects.create(", "self.assertEqual(2, SQLProduct.active_objects.filter(domain=self.domain_name).count()) all_active = SQLProduct.active_objects.filter(domain=self.domain_name).all() self.assertTrue(p1 in all_active) self.assertTrue(p2 in", "in dump_output if line.strip()] actual_model_counts = Counter([json.loads(line)['model'] for line in", "1, }) self.assertEqual(SQLMobileBackend.objects.first().domain, self.domain_name) self.assertEqual(SQLMobileBackendMapping.objects.first().domain, self.domain_name) def test_case_importer(self): from corehq.apps.case_importer.tracking.models", "delete_domain_sql_data_for_dump_load_test(domain_name): for model_class, builder in get_model_iterator_builders_to_dump(domain_name, [], []): for iterator", "= make_loc_type('county', state, domain=self.domain_name) city = make_loc_type('city', county, domain=self.domain_name) self._dump_and_load(expected_object_counts)", "= SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3', is_archived=True) self._dump_and_load(expected_object_counts) self.assertEqual(2, SQLProduct.active_objects.filter(domain=self.domain_name).count()) all_active =", "cls.domain.delete() super(BaseDumpLoadTest, cls).tearDownClass() post_delete.connect(zapier_subscription_post_delete, sender=ZapierSubscription) def delete_sql_data(self): delete_domain_sql_data_for_dump_load_test(self.domain_name) def tearDown(self):", "state, domain=self.domain_name) section = make_loc_type('section', district, domain=self.domain_name) block = make_loc_type('block',", "is_global=True, ) SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=global_backend, backend_type=SQLMobileBackend.SMS, prefix='*', ) self._dump_and_load({ SQLMobileBackendMapping:", "item2): return [item1, item2] greasy_spoon = DefaultDictWithKey(appender) with self.assertRaisesRegex( TypeError,", "from corehq.apps.case_importer.tracking.models import ( CaseUploadFileMeta, CaseUploadFormRecord, CaseUploadRecord, ) upload_file_meta =", "[]), ('Springs', []), ]), ]), ] location_types, locations = setup_locations_and_types(", "domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', ) ccuser_2 = CommCareUser.create(", "patch the chunk size so that the queue blocks loader.load_objects(dump_lines)", "( FormProcessorTestUtils, create_form_for_test, sharded, ) from corehq.messaging.scheduling.scheduling_partitioned.models import ( AlertScheduleInstance,", "attrs={'external_id': 'billie jean', 'update': {'name': '<NAME>'}} ))[0] self._dump_and_load(expected_object_counts) case_ids =", "with transaction.atomic(using=iterator.db), \\ constraint_checks_deferred(iterator.db): collector = NestedObjects(using=iterator.db) collector.collect(iterator) collector.delete() assert", "status=MessagingEvent.STATUS_COMPLETED ) MessagingSubEvent.objects.create( parent=event, date=datetime.utcnow(), recipient_type=MessagingEvent.RECIPIENT_CASE, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) self._dump_and_load(expected_object_counts)", "with self.assertRaisesRegex( TypeError, r'empty_list\\(\\) takes 0 positional arguments but 1", ") from corehq.blobs.models import BlobMeta from corehq.form_processor.backends.sql.dbaccessors import LedgerAccessorSQL from", "state, { district.id: ( district, { section.id: (section, {}), block.id:", "})) def test_transifex(self): from corehq.apps.translations.models import TransifexProject, TransifexOrganization org =", "is_archived=True) self._dump_and_load(expected_object_counts) self.assertEqual(2, SQLProduct.active_objects.filter(domain=self.domain_name).count()) all_active = SQLProduct.active_objects.filter(domain=self.domain_name).all() self.assertTrue(p1 in all_active)", "def test_ledgers(self): expected_object_counts = Counter({ XFormInstanceSQL: 3, BlobMeta: 3, CommCareCaseSQL:", "corehq.apps.dump_reload.sql.dump import ( get_model_iterator_builders_to_dump, get_objects_to_dump, ) from corehq.apps.dump_reload.sql.load import (", "BlobMeta from corehq.form_processor.backends.sql.dbaccessors import LedgerAccessorSQL from corehq.form_processor.interfaces.dbaccessors import ( CaseAccessors,", ") ccuser_2 = CommCareUser.create( domain=self.domain_name, username='user_2', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>',", "'Cape Town'] location_ids = [locations[name].location_id for name in names] result", "}) self.assertEqual(SQLMobileBackend.objects.first().domain, self.domain_name) self.assertEqual(SQLMobileBackendMapping.objects.first().domain, self.domain_name) def test_case_importer(self): from corehq.apps.case_importer.tracking.models import", "self.domain_name) submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id, 5) ], self.domain_name) pre_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id)", "handlers have been updated to handle 'raw' calls.\"\"\" whitelist_receivers =", "SMSContent()), ] ) self.addCleanup(lambda: delete_alert_schedule_instances_for_schedule(AlertScheduleInstance, schedule.schedule_id)) self._dump_and_load(Counter({AlertSchedule: 1, AlertEvent: 2,", "1, })) def test_transifex(self): from corehq.apps.translations.models import TransifexProject, TransifexOrganization org", "1}) self._dump_and_load(expected_object_counts, load_filter='sqlproduct', expected_load_counts=Counter({SQLProduct: 1})) self.assertEqual(0, LocationType.objects.count()) def test_sms_content(self): from", "upload_file_meta = CaseUploadFileMeta.objects.create( identifier=uuid.uuid4().hex, filename='picture.jpg', length=1024, ) case_upload_record = CaseUploadRecord.objects.create(", "SQLLocation: 11}) location_type_names = ['province', 'district', 'city'] location_structure = [", "models: for receiver in post_save._live_receivers(model): receiver_path = receiver.__module__ + '.'", "'Signal handler \"{}\" for model \"{}\" missing raw arg'.format( receiver,", "def tearDownClass(cls): FormProcessorTestUtils.delete_all_cases_forms_ledgers(cls.domain_name) super(TestSQLDumpLoadShardedModels, cls).tearDownClass() def test_dump_load_form(self): expected_object_counts = Counter({", "dumper_fn=None): expected_load_counts = expected_load_counts or expected_dump_counts expected_dump_counts.update(self.default_objects_counts) models = list(expected_dump_counts)", "cls.default_objects_counts.update({SQLProduct: 1}) @classmethod def tearDownClass(cls): FormProcessorTestUtils.delete_all_cases_forms_ledgers(cls.domain_name) super(TestSQLDumpLoadShardedModels, cls).tearDownClass() def test_dump_load_form(self):", "test_dump_roles(self): from corehq.apps.users.models import UserRole, Permissions, RoleAssignableBy, RolePermission expected_object_counts =", "super(TestSQLDumpLoadShardedModels, cls).tearDownClass() def test_dump_load_form(self): expected_object_counts = Counter({ XFormInstanceSQL: 2, BlobMeta:", "1 }) pre_cases = self.factory.create_or_update_case( CaseStructure( attrs={'case_name': 'child', 'update': {'age':", "import nottest from casexml.apps.case.mock import CaseFactory, CaseIndex, CaseStructure from corehq.apps.commtrack.helpers", "self.assertItemsEqual( [loc.name for loc in result], ['Gauteng', 'Ekurhuleni ', 'Alberton',", "('Cape Winelands', [ ('Stellenbosch', []), ('Paarl', []), ]), ('Cape Town',", "self._dump_and_load(expected_object_counts) def test_message_scheduling(self): AlertScheduleInstance( schedule_instance_id=uuid.uuid4(), domain=self.domain_name, recipient_type='CommCareUser', recipient_id=uuid.uuid4().hex, current_event_num=0, schedule_iteration_num=1,", "SqlDataLoader() with self.assertRaises(IntegrityError),\\ mock.patch(\"corehq.apps.dump_reload.sql.load.CHUNK_SIZE\", chunk_size): # patch the chunk size", "SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3', is_archived=True) self._dump_and_load(expected_object_counts) self.assertEqual(2, SQLProduct.active_objects.filter(domain=self.domain_name).count()) all_active = SQLProduct.active_objects.filter(domain=self.domain_name).all()", "CommCareCaseSQL: 2, CaseTransaction: 3, CommCareCaseIndexSQL: 1 }) pre_cases = self.factory.create_or_update_case(", "zip(pre_ledger_transactions, post_ledger_transactions): self.assertEqual(str(pre), str(post)) class TestSQLDumpLoad(BaseDumpLoadTest): def test_case_search_config(self): from corehq.apps.case_search.models", "receiver.__module__ + '.' + receiver.__name__ if receiver_path in whitelist_receivers: continue", "corehq.apps.users.models import WebUser from django.contrib.auth.models import User expected_object_counts = Counter({User:", "= [ ('Western Cape', [ ('Cape Winelands', [ ('Stellenbosch', []),", "= self.factory.create_or_update_case(CaseStructure( case_id=pre_cases[0].case_id, attrs={'external_id': 'billie jean', 'update': {'name': '<NAME>'}} ))[0]", "self.delete_sql_data() # resave the product to force an error self.products[0].save()", "= [ create_form_for_test(self.domain_name), create_form_for_test(self.domain_name) ] self._dump_and_load(expected_object_counts) form_ids = self.form_accessors.get_all_form_ids_in_domain('XFormInstance') self.assertEqual(set(form_ids),", "get_single_balance_block(case.case_id, self.product._id, 10) ], self.domain_name) submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id, 5) ],", "from corehq.apps.locations.models import LocationType make_loc_type('state', domain=self.domain_name) SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1') expected_object_counts", "in get_model_iterator_builders_to_dump(domain_name, [], []): for iterator in builder.querysets(): with transaction.atomic(using=iterator.db),", "test_mobile_backend(self): from corehq.apps.sms.models import ( SQLMobileBackend, SQLMobileBackendMapping, ) domain_backend =", "an error self.products[0].save() actual_model_counts, dump_lines = self._parse_dump_output(output_stream) self.assertEqual(actual_model_counts['products.sqlproduct'], 3) loader", "self.addCleanup(role1.delete) self.addCleanup(role2.delete) self._dump_and_load(expected_object_counts) role1_loaded = UserRole.objects.get(id=role1.id) role2_loaded = UserRole.objects.get(id=role2.id) self.assertEqual(role1_loaded.permissions.to_list(),", "url='example.com', user_id='user_id', ) self._dump_and_load(Counter({ZapierSubscription: 1})) @mock.patch(\"corehq.apps.dump_reload.sql.load.ENQUEUE_TIMEOUT\", 1) class TestSqlLoadWithError(BaseDumpLoadTest): def", "created_via=None, email='<EMAIL>', ) ccuser_2 = CommCareUser.create( domain=self.domain_name, username='user_2', password='<PASSWORD>', created_by=None,", "= Counter({}) @classmethod def tearDownClass(cls): cls.domain.delete() super(BaseDumpLoadTest, cls).tearDownClass() post_delete.connect(zapier_subscription_post_delete, sender=ZapierSubscription)", "self._check_signals_handle_raw(models) output_stream = StringIO() if dumper_fn: dumper_fn(output_stream) else: SqlDataDumper(self.domain_name, [],", "= Counter({LocationType: 3, SQLLocation: 11}) location_type_names = ['province', 'district', 'city']", "def test_not_enough_params(self): def empty_list(): return [] greasy_spoon = DefaultDictWithKey(empty_list) with", "corehq.apps.commtrack.helpers import make_product from corehq.apps.commtrack.tests.util import get_single_balance_block from corehq.apps.domain.models import", "cls.domain.save() cls.default_objects_counts = Counter({}) @classmethod def tearDownClass(cls): cls.domain.delete() super(BaseDumpLoadTest, cls).tearDownClass()", "backend_type=SQLMobileBackend.SMS, prefix='123', ) global_backend = SQLMobileBackend.objects.create( domain=None, name='test-global-mobile-backend', display_name='Test Global", "Counter({}) @classmethod def tearDownClass(cls): cls.domain.delete() super(BaseDumpLoadTest, cls).tearDownClass() post_delete.connect(zapier_subscription_post_delete, sender=ZapierSubscription) def", "self.assertRaisesRegex( TypeError, r'empty_list\\(\\) takes 0 positional arguments but 1 was", "SQLProduct from corehq.apps.zapier.consts import EventTypes from corehq.apps.zapier.models import ZapierSubscription from", "import User expected_object_counts = Counter({User: 3}) ccuser_1 = CommCareUser.create( domain=self.domain_name,", "import transaction, IntegrityError from django.db.models.signals import post_delete, post_save from django.test", "MessagingEvent, MessagingSubEvent expected_object_counts = Counter({PhoneNumber: 1, MessagingEvent: 1, MessagingSubEvent: 1})", "in models: for receiver in post_save._live_receivers(model): receiver_path = receiver.__module__ +", "Permissions, RoleAssignableBy, RolePermission expected_object_counts = Counter({ UserRole: 2, RolePermission: 11,", "MessagingSubEvent.objects.create( parent=event, date=datetime.utcnow(), recipient_type=MessagingEvent.RECIPIENT_CASE, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) self._dump_and_load(expected_object_counts) def test_message_scheduling(self):", "{ district.id: ( district, { section.id: (section, {}), block.id: (block,", "= loader.load_objects(dump_lines) normalized_expected_loaded_counts = _normalize_object_counter(expected_load_counts, for_loaded=True) self.assertDictEqual(dict(normalized_expected_loaded_counts), dict(loaded_model_counts)) self.assertEqual(sum(expected_load_counts.values()), sum(loaded_model_counts.values()))", "from corehq.apps.dump_reload.sql import SqlDataDumper, SqlDataLoader from corehq.apps.dump_reload.sql.dump import ( get_model_iterator_builders_to_dump,", "2 }) case = self.factory.create_case() submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id, 10) ],", "district = make_loc_type('district', state, domain=self.domain_name) section = make_loc_type('section', district, domain=self.domain_name)", "{'name': '<NAME>'}} ))[0] self._dump_and_load(expected_object_counts) case_ids = self.case_accessors.get_case_ids_in_domain() self.assertEqual(set(case_ids), set(case.case_id for", "def tearDown(self): self.delete_sql_data() super(BaseDumpLoadTest, self).tearDown() def _dump_and_load(self, expected_dump_counts, load_filter=None, expected_load_counts=None,", "ZapierSubscription.objects.create( domain=self.domain_name, case_type='case_type', event_name=EventTypes.NEW_CASE, url='example.com', user_id='user_id', ) self._dump_and_load(Counter({ZapierSubscription: 1})) @mock.patch(\"corehq.apps.dump_reload.sql.load.ENQUEUE_TIMEOUT\",", "self.assertEqual(actual_model_counts['products.sqlproduct'], 3) loader = SqlDataLoader() with self.assertRaises(IntegrityError),\\ mock.patch(\"corehq.apps.dump_reload.sql.load.CHUNK_SIZE\", chunk_size): #", "UserRole.create( self.domain_name, 'role1', permissions=Permissions(edit_web_users=True), assignable_by=[role1.id] ) self.addCleanup(role1.delete) self.addCleanup(role2.delete) self._dump_and_load(expected_object_counts) role1_loaded", "verified=True, is_two_way=True, pending_verification=False, contact_last_modified=datetime.utcnow() ) phone_number.save() event = MessagingEvent.objects.create( domain=self.domain_name,", "import SimpleTestCase, TestCase from nose.tools import nottest from casexml.apps.case.mock import", "= CommCareUser.create( domain=self.domain_name, username='user_2', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', ) web_user", ") self.addCleanup(lambda: delete_alert_schedule_instances_for_schedule(AlertScheduleInstance, schedule.schedule_id)) self._dump_and_load(Counter({AlertSchedule: 1, AlertEvent: 2, SMSContent: 2}))", "\"{}\" for model \"{}\" missing raw arg'.format( receiver, model )", "Class> keyed counter to an model label keyed counter\"\"\" def", "FormProcessorTestUtils, create_form_for_test, sharded, ) from corehq.messaging.scheduling.scheduling_partitioned.models import ( AlertScheduleInstance, )", "line in dump_output if line.strip()] actual_model_counts = Counter([json.loads(line)['model'] for line", "SMSContent, AlertEvent from corehq.messaging.scheduling.scheduling_partitioned.dbaccessors import \\ delete_alert_schedule_instances_for_schedule schedule = AlertSchedule.create_simple_alert(self.domain,", "prefix='123', ) global_backend = SQLMobileBackend.objects.create( domain=None, name='test-global-mobile-backend', display_name='Test Global Mobile", "form in pre_forms)) for pre_form in pre_forms: post_form = self.form_accessors.get_form(pre_form.form_id)", "from corehq.messaging.scheduling.scheduling_partitioned.dbaccessors import \\ delete_alert_schedule_instances_for_schedule schedule = AlertSchedule.create_simple_alert(self.domain, SMSContent()) schedule.set_custom_alert(", "self.assertEqual(2, len(post_ledger_transactions)) self.assertEqual(pre_ledger_values[0].ledger_reference, post_ledger_values[0].ledger_reference) self.assertDictEqual(pre_ledger_values[0].to_json(), post_ledger_values[0].to_json()) pre_ledger_transactions = sorted(pre_ledger_transactions, key=lambda", "create_form_for_test(self.domain_name), create_form_for_test(self.domain_name) ] self._dump_and_load(expected_object_counts) form_ids = self.form_accessors.get_all_form_ids_in_domain('XFormInstance') self.assertEqual(set(form_ids), set(form.form_id for", "for_loaded=True) self.assertDictEqual(dict(normalized_expected_loaded_counts), dict(loaded_model_counts)) self.assertEqual(sum(expected_load_counts.values()), sum(loaded_model_counts.values())) return dump_lines def _parse_dump_output(self, output_stream):", "SMSContent: 2})) def test_zapier_subscription(self): ZapierSubscription.objects.create( domain=self.domain_name, case_type='case_type', event_name=EventTypes.NEW_CASE, url='example.com', user_id='user_id',", "web_user = WebUser.create( domain=self.domain_name, username='webuser_t1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', )", "AlertScheduleInstance, ) class BaseDumpLoadTest(TestCase): @classmethod def setUpClass(cls): post_delete.disconnect(zapier_subscription_post_delete, sender=ZapierSubscription) super(BaseDumpLoadTest,", "]), ('Gauteng', [ ('Ekurhuleni ', [ ('Alberton', []), ('Benoni', []),", "CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', ) ccuser_2 =", "= self.form_accessors.get_form(pre_form.form_id) self.assertDictEqual(pre_form.to_json(), post_form.to_json()) def test_sql_dump_load_case(self): expected_object_counts = Counter({ XFormInstanceSQL:", "created_via=None, email='<EMAIL>', uuid='428d454aa9abc74e1964e16d3565d6b6' # match ID in devicelog.xml ) self.addCleanup(user.delete,", "tearDownClass(cls): cls.domain.delete() super(BaseDumpLoadTest, cls).tearDownClass() post_delete.connect(zapier_subscription_post_delete, sender=ZapierSubscription) def delete_sql_data(self): delete_domain_sql_data_for_dump_load_test(self.domain_name) def", "expected_object_counts = Counter({ User: 1, DemoUserRestore: 1 }) user_id =", "self.case_accessors.get_case_ids_in_domain() self.assertEqual(set(case_ids), set(case.case_id for case in pre_cases)) for pre_case in", "def appender(item1, item2): return [item1, item2] greasy_spoon = DefaultDictWithKey(appender) with", "): greasy_spoon['spam'] def test_no_factory(self): greasy_spoon = DefaultDictWithKey() with self.assertRaisesRegex( TypeError,", "make_loc_type('section', district, domain=self.domain_name) block = make_loc_type('block', district, domain=self.domain_name) center =", "corehq.apps.receiverwrapper.util import submit_form_locally from phonelog.models import DeviceReportEntry, ForceCloseEntry, UserEntry, UserErrorEntry", "= self.form_accessors.get_all_form_ids_in_domain('XFormInstance') self.assertEqual(set(form_ids), set(form.form_id for form in pre_forms)) for pre_form", "pre_case in pre_cases: post_case = self.case_accessors.get_case(pre_case.case_id) self.assertDictEqual(pre_case.to_json(), post_case.to_json()) def test_ledgers(self):", "was given' ): greasy_spoon['spam'] def test_too_many_params(self): def appender(item1, item2): return", "corehq.form_processor.interfaces.dbaccessors import ( CaseAccessors, FormAccessors, ) from corehq.form_processor.models import (", "devicelog.xml ) self.addCleanup(user.delete, self.domain_name, deleted_by=None) with open('corehq/ex-submodules/couchforms/tests/data/devicelogs/devicelog.xml', 'rb') as f:", "actual_model_counts, dump_lines = self._parse_dump_output(output_stream) expected_model_counts = _normalize_object_counter(expected_dump_counts) self.assertDictEqual(dict(expected_model_counts), dict(actual_model_counts)) #", "location_type_names, [], location_structure, ) self._dump_and_load(expected_object_counts) names = ['Cape Winelands', 'Paarl',", "in result], ['Cape Winelands', 'Stellenbosch', 'Paarl', 'Cape Town', 'Cape Town", "test_not_enough_params(self): def empty_list(): return [] greasy_spoon = DefaultDictWithKey(empty_list) with self.assertRaisesRegex(", "transaction, IntegrityError from django.db.models.signals import post_delete, post_save from django.test import", "case_ids = self.case_accessors.get_case_ids_in_domain() self.assertEqual(set(case_ids), set(case.case_id for case in pre_cases)) for", "product_id='test2', name='test2') parchived = SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3', is_archived=True) self._dump_and_load(expected_object_counts) self.assertEqual(2,", ") def test_sms(self): from corehq.apps.sms.models import PhoneNumber, MessagingEvent, MessagingSubEvent expected_object_counts", "test_sms_content(self): from corehq.messaging.scheduling.models import AlertSchedule, SMSContent, AlertEvent from corehq.messaging.scheduling.scheduling_partitioned.dbaccessors import", "output_stream.getvalue().split('\\n') dump_lines = [line.strip() for line in dump_output if line.strip()]", "self.assertTrue(parchived not in all_active) def test_location_type(self): from corehq.apps.locations.models import LocationType", "corehq.apps.zapier.signals.receivers import ( zapier_subscription_post_delete, ) from corehq.blobs.models import BlobMeta from", "self._dump_and_load(expected_object_counts) hierarchy = LocationType.objects.full_hierarchy(self.domain_name) desired_hierarchy = { state.id: ( state,", "= LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(post_ledger_values)) self.assertEqual(2, len(post_ledger_transactions)) self.assertEqual(pre_ledger_values[0].ledger_reference, post_ledger_values[0].ledger_reference) self.assertDictEqual(pre_ledger_values[0].to_json(), post_ledger_values[0].to_json())", "test_transifex(self): from corehq.apps.translations.models import TransifexProject, TransifexOrganization org = TransifexOrganization.objects.create(slug='test', name='demo',", "TransifexProject: 2})) def test_filtered_dump_load(self): from corehq.apps.locations.tests.test_location_types import make_loc_type from corehq.apps.products.models", "state = make_loc_type('state', domain=self.domain_name) district = make_loc_type('district', state, domain=self.domain_name) section", "load_filter='sqlproduct', expected_load_counts=Counter({SQLProduct: 1})) self.assertEqual(0, LocationType.objects.count()) def test_sms_content(self): from corehq.messaging.scheduling.models import", "chunk_size): output_stream = StringIO() SqlDataDumper(self.domain_name, [], []).dump(output_stream) self.delete_sql_data() # resave", "= LocationType.objects.full_hierarchy(self.domain_name) desired_hierarchy = { state.id: ( state, { district.id:", "= UserRole.objects.get(id=role1.id) role2_loaded = UserRole.objects.get(id=role2.id) self.assertEqual(role1_loaded.permissions.to_list(), Permissions().to_list()) self.assertEqual(role1_loaded.assignable_by, []) self.assertEqual(role2_loaded.permissions.to_list(),", "test_load_error_queue_full_on_terminate(self): \"\"\"Blocks when sending ``None`` into the queue to 'terminate'", "import ( DefaultDictWithKey, constraint_checks_deferred, ) from corehq.apps.hqcase.utils import submit_case_blocks from", "import ( CaseTransaction, CommCareCaseIndexSQL, CommCareCaseSQL, LedgerTransaction, LedgerValue, XFormInstanceSQL, ) from", "= self._parse_dump_output(output_stream) expected_model_counts = _normalize_object_counter(expected_dump_counts) self.assertDictEqual(dict(expected_model_counts), dict(actual_model_counts)) # Load loader", "def _model_class_to_label(model_class): label = '{}.{}'.format(model_class._meta.app_label, model_class.__name__) return label if for_loaded", "= list(expected_dump_counts) self._check_signals_handle_raw(models) output_stream = StringIO() if dumper_fn: dumper_fn(output_stream) else:", "TypeError, r\"appender\\(\\) missing 1 required positional argument: 'item2'\" ): greasy_spoon['spam']", "blocks loader.load_objects(dump_lines) class DefaultDictWithKeyTests(SimpleTestCase): def test_intended_use_case(self): def enlist(item): return [item]", "\"\"\"Converts a <Model Class> keyed counter to an model label", "def _dump_and_load(self, expected_dump_counts, load_filter=None, expected_load_counts=None, dumper_fn=None): expected_load_counts = expected_load_counts or", "1})) self.assertEqual(0, LocationType.objects.count()) def test_sms_content(self): from corehq.messaging.scheduling.models import AlertSchedule, SMSContent,", "corehq.form_processor.tests.utils import ( FormProcessorTestUtils, create_form_for_test, sharded, ) from corehq.messaging.scheduling.scheduling_partitioned.models import", "length=1024, ) case_upload_record = CaseUploadRecord.objects.create( domain=self.domain_name, upload_id=uuid.uuid4(), task_id=uuid.uuid4(), couch_user_id=uuid.uuid4().hex, case_type='person',", "cls).setUpClass() cls.domain_name = uuid.uuid4().hex cls.domain = Domain(name=cls.domain_name) cls.domain.save() cls.default_objects_counts =", "owner_doc_type='CommCareCase', owner_id='fake-owner-id1', phone_number='99912341234', backend_id=None, ivr_backend_id=None, verified=True, is_two_way=True, pending_verification=False, contact_last_modified=datetime.utcnow() )", "'parent', 'update': {'age': 42}, 'create': True})), ] ) ) pre_cases[0]", "signal handlers have been updated to handle 'raw' calls.\"\"\" whitelist_receivers", "CaseFactory(domain=cls.domain_name) cls.form_accessors = FormAccessors(cls.domain_name) cls.case_accessors = CaseAccessors(cls.domain_name) cls.product = make_product(cls.domain_name,", "= SQLMobileBackend.objects.create( domain=self.domain_name, name='test-domain-mobile-backend', display_name='Test Domain Mobile Backend', hq_api_id='TDMB', inbound_api_key='test-domain-mobile-backend-inbound-api-key',", "post_fuzzies = FuzzyProperties.objects.filter(domain=self.domain_name) self.assertEqual(set(f.case_type for f in post_fuzzies), {'dog', 'owner'})", "django.contrib.auth.models import User expected_object_counts = Counter({ User: 1, DemoUserRestore: 1", "Permissions(edit_web_users=True).to_list()) self.assertEqual(role2_loaded.assignable_by, [role1_loaded.get_id]) def test_device_logs(self): from corehq.apps.receiverwrapper.util import submit_form_locally from", "in objects_remaining] counts = Counter(object_classes) self.assertEqual([], objects_remaining, 'Not all data", "to handle 'raw' calls.\"\"\" whitelist_receivers = [ 'django_digest.models._post_save_persist_partial_digests' ] for", "source=MessagingEvent.SOURCE_REMINDER, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) MessagingSubEvent.objects.create( parent=event, date=datetime.utcnow(), recipient_type=MessagingEvent.RECIPIENT_CASE, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED", "product_id='test1', name='test1'), SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2'), SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3'), ] def", "('Alberton', []), ('Benoni', []), ('Springs', []), ]), ]), ] location_types,", "f: xml = f.read() submit_form_locally(xml, self.domain_name) self._dump_and_load(expected_object_counts) def test_demo_user_restore(self): from", "django.test import SimpleTestCase, TestCase from nose.tools import nottest from casexml.apps.case.mock", "updated to handle 'raw' calls.\"\"\" whitelist_receivers = [ 'django_digest.models._post_save_persist_partial_digests' ]", "io import StringIO import mock from django.contrib.admin.utils import NestedObjects from", "loader.load_objects(dump_lines) normalized_expected_loaded_counts = _normalize_object_counter(expected_load_counts, for_loaded=True) self.assertDictEqual(dict(normalized_expected_loaded_counts), dict(loaded_model_counts)) self.assertEqual(sum(expected_load_counts.values()), sum(loaded_model_counts.values())) return", "('Stellenbosch', []), ('Paarl', []), ]), ('Cape Town', [ ('Cape Town", "in all_active) def test_location_type(self): from corehq.apps.locations.models import LocationType from corehq.apps.locations.tests.test_location_types", ") SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=global_backend, backend_type=SQLMobileBackend.SMS, prefix='*', ) self._dump_and_load({ SQLMobileBackendMapping: 1,", "import \\ delete_alert_schedule_instances_for_schedule schedule = AlertSchedule.create_simple_alert(self.domain, SMSContent()) schedule.set_custom_alert( [ (AlertEvent(minutes_to_wait=5),", "self.assertDictEqual(pre_case.to_json(), post_case.to_json()) def test_ledgers(self): expected_object_counts = Counter({ XFormInstanceSQL: 3, BlobMeta:", "= StringIO() if dumper_fn: dumper_fn(output_stream) else: SqlDataDumper(self.domain_name, [], []).dump(output_stream) self.delete_sql_data()", "ccuser_1 = CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', )", "TestCase from nose.tools import nottest from casexml.apps.case.mock import CaseFactory, CaseIndex,", "[]) self.assertEqual(role2_loaded.permissions.to_list(), Permissions(edit_web_users=True).to_list()) self.assertEqual(role2_loaded.assignable_by, [role1_loaded.get_id]) def test_device_logs(self): from corehq.apps.receiverwrapper.util import", "dump_lines]) return actual_model_counts, dump_lines def _check_signals_handle_raw(self, models): \"\"\"Ensure that any", "cls.default_objects_counts = Counter({}) @classmethod def tearDownClass(cls): cls.domain.delete() super(BaseDumpLoadTest, cls).tearDownClass() post_delete.connect(zapier_subscription_post_delete,", "location_types, locations = setup_locations_and_types( self.domain_name, location_type_names, [], location_structure, ) self._dump_and_load(expected_object_counts)", "from casexml.apps.case.mock import CaseFactory, CaseIndex, CaseStructure from corehq.apps.commtrack.helpers import make_product", "CaseUploadFormRecord: 1, })) def test_transifex(self): from corehq.apps.translations.models import TransifexProject, TransifexOrganization", "chunk size so that the queue blocks loader.load_objects(dump_lines) class DefaultDictWithKeyTests(SimpleTestCase):", "collector.collect(iterator) collector.delete() assert [] == list(get_objects_to_dump(domain_name, [], [])), \"Not all", "TypeError, r'empty_list\\(\\) takes 0 positional arguments but 1 was given'", "delete_alert_schedule_instances_for_schedule schedule = AlertSchedule.create_simple_alert(self.domain, SMSContent()) schedule.set_custom_alert( [ (AlertEvent(minutes_to_wait=5), SMSContent()), (AlertEvent(minutes_to_wait=15),", "uuid from collections import Counter from datetime import datetime from", "t.pk) post_ledger_transactions = sorted(post_ledger_transactions, key=lambda t: t.pk) for pre, post", "('Cape Town', [ ('Cape Town City', []), ]) ]), ('Gauteng',", "username='webuser_t1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', ) self.addCleanup(ccuser_1.delete, self.domain_name, deleted_by=None) self.addCleanup(ccuser_2.delete,", "domain=self.domain_name, upload_id=uuid.uuid4(), task_id=uuid.uuid4(), couch_user_id=uuid.uuid4().hex, case_type='person', upload_file_meta=upload_file_meta, ) CaseUploadFormRecord.objects.create( case_upload_record=case_upload_record, form_id=uuid.uuid4().hex,", "= DefaultDictWithKey(empty_list) with self.assertRaisesRegex( TypeError, r'empty_list\\(\\) takes 0 positional arguments", "current_event_num=0, schedule_iteration_num=1, next_event_due=datetime(2017, 3, 1), active=True, alert_schedule_id=uuid.uuid4(), ).save() self._dump_and_load({AlertScheduleInstance: 1})", "case_upload_record=case_upload_record, form_id=uuid.uuid4().hex, ) self._dump_and_load(Counter({ CaseUploadFileMeta: 1, CaseUploadRecord: 1, CaseUploadFormRecord: 1,", "['province', 'district', 'city'] location_structure = [ ('Western Cape', [ ('Cape", "Counter({ XFormInstanceSQL: 2, BlobMeta: 2 }) pre_forms = [ create_form_for_test(self.domain_name),", "from corehq.apps.sms.models import PhoneNumber, MessagingEvent, MessagingSubEvent expected_object_counts = Counter({PhoneNumber: 1,", "2, RolePermission: 11, RoleAssignableBy: 1 }) role1 = UserRole.create(self.domain_name, 'role1')", "is not callable\" ): greasy_spoon['spam'] def _normalize_object_counter(counter, for_loaded=False): \"\"\"Converts a", "phone_number.save() event = MessagingEvent.objects.create( domain=self.domain_name, date=datetime.utcnow(), source=MessagingEvent.SOURCE_REMINDER, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED )", "queue blocks loader.load_objects(dump_lines) class DefaultDictWithKeyTests(SimpleTestCase): def test_intended_use_case(self): def enlist(item): return", "loaded_model_counts = loader.load_objects(dump_lines) normalized_expected_loaded_counts = _normalize_object_counter(expected_load_counts, for_loaded=True) self.assertDictEqual(dict(normalized_expected_loaded_counts), dict(loaded_model_counts)) self.assertEqual(sum(expected_load_counts.values()),", "# patch the chunk size so that the queue blocks", "[ ('Western Cape', [ ('Cape Winelands', [ ('Stellenbosch', []), ('Paarl',", ") web_user = WebUser.create( domain=self.domain_name, username='webuser_t1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>',", "import inspect import json import uuid from collections import Counter", "name='test1'), SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2'), SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3'), ] def test_load_error_queue_full(self):", "SqlDataLoader(object_filter=load_filter) loaded_model_counts = loader.load_objects(dump_lines) normalized_expected_loaded_counts = _normalize_object_counter(expected_load_counts, for_loaded=True) self.assertDictEqual(dict(normalized_expected_loaded_counts), dict(loaded_model_counts))", "] location_types, locations = setup_locations_and_types( self.domain_name, location_type_names, [], location_structure, )", "[]): for iterator in builder.querysets(): with transaction.atomic(using=iterator.db), \\ constraint_checks_deferred(iterator.db): collector", "2, }) pre_config, created = CaseSearchConfig.objects.get_or_create(pk=self.domain_name) pre_config.enabled = True pre_fuzzies", "empty_list(): return [] greasy_spoon = DefaultDictWithKey(empty_list) with self.assertRaisesRegex( TypeError, r'empty_list\\(\\)", "'update': {'name': '<NAME>'}} ))[0] self._dump_and_load(expected_object_counts) case_ids = self.case_accessors.get_case_ids_in_domain() self.assertEqual(set(case_ids), set(case.case_id", "= Counter({PhoneNumber: 1, MessagingEvent: 1, MessagingSubEvent: 1}) phone_number = PhoneNumber(", "model in models: for receiver in post_save._live_receivers(model): receiver_path = receiver.__module__", "django.db import transaction, IntegrityError from django.db.models.signals import post_delete, post_save from", "Counter([json.loads(line)['model'] for line in dump_lines]) return actual_model_counts, dump_lines def _check_signals_handle_raw(self,", "SMSContent()) schedule.set_custom_alert( [ (AlertEvent(minutes_to_wait=5), SMSContent()), (AlertEvent(minutes_to_wait=15), SMSContent()), ] ) self.addCleanup(lambda:", "CommCareCaseIndexSQL: 1 }) pre_cases = self.factory.create_or_update_case( CaseStructure( attrs={'case_name': 'child', 'update':", "self.addCleanup(lambda: delete_alert_schedule_instances_for_schedule(AlertScheduleInstance, schedule.schedule_id)) self._dump_and_load(Counter({AlertSchedule: 1, AlertEvent: 2, SMSContent: 2})) def", "self.assertEqual(greasy_spoon['spam'], ['spam', 'spam']) def test_not_enough_params(self): def empty_list(): return [] greasy_spoon", "= receiver.__module__ + '.' + receiver.__name__ if receiver_path in whitelist_receivers:", "restore_comment=\"Test migrate demo user restore\" ).save() self._dump_and_load(expected_object_counts) def test_products(self): from", "= make_loc_type('center', block, domain=self.domain_name) county = make_loc_type('county', state, domain=self.domain_name) city", "import make_loc_type from corehq.apps.products.models import SQLProduct from corehq.apps.locations.models import LocationType", "object_classes = [obj.__class__.__name__ for obj in objects_remaining] counts = Counter(object_classes)", "Counter({ UserRole: 2, RolePermission: 11, RoleAssignableBy: 1 }) role1 =", "mock.patch(\"corehq.apps.dump_reload.sql.load.CHUNK_SIZE\", chunk_size): # patch the chunk size so that the", "role2_loaded = UserRole.objects.get(id=role2.id) self.assertEqual(role1_loaded.permissions.to_list(), Permissions().to_list()) self.assertEqual(role1_loaded.assignable_by, []) self.assertEqual(role2_loaded.permissions.to_list(), Permissions(edit_web_users=True).to_list()) self.assertEqual(role2_loaded.assignable_by,", "from django.contrib.auth.models import User expected_object_counts = Counter({User: 3}) ccuser_1 =", "greasy_spoon = DefaultDictWithKey(empty_list) with self.assertRaisesRegex( TypeError, r'empty_list\\(\\) takes 0 positional", "corehq.apps.locations.tests.test_location_types import make_loc_type expected_object_counts = Counter({LocationType: 7}) state = make_loc_type('state',", "self._dump_and_load(expected_object_counts) def test_products(self): from corehq.apps.products.models import SQLProduct expected_object_counts = Counter({SQLProduct:", "StringIO() if dumper_fn: dumper_fn(output_stream) else: SqlDataDumper(self.domain_name, [], []).dump(output_stream) self.delete_sql_data() #", "dumper_fn: dumper_fn(output_stream) else: SqlDataDumper(self.domain_name, [], []).dump(output_stream) self.delete_sql_data() # make sure", "domain=self.domain_name ) self._dump_and_load(Counter({TransifexOrganization: 1, TransifexProject: 2})) def test_filtered_dump_load(self): from corehq.apps.locations.tests.test_location_types", "len(pre_ledger_values)) self.assertEqual(2, len(pre_ledger_transactions)) self._dump_and_load(expected_object_counts) post_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) post_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id)", "datetime from io import StringIO import mock from django.contrib.admin.utils import", "r'empty_list\\(\\) takes 0 positional arguments but 1 was given' ):", "corehq.apps.ota.models import DemoUserRestore from django.contrib.auth.models import User expected_object_counts = Counter({", "from corehq.apps.commtrack.tests.util import get_single_balance_block from corehq.apps.domain.models import Domain from corehq.apps.dump_reload.sql", "make_loc_type('center', block, domain=self.domain_name) county = make_loc_type('county', state, domain=self.domain_name) city =", "@nottest def delete_domain_sql_data_for_dump_load_test(domain_name): for model_class, builder in get_model_iterator_builders_to_dump(domain_name, [], []):", "make sure that there's no data left in the DB", "corehq.apps.users.models import UserRole, Permissions, RoleAssignableBy, RolePermission expected_object_counts = Counter({ UserRole:", "inspect import json import uuid from collections import Counter from", "CaseIndex(CaseStructure(attrs={'case_name': 'parent', 'update': {'age': 42}, 'create': True})), ] ) )", "in names] result = SQLLocation.objects.get_locations_and_children(location_ids) self.assertItemsEqual( [loc.name for loc in", "self._dump_and_load(expected_object_counts) case_ids = self.case_accessors.get_case_ids_in_domain() self.assertEqual(set(case_ids), set(case.case_id for case in pre_cases))", "= uuid.uuid4().hex cls.domain = Domain(name=cls.domain_name) cls.domain.save() cls.default_objects_counts = Counter({}) @classmethod", "RolePermission: 11, RoleAssignableBy: 1 }) role1 = UserRole.create(self.domain_name, 'role1') role2", "[ ('Ekurhuleni ', [ ('Alberton', []), ('Benoni', []), ('Springs', []),", "content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) self._dump_and_load(expected_object_counts) def test_message_scheduling(self): AlertScheduleInstance( schedule_instance_id=uuid.uuid4(), domain=self.domain_name, recipient_type='CommCareUser',", "= TransifexOrganization.objects.create(slug='test', name='demo', api_token='<PASSWORD>') TransifexProject.objects.create( organization=org, slug='testp', name='demop', domain=self.domain_name )", "( CaseTransaction, CommCareCaseIndexSQL, CommCareCaseSQL, LedgerTransaction, LedgerValue, XFormInstanceSQL, ) from corehq.form_processor.tests.utils", "from corehq.apps.case_search.models import CaseSearchConfig, FuzzyProperties expected_object_counts = Counter({ CaseSearchConfig: 1,", "5) ], self.domain_name) pre_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) pre_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1,", "1, CaseUploadFormRecord: 1, })) def test_transifex(self): from corehq.apps.translations.models import TransifexProject,", "CaseSearchConfig.objects.get(domain=self.domain_name) self.assertTrue(post_config.enabled) self.assertEqual(pre_config.fuzzy_properties, post_config.fuzzy_properties) post_fuzzies = FuzzyProperties.objects.filter(domain=self.domain_name) self.assertEqual(set(f.case_type for f", "IntegrityError from django.db.models.signals import post_delete, post_save from django.test import SimpleTestCase,", "MessagingSubEvent expected_object_counts = Counter({PhoneNumber: 1, MessagingEvent: 1, MessagingSubEvent: 1}) phone_number", "Counter({ XFormInstanceSQL: 2, BlobMeta: 2, CommCareCaseSQL: 2, CaseTransaction: 3, CommCareCaseIndexSQL:", ") from corehq.apps.dump_reload.sql.load import ( DefaultDictWithKey, constraint_checks_deferred, ) from corehq.apps.hqcase.utils", "been updated to handle 'raw' calls.\"\"\" whitelist_receivers = [ 'django_digest.models._post_save_persist_partial_digests'", "district.id: ( district, { section.id: (section, {}), block.id: (block, {", "CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', uuid='428d454aa9abc74e1964e16d3565d6b6' # match", "city = make_loc_type('city', county, domain=self.domain_name) self._dump_and_load(expected_object_counts) hierarchy = LocationType.objects.full_hierarchy(self.domain_name) desired_hierarchy", "]) ]), ('Gauteng', [ ('Ekurhuleni ', [ ('Alberton', []), ('Benoni',", "expected_object_counts = Counter({ CaseSearchConfig: 1, FuzzyProperties: 2, }) pre_config, created", "SQLMobileBackendMapping, ) domain_backend = SQLMobileBackend.objects.create( domain=self.domain_name, name='test-domain-mobile-backend', display_name='Test Domain Mobile", "[item1, item2] greasy_spoon = DefaultDictWithKey(appender) with self.assertRaisesRegex( TypeError, r\"appender\\(\\) missing", "\"'NoneType' object is not callable\" ): greasy_spoon['spam'] def _normalize_object_counter(counter, for_loaded=False):", "appender(item1, item2): return [item1, item2] greasy_spoon = DefaultDictWithKey(appender) with self.assertRaisesRegex(", "make_loc_type from corehq.apps.products.models import SQLProduct from corehq.apps.locations.models import LocationType make_loc_type('state',", "self.domain_name, deleted_by=None) self.addCleanup(ccuser_2.delete, self.domain_name, deleted_by=None) self.addCleanup(web_user.delete, self.domain_name, deleted_by=None) self._dump_and_load(expected_object_counts) def", "def test_load_error_queue_full(self): \"\"\"Blocks when sending 'test3'\"\"\" self._load_with_errors(chunk_size=1) def test_load_error_queue_full_on_terminate(self): \"\"\"Blocks", "self).tearDown() def _dump_and_load(self, expected_dump_counts, load_filter=None, expected_load_counts=None, dumper_fn=None): expected_load_counts = expected_load_counts", "corehq.apps.products.models import SQLProduct from corehq.apps.locations.models import LocationType make_loc_type('state', domain=self.domain_name) SQLProduct.objects.create(domain=self.domain_name,", "from corehq.apps.products.models import SQLProduct from corehq.apps.zapier.consts import EventTypes from corehq.apps.zapier.models", "location_ids = [locations[name].location_id for name in names] result = SQLLocation.objects.get_locations_and_children(location_ids)", "Permissions().to_list()) self.assertEqual(role1_loaded.assignable_by, []) self.assertEqual(role2_loaded.permissions.to_list(), Permissions(edit_web_users=True).to_list()) self.assertEqual(role2_loaded.assignable_by, [role1_loaded.get_id]) def test_device_logs(self): from", "= CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', uuid=user_id )", "def test_users(self): from corehq.apps.users.models import CommCareUser from corehq.apps.users.models import WebUser", "self.domain_name, deleted_by=None) DemoUserRestore( demo_user_id=user_id, restore_blob_id=uuid.uuid4().hex, content_length=1027, restore_comment=\"Test migrate demo user", "phone_number='99912341234', backend_id=None, ivr_backend_id=None, verified=True, is_two_way=True, pending_verification=False, contact_last_modified=datetime.utcnow() ) phone_number.save() event", "self._dump_and_load(expected_object_counts) form_ids = self.form_accessors.get_all_form_ids_in_domain('XFormInstance') self.assertEqual(set(form_ids), set(form.form_id for form in pre_forms))", "pre_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(pre_ledger_values)) self.assertEqual(2, len(pre_ledger_transactions)) self._dump_and_load(expected_object_counts) post_ledger_values =", "pre_forms = [ create_form_for_test(self.domain_name), create_form_for_test(self.domain_name) ] self._dump_and_load(expected_object_counts) form_ids = self.form_accessors.get_all_form_ids_in_domain('XFormInstance')", "get_objects_to_dump, ) from corehq.apps.dump_reload.sql.load import ( DefaultDictWithKey, constraint_checks_deferred, ) from", "all_active) self.assertTrue(parchived not in all_active) def test_location_type(self): from corehq.apps.locations.models import", "Counter({LocationType: 7}) state = make_loc_type('state', domain=self.domain_name) district = make_loc_type('district', state,", "center.id: (center, {}), }), }, ), county.id: ( county, {city.id:", "= CaseAccessors(cls.domain_name) cls.product = make_product(cls.domain_name, 'A Product', 'prodcode_a') cls.default_objects_counts.update({SQLProduct: 1})", "self.assertRaisesRegex( TypeError, \"'NoneType' object is not callable\" ): greasy_spoon['spam'] def", "collector = NestedObjects(using=iterator.db) collector.collect(iterator) collector.delete() assert [] == list(get_objects_to_dump(domain_name, [],", "NestedObjects(using=iterator.db) collector.collect(iterator) collector.delete() assert [] == list(get_objects_to_dump(domain_name, [], [])), \"Not", "the product to force an error self.products[0].save() actual_model_counts, dump_lines =", "), county.id: ( county, {city.id: (city, {})}, ), }, ),", "self.assertTrue(post_config.enabled) self.assertEqual(pre_config.fuzzy_properties, post_config.fuzzy_properties) post_fuzzies = FuzzyProperties.objects.filter(domain=self.domain_name) self.assertEqual(set(f.case_type for f in", "SqlDataDumper, SqlDataLoader from corehq.apps.dump_reload.sql.dump import ( get_model_iterator_builders_to_dump, get_objects_to_dump, ) from", "post_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) post_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(post_ledger_values)) self.assertEqual(2, len(post_ledger_transactions))", "domain=None, name='test-global-mobile-backend', display_name='Test Global Mobile Backend', hq_api_id='TGMB', inbound_api_key='test-global-mobile-backend-inbound-api-key', supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS,", "@classmethod def tearDownClass(cls): cls.domain.delete() super(BaseDumpLoadTest, cls).tearDownClass() post_delete.connect(zapier_subscription_post_delete, sender=ZapierSubscription) def delete_sql_data(self):", "self.assertEqual(str(pre), str(post)) class TestSQLDumpLoad(BaseDumpLoadTest): def test_case_search_config(self): from corehq.apps.case_search.models import CaseSearchConfig,", "required positional argument: 'item2'\" ): greasy_spoon['spam'] def test_no_factory(self): greasy_spoon =", "{'dog', 'owner'}) def test_users(self): from corehq.apps.users.models import CommCareUser from corehq.apps.users.models", "UserRole.objects.get(id=role2.id) self.assertEqual(role1_loaded.permissions.to_list(), Permissions().to_list()) self.assertEqual(role1_loaded.assignable_by, []) self.assertEqual(role2_loaded.permissions.to_list(), Permissions(edit_web_users=True).to_list()) self.assertEqual(role2_loaded.assignable_by, [role1_loaded.get_id]) def", "( county, {city.id: (city, {})}, ), }, ), } self.assertEqual(hierarchy,", "import ZapierSubscription from corehq.apps.zapier.signals.receivers import ( zapier_subscription_post_delete, ) from corehq.blobs.models", "self.domain_name) def test_case_importer(self): from corehq.apps.case_importer.tracking.models import ( CaseUploadFileMeta, CaseUploadFormRecord, CaseUploadRecord,", "def test_zapier_subscription(self): ZapierSubscription.objects.create( domain=self.domain_name, case_type='case_type', event_name=EventTypes.NEW_CASE, url='example.com', user_id='user_id', ) self._dump_and_load(Counter({ZapierSubscription:", "== list(get_objects_to_dump(domain_name, [], [])), \"Not all SQL objects deleted\" @sharded", "CaseTransaction: 3, CommCareCaseIndexSQL: 1 }) pre_cases = self.factory.create_or_update_case( CaseStructure( attrs={'case_name':", "model_class, builder in get_model_iterator_builders_to_dump(domain_name, [], []): for iterator in builder.querysets():", "= DefaultDictWithKey(appender) with self.assertRaisesRegex( TypeError, r\"appender\\(\\) missing 1 required positional", "ForceCloseEntry, UserEntry, UserErrorEntry from corehq.apps.users.models import CommCareUser from django.contrib.auth.models import", "from corehq.apps.users.models import CommCareUser from django.contrib.auth.models import User expected_object_counts =", "from corehq.apps.dump_reload.sql.dump import ( get_model_iterator_builders_to_dump, get_objects_to_dump, ) from corehq.apps.dump_reload.sql.load import", "XFormInstanceSQL: 2, BlobMeta: 2 }) pre_forms = [ create_form_for_test(self.domain_name), create_form_for_test(self.domain_name)", "TestSQLDumpLoad(BaseDumpLoadTest): def test_case_search_config(self): from corehq.apps.case_search.models import CaseSearchConfig, FuzzyProperties expected_object_counts =", "[]), ]), ('Cape Town', [ ('Cape Town City', []), ])", "= [ 'django_digest.models._post_save_persist_partial_digests' ] for model in models: for receiver", "self.assertEqual(SQLMobileBackendMapping.objects.first().domain, self.domain_name) def test_case_importer(self): from corehq.apps.case_importer.tracking.models import ( CaseUploadFileMeta, CaseUploadFormRecord,", "2, SMSContent: 2})) def test_zapier_subscription(self): ZapierSubscription.objects.create( domain=self.domain_name, case_type='case_type', event_name=EventTypes.NEW_CASE, url='example.com',", "name='test-domain-mobile-backend', display_name='Test Domain Mobile Backend', hq_api_id='TDMB', inbound_api_key='test-domain-mobile-backend-inbound-api-key', supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS, is_global=False,", "= 'Signal handler \"{}\" for model \"{}\" missing raw arg'.format(", "'Paarl', 'Cape Town', 'Cape Town City'] ) result = SQLLocation.objects.get_locations_and_children([locations['Gauteng'].location_id])", "def test_location(self): from corehq.apps.locations.models import LocationType, SQLLocation from corehq.apps.locations.tests.util import", "}), }, ), county.id: ( county, {city.id: (city, {})}, ),", "Domain Mobile Backend', hq_api_id='TDMB', inbound_api_key='test-domain-mobile-backend-inbound-api-key', supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS, is_global=False, ) SQLMobileBackendMapping.objects.create(", "{}), block.id: (block, { center.id: (center, {}), }), }, ),", "from django.db import transaction, IntegrityError from django.db.models.signals import post_delete, post_save", ") self._dump_and_load({ SQLMobileBackendMapping: 1, SQLMobileBackend: 1, }) self.assertEqual(SQLMobileBackend.objects.first().domain, self.domain_name) self.assertEqual(SQLMobileBackendMapping.objects.first().domain,", "name='test1') p2 = SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2') parchived = SQLProduct.objects.create(domain=self.domain_name, product_id='test3',", "cls.product = make_product(cls.domain_name, 'A Product', 'prodcode_a') cls.default_objects_counts.update({SQLProduct: 1}) @classmethod def", "\"\"\"Blocks when sending ``None`` into the queue to 'terminate' it.\"\"\"", "import StringIO import mock from django.contrib.admin.utils import NestedObjects from django.db", "case_type='owner', properties=['name']), ] for fuzzy in pre_fuzzies: fuzzy.save() pre_config.fuzzy_properties.set(pre_fuzzies) pre_config.save()", "expected_object_counts = Counter({ XFormInstanceSQL: 2, BlobMeta: 2, CommCareCaseSQL: 2, CaseTransaction:", "UserErrorEntry: 2, ForceCloseEntry: 1 }) user = CommCareUser.create( domain=self.domain_name, username='user_1',", "schedule_instance_id=uuid.uuid4(), domain=self.domain_name, recipient_type='CommCareUser', recipient_id=uuid.uuid4().hex, current_event_num=0, schedule_iteration_num=1, next_event_due=datetime(2017, 3, 1), active=True,", "= self.factory.create_case() submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id, 10) ], self.domain_name) submit_case_blocks([ get_single_balance_block(case.case_id,", "date=datetime.utcnow(), recipient_type=MessagingEvent.RECIPIENT_CASE, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) self._dump_and_load(expected_object_counts) def test_message_scheduling(self): AlertScheduleInstance( schedule_instance_id=uuid.uuid4(),", "dump_lines def _parse_dump_output(self, output_stream): dump_output = output_stream.getvalue().split('\\n') dump_lines = [line.strip()", "key=lambda t: t.pk) for pre, post in zip(pre_ledger_transactions, post_ledger_transactions): self.assertEqual(str(pre),", "list(get_objects_to_dump(self.domain_name, [], [])) object_classes = [obj.__class__.__name__ for obj in objects_remaining]", "parchived = SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3', is_archived=True) self._dump_and_load(expected_object_counts) self.assertEqual(2, SQLProduct.active_objects.filter(domain=self.domain_name).count()) all_active", "'update': {'age': 3, 'diabetic': False}, 'create': True}, indices=[ CaseIndex(CaseStructure(attrs={'case_name': 'parent',", "display_name='Test Domain Mobile Backend', hq_api_id='TDMB', inbound_api_key='test-domain-mobile-backend-inbound-api-key', supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS, is_global=False, )", "sending 'test3'\"\"\" self._load_with_errors(chunk_size=1) def test_load_error_queue_full_on_terminate(self): \"\"\"Blocks when sending ``None`` into", "self.assertTrue(p1 in all_active) self.assertTrue(p2 in all_active) self.assertTrue(parchived not in all_active)", "import NestedObjects from django.db import transaction, IntegrityError from django.db.models.signals import", "item2] greasy_spoon = DefaultDictWithKey(appender) with self.assertRaisesRegex( TypeError, r\"appender\\(\\) missing 1", "LedgerTransaction: 2 }) case = self.factory.create_case() submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id, 10)", "= [ SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1'), SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2'), SQLProduct.objects.create(domain=self.domain_name, product_id='test3',", "len(post_ledger_transactions)) self.assertEqual(pre_ledger_values[0].ledger_reference, post_ledger_values[0].ledger_reference) self.assertDictEqual(pre_ledger_values[0].to_json(), post_ledger_values[0].to_json()) pre_ledger_transactions = sorted(pre_ledger_transactions, key=lambda t:", "have been updated to handle 'raw' calls.\"\"\" whitelist_receivers = [", "[], []): for iterator in builder.querysets(): with transaction.atomic(using=iterator.db), \\ constraint_checks_deferred(iterator.db):", "return label if for_loaded else label.lower() return Counter({ _model_class_to_label(model_class): count", "corehq.apps.hqcase.utils import submit_case_blocks from corehq.apps.products.models import SQLProduct from corehq.apps.zapier.consts import", "pre_form in pre_forms: post_form = self.form_accessors.get_form(pre_form.form_id) self.assertDictEqual(pre_form.to_json(), post_form.to_json()) def test_sql_dump_load_case(self):", "}) case = self.factory.create_case() submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id, 10) ], self.domain_name)", "len(post_ledger_values)) self.assertEqual(2, len(post_ledger_transactions)) self.assertEqual(pre_ledger_values[0].ledger_reference, post_ledger_values[0].ledger_reference) self.assertDictEqual(pre_ledger_values[0].to_json(), post_ledger_values[0].to_json()) pre_ledger_transactions = sorted(pre_ledger_transactions,", "PhoneNumber( domain=self.domain_name, owner_doc_type='CommCareCase', owner_id='fake-owner-id1', phone_number='99912341234', backend_id=None, ivr_backend_id=None, verified=True, is_two_way=True, pending_verification=False,", "import UserRole, Permissions, RoleAssignableBy, RolePermission expected_object_counts = Counter({ UserRole: 2,", "builder.querysets(): with transaction.atomic(using=iterator.db), \\ constraint_checks_deferred(iterator.db): collector = NestedObjects(using=iterator.db) collector.collect(iterator) collector.delete()", "FormAccessors(cls.domain_name) cls.case_accessors = CaseAccessors(cls.domain_name) cls.product = make_product(cls.domain_name, 'A Product', 'prodcode_a')", "counter\"\"\" def _model_class_to_label(model_class): label = '{}.{}'.format(model_class._meta.app_label, model_class.__name__) return label if", "tearDownClass(cls): FormProcessorTestUtils.delete_all_cases_forms_ledgers(cls.domain_name) super(TestSQLDumpLoadShardedModels, cls).tearDownClass() def test_dump_load_form(self): expected_object_counts = Counter({ XFormInstanceSQL:", "ID in devicelog.xml ) self.addCleanup(user.delete, self.domain_name, deleted_by=None) with open('corehq/ex-submodules/couchforms/tests/data/devicelogs/devicelog.xml', 'rb')", "r\"appender\\(\\) missing 1 required positional argument: 'item2'\" ): greasy_spoon['spam'] def", "LocationType from corehq.apps.locations.tests.test_location_types import make_loc_type expected_object_counts = Counter({LocationType: 7}) state", "pre_forms)) for pre_form in pre_forms: post_form = self.form_accessors.get_form(pre_form.form_id) self.assertDictEqual(pre_form.to_json(), post_form.to_json())", "expected_dump_counts expected_dump_counts.update(self.default_objects_counts) models = list(expected_dump_counts) self._check_signals_handle_raw(models) output_stream = StringIO() if", "test_intended_use_case(self): def enlist(item): return [item] greasy_spoon = DefaultDictWithKey(enlist) self.assertEqual(greasy_spoon['spam'], ['spam'])", "# match ID in devicelog.xml ) self.addCleanup(user.delete, self.domain_name, deleted_by=None) with", "[obj.__class__.__name__ for obj in objects_remaining] counts = Counter(object_classes) self.assertEqual([], objects_remaining,", "takes 0 positional arguments but 1 was given' ): greasy_spoon['spam']", "LocationType make_loc_type('state', domain=self.domain_name) SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1') expected_object_counts = Counter({LocationType: 1,", "super(BaseDumpLoadTest, cls).tearDownClass() post_delete.connect(zapier_subscription_post_delete, sender=ZapierSubscription) def delete_sql_data(self): delete_domain_sql_data_for_dump_load_test(self.domain_name) def tearDown(self): self.delete_sql_data()", "corehq.apps.zapier.consts import EventTypes from corehq.apps.zapier.models import ZapierSubscription from corehq.apps.zapier.signals.receivers import", "corehq.apps.products.models import SQLProduct expected_object_counts = Counter({SQLProduct: 3}) p1 = SQLProduct.objects.create(domain=self.domain_name,", "[]), ('Benoni', []), ('Springs', []), ]), ]), ] location_types, locations", "status=MessagingEvent.STATUS_COMPLETED ) self._dump_and_load(expected_object_counts) def test_message_scheduling(self): AlertScheduleInstance( schedule_instance_id=uuid.uuid4(), domain=self.domain_name, recipient_type='CommCareUser', recipient_id=uuid.uuid4().hex,", "pre_config.enabled = True pre_fuzzies = [ FuzzyProperties(domain=self.domain, case_type='dog', properties=['breed', 'color']),", "= CaseSearchConfig.objects.get_or_create(pk=self.domain_name) pre_config.enabled = True pre_fuzzies = [ FuzzyProperties(domain=self.domain, case_type='dog',", "= ['Cape Winelands', 'Paarl', 'Cape Town'] location_ids = [locations[name].location_id for", "SQL objects deleted\" @sharded class TestSQLDumpLoadShardedModels(BaseDumpLoadTest): maxDiff = None @classmethod", "name='test1') expected_object_counts = Counter({LocationType: 1, SQLProduct: 1}) self._dump_and_load(expected_object_counts, load_filter='sqlproduct', expected_load_counts=Counter({SQLProduct:", "case_upload_record = CaseUploadRecord.objects.create( domain=self.domain_name, upload_id=uuid.uuid4(), task_id=uuid.uuid4(), couch_user_id=uuid.uuid4().hex, case_type='person', upload_file_meta=upload_file_meta, )", "uuid.uuid4().hex cls.domain = Domain(name=cls.domain_name) cls.domain.save() cls.default_objects_counts = Counter({}) @classmethod def", "test_users(self): from corehq.apps.users.models import CommCareUser from corehq.apps.users.models import WebUser from", "submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id, 5) ], self.domain_name) pre_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) pre_ledger_transactions", "pre_config.fuzzy_properties.set(pre_fuzzies) pre_config.save() self._dump_and_load(expected_object_counts) post_config = CaseSearchConfig.objects.get(domain=self.domain_name) self.assertTrue(post_config.enabled) self.assertEqual(pre_config.fuzzy_properties, post_config.fuzzy_properties) post_fuzzies", "= _normalize_object_counter(expected_load_counts, for_loaded=True) self.assertDictEqual(dict(normalized_expected_loaded_counts), dict(loaded_model_counts)) self.assertEqual(sum(expected_load_counts.values()), sum(loaded_model_counts.values())) return dump_lines def", "name='test-global-mobile-backend', display_name='Test Global Mobile Backend', hq_api_id='TGMB', inbound_api_key='test-global-mobile-backend-inbound-api-key', supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS, is_global=True,", "submit_case_blocks from corehq.apps.products.models import SQLProduct from corehq.apps.zapier.consts import EventTypes from", "from corehq.apps.users.models import CommCareUser from corehq.apps.users.models import WebUser from django.contrib.auth.models", "for model_class, builder in get_model_iterator_builders_to_dump(domain_name, [], []): for iterator in", "[line.strip() for line in dump_output if line.strip()] actual_model_counts = Counter([json.loads(line)['model']", "'role1', permissions=Permissions(edit_web_users=True), assignable_by=[role1.id] ) self.addCleanup(role1.delete) self.addCleanup(role2.delete) self._dump_and_load(expected_object_counts) role1_loaded = UserRole.objects.get(id=role1.id)", "receiver in post_save._live_receivers(model): receiver_path = receiver.__module__ + '.' + receiver.__name__", "CaseUploadFormRecord.objects.create( case_upload_record=case_upload_record, form_id=uuid.uuid4().hex, ) self._dump_and_load(Counter({ CaseUploadFileMeta: 1, CaseUploadRecord: 1, CaseUploadFormRecord:", "identifier=uuid.uuid4().hex, filename='picture.jpg', length=1024, ) case_upload_record = CaseUploadRecord.objects.create( domain=self.domain_name, upload_id=uuid.uuid4(), task_id=uuid.uuid4(),", "CaseTransaction, CommCareCaseIndexSQL, CommCareCaseSQL, LedgerTransaction, LedgerValue, XFormInstanceSQL, ) from corehq.form_processor.tests.utils import", "'Alberton', 'Benoni', 'Springs'] ) def test_sms(self): from corehq.apps.sms.models import PhoneNumber,", "DefaultDictWithKey(appender) with self.assertRaisesRegex( TypeError, r\"appender\\(\\) missing 1 required positional argument:", "]), ]), ] location_types, locations = setup_locations_and_types( self.domain_name, location_type_names, [],", "LedgerValue: 1, LedgerTransaction: 2 }) case = self.factory.create_case() submit_case_blocks([ get_single_balance_block(case.case_id,", "DefaultDictWithKey(enlist) self.assertEqual(greasy_spoon['spam'], ['spam']) greasy_spoon['spam'].append('spam') self.assertEqual(greasy_spoon['spam'], ['spam', 'spam']) def test_not_enough_params(self): def", "PhoneNumber, MessagingEvent, MessagingSubEvent expected_object_counts = Counter({PhoneNumber: 1, MessagingEvent: 1, MessagingSubEvent:", "queue to 'terminate' it.\"\"\" self._load_with_errors(chunk_size=2) def _load_with_errors(self, chunk_size): output_stream =", "LocationType.objects.count()) def test_sms_content(self): from corehq.messaging.scheduling.models import AlertSchedule, SMSContent, AlertEvent from", "post_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(post_ledger_values)) self.assertEqual(2, len(post_ledger_transactions)) self.assertEqual(pre_ledger_values[0].ledger_reference, post_ledger_values[0].ledger_reference) self.assertDictEqual(pre_ledger_values[0].to_json(),", "label = '{}.{}'.format(model_class._meta.app_label, model_class.__name__) return label if for_loaded else label.lower()", "self.form_accessors.get_all_form_ids_in_domain('XFormInstance') self.assertEqual(set(form_ids), set(form.form_id for form in pre_forms)) for pre_form in", "case_type='dog', properties=['breed', 'color']), FuzzyProperties(domain=self.domain, case_type='owner', properties=['name']), ] for fuzzy in", "super(TestSQLDumpLoadShardedModels, cls).setUpClass() cls.factory = CaseFactory(domain=cls.domain_name) cls.form_accessors = FormAccessors(cls.domain_name) cls.case_accessors =", "'color']), FuzzyProperties(domain=self.domain, case_type='owner', properties=['name']), ] for fuzzy in pre_fuzzies: fuzzy.save()", "return [] greasy_spoon = DefaultDictWithKey(empty_list) with self.assertRaisesRegex( TypeError, r'empty_list\\(\\) takes", "return actual_model_counts, dump_lines def _check_signals_handle_raw(self, models): \"\"\"Ensure that any post_save", "in builder.querysets(): with transaction.atomic(using=iterator.db), \\ constraint_checks_deferred(iterator.db): collector = NestedObjects(using=iterator.db) collector.collect(iterator)", "post_delete.connect(zapier_subscription_post_delete, sender=ZapierSubscription) def delete_sql_data(self): delete_domain_sql_data_for_dump_load_test(self.domain_name) def tearDown(self): self.delete_sql_data() super(BaseDumpLoadTest, self).tearDown()", "'<NAME>'}} ))[0] self._dump_and_load(expected_object_counts) case_ids = self.case_accessors.get_case_ids_in_domain() self.assertEqual(set(case_ids), set(case.case_id for case", "CaseUploadFileMeta.objects.create( identifier=uuid.uuid4().hex, filename='picture.jpg', length=1024, ) case_upload_record = CaseUploadRecord.objects.create( domain=self.domain_name, upload_id=uuid.uuid4(),", "1, MessagingSubEvent: 1}) phone_number = PhoneNumber( domain=self.domain_name, owner_doc_type='CommCareCase', owner_id='fake-owner-id1', phone_number='99912341234',", ") TransifexProject.objects.create( organization=org, slug='testp1', name='demop1', domain=self.domain_name ) self._dump_and_load(Counter({TransifexOrganization: 1, TransifexProject:", "district, domain=self.domain_name) block = make_loc_type('block', district, domain=self.domain_name) center = make_loc_type('center',", "SQLLocation from corehq.apps.locations.tests.util import setup_locations_and_types expected_object_counts = Counter({LocationType: 3, SQLLocation:", "_normalize_object_counter(counter, for_loaded=False): \"\"\"Converts a <Model Class> keyed counter to an", "}, ), county.id: ( county, {city.id: (city, {})}, ), },", "force an error self.products[0].save() actual_model_counts, dump_lines = self._parse_dump_output(output_stream) self.assertEqual(actual_model_counts['products.sqlproduct'], 3)", "make_loc_type('state', domain=self.domain_name) SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1') expected_object_counts = Counter({LocationType: 1, SQLProduct:", "1 required positional argument: 'item2'\" ): greasy_spoon['spam'] def test_no_factory(self): greasy_spoon", "@classmethod def setUpClass(cls): super(TestSQLDumpLoadShardedModels, cls).setUpClass() cls.factory = CaseFactory(domain=cls.domain_name) cls.form_accessors =", "TestSQLDumpLoadShardedModels(BaseDumpLoadTest): maxDiff = None @classmethod def setUpClass(cls): super(TestSQLDumpLoadShardedModels, cls).setUpClass() cls.factory", ") self._dump_and_load(Counter({ CaseUploadFileMeta: 1, CaseUploadRecord: 1, CaseUploadFormRecord: 1, })) def", "SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2') parchived = SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3', is_archived=True) self._dump_and_load(expected_object_counts)", "load_filter=None, expected_load_counts=None, dumper_fn=None): expected_load_counts = expected_load_counts or expected_dump_counts expected_dump_counts.update(self.default_objects_counts) models", "WebUser.create( domain=self.domain_name, username='webuser_t1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', ) self.addCleanup(ccuser_1.delete, self.domain_name,", "deleted_by=None) DemoUserRestore( demo_user_id=user_id, restore_blob_id=uuid.uuid4().hex, content_length=1027, restore_comment=\"Test migrate demo user restore\"", "1})) @mock.patch(\"corehq.apps.dump_reload.sql.load.ENQUEUE_TIMEOUT\", 1) class TestSqlLoadWithError(BaseDumpLoadTest): def setUp(self): self.products = [", "args = inspect.getargspec(receiver).args message = 'Signal handler \"{}\" for model", "] ) self.addCleanup(lambda: delete_alert_schedule_instances_for_schedule(AlertScheduleInstance, schedule.schedule_id)) self._dump_and_load(Counter({AlertSchedule: 1, AlertEvent: 2, SMSContent:", "greasy_spoon = DefaultDictWithKey(appender) with self.assertRaisesRegex( TypeError, r\"appender\\(\\) missing 1 required", ") class BaseDumpLoadTest(TestCase): @classmethod def setUpClass(cls): post_delete.disconnect(zapier_subscription_post_delete, sender=ZapierSubscription) super(BaseDumpLoadTest, cls).setUpClass()", ").save() self._dump_and_load(expected_object_counts) def test_products(self): from corehq.apps.products.models import SQLProduct expected_object_counts =", "message = 'Signal handler \"{}\" for model \"{}\" missing raw", "[]), ]), ]), ] location_types, locations = setup_locations_and_types( self.domain_name, location_type_names,", "missing 1 required positional argument: 'item2'\" ): greasy_spoon['spam'] def test_no_factory(self):", "= Counter({ CaseSearchConfig: 1, FuzzyProperties: 2, }) pre_config, created =", "}) role1 = UserRole.create(self.domain_name, 'role1') role2 = UserRole.create( self.domain_name, 'role1',", "expected_object_counts = Counter({SQLProduct: 3}) p1 = SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1') p2", "contact_last_modified=datetime.utcnow() ) phone_number.save() event = MessagingEvent.objects.create( domain=self.domain_name, date=datetime.utcnow(), source=MessagingEvent.SOURCE_REMINDER, content_type=MessagingEvent.CONTENT_SMS,", "arg'.format( receiver, model ) self.assertIn('raw', args, message) @nottest def delete_domain_sql_data_for_dump_load_test(domain_name):", "= self.case_accessors.get_case(pre_case.case_id) self.assertDictEqual(pre_case.to_json(), post_case.to_json()) def test_ledgers(self): expected_object_counts = Counter({ XFormInstanceSQL:", "self.assertDictEqual(pre_ledger_values[0].to_json(), post_ledger_values[0].to_json()) pre_ledger_transactions = sorted(pre_ledger_transactions, key=lambda t: t.pk) post_ledger_transactions =", "SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3'), ] def test_load_error_queue_full(self): \"\"\"Blocks when sending 'test3'\"\"\"", "super(BaseDumpLoadTest, cls).setUpClass() cls.domain_name = uuid.uuid4().hex cls.domain = Domain(name=cls.domain_name) cls.domain.save() cls.default_objects_counts", "corehq.apps.domain.models import Domain from corehq.apps.dump_reload.sql import SqlDataDumper, SqlDataLoader from corehq.apps.dump_reload.sql.dump", "expected_load_counts or expected_dump_counts expected_dump_counts.update(self.default_objects_counts) models = list(expected_dump_counts) self._check_signals_handle_raw(models) output_stream =", "output_stream = StringIO() SqlDataDumper(self.domain_name, [], []).dump(output_stream) self.delete_sql_data() # resave the", "self.addCleanup(web_user.delete, self.domain_name, deleted_by=None) self._dump_and_load(expected_object_counts) def test_dump_roles(self): from corehq.apps.users.models import UserRole,", "import ( SQLMobileBackend, SQLMobileBackendMapping, ) domain_backend = SQLMobileBackend.objects.create( domain=self.domain_name, name='test-domain-mobile-backend',", "LocationType, SQLLocation from corehq.apps.locations.tests.util import setup_locations_and_types expected_object_counts = Counter({LocationType: 3,", "# make sure that there's no data left in the", "for pre, post in zip(pre_ledger_transactions, post_ledger_transactions): self.assertEqual(str(pre), str(post)) class TestSQLDumpLoad(BaseDumpLoadTest):", "import mock from django.contrib.admin.utils import NestedObjects from django.db import transaction,", "Cape', [ ('Cape Winelands', [ ('Stellenbosch', []), ('Paarl', []), ]),", "domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', uuid=user_id ) self.addCleanup(user.delete, self.domain_name,", "AlertEvent: 2, SMSContent: 2})) def test_zapier_subscription(self): ZapierSubscription.objects.create( domain=self.domain_name, case_type='case_type', event_name=EventTypes.NEW_CASE,", "( state, { district.id: ( district, { section.id: (section, {}),", "1, TransifexProject: 2})) def test_filtered_dump_load(self): from corehq.apps.locations.tests.test_location_types import make_loc_type from", "filename='picture.jpg', length=1024, ) case_upload_record = CaseUploadRecord.objects.create( domain=self.domain_name, upload_id=uuid.uuid4(), task_id=uuid.uuid4(), couch_user_id=uuid.uuid4().hex,", "demo user restore\" ).save() self._dump_and_load(expected_object_counts) def test_products(self): from corehq.apps.products.models import", "( CaseUploadFileMeta, CaseUploadFormRecord, CaseUploadRecord, ) upload_file_meta = CaseUploadFileMeta.objects.create( identifier=uuid.uuid4().hex, filename='picture.jpg',", "match ID in devicelog.xml ) self.addCleanup(user.delete, self.domain_name, deleted_by=None) with open('corehq/ex-submodules/couchforms/tests/data/devicelogs/devicelog.xml',", "'rb') as f: xml = f.read() submit_form_locally(xml, self.domain_name) self._dump_and_load(expected_object_counts) def", "all data deleted: {}'.format(counts)) # Dump actual_model_counts, dump_lines = self._parse_dump_output(output_stream)", "CaseStructure( attrs={'case_name': 'child', 'update': {'age': 3, 'diabetic': False}, 'create': True},", "def empty_list(): return [] greasy_spoon = DefaultDictWithKey(empty_list) with self.assertRaisesRegex( TypeError,", "from corehq.form_processor.backends.sql.dbaccessors import LedgerAccessorSQL from corehq.form_processor.interfaces.dbaccessors import ( CaseAccessors, FormAccessors,", "t.pk) for pre, post in zip(pre_ledger_transactions, post_ledger_transactions): self.assertEqual(str(pre), str(post)) class", "self._dump_and_load(expected_object_counts) self.assertEqual(2, SQLProduct.active_objects.filter(domain=self.domain_name).count()) all_active = SQLProduct.active_objects.filter(domain=self.domain_name).all() self.assertTrue(p1 in all_active) self.assertTrue(p2", "CommCareUser from corehq.apps.users.models import WebUser from django.contrib.auth.models import User expected_object_counts", "RoleAssignableBy: 1 }) role1 = UserRole.create(self.domain_name, 'role1') role2 = UserRole.create(", "it.\"\"\" self._load_with_errors(chunk_size=2) def _load_with_errors(self, chunk_size): output_stream = StringIO() SqlDataDumper(self.domain_name, [],", "corehq.apps.commtrack.tests.util import get_single_balance_block from corehq.apps.domain.models import Domain from corehq.apps.dump_reload.sql import", "self.assertRaisesRegex( TypeError, r\"appender\\(\\) missing 1 required positional argument: 'item2'\" ):", "submit_form_locally(xml, self.domain_name) self._dump_and_load(expected_object_counts) def test_demo_user_restore(self): from corehq.apps.users.models import CommCareUser from", "created = CaseSearchConfig.objects.get_or_create(pk=self.domain_name) pre_config.enabled = True pre_fuzzies = [ FuzzyProperties(domain=self.domain,", "self.assertEqual(role1_loaded.assignable_by, []) self.assertEqual(role2_loaded.permissions.to_list(), Permissions(edit_web_users=True).to_list()) self.assertEqual(role2_loaded.assignable_by, [role1_loaded.get_id]) def test_device_logs(self): from corehq.apps.receiverwrapper.util", "resave the product to force an error self.products[0].save() actual_model_counts, dump_lines", "= output_stream.getvalue().split('\\n') dump_lines = [line.strip() for line in dump_output if", "in dump_lines]) return actual_model_counts, dump_lines def _check_signals_handle_raw(self, models): \"\"\"Ensure that", "location_type_names = ['province', 'district', 'city'] location_structure = [ ('Western Cape',", "[ ('Cape Winelands', [ ('Stellenbosch', []), ('Paarl', []), ]), ('Cape", "('Cape Town City', []), ]) ]), ('Gauteng', [ ('Ekurhuleni ',", "organization=org, slug='testp', name='demop', domain=self.domain_name ) TransifexProject.objects.create( organization=org, slug='testp1', name='demop1', domain=self.domain_name", "import User expected_object_counts = Counter({ User: 1, DemoUserRestore: 1 })", "self.assertEqual(role1_loaded.permissions.to_list(), Permissions().to_list()) self.assertEqual(role1_loaded.assignable_by, []) self.assertEqual(role2_loaded.permissions.to_list(), Permissions(edit_web_users=True).to_list()) self.assertEqual(role2_loaded.assignable_by, [role1_loaded.get_id]) def test_device_logs(self):", "setUpClass(cls): post_delete.disconnect(zapier_subscription_post_delete, sender=ZapierSubscription) super(BaseDumpLoadTest, cls).setUpClass() cls.domain_name = uuid.uuid4().hex cls.domain =", "1, DemoUserRestore: 1 }) user_id = uuid.uuid4().hex user = CommCareUser.create(", "DefaultDictWithKey() with self.assertRaisesRegex( TypeError, \"'NoneType' object is not callable\" ):", "ZapierSubscription from corehq.apps.zapier.signals.receivers import ( zapier_subscription_post_delete, ) from corehq.blobs.models import", "import User expected_object_counts = Counter({ User: 1, DeviceReportEntry: 7, UserEntry:", "<gh_stars>100-1000 import inspect import json import uuid from collections import", "from django.db.models.signals import post_delete, post_save from django.test import SimpleTestCase, TestCase", "3}) p1 = SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1') p2 = SQLProduct.objects.create(domain=self.domain_name, product_id='test2',", "(section, {}), block.id: (block, { center.id: (center, {}), }), },", "import EventTypes from corehq.apps.zapier.models import ZapierSubscription from corehq.apps.zapier.signals.receivers import (", "CaseTransaction: 3, LedgerValue: 1, LedgerTransaction: 2 }) case = self.factory.create_case()", "\\ delete_alert_schedule_instances_for_schedule schedule = AlertSchedule.create_simple_alert(self.domain, SMSContent()) schedule.set_custom_alert( [ (AlertEvent(minutes_to_wait=5), SMSContent()),", "in the DB objects_remaining = list(get_objects_to_dump(self.domain_name, [], [])) object_classes =", "_check_signals_handle_raw(self, models): \"\"\"Ensure that any post_save signal handlers have been", "assignable_by=[role1.id] ) self.addCleanup(role1.delete) self.addCleanup(role2.delete) self._dump_and_load(expected_object_counts) role1_loaded = UserRole.objects.get(id=role1.id) role2_loaded =", "FormAccessors, ) from corehq.form_processor.models import ( CaseTransaction, CommCareCaseIndexSQL, CommCareCaseSQL, LedgerTransaction,", "make_product from corehq.apps.commtrack.tests.util import get_single_balance_block from corehq.apps.domain.models import Domain from", "Counter({ User: 1, DemoUserRestore: 1 }) user_id = uuid.uuid4().hex user", "test_filtered_dump_load(self): from corehq.apps.locations.tests.test_location_types import make_loc_type from corehq.apps.products.models import SQLProduct from", "model label keyed counter\"\"\" def _model_class_to_label(model_class): label = '{}.{}'.format(model_class._meta.app_label, model_class.__name__)", "is_two_way=True, pending_verification=False, contact_last_modified=datetime.utcnow() ) phone_number.save() event = MessagingEvent.objects.create( domain=self.domain_name, date=datetime.utcnow(),", "Mobile Backend', hq_api_id='TGMB', inbound_api_key='test-global-mobile-backend-inbound-api-key', supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS, is_global=True, ) SQLMobileBackendMapping.objects.create( domain=self.domain_name,", "cls.domain = Domain(name=cls.domain_name) cls.domain.save() cls.default_objects_counts = Counter({}) @classmethod def tearDownClass(cls):", "'Stellenbosch', 'Paarl', 'Cape Town', 'Cape Town City'] ) result =", "whitelist_receivers: continue args = inspect.getargspec(receiver).args message = 'Signal handler \"{}\"", "Counter({LocationType: 1, SQLProduct: 1}) self._dump_and_load(expected_object_counts, load_filter='sqlproduct', expected_load_counts=Counter({SQLProduct: 1})) self.assertEqual(0, LocationType.objects.count())", "data deleted: {}'.format(counts)) # Dump actual_model_counts, dump_lines = self._parse_dump_output(output_stream) expected_model_counts", "cls).tearDownClass() def test_dump_load_form(self): expected_object_counts = Counter({ XFormInstanceSQL: 2, BlobMeta: 2", "[loc.name for loc in result], ['Cape Winelands', 'Stellenbosch', 'Paarl', 'Cape", "model_class.__name__) return label if for_loaded else label.lower() return Counter({ _model_class_to_label(model_class):", "indices=[ CaseIndex(CaseStructure(attrs={'case_name': 'parent', 'update': {'age': 42}, 'create': True})), ] )", "assert [] == list(get_objects_to_dump(domain_name, [], [])), \"Not all SQL objects", "Counter({User: 3}) ccuser_1 = CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None,", "= True pre_fuzzies = [ FuzzyProperties(domain=self.domain, case_type='dog', properties=['breed', 'color']), FuzzyProperties(domain=self.domain,", "django.contrib.admin.utils import NestedObjects from django.db import transaction, IntegrityError from django.db.models.signals", "SQLMobileBackend: 1, }) self.assertEqual(SQLMobileBackend.objects.first().domain, self.domain_name) self.assertEqual(SQLMobileBackendMapping.objects.first().domain, self.domain_name) def test_case_importer(self): from", "that the queue blocks loader.load_objects(dump_lines) class DefaultDictWithKeyTests(SimpleTestCase): def test_intended_use_case(self): def", "= AlertSchedule.create_simple_alert(self.domain, SMSContent()) schedule.set_custom_alert( [ (AlertEvent(minutes_to_wait=5), SMSContent()), (AlertEvent(minutes_to_wait=15), SMSContent()), ]", "3, 1), active=True, alert_schedule_id=uuid.uuid4(), ).save() self._dump_and_load({AlertScheduleInstance: 1}) def test_mobile_backend(self): from", "for case in pre_cases)) for pre_case in pre_cases: post_case =", "), } self.assertEqual(hierarchy, desired_hierarchy) def test_location(self): from corehq.apps.locations.models import LocationType,", "collector.delete() assert [] == list(get_objects_to_dump(domain_name, [], [])), \"Not all SQL", "Counter from datetime import datetime from io import StringIO import", "import ( FormProcessorTestUtils, create_form_for_test, sharded, ) from corehq.messaging.scheduling.scheduling_partitioned.models import (", "self._dump_and_load(expected_object_counts) post_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) post_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(post_ledger_values)) self.assertEqual(2,", "(block, { center.id: (center, {}), }), }, ), county.id: (", "def enlist(item): return [item] greasy_spoon = DefaultDictWithKey(enlist) self.assertEqual(greasy_spoon['spam'], ['spam']) greasy_spoon['spam'].append('spam')", "import BlobMeta from corehq.form_processor.backends.sql.dbaccessors import LedgerAccessorSQL from corehq.form_processor.interfaces.dbaccessors import (", "self.delete_sql_data() super(BaseDumpLoadTest, self).tearDown() def _dump_and_load(self, expected_dump_counts, load_filter=None, expected_load_counts=None, dumper_fn=None): expected_load_counts", "self.factory.create_case() submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id, 10) ], self.domain_name) submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id,", "self._dump_and_load(expected_object_counts, load_filter='sqlproduct', expected_load_counts=Counter({SQLProduct: 1})) self.assertEqual(0, LocationType.objects.count()) def test_sms_content(self): from corehq.messaging.scheduling.models", "domain=self.domain_name, backend=domain_backend, backend_type=SQLMobileBackend.SMS, prefix='123', ) global_backend = SQLMobileBackend.objects.create( domain=None, name='test-global-mobile-backend',", "for iterator in builder.querysets(): with transaction.atomic(using=iterator.db), \\ constraint_checks_deferred(iterator.db): collector =", "so that the queue blocks loader.load_objects(dump_lines) class DefaultDictWithKeyTests(SimpleTestCase): def test_intended_use_case(self):", "= CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', uuid='428d454aa9abc74e1964e16d3565d6b6' #", "from corehq.blobs.models import BlobMeta from corehq.form_processor.backends.sql.dbaccessors import LedgerAccessorSQL from corehq.form_processor.interfaces.dbaccessors", "for pre_case in pre_cases: post_case = self.case_accessors.get_case(pre_case.case_id) self.assertDictEqual(pre_case.to_json(), post_case.to_json()) def", "[]).dump(output_stream) self.delete_sql_data() # resave the product to force an error", "with self.assertRaisesRegex( TypeError, r\"appender\\(\\) missing 1 required positional argument: 'item2'\"", "[ ('Cape Town City', []), ]) ]), ('Gauteng', [ ('Ekurhuleni", "', [ ('Alberton', []), ('Benoni', []), ('Springs', []), ]), ]),", "if dumper_fn: dumper_fn(output_stream) else: SqlDataDumper(self.domain_name, [], []).dump(output_stream) self.delete_sql_data() # make", "left in the DB objects_remaining = list(get_objects_to_dump(self.domain_name, [], [])) object_classes", "pending_verification=False, contact_last_modified=datetime.utcnow() ) phone_number.save() event = MessagingEvent.objects.create( domain=self.domain_name, date=datetime.utcnow(), source=MessagingEvent.SOURCE_REMINDER,", "self.factory.create_or_update_case( CaseStructure( attrs={'case_name': 'child', 'update': {'age': 3, 'diabetic': False}, 'create':", ") domain_backend = SQLMobileBackend.objects.create( domain=self.domain_name, name='test-domain-mobile-backend', display_name='Test Domain Mobile Backend',", "post_config = CaseSearchConfig.objects.get(domain=self.domain_name) self.assertTrue(post_config.enabled) self.assertEqual(pre_config.fuzzy_properties, post_config.fuzzy_properties) post_fuzzies = FuzzyProperties.objects.filter(domain=self.domain_name) self.assertEqual(set(f.case_type", "def _load_with_errors(self, chunk_size): output_stream = StringIO() SqlDataDumper(self.domain_name, [], []).dump(output_stream) self.delete_sql_data()", "from django.test import SimpleTestCase, TestCase from nose.tools import nottest from", "else: SqlDataDumper(self.domain_name, [], []).dump(output_stream) self.delete_sql_data() # make sure that there's", "self.assertIn('raw', args, message) @nottest def delete_domain_sql_data_for_dump_load_test(domain_name): for model_class, builder in", "self.addCleanup(role2.delete) self._dump_and_load(expected_object_counts) role1_loaded = UserRole.objects.get(id=role1.id) role2_loaded = UserRole.objects.get(id=role2.id) self.assertEqual(role1_loaded.permissions.to_list(), Permissions().to_list())", "2, BlobMeta: 2, CommCareCaseSQL: 2, CaseTransaction: 3, CommCareCaseIndexSQL: 1 })", "= { state.id: ( state, { district.id: ( district, {", "domain=self.domain_name, recipient_type='CommCareUser', recipient_id=uuid.uuid4().hex, current_event_num=0, schedule_iteration_num=1, next_event_due=datetime(2017, 3, 1), active=True, alert_schedule_id=uuid.uuid4(),", "{'age': 42}, 'create': True})), ] ) ) pre_cases[0] = self.factory.create_or_update_case(CaseStructure(", "[ (AlertEvent(minutes_to_wait=5), SMSContent()), (AlertEvent(minutes_to_wait=15), SMSContent()), ] ) self.addCleanup(lambda: delete_alert_schedule_instances_for_schedule(AlertScheduleInstance, schedule.schedule_id))", "demo_user_id=user_id, restore_blob_id=uuid.uuid4().hex, content_length=1027, restore_comment=\"Test migrate demo user restore\" ).save() self._dump_and_load(expected_object_counts)", "submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id, 10) ], self.domain_name) submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id, 5)", "ForceCloseEntry: 1 }) user = CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None,", "= WebUser.create( domain=self.domain_name, username='webuser_t1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', ) self.addCleanup(ccuser_1.delete,", "3, BlobMeta: 3, CommCareCaseSQL: 1, CaseTransaction: 3, LedgerValue: 1, LedgerTransaction:", "1 }) role1 = UserRole.create(self.domain_name, 'role1') role2 = UserRole.create( self.domain_name,", "1, AlertEvent: 2, SMSContent: 2})) def test_zapier_subscription(self): ZapierSubscription.objects.create( domain=self.domain_name, case_type='case_type',", "in all_active) self.assertTrue(parchived not in all_active) def test_location_type(self): from corehq.apps.locations.models", "from corehq.apps.zapier.models import ZapierSubscription from corehq.apps.zapier.signals.receivers import ( zapier_subscription_post_delete, )", "import ( AlertScheduleInstance, ) class BaseDumpLoadTest(TestCase): @classmethod def setUpClass(cls): post_delete.disconnect(zapier_subscription_post_delete,", "self.domain_name) self.assertEqual(SQLMobileBackendMapping.objects.first().domain, self.domain_name) def test_case_importer(self): from corehq.apps.case_importer.tracking.models import ( CaseUploadFileMeta,", "pre_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) pre_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(pre_ledger_values)) self.assertEqual(2, len(pre_ledger_transactions))", "setUpClass(cls): super(TestSQLDumpLoadShardedModels, cls).setUpClass() cls.factory = CaseFactory(domain=cls.domain_name) cls.form_accessors = FormAccessors(cls.domain_name) cls.case_accessors", "created_by=None, created_via=None, email='<EMAIL>', ) web_user = WebUser.create( domain=self.domain_name, username='webuser_t1', password='<PASSWORD>',", "self.assertEqual(0, LocationType.objects.count()) def test_sms_content(self): from corehq.messaging.scheduling.models import AlertSchedule, SMSContent, AlertEvent", "[ ('Stellenbosch', []), ('Paarl', []), ]), ('Cape Town', [ ('Cape", "'create': True})), ] ) ) pre_cases[0] = self.factory.create_or_update_case(CaseStructure( case_id=pre_cases[0].case_id, attrs={'external_id':", "3) loader = SqlDataLoader() with self.assertRaises(IntegrityError),\\ mock.patch(\"corehq.apps.dump_reload.sql.load.CHUNK_SIZE\", chunk_size): # patch", "= self.case_accessors.get_case_ids_in_domain() self.assertEqual(set(case_ids), set(case.case_id for case in pre_cases)) for pre_case", "self.domain_name, 'role1', permissions=Permissions(edit_web_users=True), assignable_by=[role1.id] ) self.addCleanup(role1.delete) self.addCleanup(role2.delete) self._dump_and_load(expected_object_counts) role1_loaded =", "def test_sms_content(self): from corehq.messaging.scheduling.models import AlertSchedule, SMSContent, AlertEvent from corehq.messaging.scheduling.scheduling_partitioned.dbaccessors", "user restore\" ).save() self._dump_and_load(expected_object_counts) def test_products(self): from corehq.apps.products.models import SQLProduct", "('Western Cape', [ ('Cape Winelands', [ ('Stellenbosch', []), ('Paarl', []),", "password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', ) web_user = WebUser.create( domain=self.domain_name, username='webuser_t1',", "corehq.messaging.scheduling.scheduling_partitioned.dbaccessors import \\ delete_alert_schedule_instances_for_schedule schedule = AlertSchedule.create_simple_alert(self.domain, SMSContent()) schedule.set_custom_alert( [", "_load_with_errors(self, chunk_size): output_stream = StringIO() SqlDataDumper(self.domain_name, [], []).dump(output_stream) self.delete_sql_data() #", "Town City', []), ]) ]), ('Gauteng', [ ('Ekurhuleni ', [", "def tearDownClass(cls): cls.domain.delete() super(BaseDumpLoadTest, cls).tearDownClass() post_delete.connect(zapier_subscription_post_delete, sender=ZapierSubscription) def delete_sql_data(self): delete_domain_sql_data_for_dump_load_test(self.domain_name)", "CaseSearchConfig.objects.get_or_create(pk=self.domain_name) pre_config.enabled = True pre_fuzzies = [ FuzzyProperties(domain=self.domain, case_type='dog', properties=['breed',", "UserRole: 2, RolePermission: 11, RoleAssignableBy: 1 }) role1 = UserRole.create(self.domain_name,", "a <Model Class> keyed counter to an model label keyed", "line in dump_lines]) return actual_model_counts, dump_lines def _check_signals_handle_raw(self, models): \"\"\"Ensure", "receiver_path in whitelist_receivers: continue args = inspect.getargspec(receiver).args message = 'Signal", "backend_type=SQLMobileBackend.SMS, is_global=True, ) SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=global_backend, backend_type=SQLMobileBackend.SMS, prefix='*', ) self._dump_and_load({", "User: 1, DeviceReportEntry: 7, UserEntry: 1, UserErrorEntry: 2, ForceCloseEntry: 1", "pre, post in zip(pre_ledger_transactions, post_ledger_transactions): self.assertEqual(str(pre), str(post)) class TestSQLDumpLoad(BaseDumpLoadTest): def", "self.assertEqual(role2_loaded.permissions.to_list(), Permissions(edit_web_users=True).to_list()) self.assertEqual(role2_loaded.assignable_by, [role1_loaded.get_id]) def test_device_logs(self): from corehq.apps.receiverwrapper.util import submit_form_locally", "self.assertItemsEqual( [loc.name for loc in result], ['Cape Winelands', 'Stellenbosch', 'Paarl',", "CommCareUser.create( domain=self.domain_name, username='user_2', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', ) web_user =", "BlobMeta: 2, CommCareCaseSQL: 2, CaseTransaction: 3, CommCareCaseIndexSQL: 1 }) pre_cases", "actual_model_counts, dump_lines def _check_signals_handle_raw(self, models): \"\"\"Ensure that any post_save signal", "{}'.format(counts)) # Dump actual_model_counts, dump_lines = self._parse_dump_output(output_stream) expected_model_counts = _normalize_object_counter(expected_dump_counts)", "self._dump_and_load(Counter({TransifexOrganization: 1, TransifexProject: 2})) def test_filtered_dump_load(self): from corehq.apps.locations.tests.test_location_types import make_loc_type", "email='<EMAIL>', ) self.addCleanup(ccuser_1.delete, self.domain_name, deleted_by=None) self.addCleanup(ccuser_2.delete, self.domain_name, deleted_by=None) self.addCleanup(web_user.delete, self.domain_name,", "objects_remaining, 'Not all data deleted: {}'.format(counts)) # Dump actual_model_counts, dump_lines", "desired_hierarchy) def test_location(self): from corehq.apps.locations.models import LocationType, SQLLocation from corehq.apps.locations.tests.util", "LedgerValue, XFormInstanceSQL, ) from corehq.form_processor.tests.utils import ( FormProcessorTestUtils, create_form_for_test, sharded,", "= SQLProduct.active_objects.filter(domain=self.domain_name).all() self.assertTrue(p1 in all_active) self.assertTrue(p2 in all_active) self.assertTrue(parchived not", "import ( zapier_subscription_post_delete, ) from corehq.blobs.models import BlobMeta from corehq.form_processor.backends.sql.dbaccessors", "] def test_load_error_queue_full(self): \"\"\"Blocks when sending 'test3'\"\"\" self._load_with_errors(chunk_size=1) def test_load_error_queue_full_on_terminate(self):", "Town', 'Cape Town City'] ) result = SQLLocation.objects.get_locations_and_children([locations['Gauteng'].location_id]) self.assertItemsEqual( [loc.name", "FuzzyProperties(domain=self.domain, case_type='dog', properties=['breed', 'color']), FuzzyProperties(domain=self.domain, case_type='owner', properties=['name']), ] for fuzzy", "state, domain=self.domain_name) city = make_loc_type('city', county, domain=self.domain_name) self._dump_and_load(expected_object_counts) hierarchy =", "domain=self.domain_name) section = make_loc_type('section', district, domain=self.domain_name) block = make_loc_type('block', district,", "case_type='person', upload_file_meta=upload_file_meta, ) CaseUploadFormRecord.objects.create( case_upload_record=case_upload_record, form_id=uuid.uuid4().hex, ) self._dump_and_load(Counter({ CaseUploadFileMeta: 1,", "}) pre_config, created = CaseSearchConfig.objects.get_or_create(pk=self.domain_name) pre_config.enabled = True pre_fuzzies =", "list(get_objects_to_dump(domain_name, [], [])), \"Not all SQL objects deleted\" @sharded class", "hq_api_id='TDMB', inbound_api_key='test-domain-mobile-backend-inbound-api-key', supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS, is_global=False, ) SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=domain_backend, backend_type=SQLMobileBackend.SMS,", "= DefaultDictWithKey(enlist) self.assertEqual(greasy_spoon['spam'], ['spam']) greasy_spoon['spam'].append('spam') self.assertEqual(greasy_spoon['spam'], ['spam', 'spam']) def test_not_enough_params(self):", "from django.contrib.auth.models import User expected_object_counts = Counter({ User: 1, DemoUserRestore:", ") global_backend = SQLMobileBackend.objects.create( domain=None, name='test-global-mobile-backend', display_name='Test Global Mobile Backend',", "def test_sms(self): from corehq.apps.sms.models import PhoneNumber, MessagingEvent, MessagingSubEvent expected_object_counts =", "loader = SqlDataLoader() with self.assertRaises(IntegrityError),\\ mock.patch(\"corehq.apps.dump_reload.sql.load.CHUNK_SIZE\", chunk_size): # patch the", "username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', uuid='428d454aa9abc74e1964e16d3565d6b6' # match ID in", "sorted(post_ledger_transactions, key=lambda t: t.pk) for pre, post in zip(pre_ledger_transactions, post_ledger_transactions):", "UserRole.create(self.domain_name, 'role1') role2 = UserRole.create( self.domain_name, 'role1', permissions=Permissions(edit_web_users=True), assignable_by=[role1.id] )", "{'age': 3, 'diabetic': False}, 'create': True}, indices=[ CaseIndex(CaseStructure(attrs={'case_name': 'parent', 'update':", "7, UserEntry: 1, UserErrorEntry: 2, ForceCloseEntry: 1 }) user =", ") self._dump_and_load(Counter({TransifexOrganization: 1, TransifexProject: 2})) def test_filtered_dump_load(self): from corehq.apps.locations.tests.test_location_types import", "objects_remaining] counts = Counter(object_classes) self.assertEqual([], objects_remaining, 'Not all data deleted:", "inspect.getargspec(receiver).args message = 'Signal handler \"{}\" for model \"{}\" missing", "deleted_by=None) self.addCleanup(web_user.delete, self.domain_name, deleted_by=None) self._dump_and_load(expected_object_counts) def test_dump_roles(self): from corehq.apps.users.models import", "self._load_with_errors(chunk_size=2) def _load_with_errors(self, chunk_size): output_stream = StringIO() SqlDataDumper(self.domain_name, [], []).dump(output_stream)", "hierarchy = LocationType.objects.full_hierarchy(self.domain_name) desired_hierarchy = { state.id: ( state, {", "RolePermission expected_object_counts = Counter({ UserRole: 2, RolePermission: 11, RoleAssignableBy: 1", "import SQLProduct from corehq.apps.zapier.consts import EventTypes from corehq.apps.zapier.models import ZapierSubscription", "all SQL objects deleted\" @sharded class TestSQLDumpLoadShardedModels(BaseDumpLoadTest): maxDiff = None", "Product', 'prodcode_a') cls.default_objects_counts.update({SQLProduct: 1}) @classmethod def tearDownClass(cls): FormProcessorTestUtils.delete_all_cases_forms_ledgers(cls.domain_name) super(TestSQLDumpLoadShardedModels, cls).tearDownClass()", "from nose.tools import nottest from casexml.apps.case.mock import CaseFactory, CaseIndex, CaseStructure", "given' ): greasy_spoon['spam'] def test_too_many_params(self): def appender(item1, item2): return [item1,", "CaseUploadRecord: 1, CaseUploadFormRecord: 1, })) def test_transifex(self): from corehq.apps.translations.models import", "delete_alert_schedule_instances_for_schedule(AlertScheduleInstance, schedule.schedule_id)) self._dump_and_load(Counter({AlertSchedule: 1, AlertEvent: 2, SMSContent: 2})) def test_zapier_subscription(self):", "from corehq.apps.products.models import SQLProduct expected_object_counts = Counter({SQLProduct: 3}) p1 =", "LedgerAccessorSQL from corehq.form_processor.interfaces.dbaccessors import ( CaseAccessors, FormAccessors, ) from corehq.form_processor.models", "def setUpClass(cls): super(TestSQLDumpLoadShardedModels, cls).setUpClass() cls.factory = CaseFactory(domain=cls.domain_name) cls.form_accessors = FormAccessors(cls.domain_name)", "mock from django.contrib.admin.utils import NestedObjects from django.db import transaction, IntegrityError", "user_id = uuid.uuid4().hex user = CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None,", "created_by=None, created_via=None, email='<EMAIL>', uuid=user_id ) self.addCleanup(user.delete, self.domain_name, deleted_by=None) DemoUserRestore( demo_user_id=user_id,", "from corehq.apps.users.models import CommCareUser from corehq.apps.ota.models import DemoUserRestore from django.contrib.auth.models", "callable\" ): greasy_spoon['spam'] def _normalize_object_counter(counter, for_loaded=False): \"\"\"Converts a <Model Class>", "self.factory.create_or_update_case(CaseStructure( case_id=pre_cases[0].case_id, attrs={'external_id': 'billie jean', 'update': {'name': '<NAME>'}} ))[0] self._dump_and_load(expected_object_counts)", "domain=self.domain_name) block = make_loc_type('block', district, domain=self.domain_name) center = make_loc_type('center', block,", "self.domain_name, deleted_by=None) self._dump_and_load(expected_object_counts) def test_dump_roles(self): from corehq.apps.users.models import UserRole, Permissions,", "'role1') role2 = UserRole.create( self.domain_name, 'role1', permissions=Permissions(edit_web_users=True), assignable_by=[role1.id] ) self.addCleanup(role1.delete)", "collections import Counter from datetime import datetime from io import", "def delete_sql_data(self): delete_domain_sql_data_for_dump_load_test(self.domain_name) def tearDown(self): self.delete_sql_data() super(BaseDumpLoadTest, self).tearDown() def _dump_and_load(self,", "line.strip()] actual_model_counts = Counter([json.loads(line)['model'] for line in dump_lines]) return actual_model_counts,", "error self.products[0].save() actual_model_counts, dump_lines = self._parse_dump_output(output_stream) self.assertEqual(actual_model_counts['products.sqlproduct'], 3) loader =", "AlertSchedule.create_simple_alert(self.domain, SMSContent()) schedule.set_custom_alert( [ (AlertEvent(minutes_to_wait=5), SMSContent()), (AlertEvent(minutes_to_wait=15), SMSContent()), ] )", "import get_single_balance_block from corehq.apps.domain.models import Domain from corehq.apps.dump_reload.sql import SqlDataDumper,", "self.domain_name, location_type_names, [], location_structure, ) self._dump_and_load(expected_object_counts) names = ['Cape Winelands',", "CaseUploadRecord.objects.create( domain=self.domain_name, upload_id=uuid.uuid4(), task_id=uuid.uuid4(), couch_user_id=uuid.uuid4().hex, case_type='person', upload_file_meta=upload_file_meta, ) CaseUploadFormRecord.objects.create( case_upload_record=case_upload_record,", "= ['province', 'district', 'city'] location_structure = [ ('Western Cape', [", "= Counter({LocationType: 1, SQLProduct: 1}) self._dump_and_load(expected_object_counts, load_filter='sqlproduct', expected_load_counts=Counter({SQLProduct: 1})) self.assertEqual(0,", "block, domain=self.domain_name) county = make_loc_type('county', state, domain=self.domain_name) city = make_loc_type('city',", "1}) phone_number = PhoneNumber( domain=self.domain_name, owner_doc_type='CommCareCase', owner_id='fake-owner-id1', phone_number='99912341234', backend_id=None, ivr_backend_id=None,", "domain=self.domain_name) district = make_loc_type('district', state, domain=self.domain_name) section = make_loc_type('section', district,", "SqlDataLoader from corehq.apps.dump_reload.sql.dump import ( get_model_iterator_builders_to_dump, get_objects_to_dump, ) from corehq.apps.dump_reload.sql.load", "actual_model_counts = Counter([json.loads(line)['model'] for line in dump_lines]) return actual_model_counts, dump_lines", "1 }) user = CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None,", "attrs={'case_name': 'child', 'update': {'age': 3, 'diabetic': False}, 'create': True}, indices=[", "2, CaseTransaction: 3, CommCareCaseIndexSQL: 1 }) pre_cases = self.factory.create_or_update_case( CaseStructure(", "domain_backend = SQLMobileBackend.objects.create( domain=self.domain_name, name='test-domain-mobile-backend', display_name='Test Domain Mobile Backend', hq_api_id='TDMB',", "set(form.form_id for form in pre_forms)) for pre_form in pre_forms: post_form", "test_products(self): from corehq.apps.products.models import SQLProduct expected_object_counts = Counter({SQLProduct: 3}) p1", "expected_object_counts = Counter({LocationType: 7}) state = make_loc_type('state', domain=self.domain_name) district =", "FuzzyProperties(domain=self.domain, case_type='owner', properties=['name']), ] for fuzzy in pre_fuzzies: fuzzy.save() pre_config.fuzzy_properties.set(pre_fuzzies)", "def _check_signals_handle_raw(self, models): \"\"\"Ensure that any post_save signal handlers have", "3, CommCareCaseSQL: 1, CaseTransaction: 3, LedgerValue: 1, LedgerTransaction: 2 })", "name='test2') parchived = SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3', is_archived=True) self._dump_and_load(expected_object_counts) self.assertEqual(2, SQLProduct.active_objects.filter(domain=self.domain_name).count())", "Domain(name=cls.domain_name) cls.domain.save() cls.default_objects_counts = Counter({}) @classmethod def tearDownClass(cls): cls.domain.delete() super(BaseDumpLoadTest,", "['Cape Winelands', 'Stellenbosch', 'Paarl', 'Cape Town', 'Cape Town City'] )", "SQLProduct: 1}) self._dump_and_load(expected_object_counts, load_filter='sqlproduct', expected_load_counts=Counter({SQLProduct: 1})) self.assertEqual(0, LocationType.objects.count()) def test_sms_content(self):", "recipient_id=uuid.uuid4().hex, current_event_num=0, schedule_iteration_num=1, next_event_due=datetime(2017, 3, 1), active=True, alert_schedule_id=uuid.uuid4(), ).save() self._dump_and_load({AlertScheduleInstance:", "in result], ['Gauteng', 'Ekurhuleni ', 'Alberton', 'Benoni', 'Springs'] ) def", "cls.case_accessors = CaseAccessors(cls.domain_name) cls.product = make_product(cls.domain_name, 'A Product', 'prodcode_a') cls.default_objects_counts.update({SQLProduct:", "missing raw arg'.format( receiver, model ) self.assertIn('raw', args, message) @nottest", "= _normalize_object_counter(expected_dump_counts) self.assertDictEqual(dict(expected_model_counts), dict(actual_model_counts)) # Load loader = SqlDataLoader(object_filter=load_filter) loaded_model_counts", "form_ids = self.form_accessors.get_all_form_ids_in_domain('XFormInstance') self.assertEqual(set(form_ids), set(form.form_id for form in pre_forms)) for", "self.addCleanup(ccuser_2.delete, self.domain_name, deleted_by=None) self.addCleanup(web_user.delete, self.domain_name, deleted_by=None) self._dump_and_load(expected_object_counts) def test_dump_roles(self): from", "SQLMobileBackendMapping: 1, SQLMobileBackend: 1, }) self.assertEqual(SQLMobileBackend.objects.first().domain, self.domain_name) self.assertEqual(SQLMobileBackendMapping.objects.first().domain, self.domain_name) def", "self.assertDictEqual(dict(expected_model_counts), dict(actual_model_counts)) # Load loader = SqlDataLoader(object_filter=load_filter) loaded_model_counts = loader.load_objects(dump_lines)", "self.domain_name) pre_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) pre_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(pre_ledger_values)) self.assertEqual(2,", "greasy_spoon['spam'] def test_too_many_params(self): def appender(item1, item2): return [item1, item2] greasy_spoon", "1, CaseUploadRecord: 1, CaseUploadFormRecord: 1, })) def test_transifex(self): from corehq.apps.translations.models", "product_id='test3', name='test3'), ] def test_load_error_queue_full(self): \"\"\"Blocks when sending 'test3'\"\"\" self._load_with_errors(chunk_size=1)", "corehq.form_processor.models import ( CaseTransaction, CommCareCaseIndexSQL, CommCareCaseSQL, LedgerTransaction, LedgerValue, XFormInstanceSQL, )", "StringIO import mock from django.contrib.admin.utils import NestedObjects from django.db import", "def _normalize_object_counter(counter, for_loaded=False): \"\"\"Converts a <Model Class> keyed counter to", "to an model label keyed counter\"\"\" def _model_class_to_label(model_class): label =", "for loc in result], ['Cape Winelands', 'Stellenbosch', 'Paarl', 'Cape Town',", "CaseAccessors(cls.domain_name) cls.product = make_product(cls.domain_name, 'A Product', 'prodcode_a') cls.default_objects_counts.update({SQLProduct: 1}) @classmethod", "test_dump_load_form(self): expected_object_counts = Counter({ XFormInstanceSQL: 2, BlobMeta: 2 }) pre_forms", "from corehq.apps.locations.tests.util import setup_locations_and_types expected_object_counts = Counter({LocationType: 3, SQLLocation: 11})", "self.assertEqual(role2_loaded.assignable_by, [role1_loaded.get_id]) def test_device_logs(self): from corehq.apps.receiverwrapper.util import submit_form_locally from phonelog.models", ") self.assertIn('raw', args, message) @nottest def delete_domain_sql_data_for_dump_load_test(domain_name): for model_class, builder", "{}), }), }, ), county.id: ( county, {city.id: (city, {})},", "schedule.schedule_id)) self._dump_and_load(Counter({AlertSchedule: 1, AlertEvent: 2, SMSContent: 2})) def test_zapier_subscription(self): ZapierSubscription.objects.create(", "super(BaseDumpLoadTest, self).tearDown() def _dump_and_load(self, expected_dump_counts, load_filter=None, expected_load_counts=None, dumper_fn=None): expected_load_counts =", "post_ledger_transactions): self.assertEqual(str(pre), str(post)) class TestSQLDumpLoad(BaseDumpLoadTest): def test_case_search_config(self): from corehq.apps.case_search.models import", "corehq.apps.users.models import CommCareUser from django.contrib.auth.models import User expected_object_counts = Counter({", "Counter(object_classes) self.assertEqual([], objects_remaining, 'Not all data deleted: {}'.format(counts)) # Dump", "CaseAccessors, FormAccessors, ) from corehq.form_processor.models import ( CaseTransaction, CommCareCaseIndexSQL, CommCareCaseSQL,", "= self.factory.create_or_update_case( CaseStructure( attrs={'case_name': 'child', 'update': {'age': 3, 'diabetic': False},", "next_event_due=datetime(2017, 3, 1), active=True, alert_schedule_id=uuid.uuid4(), ).save() self._dump_and_load({AlertScheduleInstance: 1}) def test_mobile_backend(self):", "'A Product', 'prodcode_a') cls.default_objects_counts.update({SQLProduct: 1}) @classmethod def tearDownClass(cls): FormProcessorTestUtils.delete_all_cases_forms_ledgers(cls.domain_name) super(TestSQLDumpLoadShardedModels,", "self._dump_and_load(Counter({ZapierSubscription: 1})) @mock.patch(\"corehq.apps.dump_reload.sql.load.ENQUEUE_TIMEOUT\", 1) class TestSqlLoadWithError(BaseDumpLoadTest): def setUp(self): self.products =", "message) @nottest def delete_domain_sql_data_for_dump_load_test(domain_name): for model_class, builder in get_model_iterator_builders_to_dump(domain_name, [],", "self.assertEqual(1, len(post_ledger_values)) self.assertEqual(2, len(post_ledger_transactions)) self.assertEqual(pre_ledger_values[0].ledger_reference, post_ledger_values[0].ledger_reference) self.assertDictEqual(pre_ledger_values[0].to_json(), post_ledger_values[0].to_json()) pre_ledger_transactions =", "3, SQLLocation: 11}) location_type_names = ['province', 'district', 'city'] location_structure =", "[ SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1'), SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2'), SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3'),", "t: t.pk) for pre, post in zip(pre_ledger_transactions, post_ledger_transactions): self.assertEqual(str(pre), str(post))", "from corehq.form_processor.interfaces.dbaccessors import ( CaseAccessors, FormAccessors, ) from corehq.form_processor.models import", "sender=ZapierSubscription) def delete_sql_data(self): delete_domain_sql_data_for_dump_load_test(self.domain_name) def tearDown(self): self.delete_sql_data() super(BaseDumpLoadTest, self).tearDown() def", "self.domain_name, deleted_by=None) with open('corehq/ex-submodules/couchforms/tests/data/devicelogs/devicelog.xml', 'rb') as f: xml = f.read()", "for_loaded else label.lower() return Counter({ _model_class_to_label(model_class): count for model_class, count", "[ 'django_digest.models._post_save_persist_partial_digests' ] for model in models: for receiver in", "def test_load_error_queue_full_on_terminate(self): \"\"\"Blocks when sending ``None`` into the queue to", "corehq.apps.case_importer.tracking.models import ( CaseUploadFileMeta, CaseUploadFormRecord, CaseUploadRecord, ) upload_file_meta = CaseUploadFileMeta.objects.create(", "import setup_locations_and_types expected_object_counts = Counter({LocationType: 3, SQLLocation: 11}) location_type_names =", "from datetime import datetime from io import StringIO import mock", "_normalize_object_counter(expected_load_counts, for_loaded=True) self.assertDictEqual(dict(normalized_expected_loaded_counts), dict(loaded_model_counts)) self.assertEqual(sum(expected_load_counts.values()), sum(loaded_model_counts.values())) return dump_lines def _parse_dump_output(self,", ") from corehq.form_processor.models import ( CaseTransaction, CommCareCaseIndexSQL, CommCareCaseSQL, LedgerTransaction, LedgerValue,", "from corehq.form_processor.models import ( CaseTransaction, CommCareCaseIndexSQL, CommCareCaseSQL, LedgerTransaction, LedgerValue, XFormInstanceSQL,", "self.delete_sql_data() # make sure that there's no data left in", "['spam']) greasy_spoon['spam'].append('spam') self.assertEqual(greasy_spoon['spam'], ['spam', 'spam']) def test_not_enough_params(self): def empty_list(): return", "name in names] result = SQLLocation.objects.get_locations_and_children(location_ids) self.assertItemsEqual( [loc.name for loc", "for model in models: for receiver in post_save._live_receivers(model): receiver_path =", "= LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) pre_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(pre_ledger_values)) self.assertEqual(2, len(pre_ledger_transactions)) self._dump_and_load(expected_object_counts)", "User expected_object_counts = Counter({User: 3}) ccuser_1 = CommCareUser.create( domain=self.domain_name, username='user_1',", "corehq.apps.dump_reload.sql import SqlDataDumper, SqlDataLoader from corehq.apps.dump_reload.sql.dump import ( get_model_iterator_builders_to_dump, get_objects_to_dump,", "Counter({PhoneNumber: 1, MessagingEvent: 1, MessagingSubEvent: 1}) phone_number = PhoneNumber( domain=self.domain_name,", "1, SQLProduct: 1}) self._dump_and_load(expected_object_counts, load_filter='sqlproduct', expected_load_counts=Counter({SQLProduct: 1})) self.assertEqual(0, LocationType.objects.count()) def", "Counter({ CaseSearchConfig: 1, FuzzyProperties: 2, }) pre_config, created = CaseSearchConfig.objects.get_or_create(pk=self.domain_name)", "to force an error self.products[0].save() actual_model_counts, dump_lines = self._parse_dump_output(output_stream) self.assertEqual(actual_model_counts['products.sqlproduct'],", "[], []).dump(output_stream) self.delete_sql_data() # resave the product to force an", "post in zip(pre_ledger_transactions, post_ledger_transactions): self.assertEqual(str(pre), str(post)) class TestSQLDumpLoad(BaseDumpLoadTest): def test_case_search_config(self):", "[]), ]) ]), ('Gauteng', [ ('Ekurhuleni ', [ ('Alberton', []),", "password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', ) self.addCleanup(ccuser_1.delete, self.domain_name, deleted_by=None) self.addCleanup(ccuser_2.delete, self.domain_name,", "counter to an model label keyed counter\"\"\" def _model_class_to_label(model_class): label", "phone_number = PhoneNumber( domain=self.domain_name, owner_doc_type='CommCareCase', owner_id='fake-owner-id1', phone_number='99912341234', backend_id=None, ivr_backend_id=None, verified=True,", "for name in names] result = SQLLocation.objects.get_locations_and_children(location_ids) self.assertItemsEqual( [loc.name for", "get_model_iterator_builders_to_dump, get_objects_to_dump, ) from corehq.apps.dump_reload.sql.load import ( DefaultDictWithKey, constraint_checks_deferred, )", "is_global=False, ) SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=domain_backend, backend_type=SQLMobileBackend.SMS, prefix='123', ) global_backend =", "TransifexOrganization.objects.create(slug='test', name='demo', api_token='<PASSWORD>') TransifexProject.objects.create( organization=org, slug='testp', name='demop', domain=self.domain_name ) TransifexProject.objects.create(", "): greasy_spoon['spam'] def test_too_many_params(self): def appender(item1, item2): return [item1, item2]", "['Cape Winelands', 'Paarl', 'Cape Town'] location_ids = [locations[name].location_id for name", "domain=self.domain_name, name='test-domain-mobile-backend', display_name='Test Domain Mobile Backend', hq_api_id='TDMB', inbound_api_key='test-domain-mobile-backend-inbound-api-key', supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS,", "corehq.apps.locations.models import LocationType make_loc_type('state', domain=self.domain_name) SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1') expected_object_counts =", "from corehq.apps.users.models import WebUser from django.contrib.auth.models import User expected_object_counts =", "[ create_form_for_test(self.domain_name), create_form_for_test(self.domain_name) ] self._dump_and_load(expected_object_counts) form_ids = self.form_accessors.get_all_form_ids_in_domain('XFormInstance') self.assertEqual(set(form_ids), set(form.form_id", "] for fuzzy in pre_fuzzies: fuzzy.save() pre_config.fuzzy_properties.set(pre_fuzzies) pre_config.save() self._dump_and_load(expected_object_counts) post_config", "create_form_for_test(self.domain_name) ] self._dump_and_load(expected_object_counts) form_ids = self.form_accessors.get_all_form_ids_in_domain('XFormInstance') self.assertEqual(set(form_ids), set(form.form_id for form", "cls.domain_name = uuid.uuid4().hex cls.domain = Domain(name=cls.domain_name) cls.domain.save() cls.default_objects_counts = Counter({})", "args, message) @nottest def delete_domain_sql_data_for_dump_load_test(domain_name): for model_class, builder in get_model_iterator_builders_to_dump(domain_name,", "LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(pre_ledger_values)) self.assertEqual(2, len(pre_ledger_transactions)) self._dump_and_load(expected_object_counts) post_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) post_ledger_transactions", "CaseUploadRecord, ) upload_file_meta = CaseUploadFileMeta.objects.create( identifier=uuid.uuid4().hex, filename='picture.jpg', length=1024, ) case_upload_record", "upload_id=uuid.uuid4(), task_id=uuid.uuid4(), couch_user_id=uuid.uuid4().hex, case_type='person', upload_file_meta=upload_file_meta, ) CaseUploadFormRecord.objects.create( case_upload_record=case_upload_record, form_id=uuid.uuid4().hex, )", "2 }) pre_forms = [ create_form_for_test(self.domain_name), create_form_for_test(self.domain_name) ] self._dump_and_load(expected_object_counts) form_ids", "created_via=None, email='<EMAIL>', uuid=user_id ) self.addCleanup(user.delete, self.domain_name, deleted_by=None) DemoUserRestore( demo_user_id=user_id, restore_blob_id=uuid.uuid4().hex,", "DefaultDictWithKeyTests(SimpleTestCase): def test_intended_use_case(self): def enlist(item): return [item] greasy_spoon = DefaultDictWithKey(enlist)", "): greasy_spoon['spam'] def _normalize_object_counter(counter, for_loaded=False): \"\"\"Converts a <Model Class> keyed", "post_ledger_values[0].to_json()) pre_ledger_transactions = sorted(pre_ledger_transactions, key=lambda t: t.pk) post_ledger_transactions = sorted(post_ledger_transactions,", "['Gauteng', 'Ekurhuleni ', 'Alberton', 'Benoni', 'Springs'] ) def test_sms(self): from", "upload_file_meta=upload_file_meta, ) CaseUploadFormRecord.objects.create( case_upload_record=case_upload_record, form_id=uuid.uuid4().hex, ) self._dump_and_load(Counter({ CaseUploadFileMeta: 1, CaseUploadRecord:", "UserRole.objects.get(id=role1.id) role2_loaded = UserRole.objects.get(id=role2.id) self.assertEqual(role1_loaded.permissions.to_list(), Permissions().to_list()) self.assertEqual(role1_loaded.assignable_by, []) self.assertEqual(role2_loaded.permissions.to_list(), Permissions(edit_web_users=True).to_list())", "label.lower() return Counter({ _model_class_to_label(model_class): count for model_class, count in counter.items()", "dump_output = output_stream.getvalue().split('\\n') dump_lines = [line.strip() for line in dump_output", "self.assertEqual(1, len(pre_ledger_values)) self.assertEqual(2, len(pre_ledger_transactions)) self._dump_and_load(expected_object_counts) post_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) post_ledger_transactions =", "pre_cases[0] = self.factory.create_or_update_case(CaseStructure( case_id=pre_cases[0].case_id, attrs={'external_id': 'billie jean', 'update': {'name': '<NAME>'}}", "= SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2') parchived = SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3', is_archived=True)", "corehq.apps.zapier.models import ZapierSubscription from corehq.apps.zapier.signals.receivers import ( zapier_subscription_post_delete, ) from", "= self._parse_dump_output(output_stream) self.assertEqual(actual_model_counts['products.sqlproduct'], 3) loader = SqlDataLoader() with self.assertRaises(IntegrityError),\\ mock.patch(\"corehq.apps.dump_reload.sql.load.CHUNK_SIZE\",", "= CaseUploadFileMeta.objects.create( identifier=uuid.uuid4().hex, filename='picture.jpg', length=1024, ) case_upload_record = CaseUploadRecord.objects.create( domain=self.domain_name,", "self.assertEqual(2, len(pre_ledger_transactions)) self._dump_and_load(expected_object_counts) post_ledger_values = LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) post_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1,", "backend=global_backend, backend_type=SQLMobileBackend.SMS, prefix='*', ) self._dump_and_load({ SQLMobileBackendMapping: 1, SQLMobileBackend: 1, })", "user_id='user_id', ) self._dump_and_load(Counter({ZapierSubscription: 1})) @mock.patch(\"corehq.apps.dump_reload.sql.load.ENQUEUE_TIMEOUT\", 1) class TestSqlLoadWithError(BaseDumpLoadTest): def setUp(self):", "def delete_domain_sql_data_for_dump_load_test(domain_name): for model_class, builder in get_model_iterator_builders_to_dump(domain_name, [], []): for", "test_load_error_queue_full(self): \"\"\"Blocks when sending 'test3'\"\"\" self._load_with_errors(chunk_size=1) def test_load_error_queue_full_on_terminate(self): \"\"\"Blocks when", "dump_lines = self._parse_dump_output(output_stream) self.assertEqual(actual_model_counts['products.sqlproduct'], 3) loader = SqlDataLoader() with self.assertRaises(IntegrityError),\\", "for fuzzy in pre_fuzzies: fuzzy.save() pre_config.fuzzy_properties.set(pre_fuzzies) pre_config.save() self._dump_and_load(expected_object_counts) post_config =", "= Counter({LocationType: 7}) state = make_loc_type('state', domain=self.domain_name) district = make_loc_type('district',", "deleted_by=None) self.addCleanup(ccuser_2.delete, self.domain_name, deleted_by=None) self.addCleanup(web_user.delete, self.domain_name, deleted_by=None) self._dump_and_load(expected_object_counts) def test_dump_roles(self):", "product to force an error self.products[0].save() actual_model_counts, dump_lines = self._parse_dump_output(output_stream)", "2})) def test_filtered_dump_load(self): from corehq.apps.locations.tests.test_location_types import make_loc_type from corehq.apps.products.models import", "from corehq.apps.commtrack.helpers import make_product from corehq.apps.commtrack.tests.util import get_single_balance_block from corehq.apps.domain.models", "from corehq.apps.hqcase.utils import submit_case_blocks from corehq.apps.products.models import SQLProduct from corehq.apps.zapier.consts", "dump_lines def _check_signals_handle_raw(self, models): \"\"\"Ensure that any post_save signal handlers", "( DefaultDictWithKey, constraint_checks_deferred, ) from corehq.apps.hqcase.utils import submit_case_blocks from corehq.apps.products.models", "= SqlDataLoader(object_filter=load_filter) loaded_model_counts = loader.load_objects(dump_lines) normalized_expected_loaded_counts = _normalize_object_counter(expected_load_counts, for_loaded=True) self.assertDictEqual(dict(normalized_expected_loaded_counts),", "Town City'] ) result = SQLLocation.objects.get_locations_and_children([locations['Gauteng'].location_id]) self.assertItemsEqual( [loc.name for loc", "supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS, is_global=True, ) SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=global_backend, backend_type=SQLMobileBackend.SMS, prefix='*', )", "'django_digest.models._post_save_persist_partial_digests' ] for model in models: for receiver in post_save._live_receivers(model):", "result = SQLLocation.objects.get_locations_and_children([locations['Gauteng'].location_id]) self.assertItemsEqual( [loc.name for loc in result], ['Gauteng',", "name='demop1', domain=self.domain_name ) self._dump_and_load(Counter({TransifexOrganization: 1, TransifexProject: 2})) def test_filtered_dump_load(self): from", "= Domain(name=cls.domain_name) cls.domain.save() cls.default_objects_counts = Counter({}) @classmethod def tearDownClass(cls): cls.domain.delete()", "user = CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', uuid='428d454aa9abc74e1964e16d3565d6b6'", "block.id: (block, { center.id: (center, {}), }), }, ), county.id:", "uuid.uuid4().hex user = CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>',", "def _parse_dump_output(self, output_stream): dump_output = output_stream.getvalue().split('\\n') dump_lines = [line.strip() for", "DemoUserRestore from django.contrib.auth.models import User expected_object_counts = Counter({ User: 1,", "in pre_cases)) for pre_case in pre_cases: post_case = self.case_accessors.get_case(pre_case.case_id) self.assertDictEqual(pre_case.to_json(),", "= CaseUploadRecord.objects.create( domain=self.domain_name, upload_id=uuid.uuid4(), task_id=uuid.uuid4(), couch_user_id=uuid.uuid4().hex, case_type='person', upload_file_meta=upload_file_meta, ) CaseUploadFormRecord.objects.create(", "properties=['breed', 'color']), FuzzyProperties(domain=self.domain, case_type='owner', properties=['name']), ] for fuzzy in pre_fuzzies:", "expected_object_counts = Counter({User: 3}) ccuser_1 = CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>',", "when sending ``None`` into the queue to 'terminate' it.\"\"\" self._load_with_errors(chunk_size=2)", "self.assertRaises(IntegrityError),\\ mock.patch(\"corehq.apps.dump_reload.sql.load.CHUNK_SIZE\", chunk_size): # patch the chunk size so that", "1, DeviceReportEntry: 7, UserEntry: 1, UserErrorEntry: 2, ForceCloseEntry: 1 })", "[])) object_classes = [obj.__class__.__name__ for obj in objects_remaining] counts =", "t: t.pk) post_ledger_transactions = sorted(post_ledger_transactions, key=lambda t: t.pk) for pre,", "import SqlDataDumper, SqlDataLoader from corehq.apps.dump_reload.sql.dump import ( get_model_iterator_builders_to_dump, get_objects_to_dump, )", "class TestSqlLoadWithError(BaseDumpLoadTest): def setUp(self): self.products = [ SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1'),", "FuzzyProperties: 2, }) pre_config, created = CaseSearchConfig.objects.get_or_create(pk=self.domain_name) pre_config.enabled = True", "= make_loc_type('district', state, domain=self.domain_name) section = make_loc_type('section', district, domain=self.domain_name) block", "self._dump_and_load({AlertScheduleInstance: 1}) def test_mobile_backend(self): from corehq.apps.sms.models import ( SQLMobileBackend, SQLMobileBackendMapping,", "for_loaded=False): \"\"\"Converts a <Model Class> keyed counter to an model", "def test_dump_roles(self): from corehq.apps.users.models import UserRole, Permissions, RoleAssignableBy, RolePermission expected_object_counts", "SQLProduct.active_objects.filter(domain=self.domain_name).count()) all_active = SQLProduct.active_objects.filter(domain=self.domain_name).all() self.assertTrue(p1 in all_active) self.assertTrue(p2 in all_active)", "from corehq.apps.dump_reload.sql.load import ( DefaultDictWithKey, constraint_checks_deferred, ) from corehq.apps.hqcase.utils import", "backend_type=SQLMobileBackend.SMS, prefix='*', ) self._dump_and_load({ SQLMobileBackendMapping: 1, SQLMobileBackend: 1, }) self.assertEqual(SQLMobileBackend.objects.first().domain,", "def test_intended_use_case(self): def enlist(item): return [item] greasy_spoon = DefaultDictWithKey(enlist) self.assertEqual(greasy_spoon['spam'],", "not callable\" ): greasy_spoon['spam'] def _normalize_object_counter(counter, for_loaded=False): \"\"\"Converts a <Model", "schedule.set_custom_alert( [ (AlertEvent(minutes_to_wait=5), SMSContent()), (AlertEvent(minutes_to_wait=15), SMSContent()), ] ) self.addCleanup(lambda: delete_alert_schedule_instances_for_schedule(AlertScheduleInstance,", "locations = setup_locations_and_types( self.domain_name, location_type_names, [], location_structure, ) self._dump_and_load(expected_object_counts) names", "domain=self.domain_name, username='user_2', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', ) web_user = WebUser.create(", "if line.strip()] actual_model_counts = Counter([json.loads(line)['model'] for line in dump_lines]) return", "expected_dump_counts.update(self.default_objects_counts) models = list(expected_dump_counts) self._check_signals_handle_raw(models) output_stream = StringIO() if dumper_fn:", "name='demop', domain=self.domain_name ) TransifexProject.objects.create( organization=org, slug='testp1', name='demop1', domain=self.domain_name ) self._dump_and_load(Counter({TransifexOrganization:", "county, {city.id: (city, {})}, ), }, ), } self.assertEqual(hierarchy, desired_hierarchy)", "keyed counter to an model label keyed counter\"\"\" def _model_class_to_label(model_class):", "= UserRole.create(self.domain_name, 'role1') role2 = UserRole.create( self.domain_name, 'role1', permissions=Permissions(edit_web_users=True), assignable_by=[role1.id]", "import CaseFactory, CaseIndex, CaseStructure from corehq.apps.commtrack.helpers import make_product from corehq.apps.commtrack.tests.util", "objects deleted\" @sharded class TestSQLDumpLoadShardedModels(BaseDumpLoadTest): maxDiff = None @classmethod def", "self.domain_name, deleted_by=None) self.addCleanup(web_user.delete, self.domain_name, deleted_by=None) self._dump_and_load(expected_object_counts) def test_dump_roles(self): from corehq.apps.users.models", "[]), ('Paarl', []), ]), ('Cape Town', [ ('Cape Town City',", "= [locations[name].location_id for name in names] result = SQLLocation.objects.get_locations_and_children(location_ids) self.assertItemsEqual(", "test_ledgers(self): expected_object_counts = Counter({ XFormInstanceSQL: 3, BlobMeta: 3, CommCareCaseSQL: 1,", "domain=self.domain_name) county = make_loc_type('county', state, domain=self.domain_name) city = make_loc_type('city', county,", "class DefaultDictWithKeyTests(SimpleTestCase): def test_intended_use_case(self): def enlist(item): return [item] greasy_spoon =", "username='user_2', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', ) web_user = WebUser.create( domain=self.domain_name,", "TestSqlLoadWithError(BaseDumpLoadTest): def setUp(self): self.products = [ SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1'), SQLProduct.objects.create(domain=self.domain_name,", "[] greasy_spoon = DefaultDictWithKey(empty_list) with self.assertRaisesRegex( TypeError, r'empty_list\\(\\) takes 0", ") pre_cases[0] = self.factory.create_or_update_case(CaseStructure( case_id=pre_cases[0].case_id, attrs={'external_id': 'billie jean', 'update': {'name':", "'Benoni', 'Springs'] ) def test_sms(self): from corehq.apps.sms.models import PhoneNumber, MessagingEvent,", "corehq.apps.products.models import SQLProduct from corehq.apps.zapier.consts import EventTypes from corehq.apps.zapier.models import", "dump_lines = [line.strip() for line in dump_output if line.strip()] actual_model_counts", "7}) state = make_loc_type('state', domain=self.domain_name) district = make_loc_type('district', state, domain=self.domain_name)", "dumper_fn(output_stream) else: SqlDataDumper(self.domain_name, [], []).dump(output_stream) self.delete_sql_data() # make sure that", "chunk_size): # patch the chunk size so that the queue", "'item2'\" ): greasy_spoon['spam'] def test_no_factory(self): greasy_spoon = DefaultDictWithKey() with self.assertRaisesRegex(", "calls.\"\"\" whitelist_receivers = [ 'django_digest.models._post_save_persist_partial_digests' ] for model in models:", "corehq.apps.locations.tests.util import setup_locations_and_types expected_object_counts = Counter({LocationType: 3, SQLLocation: 11}) location_type_names", "location_structure, ) self._dump_and_load(expected_object_counts) names = ['Cape Winelands', 'Paarl', 'Cape Town']", "TransifexProject, TransifexOrganization org = TransifexOrganization.objects.create(slug='test', name='demo', api_token='<PASSWORD>') TransifexProject.objects.create( organization=org, slug='testp',", "cls).tearDownClass() post_delete.connect(zapier_subscription_post_delete, sender=ZapierSubscription) def delete_sql_data(self): delete_domain_sql_data_for_dump_load_test(self.domain_name) def tearDown(self): self.delete_sql_data() super(BaseDumpLoadTest,", "User expected_object_counts = Counter({ User: 1, DeviceReportEntry: 7, UserEntry: 1,", "self.assertDictEqual(dict(normalized_expected_loaded_counts), dict(loaded_model_counts)) self.assertEqual(sum(expected_load_counts.values()), sum(loaded_model_counts.values())) return dump_lines def _parse_dump_output(self, output_stream): dump_output", "self.assertEqual(pre_config.fuzzy_properties, post_config.fuzzy_properties) post_fuzzies = FuzzyProperties.objects.filter(domain=self.domain_name) self.assertEqual(set(f.case_type for f in post_fuzzies),", "DeviceReportEntry: 7, UserEntry: 1, UserErrorEntry: 2, ForceCloseEntry: 1 }) user", "_dump_and_load(self, expected_dump_counts, load_filter=None, expected_load_counts=None, dumper_fn=None): expected_load_counts = expected_load_counts or expected_dump_counts", "from corehq.apps.ota.models import DemoUserRestore from django.contrib.auth.models import User expected_object_counts =", "in pre_cases: post_case = self.case_accessors.get_case(pre_case.case_id) self.assertDictEqual(pre_case.to_json(), post_case.to_json()) def test_ledgers(self): expected_object_counts", "BaseDumpLoadTest(TestCase): @classmethod def setUpClass(cls): post_delete.disconnect(zapier_subscription_post_delete, sender=ZapierSubscription) super(BaseDumpLoadTest, cls).setUpClass() cls.domain_name =", "AlertSchedule, SMSContent, AlertEvent from corehq.messaging.scheduling.scheduling_partitioned.dbaccessors import \\ delete_alert_schedule_instances_for_schedule schedule =", "key=lambda t: t.pk) post_ledger_transactions = sorted(post_ledger_transactions, key=lambda t: t.pk) for", "from corehq.apps.locations.models import LocationType, SQLLocation from corehq.apps.locations.tests.util import setup_locations_and_types expected_object_counts", "{ center.id: (center, {}), }), }, ), county.id: ( county,", "self.assertEqual(SQLMobileBackend.objects.first().domain, self.domain_name) self.assertEqual(SQLMobileBackendMapping.objects.first().domain, self.domain_name) def test_case_importer(self): from corehq.apps.case_importer.tracking.models import (", "from corehq.apps.zapier.consts import EventTypes from corehq.apps.zapier.models import ZapierSubscription from corehq.apps.zapier.signals.receivers", "all_active) self.assertTrue(p2 in all_active) self.assertTrue(parchived not in all_active) def test_location_type(self):", "= sorted(post_ledger_transactions, key=lambda t: t.pk) for pre, post in zip(pre_ledger_transactions,", "def test_demo_user_restore(self): from corehq.apps.users.models import CommCareUser from corehq.apps.ota.models import DemoUserRestore", "= Counter(object_classes) self.assertEqual([], objects_remaining, 'Not all data deleted: {}'.format(counts)) #", "( AlertScheduleInstance, ) class BaseDumpLoadTest(TestCase): @classmethod def setUpClass(cls): post_delete.disconnect(zapier_subscription_post_delete, sender=ZapierSubscription)", "but 1 was given' ): greasy_spoon['spam'] def test_too_many_params(self): def appender(item1,", "= DefaultDictWithKey() with self.assertRaisesRegex( TypeError, \"'NoneType' object is not callable\"", "email='<EMAIL>', uuid='428d454aa9abc74e1964e16d3565d6b6' # match ID in devicelog.xml ) self.addCleanup(user.delete, self.domain_name,", "import submit_form_locally from phonelog.models import DeviceReportEntry, ForceCloseEntry, UserEntry, UserErrorEntry from", "django.contrib.auth.models import User expected_object_counts = Counter({ User: 1, DeviceReportEntry: 7,", "UserEntry: 1, UserErrorEntry: 2, ForceCloseEntry: 1 }) user = CommCareUser.create(", "('Benoni', []), ('Springs', []), ]), ]), ] location_types, locations =", "return [item1, item2] greasy_spoon = DefaultDictWithKey(appender) with self.assertRaisesRegex( TypeError, r\"appender\\(\\)", "test_demo_user_restore(self): from corehq.apps.users.models import CommCareUser from corehq.apps.ota.models import DemoUserRestore from", "EventTypes from corehq.apps.zapier.models import ZapierSubscription from corehq.apps.zapier.signals.receivers import ( zapier_subscription_post_delete,", "for loc in result], ['Gauteng', 'Ekurhuleni ', 'Alberton', 'Benoni', 'Springs']", "the queue to 'terminate' it.\"\"\" self._load_with_errors(chunk_size=2) def _load_with_errors(self, chunk_size): output_stream", "created_by=None, created_via=None, email='<EMAIL>', uuid='428d454aa9abc74e1964e16d3565d6b6' # match ID in devicelog.xml )", "[]).dump(output_stream) self.delete_sql_data() # make sure that there's no data left", "DB objects_remaining = list(get_objects_to_dump(self.domain_name, [], [])) object_classes = [obj.__class__.__name__ for", "district, domain=self.domain_name) center = make_loc_type('center', block, domain=self.domain_name) county = make_loc_type('county',", "], self.domain_name) submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id, 5) ], self.domain_name) pre_ledger_values =", "SQLMobileBackend.objects.create( domain=None, name='test-global-mobile-backend', display_name='Test Global Mobile Backend', hq_api_id='TGMB', inbound_api_key='test-global-mobile-backend-inbound-api-key', supported_countries=[\"*\"],", "get_model_iterator_builders_to_dump(domain_name, [], []): for iterator in builder.querysets(): with transaction.atomic(using=iterator.db), \\", "from corehq.form_processor.tests.utils import ( FormProcessorTestUtils, create_form_for_test, sharded, ) from corehq.messaging.scheduling.scheduling_partitioned.models", "corehq.messaging.scheduling.models import AlertSchedule, SMSContent, AlertEvent from corehq.messaging.scheduling.scheduling_partitioned.dbaccessors import \\ delete_alert_schedule_instances_for_schedule", "section = make_loc_type('section', district, domain=self.domain_name) block = make_loc_type('block', district, domain=self.domain_name)", "('Gauteng', [ ('Ekurhuleni ', [ ('Alberton', []), ('Benoni', []), ('Springs',", "= SqlDataLoader() with self.assertRaises(IntegrityError),\\ mock.patch(\"corehq.apps.dump_reload.sql.load.CHUNK_SIZE\", chunk_size): # patch the chunk", "( district, { section.id: (section, {}), block.id: (block, { center.id:", "password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', ) ccuser_2 = CommCareUser.create( domain=self.domain_name, username='user_2',", "self._dump_and_load(Counter({AlertSchedule: 1, AlertEvent: 2, SMSContent: 2})) def test_zapier_subscription(self): ZapierSubscription.objects.create( domain=self.domain_name,", "Backend', hq_api_id='TDMB', inbound_api_key='test-domain-mobile-backend-inbound-api-key', supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS, is_global=False, ) SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=domain_backend,", "slug='testp', name='demop', domain=self.domain_name ) TransifexProject.objects.create( organization=org, slug='testp1', name='demop1', domain=self.domain_name )", "list(expected_dump_counts) self._check_signals_handle_raw(models) output_stream = StringIO() if dumper_fn: dumper_fn(output_stream) else: SqlDataDumper(self.domain_name,", "iterator in builder.querysets(): with transaction.atomic(using=iterator.db), \\ constraint_checks_deferred(iterator.db): collector = NestedObjects(using=iterator.db)", "expected_object_counts = Counter({LocationType: 3, SQLLocation: 11}) location_type_names = ['province', 'district',", "from corehq.messaging.scheduling.scheduling_partitioned.models import ( AlertScheduleInstance, ) class BaseDumpLoadTest(TestCase): @classmethod def", "UserRole, Permissions, RoleAssignableBy, RolePermission expected_object_counts = Counter({ UserRole: 2, RolePermission:", "domain=self.domain_name) center = make_loc_type('center', block, domain=self.domain_name) county = make_loc_type('county', state,", "def test_case_search_config(self): from corehq.apps.case_search.models import CaseSearchConfig, FuzzyProperties expected_object_counts = Counter({", "0 positional arguments but 1 was given' ): greasy_spoon['spam'] def", "section.id: (section, {}), block.id: (block, { center.id: (center, {}), }),", "post_ledger_transactions = sorted(post_ledger_transactions, key=lambda t: t.pk) for pre, post in", "2, CommCareCaseSQL: 2, CaseTransaction: 3, CommCareCaseIndexSQL: 1 }) pre_cases =", "from corehq.apps.users.models import UserRole, Permissions, RoleAssignableBy, RolePermission expected_object_counts = Counter({", "'terminate' it.\"\"\" self._load_with_errors(chunk_size=2) def _load_with_errors(self, chunk_size): output_stream = StringIO() SqlDataDumper(self.domain_name,", "self._dump_and_load(expected_object_counts) role1_loaded = UserRole.objects.get(id=role1.id) role2_loaded = UserRole.objects.get(id=role2.id) self.assertEqual(role1_loaded.permissions.to_list(), Permissions().to_list()) self.assertEqual(role1_loaded.assignable_by,", "Winelands', 'Paarl', 'Cape Town'] location_ids = [locations[name].location_id for name in", "role2 = UserRole.create( self.domain_name, 'role1', permissions=Permissions(edit_web_users=True), assignable_by=[role1.id] ) self.addCleanup(role1.delete) self.addCleanup(role2.delete)", "case in pre_cases)) for pre_case in pre_cases: post_case = self.case_accessors.get_case(pre_case.case_id)", "= [obj.__class__.__name__ for obj in objects_remaining] counts = Counter(object_classes) self.assertEqual([],", "expected_object_counts = Counter({ User: 1, DeviceReportEntry: 7, UserEntry: 1, UserErrorEntry:", "CaseStructure from corehq.apps.commtrack.helpers import make_product from corehq.apps.commtrack.tests.util import get_single_balance_block from", "import WebUser from django.contrib.auth.models import User expected_object_counts = Counter({User: 3})", "created_via=None, email='<EMAIL>', ) self.addCleanup(ccuser_1.delete, self.domain_name, deleted_by=None) self.addCleanup(ccuser_2.delete, self.domain_name, deleted_by=None) self.addCleanup(web_user.delete,", "fuzzy in pre_fuzzies: fuzzy.save() pre_config.fuzzy_properties.set(pre_fuzzies) pre_config.save() self._dump_and_load(expected_object_counts) post_config = CaseSearchConfig.objects.get(domain=self.domain_name)", "user = CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', uuid=user_id", "display_name='Test Global Mobile Backend', hq_api_id='TGMB', inbound_api_key='test-global-mobile-backend-inbound-api-key', supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS, is_global=True, )", "alert_schedule_id=uuid.uuid4(), ).save() self._dump_and_load({AlertScheduleInstance: 1}) def test_mobile_backend(self): from corehq.apps.sms.models import (", "Counter({ User: 1, DeviceReportEntry: 7, UserEntry: 1, UserErrorEntry: 2, ForceCloseEntry:", "event = MessagingEvent.objects.create( domain=self.domain_name, date=datetime.utcnow(), source=MessagingEvent.SOURCE_REMINDER, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) MessagingSubEvent.objects.create(", "product_id='test2', name='test2'), SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3'), ] def test_load_error_queue_full(self): \"\"\"Blocks when", "data left in the DB objects_remaining = list(get_objects_to_dump(self.domain_name, [], []))", "api_token='<PASSWORD>') TransifexProject.objects.create( organization=org, slug='testp', name='demop', domain=self.domain_name ) TransifexProject.objects.create( organization=org, slug='testp1',", "= CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', ) ccuser_2", "AlertScheduleInstance( schedule_instance_id=uuid.uuid4(), domain=self.domain_name, recipient_type='CommCareUser', recipient_id=uuid.uuid4().hex, current_event_num=0, schedule_iteration_num=1, next_event_due=datetime(2017, 3, 1),", "True})), ] ) ) pre_cases[0] = self.factory.create_or_update_case(CaseStructure( case_id=pre_cases[0].case_id, attrs={'external_id': 'billie", "3}) ccuser_1 = CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>',", "# resave the product to force an error self.products[0].save() actual_model_counts,", "def test_transifex(self): from corehq.apps.translations.models import TransifexProject, TransifexOrganization org = TransifexOrganization.objects.create(slug='test',", "post_save signal handlers have been updated to handle 'raw' calls.\"\"\"", "\\ constraint_checks_deferred(iterator.db): collector = NestedObjects(using=iterator.db) collector.collect(iterator) collector.delete() assert [] ==", "sender=ZapierSubscription) super(BaseDumpLoadTest, cls).setUpClass() cls.domain_name = uuid.uuid4().hex cls.domain = Domain(name=cls.domain_name) cls.domain.save()", "cls.factory = CaseFactory(domain=cls.domain_name) cls.form_accessors = FormAccessors(cls.domain_name) cls.case_accessors = CaseAccessors(cls.domain_name) cls.product", "import CommCareUser from corehq.apps.users.models import WebUser from django.contrib.auth.models import User", "post_form = self.form_accessors.get_form(pre_form.form_id) self.assertDictEqual(pre_form.to_json(), post_form.to_json()) def test_sql_dump_load_case(self): expected_object_counts = Counter({", "set(case.case_id for case in pre_cases)) for pre_case in pre_cases: post_case", "FormProcessorTestUtils.delete_all_cases_forms_ledgers(cls.domain_name) super(TestSQLDumpLoadShardedModels, cls).tearDownClass() def test_dump_load_form(self): expected_object_counts = Counter({ XFormInstanceSQL: 2,", "domain=self.domain_name ) TransifexProject.objects.create( organization=org, slug='testp1', name='demop1', domain=self.domain_name ) self._dump_and_load(Counter({TransifexOrganization: 1,", "DefaultDictWithKey(empty_list) with self.assertRaisesRegex( TypeError, r'empty_list\\(\\) takes 0 positional arguments but", "expected_dump_counts, load_filter=None, expected_load_counts=None, dumper_fn=None): expected_load_counts = expected_load_counts or expected_dump_counts expected_dump_counts.update(self.default_objects_counts)", "self._dump_and_load({ SQLMobileBackendMapping: 1, SQLMobileBackend: 1, }) self.assertEqual(SQLMobileBackend.objects.first().domain, self.domain_name) self.assertEqual(SQLMobileBackendMapping.objects.first().domain, self.domain_name)", "else label.lower() return Counter({ _model_class_to_label(model_class): count for model_class, count in", ") phone_number.save() event = MessagingEvent.objects.create( domain=self.domain_name, date=datetime.utcnow(), source=MessagingEvent.SOURCE_REMINDER, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED", "transaction.atomic(using=iterator.db), \\ constraint_checks_deferred(iterator.db): collector = NestedObjects(using=iterator.db) collector.collect(iterator) collector.delete() assert []", "= uuid.uuid4().hex user = CommCareUser.create( domain=self.domain_name, username='user_1', password='<PASSWORD>', created_by=None, created_via=None,", "('Ekurhuleni ', [ ('Alberton', []), ('Benoni', []), ('Springs', []), ]),", "make_loc_type('district', state, domain=self.domain_name) section = make_loc_type('section', district, domain=self.domain_name) block =", "'Not all data deleted: {}'.format(counts)) # Dump actual_model_counts, dump_lines =", "= UserRole.objects.get(id=role2.id) self.assertEqual(role1_loaded.permissions.to_list(), Permissions().to_list()) self.assertEqual(role1_loaded.assignable_by, []) self.assertEqual(role2_loaded.permissions.to_list(), Permissions(edit_web_users=True).to_list()) self.assertEqual(role2_loaded.assignable_by, [role1_loaded.get_id])", "setUp(self): self.products = [ SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1'), SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2'),", "expected_load_counts = expected_load_counts or expected_dump_counts expected_dump_counts.update(self.default_objects_counts) models = list(expected_dump_counts) self._check_signals_handle_raw(models)", "expected_object_counts = Counter({LocationType: 1, SQLProduct: 1}) self._dump_and_load(expected_object_counts, load_filter='sqlproduct', expected_load_counts=Counter({SQLProduct: 1}))", "import ( get_model_iterator_builders_to_dump, get_objects_to_dump, ) from corehq.apps.dump_reload.sql.load import ( DefaultDictWithKey,", "SQLMobileBackend.objects.create( domain=self.domain_name, name='test-domain-mobile-backend', display_name='Test Domain Mobile Backend', hq_api_id='TDMB', inbound_api_key='test-domain-mobile-backend-inbound-api-key', supported_countries=[\"*\"],", "corehq.apps.case_search.models import CaseSearchConfig, FuzzyProperties expected_object_counts = Counter({ CaseSearchConfig: 1, FuzzyProperties:", "= Counter({SQLProduct: 3}) p1 = SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1') p2 =", "def test_device_logs(self): from corehq.apps.receiverwrapper.util import submit_form_locally from phonelog.models import DeviceReportEntry,", "post_fuzzies), {'dog', 'owner'}) def test_users(self): from corehq.apps.users.models import CommCareUser from", "content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) MessagingSubEvent.objects.create( parent=event, date=datetime.utcnow(), recipient_type=MessagingEvent.RECIPIENT_CASE, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED )", "case_id=pre_cases[0].case_id, attrs={'external_id': 'billie jean', 'update': {'name': '<NAME>'}} ))[0] self._dump_and_load(expected_object_counts) case_ids", "('Springs', []), ]), ]), ] location_types, locations = setup_locations_and_types( self.domain_name,", "{})}, ), }, ), } self.assertEqual(hierarchy, desired_hierarchy) def test_location(self): from", "CaseIndex, CaseStructure from corehq.apps.commtrack.helpers import make_product from corehq.apps.commtrack.tests.util import get_single_balance_block", "= [ FuzzyProperties(domain=self.domain, case_type='dog', properties=['breed', 'color']), FuzzyProperties(domain=self.domain, case_type='owner', properties=['name']), ]", "self.assertEqual(set(f.case_type for f in post_fuzzies), {'dog', 'owner'}) def test_users(self): from", "when sending 'test3'\"\"\" self._load_with_errors(chunk_size=1) def test_load_error_queue_full_on_terminate(self): \"\"\"Blocks when sending ``None``", "inbound_api_key='test-domain-mobile-backend-inbound-api-key', supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS, is_global=False, ) SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=domain_backend, backend_type=SQLMobileBackend.SMS, prefix='123',", "= list(get_objects_to_dump(self.domain_name, [], [])) object_classes = [obj.__class__.__name__ for obj in", "receiver_path = receiver.__module__ + '.' + receiver.__name__ if receiver_path in", "schedule = AlertSchedule.create_simple_alert(self.domain, SMSContent()) schedule.set_custom_alert( [ (AlertEvent(minutes_to_wait=5), SMSContent()), (AlertEvent(minutes_to_wait=15), SMSContent()),", "import CaseSearchConfig, FuzzyProperties expected_object_counts = Counter({ CaseSearchConfig: 1, FuzzyProperties: 2,", "11, RoleAssignableBy: 1 }) role1 = UserRole.create(self.domain_name, 'role1') role2 =", "make_loc_type('block', district, domain=self.domain_name) center = make_loc_type('center', block, domain=self.domain_name) county =", "self.domain_name) self._dump_and_load(expected_object_counts) def test_demo_user_restore(self): from corehq.apps.users.models import CommCareUser from corehq.apps.ota.models", "tearDown(self): self.delete_sql_data() super(BaseDumpLoadTest, self).tearDown() def _dump_and_load(self, expected_dump_counts, load_filter=None, expected_load_counts=None, dumper_fn=None):", "import TransifexProject, TransifexOrganization org = TransifexOrganization.objects.create(slug='test', name='demo', api_token='<PASSWORD>') TransifexProject.objects.create( organization=org,", "inbound_api_key='test-global-mobile-backend-inbound-api-key', supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS, is_global=True, ) SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=global_backend, backend_type=SQLMobileBackend.SMS, prefix='*',", ") from corehq.messaging.scheduling.scheduling_partitioned.models import ( AlertScheduleInstance, ) class BaseDumpLoadTest(TestCase): @classmethod", "'child', 'update': {'age': 3, 'diabetic': False}, 'create': True}, indices=[ CaseIndex(CaseStructure(attrs={'case_name':", "case = self.factory.create_case() submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id, 10) ], self.domain_name) submit_case_blocks([", "test_case_search_config(self): from corehq.apps.case_search.models import CaseSearchConfig, FuzzyProperties expected_object_counts = Counter({ CaseSearchConfig:", "@sharded class TestSQLDumpLoadShardedModels(BaseDumpLoadTest): maxDiff = None @classmethod def setUpClass(cls): super(TestSQLDumpLoadShardedModels,", "name='test3'), ] def test_load_error_queue_full(self): \"\"\"Blocks when sending 'test3'\"\"\" self._load_with_errors(chunk_size=1) def", "from corehq.apps.locations.models import LocationType from corehq.apps.locations.tests.test_location_types import make_loc_type expected_object_counts =", "MessagingSubEvent: 1}) phone_number = PhoneNumber( domain=self.domain_name, owner_doc_type='CommCareCase', owner_id='fake-owner-id1', phone_number='99912341234', backend_id=None,", "global_backend = SQLMobileBackend.objects.create( domain=None, name='test-global-mobile-backend', display_name='Test Global Mobile Backend', hq_api_id='TGMB',", "submit_form_locally from phonelog.models import DeviceReportEntry, ForceCloseEntry, UserEntry, UserErrorEntry from corehq.apps.users.models", "recipient_type=MessagingEvent.RECIPIENT_CASE, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) self._dump_and_load(expected_object_counts) def test_message_scheduling(self): AlertScheduleInstance( schedule_instance_id=uuid.uuid4(), domain=self.domain_name,", "import LocationType, SQLLocation from corehq.apps.locations.tests.util import setup_locations_and_types expected_object_counts = Counter({LocationType:", "def test_filtered_dump_load(self): from corehq.apps.locations.tests.test_location_types import make_loc_type from corehq.apps.products.models import SQLProduct", "TypeError, \"'NoneType' object is not callable\" ): greasy_spoon['spam'] def _normalize_object_counter(counter,", "ccuser_2 = CommCareUser.create( domain=self.domain_name, username='user_2', password='<PASSWORD>', created_by=None, created_via=None, email='<EMAIL>', )", "greasy_spoon['spam'].append('spam') self.assertEqual(greasy_spoon['spam'], ['spam', 'spam']) def test_not_enough_params(self): def empty_list(): return []", "for receiver in post_save._live_receivers(model): receiver_path = receiver.__module__ + '.' +", "'Cape Town', 'Cape Town City'] ) result = SQLLocation.objects.get_locations_and_children([locations['Gauteng'].location_id]) self.assertItemsEqual(", "'{}.{}'.format(model_class._meta.app_label, model_class.__name__) return label if for_loaded else label.lower() return Counter({", "= setup_locations_and_types( self.domain_name, location_type_names, [], location_structure, ) self._dump_and_load(expected_object_counts) names =", "corehq.form_processor.backends.sql.dbaccessors import LedgerAccessorSQL from corehq.form_processor.interfaces.dbaccessors import ( CaseAccessors, FormAccessors, )", "corehq.messaging.scheduling.scheduling_partitioned.models import ( AlertScheduleInstance, ) class BaseDumpLoadTest(TestCase): @classmethod def setUpClass(cls):", "self._dump_and_load(expected_object_counts) def test_demo_user_restore(self): from corehq.apps.users.models import CommCareUser from corehq.apps.ota.models import", "CaseFactory, CaseIndex, CaseStructure from corehq.apps.commtrack.helpers import make_product from corehq.apps.commtrack.tests.util import", "SQLProduct expected_object_counts = Counter({SQLProduct: 3}) p1 = SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1')", "1, LedgerTransaction: 2 }) case = self.factory.create_case() submit_case_blocks([ get_single_balance_block(case.case_id, self.product._id,", "domain=self.domain_name, case_type='case_type', event_name=EventTypes.NEW_CASE, url='example.com', user_id='user_id', ) self._dump_and_load(Counter({ZapierSubscription: 1})) @mock.patch(\"corehq.apps.dump_reload.sql.load.ENQUEUE_TIMEOUT\", 1)", "self._parse_dump_output(output_stream) self.assertEqual(actual_model_counts['products.sqlproduct'], 3) loader = SqlDataLoader() with self.assertRaises(IntegrityError),\\ mock.patch(\"corehq.apps.dump_reload.sql.load.CHUNK_SIZE\", chunk_size):", "pre_fuzzies: fuzzy.save() pre_config.fuzzy_properties.set(pre_fuzzies) pre_config.save() self._dump_and_load(expected_object_counts) post_config = CaseSearchConfig.objects.get(domain=self.domain_name) self.assertTrue(post_config.enabled) self.assertEqual(pre_config.fuzzy_properties,", "post_ledger_values[0].ledger_reference) self.assertDictEqual(pre_ledger_values[0].to_json(), post_ledger_values[0].to_json()) pre_ledger_transactions = sorted(pre_ledger_transactions, key=lambda t: t.pk) post_ledger_transactions", "[locations[name].location_id for name in names] result = SQLLocation.objects.get_locations_and_children(location_ids) self.assertItemsEqual( [loc.name", "( SQLMobileBackend, SQLMobileBackendMapping, ) domain_backend = SQLMobileBackend.objects.create( domain=self.domain_name, name='test-domain-mobile-backend', display_name='Test", "CommCareCaseIndexSQL, CommCareCaseSQL, LedgerTransaction, LedgerValue, XFormInstanceSQL, ) from corehq.form_processor.tests.utils import (", "p2 = SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2') parchived = SQLProduct.objects.create(domain=self.domain_name, product_id='test3', name='test3',", "created_by=None, created_via=None, email='<EMAIL>', ) self.addCleanup(ccuser_1.delete, self.domain_name, deleted_by=None) self.addCleanup(ccuser_2.delete, self.domain_name, deleted_by=None)", "constraint_checks_deferred, ) from corehq.apps.hqcase.utils import submit_case_blocks from corehq.apps.products.models import SQLProduct", "constraint_checks_deferred(iterator.db): collector = NestedObjects(using=iterator.db) collector.collect(iterator) collector.delete() assert [] == list(get_objects_to_dump(domain_name,", "= [line.strip() for line in dump_output if line.strip()] actual_model_counts =", "def test_dump_load_form(self): expected_object_counts = Counter({ XFormInstanceSQL: 2, BlobMeta: 2 })", "] self._dump_and_load(expected_object_counts) form_ids = self.form_accessors.get_all_form_ids_in_domain('XFormInstance') self.assertEqual(set(form_ids), set(form.form_id for form in", "if receiver_path in whitelist_receivers: continue args = inspect.getargspec(receiver).args message =", "maxDiff = None @classmethod def setUpClass(cls): super(TestSQLDumpLoadShardedModels, cls).setUpClass() cls.factory =", "create_form_for_test, sharded, ) from corehq.messaging.scheduling.scheduling_partitioned.models import ( AlertScheduleInstance, ) class", "City', []), ]) ]), ('Gauteng', [ ('Ekurhuleni ', [ ('Alberton',", "DemoUserRestore: 1 }) user_id = uuid.uuid4().hex user = CommCareUser.create( domain=self.domain_name,", "= Counter({ XFormInstanceSQL: 2, BlobMeta: 2, CommCareCaseSQL: 2, CaseTransaction: 3,", "from corehq.apps.locations.tests.test_location_types import make_loc_type from corehq.apps.products.models import SQLProduct from corehq.apps.locations.models", "org = TransifexOrganization.objects.create(slug='test', name='demo', api_token='<PASSWORD>') TransifexProject.objects.create( organization=org, slug='testp', name='demop', domain=self.domain_name", "{city.id: (city, {})}, ), }, ), } self.assertEqual(hierarchy, desired_hierarchy) def", "self.assertEqual(set(form_ids), set(form.form_id for form in pre_forms)) for pre_form in pre_forms:", "True pre_fuzzies = [ FuzzyProperties(domain=self.domain, case_type='dog', properties=['breed', 'color']), FuzzyProperties(domain=self.domain, case_type='owner',", "= SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1') p2 = SQLProduct.objects.create(domain=self.domain_name, product_id='test2', name='test2') parchived", "SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=global_backend, backend_type=SQLMobileBackend.SMS, prefix='*', ) self._dump_and_load({ SQLMobileBackendMapping: 1, SQLMobileBackend:", "= Counter({ User: 1, DemoUserRestore: 1 }) user_id = uuid.uuid4().hex", "SqlDataDumper(self.domain_name, [], []).dump(output_stream) self.delete_sql_data() # make sure that there's no", "models): \"\"\"Ensure that any post_save signal handlers have been updated", "handler \"{}\" for model \"{}\" missing raw arg'.format( receiver, model", "objects_remaining = list(get_objects_to_dump(self.domain_name, [], [])) object_classes = [obj.__class__.__name__ for obj", "[ FuzzyProperties(domain=self.domain, case_type='dog', properties=['breed', 'color']), FuzzyProperties(domain=self.domain, case_type='owner', properties=['name']), ] for", "'city'] location_structure = [ ('Western Cape', [ ('Cape Winelands', [", "= make_product(cls.domain_name, 'A Product', 'prodcode_a') cls.default_objects_counts.update({SQLProduct: 1}) @classmethod def tearDownClass(cls):", "BlobMeta: 3, CommCareCaseSQL: 1, CaseTransaction: 3, LedgerValue: 1, LedgerTransaction: 2", "django.contrib.auth.models import User expected_object_counts = Counter({User: 3}) ccuser_1 = CommCareUser.create(", "self._dump_and_load(expected_object_counts) post_config = CaseSearchConfig.objects.get(domain=self.domain_name) self.assertTrue(post_config.enabled) self.assertEqual(pre_config.fuzzy_properties, post_config.fuzzy_properties) post_fuzzies = FuzzyProperties.objects.filter(domain=self.domain_name)", "block = make_loc_type('block', district, domain=self.domain_name) center = make_loc_type('center', block, domain=self.domain_name)", "import CommCareUser from django.contrib.auth.models import User expected_object_counts = Counter({ User:", "restore\" ).save() self._dump_and_load(expected_object_counts) def test_products(self): from corehq.apps.products.models import SQLProduct expected_object_counts", "1}) @classmethod def tearDownClass(cls): FormProcessorTestUtils.delete_all_cases_forms_ledgers(cls.domain_name) super(TestSQLDumpLoadShardedModels, cls).tearDownClass() def test_dump_load_form(self): expected_object_counts", ") case_upload_record = CaseUploadRecord.objects.create( domain=self.domain_name, upload_id=uuid.uuid4(), task_id=uuid.uuid4(), couch_user_id=uuid.uuid4().hex, case_type='person', upload_file_meta=upload_file_meta,", "for line in dump_lines]) return actual_model_counts, dump_lines def _check_signals_handle_raw(self, models):", "'owner'}) def test_users(self): from corehq.apps.users.models import CommCareUser from corehq.apps.users.models import", "label keyed counter\"\"\" def _model_class_to_label(model_class): label = '{}.{}'.format(model_class._meta.app_label, model_class.__name__) return", "restore_blob_id=uuid.uuid4().hex, content_length=1027, restore_comment=\"Test migrate demo user restore\" ).save() self._dump_and_load(expected_object_counts) def", "in pre_fuzzies: fuzzy.save() pre_config.fuzzy_properties.set(pre_fuzzies) pre_config.save() self._dump_and_load(expected_object_counts) post_config = CaseSearchConfig.objects.get(domain=self.domain_name) self.assertTrue(post_config.enabled)", "2, BlobMeta: 2 }) pre_forms = [ create_form_for_test(self.domain_name), create_form_for_test(self.domain_name) ]", "'create': True}, indices=[ CaseIndex(CaseStructure(attrs={'case_name': 'parent', 'update': {'age': 42}, 'create': True})),", "['spam', 'spam']) def test_not_enough_params(self): def empty_list(): return [] greasy_spoon =", "pre_ledger_transactions = sorted(pre_ledger_transactions, key=lambda t: t.pk) post_ledger_transactions = sorted(post_ledger_transactions, key=lambda", "self.assertDictEqual(pre_form.to_json(), post_form.to_json()) def test_sql_dump_load_case(self): expected_object_counts = Counter({ XFormInstanceSQL: 2, BlobMeta:", "def setUpClass(cls): post_delete.disconnect(zapier_subscription_post_delete, sender=ZapierSubscription) super(BaseDumpLoadTest, cls).setUpClass() cls.domain_name = uuid.uuid4().hex cls.domain", "= inspect.getargspec(receiver).args message = 'Signal handler \"{}\" for model \"{}\"", "self._parse_dump_output(output_stream) expected_model_counts = _normalize_object_counter(expected_dump_counts) self.assertDictEqual(dict(expected_model_counts), dict(actual_model_counts)) # Load loader =", "(city, {})}, ), }, ), } self.assertEqual(hierarchy, desired_hierarchy) def test_location(self):", "post_delete.disconnect(zapier_subscription_post_delete, sender=ZapierSubscription) super(BaseDumpLoadTest, cls).setUpClass() cls.domain_name = uuid.uuid4().hex cls.domain = Domain(name=cls.domain_name)", "supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS, is_global=False, ) SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=domain_backend, backend_type=SQLMobileBackend.SMS, prefix='123', )", "import json import uuid from collections import Counter from datetime", "class TestSQLDumpLoad(BaseDumpLoadTest): def test_case_search_config(self): from corehq.apps.case_search.models import CaseSearchConfig, FuzzyProperties expected_object_counts", "= Counter({ UserRole: 2, RolePermission: 11, RoleAssignableBy: 1 }) role1", "with self.assertRaises(IntegrityError),\\ mock.patch(\"corehq.apps.dump_reload.sql.load.CHUNK_SIZE\", chunk_size): # patch the chunk size so", "'Paarl', 'Cape Town'] location_ids = [locations[name].location_id for name in names]", "from corehq.apps.domain.models import Domain from corehq.apps.dump_reload.sql import SqlDataDumper, SqlDataLoader from", "import SQLProduct expected_object_counts = Counter({SQLProduct: 3}) p1 = SQLProduct.objects.create(domain=self.domain_name, product_id='test1',", "CaseUploadFileMeta: 1, CaseUploadRecord: 1, CaseUploadFormRecord: 1, })) def test_transifex(self): from", "2})) def test_zapier_subscription(self): ZapierSubscription.objects.create( domain=self.domain_name, case_type='case_type', event_name=EventTypes.NEW_CASE, url='example.com', user_id='user_id', )", "SimpleTestCase, TestCase from nose.tools import nottest from casexml.apps.case.mock import CaseFactory,", "1}) def test_mobile_backend(self): from corehq.apps.sms.models import ( SQLMobileBackend, SQLMobileBackendMapping, )", "in devicelog.xml ) self.addCleanup(user.delete, self.domain_name, deleted_by=None) with open('corehq/ex-submodules/couchforms/tests/data/devicelogs/devicelog.xml', 'rb') as", "Counter({LocationType: 3, SQLLocation: 11}) location_type_names = ['province', 'district', 'city'] location_structure", "TransifexProject.objects.create( organization=org, slug='testp1', name='demop1', domain=self.domain_name ) self._dump_and_load(Counter({TransifexOrganization: 1, TransifexProject: 2}))", "test_location_type(self): from corehq.apps.locations.models import LocationType from corehq.apps.locations.tests.test_location_types import make_loc_type expected_object_counts", "loc in result], ['Gauteng', 'Ekurhuleni ', 'Alberton', 'Benoni', 'Springs'] )", "} self.assertEqual(hierarchy, desired_hierarchy) def test_location(self): from corehq.apps.locations.models import LocationType, SQLLocation", "CaseSearchConfig, FuzzyProperties expected_object_counts = Counter({ CaseSearchConfig: 1, FuzzyProperties: 2, })", "date=datetime.utcnow(), source=MessagingEvent.SOURCE_REMINDER, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) MessagingSubEvent.objects.create( parent=event, date=datetime.utcnow(), recipient_type=MessagingEvent.RECIPIENT_CASE, content_type=MessagingEvent.CONTENT_SMS,", "import uuid from collections import Counter from datetime import datetime", "active=True, alert_schedule_id=uuid.uuid4(), ).save() self._dump_and_load({AlertScheduleInstance: 1}) def test_mobile_backend(self): from corehq.apps.sms.models import", "loader.load_objects(dump_lines) class DefaultDictWithKeyTests(SimpleTestCase): def test_intended_use_case(self): def enlist(item): return [item] greasy_spoon", "sorted(pre_ledger_transactions, key=lambda t: t.pk) post_ledger_transactions = sorted(post_ledger_transactions, key=lambda t: t.pk)", "an model label keyed counter\"\"\" def _model_class_to_label(model_class): label = '{}.{}'.format(model_class._meta.app_label,", "any post_save signal handlers have been updated to handle 'raw'", "location_structure = [ ('Western Cape', [ ('Cape Winelands', [ ('Stellenbosch',", "county, domain=self.domain_name) self._dump_and_load(expected_object_counts) hierarchy = LocationType.objects.full_hierarchy(self.domain_name) desired_hierarchy = { state.id:", "hq_api_id='TGMB', inbound_api_key='test-global-mobile-backend-inbound-api-key', supported_countries=[\"*\"], backend_type=SQLMobileBackend.SMS, is_global=True, ) SQLMobileBackendMapping.objects.create( domain=self.domain_name, backend=global_backend, backend_type=SQLMobileBackend.SMS,", "there's no data left in the DB objects_remaining = list(get_objects_to_dump(self.domain_name,", "Counter({SQLProduct: 3}) p1 = SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1') p2 = SQLProduct.objects.create(domain=self.domain_name,", "import ( CaseAccessors, FormAccessors, ) from corehq.form_processor.models import ( CaseTransaction,", "class BaseDumpLoadTest(TestCase): @classmethod def setUpClass(cls): post_delete.disconnect(zapier_subscription_post_delete, sender=ZapierSubscription) super(BaseDumpLoadTest, cls).setUpClass() cls.domain_name", "DemoUserRestore( demo_user_id=user_id, restore_blob_id=uuid.uuid4().hex, content_length=1027, restore_comment=\"Test migrate demo user restore\" ).save()", "schedule_iteration_num=1, next_event_due=datetime(2017, 3, 1), active=True, alert_schedule_id=uuid.uuid4(), ).save() self._dump_and_load({AlertScheduleInstance: 1}) def", "}, ), } self.assertEqual(hierarchy, desired_hierarchy) def test_location(self): from corehq.apps.locations.models import", "pre_fuzzies = [ FuzzyProperties(domain=self.domain, case_type='dog', properties=['breed', 'color']), FuzzyProperties(domain=self.domain, case_type='owner', properties=['name']),", "product_id='test1', name='test1') expected_object_counts = Counter({LocationType: 1, SQLProduct: 1}) self._dump_and_load(expected_object_counts, load_filter='sqlproduct',", "RoleAssignableBy, RolePermission expected_object_counts = Counter({ UserRole: 2, RolePermission: 11, RoleAssignableBy:", "}) pre_forms = [ create_form_for_test(self.domain_name), create_form_for_test(self.domain_name) ] self._dump_and_load(expected_object_counts) form_ids =", "``None`` into the queue to 'terminate' it.\"\"\" self._load_with_errors(chunk_size=2) def _load_with_errors(self,", "no data left in the DB objects_remaining = list(get_objects_to_dump(self.domain_name, [],", "f in post_fuzzies), {'dog', 'owner'}) def test_users(self): from corehq.apps.users.models import", "= StringIO() SqlDataDumper(self.domain_name, [], []).dump(output_stream) self.delete_sql_data() # resave the product", "from collections import Counter from datetime import datetime from io", "size so that the queue blocks loader.load_objects(dump_lines) class DefaultDictWithKeyTests(SimpleTestCase): def", "\"{}\" missing raw arg'.format( receiver, model ) self.assertIn('raw', args, message)", "def test_too_many_params(self): def appender(item1, item2): return [item1, item2] greasy_spoon =", "result], ['Gauteng', 'Ekurhuleni ', 'Alberton', 'Benoni', 'Springs'] ) def test_sms(self):", "import LocationType make_loc_type('state', domain=self.domain_name) SQLProduct.objects.create(domain=self.domain_name, product_id='test1', name='test1') expected_object_counts = Counter({LocationType:", "raw arg'.format( receiver, model ) self.assertIn('raw', args, message) @nottest def", "(AlertEvent(minutes_to_wait=5), SMSContent()), (AlertEvent(minutes_to_wait=15), SMSContent()), ] ) self.addCleanup(lambda: delete_alert_schedule_instances_for_schedule(AlertScheduleInstance, schedule.schedule_id)) self._dump_and_load(Counter({AlertSchedule:", "[])), \"Not all SQL objects deleted\" @sharded class TestSQLDumpLoadShardedModels(BaseDumpLoadTest): maxDiff", "def test_case_importer(self): from corehq.apps.case_importer.tracking.models import ( CaseUploadFileMeta, CaseUploadFormRecord, CaseUploadRecord, )", "1 }) user_id = uuid.uuid4().hex user = CommCareUser.create( domain=self.domain_name, username='user_1',", "UserEntry, UserErrorEntry from corehq.apps.users.models import CommCareUser from django.contrib.auth.models import User", "= PhoneNumber( domain=self.domain_name, owner_doc_type='CommCareCase', owner_id='fake-owner-id1', phone_number='99912341234', backend_id=None, ivr_backend_id=None, verified=True, is_two_way=True,", "def test_products(self): from corehq.apps.products.models import SQLProduct expected_object_counts = Counter({SQLProduct: 3})", "greasy_spoon = DefaultDictWithKey(enlist) self.assertEqual(greasy_spoon['spam'], ['spam']) greasy_spoon['spam'].append('spam') self.assertEqual(greasy_spoon['spam'], ['spam', 'spam']) def", "import ( CaseUploadFileMeta, CaseUploadFormRecord, CaseUploadRecord, ) upload_file_meta = CaseUploadFileMeta.objects.create( identifier=uuid.uuid4().hex,", "import datetime from io import StringIO import mock from django.contrib.admin.utils", "return [item] greasy_spoon = DefaultDictWithKey(enlist) self.assertEqual(greasy_spoon['spam'], ['spam']) greasy_spoon['spam'].append('spam') self.assertEqual(greasy_spoon['spam'], ['spam',", "django.db.models.signals import post_delete, post_save from django.test import SimpleTestCase, TestCase from", "def test_mobile_backend(self): from corehq.apps.sms.models import ( SQLMobileBackend, SQLMobileBackendMapping, ) domain_backend", "uuid=user_id ) self.addCleanup(user.delete, self.domain_name, deleted_by=None) DemoUserRestore( demo_user_id=user_id, restore_blob_id=uuid.uuid4().hex, content_length=1027, restore_comment=\"Test", "'raw' calls.\"\"\" whitelist_receivers = [ 'django_digest.models._post_save_persist_partial_digests' ] for model in", "<Model Class> keyed counter to an model label keyed counter\"\"\"", "from corehq.apps.zapier.signals.receivers import ( zapier_subscription_post_delete, ) from corehq.blobs.models import BlobMeta", "+ '.' + receiver.__name__ if receiver_path in whitelist_receivers: continue args", "1, CaseTransaction: 3, LedgerValue: 1, LedgerTransaction: 2 }) case =", "@classmethod def tearDownClass(cls): FormProcessorTestUtils.delete_all_cases_forms_ledgers(cls.domain_name) super(TestSQLDumpLoadShardedModels, cls).tearDownClass() def test_dump_load_form(self): expected_object_counts =", "expected_object_counts = Counter({PhoneNumber: 1, MessagingEvent: 1, MessagingSubEvent: 1}) phone_number =", "CaseUploadFileMeta, CaseUploadFormRecord, CaseUploadRecord, ) upload_file_meta = CaseUploadFileMeta.objects.create( identifier=uuid.uuid4().hex, filename='picture.jpg', length=1024,", "LedgerAccessorSQL.get_ledger_values_for_case(case.case_id) post_ledger_transactions = LedgerAccessorSQL.get_ledger_transactions_for_case(case.case_id) self.assertEqual(1, len(post_ledger_values)) self.assertEqual(2, len(post_ledger_transactions)) self.assertEqual(pre_ledger_values[0].ledger_reference, post_ledger_values[0].ledger_reference)", "post_config.fuzzy_properties) post_fuzzies = FuzzyProperties.objects.filter(domain=self.domain_name) self.assertEqual(set(f.case_type for f in post_fuzzies), {'dog',", ") result = SQLLocation.objects.get_locations_and_children([locations['Gauteng'].location_id]) self.assertItemsEqual( [loc.name for loc in result],", "task_id=uuid.uuid4(), couch_user_id=uuid.uuid4().hex, case_type='person', upload_file_meta=upload_file_meta, ) CaseUploadFormRecord.objects.create( case_upload_record=case_upload_record, form_id=uuid.uuid4().hex, ) self._dump_and_load(Counter({", "owner_id='fake-owner-id1', phone_number='99912341234', backend_id=None, ivr_backend_id=None, verified=True, is_two_way=True, pending_verification=False, contact_last_modified=datetime.utcnow() ) phone_number.save()", "import AlertSchedule, SMSContent, AlertEvent from corehq.messaging.scheduling.scheduling_partitioned.dbaccessors import \\ delete_alert_schedule_instances_for_schedule schedule", "'test3'\"\"\" self._load_with_errors(chunk_size=1) def test_load_error_queue_full_on_terminate(self): \"\"\"Blocks when sending ``None`` into the", "= None @classmethod def setUpClass(cls): super(TestSQLDumpLoadShardedModels, cls).setUpClass() cls.factory = CaseFactory(domain=cls.domain_name)", "post_delete, post_save from django.test import SimpleTestCase, TestCase from nose.tools import", "recipient_type='CommCareUser', recipient_id=uuid.uuid4().hex, current_event_num=0, schedule_iteration_num=1, next_event_due=datetime(2017, 3, 1), active=True, alert_schedule_id=uuid.uuid4(), ).save()", "post_save._live_receivers(model): receiver_path = receiver.__module__ + '.' + receiver.__name__ if receiver_path", "import DeviceReportEntry, ForceCloseEntry, UserEntry, UserErrorEntry from corehq.apps.users.models import CommCareUser from", "parent=event, date=datetime.utcnow(), recipient_type=MessagingEvent.RECIPIENT_CASE, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED ) self._dump_and_load(expected_object_counts) def test_message_scheduling(self): AlertScheduleInstance(", "= '{}.{}'.format(model_class._meta.app_label, model_class.__name__) return label if for_loaded else label.lower() return", "] ) ) pre_cases[0] = self.factory.create_or_update_case(CaseStructure( case_id=pre_cases[0].case_id, attrs={'external_id': 'billie jean',", "loc in result], ['Cape Winelands', 'Stellenbosch', 'Paarl', 'Cape Town', 'Cape", "uuid='428d454aa9abc74e1964e16d3565d6b6' # match ID in devicelog.xml ) self.addCleanup(user.delete, self.domain_name, deleted_by=None)", "backend=domain_backend, backend_type=SQLMobileBackend.SMS, prefix='123', ) global_backend = SQLMobileBackend.objects.create( domain=None, name='test-global-mobile-backend', display_name='Test", "receiver, model ) self.assertIn('raw', args, message) @nottest def delete_domain_sql_data_for_dump_load_test(domain_name): for", "= make_loc_type('block', district, domain=self.domain_name) center = make_loc_type('center', block, domain=self.domain_name) county", "User: 1, DemoUserRestore: 1 }) user_id = uuid.uuid4().hex user =", "corehq.apps.sms.models import ( SQLMobileBackend, SQLMobileBackendMapping, ) domain_backend = SQLMobileBackend.objects.create( domain=self.domain_name,", "expected_load_counts=None, dumper_fn=None): expected_load_counts = expected_load_counts or expected_dump_counts expected_dump_counts.update(self.default_objects_counts) models =" ]
[ "def test_softsign(): ''' Test using a reference softsign implementation '''", "[activations.softmax(x)]) test_values = get_standard_values() result = f([test_values])[0] expected = softmax(test_values)", "(x * 0.2) + 0.5 z = 0.0 if x", "K.function([x], [activations.sigmoid(x)]) test_values = get_standard_values() result = f([test_values])[0] expected =", "theano tensors. ''' x = K.placeholder(ndim=2) f = K.function([x], [activations.relu(x)])", "K.placeholder(ndim=2) exp = activations.tanh(x) f = K.function([x], [exp]) result =", "m) return e / np.sum(e) x = K.placeholder(ndim=2) f =", "ref_sigmoid(x): if x >= 0: return 1 / (1 +", "test_values = get_standard_values() result = f([test_values])[0] expected = softsign(test_values) assert_allclose(result,", "reference softsign implementation ''' def softsign(x): return np.divide(x, np.ones_like(x) +", "hard sigmoid with slope and shift values from theano, see", "= K.function([x], [activations.sigmoid(x)]) test_values = get_standard_values() result = f([test_values])[0] expected", "return np.array([[0, 0.1, 0.5, 0.9, 1.0]], dtype=K.floatx()) def test_softmax(): '''", "f = K.function([x], [exp]) result = f([test_values])[0] expected = np.tanh(test_values)", "xs = [1, 5, True, None, 'foo'] for x in", "1.0]], dtype=K.floatx()) def test_softmax(): ''' Test using a reference implementation", "expected = hard_sigmoid(test_values) assert_allclose(result, expected, rtol=1e-05) def test_relu(): ''' Relu", "get_standard_values() result = f([test_values])[0] expected = softsign(test_values) assert_allclose(result, expected, rtol=1e-05)", "+ np.exp(-x)) else: z = np.exp(x) return z / (1", "np.exp(x)) x = K.placeholder(ndim=2) f = K.function([x], [activations.softplus(x)]) test_values =", "get_standard_values() test_values = np.reshape(test_values, (1, 1, np.size(test_values))) f([test_values])[0] def test_softplus():", "[activations.elu(x, 0.5)]) test_values = get_standard_values() result = f([test_values])[0] # because", "true_result = (np.exp(negative_values) - 1) / 2 assert_allclose(result, true_result) def", "from theano, see https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/sigm.py ''' x = (x * 0.2)", "keras import activations def get_standard_values(): ''' These are just a", "= np.max(values) e = np.exp(values - m) return e /", "dtype=K.floatx()) def test_softmax(): ''' Test using a reference implementation of", "if x <= 0 else (1.0 if x >= 1", "= f([test_values])[0] # because no negatives in test values assert_allclose(result,", "= [1, 5, True, None, 'foo'] for x in xs:", "using a reference softplus implementation ''' def softplus(x): return np.log(np.ones_like(x)", "result = f([test_values])[0] expected = softsign(test_values) assert_allclose(result, expected, rtol=1e-05) def", "np from numpy.testing import assert_allclose from keras import backend as", "def test_elu(): x = K.placeholder(ndim=2) f = K.function([x], [activations.elu(x, 0.5)])", "Test using a numerically stable reference sigmoid implementation ''' def", "= np.reshape(test_values, (1, 1, np.size(test_values))) f([test_values])[0] def test_softplus(): ''' Test", "f = K.function([x], [activations.softsign(x)]) test_values = get_standard_values() result = f([test_values])[0]", "slope and shift values from theano, see https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/sigm.py ''' x", "f([test_values])[0] expected = softplus(test_values) assert_allclose(result, expected, rtol=1e-05) def test_softsign(): '''", "expected, rtol=1e-05) def test_sigmoid(): ''' Test using a numerically stable", "x in xs: assert(x == activations.linear(x)) if __name__ == '__main__':", "else x) return z hard_sigmoid = np.vectorize(ref_hard_sigmoid) x = K.placeholder(ndim=2)", "Test using a reference softplus implementation ''' def softplus(x): return", "= get_standard_values() result = f([test_values])[0] expected = softmax(test_values) assert_allclose(result, expected,", "rtol=1e-05) negative_values = np.array([[-1, -2]], dtype=K.floatx()) result = f([negative_values])[0] true_result", "function does no input validation, it just returns the thing", "0.1, 0.5, 0.9, 1.0]], dtype=K.floatx()) def test_softmax(): ''' Test using", "test_softplus(): ''' Test using a reference softplus implementation ''' def", "def test_tanh(): test_values = get_standard_values() x = K.placeholder(ndim=2) exp =", "result = f([test_values])[0] # because no negatives in test values", "true_result) def test_tanh(): test_values = get_standard_values() x = K.placeholder(ndim=2) exp", "of floats used for testing the activation functions, and are", "(np.exp(negative_values) - 1) / 2 assert_allclose(result, true_result) def test_tanh(): test_values", "are useful in multiple tests. ''' return np.array([[0, 0.1, 0.5,", "z) sigmoid = np.vectorize(ref_sigmoid) x = K.placeholder(ndim=2) f = K.function([x],", "negatives in test values assert_allclose(result, test_values, rtol=1e-05) def test_elu(): x", "x >= 0: return 1 / (1 + np.exp(-x)) else:", "f([test_values])[0] expected = sigmoid(test_values) assert_allclose(result, expected, rtol=1e-05) def test_hard_sigmoid(): '''", "def get_standard_values(): ''' These are just a set of floats", "theano, see https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/sigm.py ''' x = (x * 0.2) +", "test_softsign(): ''' Test using a reference softsign implementation ''' def", "softplus(x): return np.log(np.ones_like(x) + np.exp(x)) x = K.placeholder(ndim=2) f =", "= K.placeholder(ndim=2) exp = activations.tanh(x) f = K.function([x], [exp]) result", "2 assert_allclose(result, true_result) def test_tanh(): test_values = get_standard_values() x =", "f = K.function([x], [activations.softmax(x)]) test_values = get_standard_values() test_values = np.reshape(test_values,", "def ref_hard_sigmoid(x): ''' Reference hard sigmoid with slope and shift", "z / (1 + z) sigmoid = np.vectorize(ref_sigmoid) x =", "passed in. ''' xs = [1, 5, True, None, 'foo']", "- m) return e / np.sum(e) x = K.placeholder(ndim=2) f", "a theano variable. Testing ints, floats and theano tensors. '''", "keras import backend as K from keras import activations def", "result = f([test_values])[0] expected = softmax(test_values) assert_allclose(result, expected, rtol=1e-05) def", "softsign(x): return np.divide(x, np.ones_like(x) + np.absolute(x)) x = K.placeholder(ndim=2) f", "''' Relu implementation doesn't depend on the value being a", "[exp]) result = f([test_values])[0] expected = np.tanh(test_values) assert_allclose(result, expected, rtol=1e-05)", "''' This function does no input validation, it just returns", "sigmoid(test_values) assert_allclose(result, expected, rtol=1e-05) def test_hard_sigmoid(): ''' Test using a", "K.placeholder(ndim=2) f = K.function([x], [activations.softmax(x)]) test_values = get_standard_values() result =", "x <= 0 else (1.0 if x >= 1 else", "5)) f = K.function([x], [activations.softmax(x)]) test_values = get_standard_values() test_values =", "import assert_allclose from keras import backend as K from keras", "test_hard_sigmoid(): ''' Test using a reference hard sigmoid implementation '''", "return 1 / (1 + np.exp(-x)) else: z = np.exp(x)", "= K.placeholder(ndim=2) f = K.function([x], [activations.softsign(x)]) test_values = get_standard_values() result", "= hard_sigmoid(test_values) assert_allclose(result, expected, rtol=1e-05) def test_relu(): ''' Relu implementation", "(1 + np.exp(-x)) else: z = np.exp(x) return z /", "K.function([x], [activations.softsign(x)]) test_values = get_standard_values() result = f([test_values])[0] expected =", "K.placeholder(ndim=2) f = K.function([x], [activations.softplus(x)]) test_values = get_standard_values() result =", "for testing the activation functions, and are useful in multiple", "= get_standard_values() test_values = np.reshape(test_values, (1, 1, np.size(test_values))) f([test_values])[0] def", "z = 0.0 if x <= 0 else (1.0 if", "z hard_sigmoid = np.vectorize(ref_hard_sigmoid) x = K.placeholder(ndim=2) f = K.function([x],", "f([negative_values])[0] true_result = (np.exp(negative_values) - 1) / 2 assert_allclose(result, true_result)", "e = np.exp(values - m) return e / np.sum(e) x", "''' Test using a reference softsign implementation ''' def softsign(x):", "K.function([x], [activations.softplus(x)]) test_values = get_standard_values() result = f([test_values])[0] expected =", "Test using a reference implementation of softmax ''' def softmax(values):", "K.placeholder(shape=(1, 1, 5)) f = K.function([x], [activations.softmax(x)]) test_values = get_standard_values()", "def test_linear(): ''' This function does no input validation, it", "''' Reference hard sigmoid with slope and shift values from", "assert_allclose(result, expected, rtol=1e-05) def test_linear(): ''' This function does no", "np.max(values) e = np.exp(values - m) return e / np.sum(e)", "x = K.placeholder(ndim=2) f = K.function([x], [activations.relu(x)]) test_values = get_standard_values()", "= K.function([x], [activations.relu(x)]) test_values = get_standard_values() result = f([test_values])[0] #", "f([test_values])[0] expected = hard_sigmoid(test_values) assert_allclose(result, expected, rtol=1e-05) def test_relu(): '''", "1, 5)) f = K.function([x], [activations.softmax(x)]) test_values = get_standard_values() test_values", "softmax ''' def softmax(values): m = np.max(values) e = np.exp(values", "import pytest import numpy as np from numpy.testing import assert_allclose", "''' def softmax(values): m = np.max(values) e = np.exp(values -", "softplus implementation ''' def softplus(x): return np.log(np.ones_like(x) + np.exp(x)) x", "def test_sigmoid(): ''' Test using a numerically stable reference sigmoid", "as np from numpy.testing import assert_allclose from keras import backend", "implementation ''' def softsign(x): return np.divide(x, np.ones_like(x) + np.absolute(x)) x", "np.absolute(x)) x = K.placeholder(ndim=2) f = K.function([x], [activations.softsign(x)]) test_values =", "get_standard_values(): ''' These are just a set of floats used", "x = K.placeholder(ndim=2) f = K.function([x], [activations.softsign(x)]) test_values = get_standard_values()", "else: z = np.exp(x) return z / (1 + z)", "tests. ''' return np.array([[0, 0.1, 0.5, 0.9, 1.0]], dtype=K.floatx()) def", "a numerically stable reference sigmoid implementation ''' def ref_sigmoid(x): if", "values assert_allclose(result, test_values, rtol=1e-05) negative_values = np.array([[-1, -2]], dtype=K.floatx()) result", "test_relu(): ''' Relu implementation doesn't depend on the value being", "-2]], dtype=K.floatx()) result = f([negative_values])[0] true_result = (np.exp(negative_values) - 1)", "doesn't depend on the value being a theano variable. Testing", "np.exp(values - m) return e / np.sum(e) x = K.placeholder(ndim=2)", "f([test_values])[0] expected = softsign(test_values) assert_allclose(result, expected, rtol=1e-05) def test_sigmoid(): '''", "stable reference sigmoid implementation ''' def ref_sigmoid(x): if x >=", "''' Test using a reference softplus implementation ''' def softplus(x):", "hard_sigmoid = np.vectorize(ref_hard_sigmoid) x = K.placeholder(ndim=2) f = K.function([x], [activations.hard_sigmoid(x)])", "see https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/sigm.py ''' x = (x * 0.2) + 0.5", "= np.array([[-1, -2]], dtype=K.floatx()) result = f([negative_values])[0] true_result = (np.exp(negative_values)", "x = (x * 0.2) + 0.5 z = 0.0", "expected = sigmoid(test_values) assert_allclose(result, expected, rtol=1e-05) def test_hard_sigmoid(): ''' Test", "<= 0 else (1.0 if x >= 1 else x)", "0 else (1.0 if x >= 1 else x) return", "it just returns the thing that was passed in. '''", "f([test_values])[0] # because no negatives in test values assert_allclose(result, test_values,", "assert_allclose(result, expected, rtol=1e-05) def test_sigmoid(): ''' Test using a numerically", "= f([test_values])[0] expected = softsign(test_values) assert_allclose(result, expected, rtol=1e-05) def test_sigmoid():", "if x >= 1 else x) return z hard_sigmoid =", "''' def ref_hard_sigmoid(x): ''' Reference hard sigmoid with slope and", "def softplus(x): return np.log(np.ones_like(x) + np.exp(x)) x = K.placeholder(ndim=2) f", "def test_hard_sigmoid(): ''' Test using a reference hard sigmoid implementation", "test_tanh(): test_values = get_standard_values() x = K.placeholder(ndim=2) exp = activations.tanh(x)", "import activations def get_standard_values(): ''' These are just a set", "the activation functions, and are useful in multiple tests. '''", "z = np.exp(x) return z / (1 + z) sigmoid", "activations def get_standard_values(): ''' These are just a set of", "0.9, 1.0]], dtype=K.floatx()) def test_softmax(): ''' Test using a reference", "= np.exp(values - m) return e / np.sum(e) x =", "/ (1 + z) sigmoid = np.vectorize(ref_sigmoid) x = K.placeholder(ndim=2)", "as K from keras import activations def get_standard_values(): ''' These", "x = K.placeholder(ndim=2) f = K.function([x], [activations.sigmoid(x)]) test_values = get_standard_values()", "a reference implementation of softmax ''' def softmax(values): m =", "x = K.placeholder(ndim=2) f = K.function([x], [activations.elu(x, 0.5)]) test_values =", "0.2) + 0.5 z = 0.0 if x <= 0", "get_standard_values() result = f([test_values])[0] # because no negatives in test", "K.function([x], [activations.elu(x, 0.5)]) test_values = get_standard_values() result = f([test_values])[0] #", "x = K.placeholder(shape=(1, 1, 5)) f = K.function([x], [activations.softmax(x)]) test_values", "= np.tanh(test_values) assert_allclose(result, expected, rtol=1e-05) def test_linear(): ''' This function", "softsign(test_values) assert_allclose(result, expected, rtol=1e-05) def test_sigmoid(): ''' Test using a", "= K.function([x], [exp]) result = f([test_values])[0] expected = np.tanh(test_values) assert_allclose(result,", "= get_standard_values() result = f([test_values])[0] expected = softplus(test_values) assert_allclose(result, expected,", "f = K.function([x], [activations.softplus(x)]) test_values = get_standard_values() result = f([test_values])[0]", "implementation ''' def softplus(x): return np.log(np.ones_like(x) + np.exp(x)) x =", "from keras import activations def get_standard_values(): ''' These are just", "and shift values from theano, see https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/sigm.py ''' x =", "get_standard_values() result = f([test_values])[0] expected = hard_sigmoid(test_values) assert_allclose(result, expected, rtol=1e-05)", "test_values = get_standard_values() result = f([test_values])[0] expected = softplus(test_values) assert_allclose(result,", "K.placeholder(ndim=2) f = K.function([x], [activations.sigmoid(x)]) test_values = get_standard_values() result =", "set of floats used for testing the activation functions, and", "K.placeholder(ndim=2) f = K.function([x], [activations.hard_sigmoid(x)]) test_values = get_standard_values() result =", "the value being a theano variable. Testing ints, floats and", "''' Test using a reference hard sigmoid implementation ''' def", "* 0.2) + 0.5 z = 0.0 if x <=", "K from keras import activations def get_standard_values(): ''' These are", "1, np.size(test_values))) f([test_values])[0] def test_softplus(): ''' Test using a reference", "result = f([negative_values])[0] true_result = (np.exp(negative_values) - 1) / 2", "no negatives in test values assert_allclose(result, test_values, rtol=1e-05) negative_values =", "numpy as np from numpy.testing import assert_allclose from keras import", "expected = softplus(test_values) assert_allclose(result, expected, rtol=1e-05) def test_softsign(): ''' Test", "+ np.absolute(x)) x = K.placeholder(ndim=2) f = K.function([x], [activations.softsign(x)]) test_values", "softmax(test_values) assert_allclose(result, expected, rtol=1e-05) def test_time_distributed_softmax(): x = K.placeholder(shape=(1, 1,", "/ (1 + np.exp(-x)) else: z = np.exp(x) return z", "test_values = get_standard_values() result = f([test_values])[0] expected = sigmoid(test_values) assert_allclose(result,", "K.placeholder(ndim=2) f = K.function([x], [activations.relu(x)]) test_values = get_standard_values() result =", "import numpy as np from numpy.testing import assert_allclose from keras", "K.function([x], [activations.softmax(x)]) test_values = get_standard_values() result = f([test_values])[0] expected =", "assert_allclose(result, expected, rtol=1e-05) def test_softsign(): ''' Test using a reference", "with slope and shift values from theano, see https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/sigm.py '''", "def softmax(values): m = np.max(values) e = np.exp(values - m)", "np.ones_like(x) + np.absolute(x)) x = K.placeholder(ndim=2) f = K.function([x], [activations.softsign(x)])", "K.function([x], [activations.relu(x)]) test_values = get_standard_values() result = f([test_values])[0] # because", "# because no negatives in test values assert_allclose(result, test_values, rtol=1e-05)", "test_values, rtol=1e-05) negative_values = np.array([[-1, -2]], dtype=K.floatx()) result = f([negative_values])[0]", "np.vectorize(ref_sigmoid) x = K.placeholder(ndim=2) f = K.function([x], [activations.sigmoid(x)]) test_values =", "x = K.placeholder(ndim=2) f = K.function([x], [activations.hard_sigmoid(x)]) test_values = get_standard_values()", "= f([negative_values])[0] true_result = (np.exp(negative_values) - 1) / 2 assert_allclose(result,", "[activations.softmax(x)]) test_values = get_standard_values() test_values = np.reshape(test_values, (1, 1, np.size(test_values)))", "test_softmax(): ''' Test using a reference implementation of softmax '''", "value being a theano variable. Testing ints, floats and theano", "= get_standard_values() result = f([test_values])[0] expected = hard_sigmoid(test_values) assert_allclose(result, expected,", "reference implementation of softmax ''' def softmax(values): m = np.max(values)", "np.exp(-x)) else: z = np.exp(x) return z / (1 +", "= np.vectorize(ref_hard_sigmoid) x = K.placeholder(ndim=2) f = K.function([x], [activations.hard_sigmoid(x)]) test_values", "being a theano variable. Testing ints, floats and theano tensors.", "for x in xs: assert(x == activations.linear(x)) if __name__ ==", "''' def softplus(x): return np.log(np.ones_like(x) + np.exp(x)) x = K.placeholder(ndim=2)", "get_standard_values() x = K.placeholder(ndim=2) exp = activations.tanh(x) f = K.function([x],", "dtype=K.floatx()) result = f([negative_values])[0] true_result = (np.exp(negative_values) - 1) /", "= K.placeholder(shape=(1, 1, 5)) f = K.function([x], [activations.softmax(x)]) test_values =", "expected = softsign(test_values) assert_allclose(result, expected, rtol=1e-05) def test_sigmoid(): ''' Test", "sigmoid with slope and shift values from theano, see https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/sigm.py", "implementation doesn't depend on the value being a theano variable.", "''' x = (x * 0.2) + 0.5 z =", "np.reshape(test_values, (1, 1, np.size(test_values))) f([test_values])[0] def test_softplus(): ''' Test using", "def test_softmax(): ''' Test using a reference implementation of softmax", "= K.function([x], [activations.softmax(x)]) test_values = get_standard_values() test_values = np.reshape(test_values, (1,", "f = K.function([x], [activations.sigmoid(x)]) test_values = get_standard_values() result = f([test_values])[0]", "import backend as K from keras import activations def get_standard_values():", "Test using a reference hard sigmoid implementation ''' def ref_hard_sigmoid(x):", "floats and theano tensors. ''' x = K.placeholder(ndim=2) f =", "5, True, None, 'foo'] for x in xs: assert(x ==", "+ 0.5 z = 0.0 if x <= 0 else", "expected, rtol=1e-05) def test_time_distributed_softmax(): x = K.placeholder(shape=(1, 1, 5)) f", "= K.function([x], [activations.softmax(x)]) test_values = get_standard_values() result = f([test_values])[0] expected", "rtol=1e-05) def test_elu(): x = K.placeholder(ndim=2) f = K.function([x], [activations.elu(x,", "hard_sigmoid(test_values) assert_allclose(result, expected, rtol=1e-05) def test_relu(): ''' Relu implementation doesn't", "expected, rtol=1e-05) def test_softsign(): ''' Test using a reference softsign", "negatives in test values assert_allclose(result, test_values, rtol=1e-05) negative_values = np.array([[-1,", "= np.exp(x) return z / (1 + z) sigmoid =", "return np.divide(x, np.ones_like(x) + np.absolute(x)) x = K.placeholder(ndim=2) f =", "using a reference hard sigmoid implementation ''' def ref_hard_sigmoid(x): '''", "expected = softmax(test_values) assert_allclose(result, expected, rtol=1e-05) def test_time_distributed_softmax(): x =", "https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/sigm.py ''' x = (x * 0.2) + 0.5 z", "functions, and are useful in multiple tests. ''' return np.array([[0,", "from numpy.testing import assert_allclose from keras import backend as K", "= f([test_values])[0] expected = sigmoid(test_values) assert_allclose(result, expected, rtol=1e-05) def test_hard_sigmoid():", "in test values assert_allclose(result, test_values, rtol=1e-05) def test_elu(): x =", "0.5)]) test_values = get_standard_values() result = f([test_values])[0] # because no", "assert_allclose(result, test_values, rtol=1e-05) def test_elu(): x = K.placeholder(ndim=2) f =", "numerically stable reference sigmoid implementation ''' def ref_sigmoid(x): if x", "x) return z hard_sigmoid = np.vectorize(ref_hard_sigmoid) x = K.placeholder(ndim=2) f", "thing that was passed in. ''' xs = [1, 5,", "a set of floats used for testing the activation functions,", "''' x = K.placeholder(ndim=2) f = K.function([x], [activations.relu(x)]) test_values =", "/ np.sum(e) x = K.placeholder(ndim=2) f = K.function([x], [activations.softmax(x)]) test_values", "f([test_values])[0] expected = softmax(test_values) assert_allclose(result, expected, rtol=1e-05) def test_time_distributed_softmax(): x", "= K.function([x], [activations.softsign(x)]) test_values = get_standard_values() result = f([test_values])[0] expected", "''' return np.array([[0, 0.1, 0.5, 0.9, 1.0]], dtype=K.floatx()) def test_softmax():", "= K.function([x], [activations.softplus(x)]) test_values = get_standard_values() result = f([test_values])[0] expected", "because no negatives in test values assert_allclose(result, test_values, rtol=1e-05) def", "assert_allclose(result, expected, rtol=1e-05) def test_hard_sigmoid(): ''' Test using a reference", "using a reference implementation of softmax ''' def softmax(values): m", "Test using a reference softsign implementation ''' def softsign(x): return", "return np.log(np.ones_like(x) + np.exp(x)) x = K.placeholder(ndim=2) f = K.function([x],", "Relu implementation doesn't depend on the value being a theano", "= get_standard_values() result = f([test_values])[0] expected = sigmoid(test_values) assert_allclose(result, expected,", "K.placeholder(ndim=2) f = K.function([x], [activations.elu(x, 0.5)]) test_values = get_standard_values() result", "using a numerically stable reference sigmoid implementation ''' def ref_sigmoid(x):", "= 0.0 if x <= 0 else (1.0 if x", "= np.vectorize(ref_sigmoid) x = K.placeholder(ndim=2) f = K.function([x], [activations.sigmoid(x)]) test_values", "test values assert_allclose(result, test_values, rtol=1e-05) negative_values = np.array([[-1, -2]], dtype=K.floatx())", "test_values = get_standard_values() result = f([test_values])[0] # because no negatives", "expected, rtol=1e-05) def test_hard_sigmoid(): ''' Test using a reference hard", "test_values = get_standard_values() test_values = np.reshape(test_values, (1, 1, np.size(test_values))) f([test_values])[0]", "reference sigmoid implementation ''' def ref_sigmoid(x): if x >= 0:", "exp = activations.tanh(x) f = K.function([x], [exp]) result = f([test_values])[0]", "variable. Testing ints, floats and theano tensors. ''' x =", "expected = np.tanh(test_values) assert_allclose(result, expected, rtol=1e-05) def test_linear(): ''' This", "test_values = get_standard_values() x = K.placeholder(ndim=2) exp = activations.tanh(x) f", "[activations.sigmoid(x)]) test_values = get_standard_values() result = f([test_values])[0] expected = sigmoid(test_values)", "rtol=1e-05) def test_time_distributed_softmax(): x = K.placeholder(shape=(1, 1, 5)) f =", "hard sigmoid implementation ''' def ref_hard_sigmoid(x): ''' Reference hard sigmoid", "[1, 5, True, None, 'foo'] for x in xs: assert(x", "softmax(values): m = np.max(values) e = np.exp(values - m) return", "using a reference softsign implementation ''' def softsign(x): return np.divide(x,", "assert_allclose from keras import backend as K from keras import", "''' xs = [1, 5, True, None, 'foo'] for x", "'foo'] for x in xs: assert(x == activations.linear(x)) if __name__", "= K.placeholder(ndim=2) f = K.function([x], [activations.softplus(x)]) test_values = get_standard_values() result", "m = np.max(values) e = np.exp(values - m) return e", "implementation ''' def ref_sigmoid(x): if x >= 0: return 1", "f([test_values])[0] expected = np.tanh(test_values) assert_allclose(result, expected, rtol=1e-05) def test_linear(): '''", "+ z) sigmoid = np.vectorize(ref_sigmoid) x = K.placeholder(ndim=2) f =", "1 / (1 + np.exp(-x)) else: z = np.exp(x) return", "returns the thing that was passed in. ''' xs =", "np.vectorize(ref_hard_sigmoid) x = K.placeholder(ndim=2) f = K.function([x], [activations.hard_sigmoid(x)]) test_values =", "result = f([test_values])[0] expected = sigmoid(test_values) assert_allclose(result, expected, rtol=1e-05) def", "''' def softsign(x): return np.divide(x, np.ones_like(x) + np.absolute(x)) x =", "result = f([test_values])[0] expected = softplus(test_values) assert_allclose(result, expected, rtol=1e-05) def", "in test values assert_allclose(result, test_values, rtol=1e-05) negative_values = np.array([[-1, -2]],", "ints, floats and theano tensors. ''' x = K.placeholder(ndim=2) f", "get_standard_values() result = f([test_values])[0] expected = softplus(test_values) assert_allclose(result, expected, rtol=1e-05)", "rtol=1e-05) def test_linear(): ''' This function does no input validation,", "testing the activation functions, and are useful in multiple tests.", "= (x * 0.2) + 0.5 z = 0.0 if", "input validation, it just returns the thing that was passed", "pytest import numpy as np from numpy.testing import assert_allclose from", "None, 'foo'] for x in xs: assert(x == activations.linear(x)) if", "on the value being a theano variable. Testing ints, floats", "was passed in. ''' xs = [1, 5, True, None,", "useful in multiple tests. ''' return np.array([[0, 0.1, 0.5, 0.9,", "Reference hard sigmoid with slope and shift values from theano,", "0.0 if x <= 0 else (1.0 if x >=", "rtol=1e-05) def test_softsign(): ''' Test using a reference softsign implementation", "1) / 2 assert_allclose(result, true_result) def test_tanh(): test_values = get_standard_values()", "= get_standard_values() x = K.placeholder(ndim=2) exp = activations.tanh(x) f =", "test_values = np.reshape(test_values, (1, 1, np.size(test_values))) f([test_values])[0] def test_softplus(): '''", "test_values, rtol=1e-05) def test_elu(): x = K.placeholder(ndim=2) f = K.function([x],", "get_standard_values() result = f([test_values])[0] expected = softmax(test_values) assert_allclose(result, expected, rtol=1e-05)", "assert_allclose(result, test_values, rtol=1e-05) negative_values = np.array([[-1, -2]], dtype=K.floatx()) result =", "= softplus(test_values) assert_allclose(result, expected, rtol=1e-05) def test_softsign(): ''' Test using", "return z / (1 + z) sigmoid = np.vectorize(ref_sigmoid) x", "because no negatives in test values assert_allclose(result, test_values, rtol=1e-05) negative_values", "e / np.sum(e) x = K.placeholder(ndim=2) f = K.function([x], [activations.softmax(x)])", "shift values from theano, see https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/sigm.py ''' x = (x", "numpy.testing import assert_allclose from keras import backend as K from", "values assert_allclose(result, test_values, rtol=1e-05) def test_elu(): x = K.placeholder(ndim=2) f", "True, None, 'foo'] for x in xs: assert(x == activations.linear(x))", "return e / np.sum(e) x = K.placeholder(ndim=2) f = K.function([x],", "test_elu(): x = K.placeholder(ndim=2) f = K.function([x], [activations.elu(x, 0.5)]) test_values", "K.placeholder(ndim=2) f = K.function([x], [activations.softsign(x)]) test_values = get_standard_values() result =", "= (np.exp(negative_values) - 1) / 2 assert_allclose(result, true_result) def test_tanh():", "= f([test_values])[0] expected = softmax(test_values) assert_allclose(result, expected, rtol=1e-05) def test_time_distributed_softmax():", "[activations.softsign(x)]) test_values = get_standard_values() result = f([test_values])[0] expected = softsign(test_values)", "= get_standard_values() result = f([test_values])[0] expected = softsign(test_values) assert_allclose(result, expected,", "= K.placeholder(ndim=2) f = K.function([x], [activations.sigmoid(x)]) test_values = get_standard_values() result", "floats used for testing the activation functions, and are useful", "(1 + z) sigmoid = np.vectorize(ref_sigmoid) x = K.placeholder(ndim=2) f", "np.array([[0, 0.1, 0.5, 0.9, 1.0]], dtype=K.floatx()) def test_softmax(): ''' Test", "a reference softsign implementation ''' def softsign(x): return np.divide(x, np.ones_like(x)", "= softmax(test_values) assert_allclose(result, expected, rtol=1e-05) def test_time_distributed_softmax(): x = K.placeholder(shape=(1,", "- 1) / 2 assert_allclose(result, true_result) def test_tanh(): test_values =", "[activations.relu(x)]) test_values = get_standard_values() result = f([test_values])[0] # because no", "np.log(np.ones_like(x) + np.exp(x)) x = K.placeholder(ndim=2) f = K.function([x], [activations.softplus(x)])", "np.exp(x) return z / (1 + z) sigmoid = np.vectorize(ref_sigmoid)", "This function does no input validation, it just returns the", "def test_relu(): ''' Relu implementation doesn't depend on the value", "f = K.function([x], [activations.softmax(x)]) test_values = get_standard_values() result = f([test_values])[0]", "/ 2 assert_allclose(result, true_result) def test_tanh(): test_values = get_standard_values() x", "np.divide(x, np.ones_like(x) + np.absolute(x)) x = K.placeholder(ndim=2) f = K.function([x],", "and theano tensors. ''' x = K.placeholder(ndim=2) f = K.function([x],", "(1.0 if x >= 1 else x) return z hard_sigmoid", "result = f([test_values])[0] expected = np.tanh(test_values) assert_allclose(result, expected, rtol=1e-05) def", "def softsign(x): return np.divide(x, np.ones_like(x) + np.absolute(x)) x = K.placeholder(ndim=2)", "np.tanh(test_values) assert_allclose(result, expected, rtol=1e-05) def test_linear(): ''' This function does", "= sigmoid(test_values) assert_allclose(result, expected, rtol=1e-05) def test_hard_sigmoid(): ''' Test using", "sigmoid = np.vectorize(ref_sigmoid) x = K.placeholder(ndim=2) f = K.function([x], [activations.sigmoid(x)])", "validation, it just returns the thing that was passed in.", "[activations.hard_sigmoid(x)]) test_values = get_standard_values() result = f([test_values])[0] expected = hard_sigmoid(test_values)", "just a set of floats used for testing the activation", "backend as K from keras import activations def get_standard_values(): '''", "result = f([test_values])[0] expected = hard_sigmoid(test_values) assert_allclose(result, expected, rtol=1e-05) def", "are just a set of floats used for testing the", "else (1.0 if x >= 1 else x) return z", "multiple tests. ''' return np.array([[0, 0.1, 0.5, 0.9, 1.0]], dtype=K.floatx())", "assert_allclose(result, expected, rtol=1e-05) def test_time_distributed_softmax(): x = K.placeholder(shape=(1, 1, 5))", "''' These are just a set of floats used for", "x = K.placeholder(ndim=2) f = K.function([x], [activations.softplus(x)]) test_values = get_standard_values()", "These are just a set of floats used for testing", "depend on the value being a theano variable. Testing ints,", "np.array([[-1, -2]], dtype=K.floatx()) result = f([negative_values])[0] true_result = (np.exp(negative_values) -", "reference hard sigmoid implementation ''' def ref_hard_sigmoid(x): ''' Reference hard", "= activations.tanh(x) f = K.function([x], [exp]) result = f([test_values])[0] expected", "rtol=1e-05) def test_sigmoid(): ''' Test using a numerically stable reference", "in. ''' xs = [1, 5, True, None, 'foo'] for", "if x >= 0: return 1 / (1 + np.exp(-x))", "x = K.placeholder(ndim=2) exp = activations.tanh(x) f = K.function([x], [exp])", "assert_allclose(result, true_result) def test_tanh(): test_values = get_standard_values() x = K.placeholder(ndim=2)", "test_time_distributed_softmax(): x = K.placeholder(shape=(1, 1, 5)) f = K.function([x], [activations.softmax(x)])", "implementation ''' def ref_hard_sigmoid(x): ''' Reference hard sigmoid with slope", "test_values = get_standard_values() result = f([test_values])[0] expected = hard_sigmoid(test_values) assert_allclose(result,", "f = K.function([x], [activations.hard_sigmoid(x)]) test_values = get_standard_values() result = f([test_values])[0]", "activation functions, and are useful in multiple tests. ''' return", "expected, rtol=1e-05) def test_relu(): ''' Relu implementation doesn't depend on", "implementation of softmax ''' def softmax(values): m = np.max(values) e", "x = K.placeholder(ndim=2) f = K.function([x], [activations.softmax(x)]) test_values = get_standard_values()", "test_values = get_standard_values() result = f([test_values])[0] expected = softmax(test_values) assert_allclose(result,", "softplus(test_values) assert_allclose(result, expected, rtol=1e-05) def test_softsign(): ''' Test using a", "K.function([x], [activations.hard_sigmoid(x)]) test_values = get_standard_values() result = f([test_values])[0] expected =", "softsign implementation ''' def softsign(x): return np.divide(x, np.ones_like(x) + np.absolute(x))", "= K.function([x], [activations.elu(x, 0.5)]) test_values = get_standard_values() result = f([test_values])[0]", "a reference softplus implementation ''' def softplus(x): return np.log(np.ones_like(x) +", "x >= 1 else x) return z hard_sigmoid = np.vectorize(ref_hard_sigmoid)", ">= 0: return 1 / (1 + np.exp(-x)) else: z", "sigmoid implementation ''' def ref_hard_sigmoid(x): ''' Reference hard sigmoid with", "+ np.exp(x)) x = K.placeholder(ndim=2) f = K.function([x], [activations.softplus(x)]) test_values", "test_linear(): ''' This function does no input validation, it just", "def ref_sigmoid(x): if x >= 0: return 1 / (1", "= get_standard_values() result = f([test_values])[0] # because no negatives in", "and are useful in multiple tests. ''' return np.array([[0, 0.1,", "np.sum(e) x = K.placeholder(ndim=2) f = K.function([x], [activations.softmax(x)]) test_values =", "negative_values = np.array([[-1, -2]], dtype=K.floatx()) result = f([negative_values])[0] true_result =", "test values assert_allclose(result, test_values, rtol=1e-05) def test_elu(): x = K.placeholder(ndim=2)", "that was passed in. ''' xs = [1, 5, True,", "return z hard_sigmoid = np.vectorize(ref_hard_sigmoid) x = K.placeholder(ndim=2) f =", "of softmax ''' def softmax(values): m = np.max(values) e =", "a reference hard sigmoid implementation ''' def ref_hard_sigmoid(x): ''' Reference", "just returns the thing that was passed in. ''' xs", "def test_time_distributed_softmax(): x = K.placeholder(shape=(1, 1, 5)) f = K.function([x],", "in multiple tests. ''' return np.array([[0, 0.1, 0.5, 0.9, 1.0]],", ">= 1 else x) return z hard_sigmoid = np.vectorize(ref_hard_sigmoid) x", "tensors. ''' x = K.placeholder(ndim=2) f = K.function([x], [activations.relu(x)]) test_values", "theano variable. Testing ints, floats and theano tensors. ''' x", "values from theano, see https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/sigm.py ''' x = (x *", "reference softplus implementation ''' def softplus(x): return np.log(np.ones_like(x) + np.exp(x))", "f = K.function([x], [activations.elu(x, 0.5)]) test_values = get_standard_values() result =", "def test_softplus(): ''' Test using a reference softplus implementation '''", "activations.tanh(x) f = K.function([x], [exp]) result = f([test_values])[0] expected =", "K.function([x], [activations.softmax(x)]) test_values = get_standard_values() test_values = np.reshape(test_values, (1, 1,", "does no input validation, it just returns the thing that", "1 else x) return z hard_sigmoid = np.vectorize(ref_hard_sigmoid) x =", "''' Test using a reference implementation of softmax ''' def", "rtol=1e-05) def test_hard_sigmoid(): ''' Test using a reference hard sigmoid", "sigmoid implementation ''' def ref_sigmoid(x): if x >= 0: return", "assert_allclose(result, expected, rtol=1e-05) def test_relu(): ''' Relu implementation doesn't depend", "= K.placeholder(ndim=2) f = K.function([x], [activations.softmax(x)]) test_values = get_standard_values() result", "0.5, 0.9, 1.0]], dtype=K.floatx()) def test_softmax(): ''' Test using a", "f([test_values])[0] def test_softplus(): ''' Test using a reference softplus implementation", "ref_hard_sigmoid(x): ''' Reference hard sigmoid with slope and shift values", "Testing ints, floats and theano tensors. ''' x = K.placeholder(ndim=2)", "test_sigmoid(): ''' Test using a numerically stable reference sigmoid implementation", "no negatives in test values assert_allclose(result, test_values, rtol=1e-05) def test_elu():", "expected, rtol=1e-05) def test_linear(): ''' This function does no input", "= f([test_values])[0] expected = hard_sigmoid(test_values) assert_allclose(result, expected, rtol=1e-05) def test_relu():", "from keras import backend as K from keras import activations", "np.size(test_values))) f([test_values])[0] def test_softplus(): ''' Test using a reference softplus", "= K.placeholder(ndim=2) f = K.function([x], [activations.hard_sigmoid(x)]) test_values = get_standard_values() result", "used for testing the activation functions, and are useful in", "[activations.softplus(x)]) test_values = get_standard_values() result = f([test_values])[0] expected = softplus(test_values)", "f = K.function([x], [activations.relu(x)]) test_values = get_standard_values() result = f([test_values])[0]", "in xs: assert(x == activations.linear(x)) if __name__ == '__main__': pytest.main([__file__])", "get_standard_values() result = f([test_values])[0] expected = sigmoid(test_values) assert_allclose(result, expected, rtol=1e-05)", "= K.function([x], [activations.hard_sigmoid(x)]) test_values = get_standard_values() result = f([test_values])[0] expected", "0.5 z = 0.0 if x <= 0 else (1.0", "= K.placeholder(ndim=2) f = K.function([x], [activations.relu(x)]) test_values = get_standard_values() result", "= f([test_values])[0] expected = np.tanh(test_values) assert_allclose(result, expected, rtol=1e-05) def test_linear():", "= softsign(test_values) assert_allclose(result, expected, rtol=1e-05) def test_sigmoid(): ''' Test using", "no input validation, it just returns the thing that was", "''' def ref_sigmoid(x): if x >= 0: return 1 /", "the thing that was passed in. ''' xs = [1,", "rtol=1e-05) def test_relu(): ''' Relu implementation doesn't depend on the", "= K.placeholder(ndim=2) f = K.function([x], [activations.elu(x, 0.5)]) test_values = get_standard_values()", "''' Test using a numerically stable reference sigmoid implementation '''", "K.function([x], [exp]) result = f([test_values])[0] expected = np.tanh(test_values) assert_allclose(result, expected,", "0: return 1 / (1 + np.exp(-x)) else: z =", "(1, 1, np.size(test_values))) f([test_values])[0] def test_softplus(): ''' Test using a", "= f([test_values])[0] expected = softplus(test_values) assert_allclose(result, expected, rtol=1e-05) def test_softsign():" ]
[ "filename + ':/p</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"phid\": XMFfile.write", "range(start,finaltime+1,stride): XMFfile = open(basename+\".\"+str(step)+\".xmf\",\"w\") XMFfile.write(r\"\"\"<?xml version=\"1.0\" ?> <!DOCTYPE Xdmf SYSTEM", "4\" Format=\"HDF\">' + filename + ':/elements</DataItem>'+\"\\n\") XMFfile.write (r'</Topology>'+\"\\n\") if tmp.name", "= OptionParser(usage=usage) parser.add_option(\"-n\",\"--size\", help=\"number of processors for run\", action=\"store\", type=\"int\",", "default=1000) parser.add_option(\"-f\",\"--filebase_flow\", help=\"base name for storage files\", action=\"store\", type=\"string\", dest=\"filebase\",", "tmp in f1.root: if tmp.name == \"elements\": XMFfile.write (r'<Topology NumberOfElements=\"'", "+ ':/w</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"p\": XMFfile.write (r'<Attribute", "filename + ':/u</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"v\": XMFfile.write", "+str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename + ':/v</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\")", "action=\"store\", type=\"int\", dest=\"stride\", default=0) parser.add_option(\"-t\",\"--finaltime\", help=\"finaltime\", action=\"store\", type=\"int\", dest=\"finaltime\", default=1000)", "storage files\", action=\"store\", type=\"string\", dest=\"filebase\", default=\"solution\") (opts,args) = parser.parse_args() start", "(opts,args) = parser.parse_args() start = 0 if opts.stride == 0", "Name=\"p\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">'", "(r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"p\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+", "[]> <Xdmf Version=\"2.0\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"> <Domain>\"\"\"+\"\\n\") XMFfile.write(r' <Grid GridType=\"Collection\" CollectionType=\"Spatial\">'+\"\\n\") for", "GridType=\"Uniform\">'+\"\\n\") XMFfile.write(r' <Time Value=\"'+str(step)+'\" />'+\"\\n\") for tmp in f1.root: if", "XMFfile.write (r'</Topology>'+\"\\n\") if tmp.name == \"nodes\": XMFfile.write (r'<Geometry Type=\"XYZ\">'+\"\\n\") XMFfile.write", "\"elements\": XMFfile.write (r'<Topology NumberOfElements=\"' +str(len(tmp[:]))+ '\" Type=\"Tetrahedron\">'+\"\\n\") XMFfile.write (r' <DataItem", "XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"w\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"'", "(r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"w\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+", "Precision=\"8\">' + filename + ':/p</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name ==", "</Grid>'+\"\\n\") XMFfile.write(' </Domain>'+\"\\n\") XMFfile.write(' </Xdmf>'+\"\\n\") XMFfile.close() if __name__ == '__main__':", "Format=\"HDF\" Precision=\"8\">' + filename + ':/nodes</DataItem>'+\"\\n\") XMFfile.write (r'</Geometry>'+\"\\n\") if tmp.name", "OptionParser(usage=usage) parser.add_option(\"-n\",\"--size\", help=\"number of processors for run\", action=\"store\", type=\"int\", dest=\"size\",", "(r'</Attribute>'+\"\\n\") if tmp.name == \"w\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"w\">'+\"\\n\")", "</Domain>'+\"\\n\") XMFfile.write(' </Xdmf>'+\"\\n\") XMFfile.close() if __name__ == '__main__': from optparse", "os #from xml.etree.ElementTree import * import tables #from Xdmf import", "Name=\"w\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">'", "(r'</Attribute>'+\"\\n\") f1.close() XMFfile.write(' </Grid>'+\"\\n\") XMFfile.write(' </Grid>'+\"\\n\") XMFfile.write(' </Domain>'+\"\\n\") XMFfile.write(' </Xdmf>'+\"\\n\")", "Format=\"HDF\" Precision=\"8\">' + filename + ':/p</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name", "open(basename+\".\"+str(step)+\".xmf\",\"w\") XMFfile.write(r\"\"\"<?xml version=\"1.0\" ?> <!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []> <Xdmf", "name for storage files\", action=\"store\", type=\"string\", dest=\"filebase\", default=\"solution\") (opts,args) =", "#import numpy #import os #from xml.etree.ElementTree import * import tables", "Precision=\"8\">' + filename + ':/v</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name ==", "+ filename + ':/v</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"w\":", "DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename + ':/v</DataItem>'+\"\\n\")", "CollectionType=\"Spatial\">'+\"\\n\") for proc in range(0,size): filename=\"solution.p\"+str(proc)+\".\"+str(step)+\".h5\" print filename f1 =", "+ ':/phid</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") f1.close() XMFfile.write(' </Grid>'+\"\\n\") XMFfile.write(' </Grid>'+\"\\n\") XMFfile.write('", "DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename + ':/w</DataItem>'+\"\\n\")", "Precision=\"8\">' + filename + ':/u</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name ==", "(r'</Attribute>'+\"\\n\") if tmp.name == \"p\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"p\">'+\"\\n\")", "H5toXMF(basename,size,start,finaltime,stride): # Open XMF files for step in range(start,finaltime+1,stride): XMFfile", "= 0 if opts.stride == 0 : start = opts.finaltime", "usage = \"\" parser = OptionParser(usage=usage) parser.add_option(\"-n\",\"--size\", help=\"number of processors", "+ filename + ':/nodes</DataItem>'+\"\\n\") XMFfile.write (r'</Geometry>'+\"\\n\") if tmp.name == \"u\":", "DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename + ':/u</DataItem>'+\"\\n\")", "of processors for run\", action=\"store\", type=\"int\", dest=\"size\", default=1) parser.add_option(\"-s\",\"--stride\", help=\"stride", "* def H5toXMF(basename,size,start,finaltime,stride): # Open XMF files for step in", "XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"v\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"'", "f1.close() XMFfile.write(' </Grid>'+\"\\n\") XMFfile.write(' </Grid>'+\"\\n\") XMFfile.write(' </Domain>'+\"\\n\") XMFfile.write(' </Xdmf>'+\"\\n\") XMFfile.close()", "(r' <DataItem DataType=\"Int\" Dimensions=\"' +str(len(tmp[:]))+ ' 4\" Format=\"HDF\">' + filename", "type=\"int\", dest=\"finaltime\", default=1000) parser.add_option(\"-f\",\"--filebase_flow\", help=\"base name for storage files\", action=\"store\",", "Dimensions=\"' +str(len(tmp[:]))+ ' 4\" Format=\"HDF\">' + filename + ':/elements</DataItem>'+\"\\n\") XMFfile.write", "filename + ':/w</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"p\": XMFfile.write", "== '__main__': from optparse import OptionParser usage = \"\" parser", "opts.stride == 0 : start = opts.finaltime opts.stride = 1", "':/elements</DataItem>'+\"\\n\") XMFfile.write (r'</Topology>'+\"\\n\") if tmp.name == \"nodes\": XMFfile.write (r'<Geometry Type=\"XYZ\">'+\"\\n\")", "+str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename + ':/phid</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\")", "files for step in range(start,finaltime+1,stride): XMFfile = open(basename+\".\"+str(step)+\".xmf\",\"w\") XMFfile.write(r\"\"\"<?xml version=\"1.0\"", "for tmp in f1.root: if tmp.name == \"elements\": XMFfile.write (r'<Topology", "(r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ ' 3\" Format=\"HDF\" Precision=\"8\">' +", "Precision=\"8\">' + filename + ':/w</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name ==", "':/v</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"w\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\"", "XMFfile.write (r'</Geometry>'+\"\\n\") if tmp.name == \"u\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\"", "XMF files for step in range(start,finaltime+1,stride): XMFfile = open(basename+\".\"+str(step)+\".xmf\",\"w\") XMFfile.write(r\"\"\"<?xml", "= tables.openFile(filename) XMFfile.write (r'<Grid GridType=\"Uniform\">'+\"\\n\") XMFfile.write(r' <Time Value=\"'+str(step)+'\" />'+\"\\n\") for", "solution output\", action=\"store\", type=\"int\", dest=\"stride\", default=0) parser.add_option(\"-t\",\"--finaltime\", help=\"finaltime\", action=\"store\", type=\"int\",", "Xdmf import * def H5toXMF(basename,size,start,finaltime,stride): # Open XMF files for", "Format=\"HDF\" Precision=\"8\">' + filename + ':/v</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name", "in range(0,size): filename=\"solution.p\"+str(proc)+\".\"+str(step)+\".h5\" print filename f1 = tables.openFile(filename) XMFfile.write (r'<Grid", "XMFfile.close() if __name__ == '__main__': from optparse import OptionParser usage", "parser.add_option(\"-n\",\"--size\", help=\"number of processors for run\", action=\"store\", type=\"int\", dest=\"size\", default=1)", "OptionParser usage = \"\" parser = OptionParser(usage=usage) parser.add_option(\"-n\",\"--size\", help=\"number of", "+ ':/nodes</DataItem>'+\"\\n\") XMFfile.write (r'</Geometry>'+\"\\n\") if tmp.name == \"u\": XMFfile.write (r'<Attribute", "<DataItem DataType=\"Int\" Dimensions=\"' +str(len(tmp[:]))+ ' 4\" Format=\"HDF\">' + filename +", "+ filename + ':/u</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"v\":", "if tmp.name == \"w\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"w\">'+\"\\n\") XMFfile.write", "#import os #from xml.etree.ElementTree import * import tables #from Xdmf", "tmp.name == \"w\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"w\">'+\"\\n\") XMFfile.write (r'", "__name__ == '__main__': from optparse import OptionParser usage = \"\"", "if tmp.name == \"elements\": XMFfile.write (r'<Topology NumberOfElements=\"' +str(len(tmp[:]))+ '\" Type=\"Tetrahedron\">'+\"\\n\")", "\"nodes\": XMFfile.write (r'<Geometry Type=\"XYZ\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+", "+str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename + ':/u</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\")", "Format=\"HDF\" Precision=\"8\">' + filename + ':/u</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name", "if opts.stride == 0 : start = opts.finaltime opts.stride =", "'\" Format=\"HDF\" Precision=\"8\">' + filename + ':/p</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if", "#from xml.etree.ElementTree import * import tables #from Xdmf import *", "= open(basename+\".\"+str(step)+\".xmf\",\"w\") XMFfile.write(r\"\"\"<?xml version=\"1.0\" ?> <!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []>", "' 4\" Format=\"HDF\">' + filename + ':/elements</DataItem>'+\"\\n\") XMFfile.write (r'</Topology>'+\"\\n\") if", "<Time Value=\"'+str(step)+'\" />'+\"\\n\") for tmp in f1.root: if tmp.name ==", "XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ ' 3\" Format=\"HDF\" Precision=\"8\">'", "(r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename", "XMFfile = open(basename+\".\"+str(step)+\".xmf\",\"w\") XMFfile.write(r\"\"\"<?xml version=\"1.0\" ?> <!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\"", "':/w</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"p\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\"", "filename + ':/phid</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") f1.close() XMFfile.write(' </Grid>'+\"\\n\") XMFfile.write(' </Grid>'+\"\\n\")", "<DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename +", "(r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"phid\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+", "XMFfile.write (r'<Geometry Type=\"XYZ\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '", "version=\"1.0\" ?> <!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []> <Xdmf Version=\"2.0\" xmlns:xi=\"http://www.w3.org/2001/XInclude\">", "if tmp.name == \"phid\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"phid\">'+\"\\n\") XMFfile.write", "DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ ' 3\" Format=\"HDF\" Precision=\"8\">' + filename +", "Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename + ':/w</DataItem>'+\"\\n\") XMFfile.write", "\"phid\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"phid\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\"", "if __name__ == '__main__': from optparse import OptionParser usage =", "+ filename + ':/p</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"phid\":", "XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"p\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\"", "+ filename + ':/w</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"p\":", "files\", action=\"store\", type=\"string\", dest=\"filebase\", default=\"solution\") (opts,args) = parser.parse_args() start =", "f1 = tables.openFile(filename) XMFfile.write (r'<Grid GridType=\"Uniform\">'+\"\\n\") XMFfile.write(r' <Time Value=\"'+str(step)+'\" />'+\"\\n\")", "(r'<Topology NumberOfElements=\"' +str(len(tmp[:]))+ '\" Type=\"Tetrahedron\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Int\" Dimensions=\"'", "= \"\" parser = OptionParser(usage=usage) parser.add_option(\"-n\",\"--size\", help=\"number of processors for", "in range(start,finaltime+1,stride): XMFfile = open(basename+\".\"+str(step)+\".xmf\",\"w\") XMFfile.write(r\"\"\"<?xml version=\"1.0\" ?> <!DOCTYPE Xdmf", "== \"phid\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"phid\">'+\"\\n\") XMFfile.write (r' <DataItem", "Type=\"Tetrahedron\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Int\" Dimensions=\"' +str(len(tmp[:]))+ ' 4\" Format=\"HDF\">'", "action=\"store\", type=\"string\", dest=\"filebase\", default=\"solution\") (opts,args) = parser.parse_args() start = 0", "filename f1 = tables.openFile(filename) XMFfile.write (r'<Grid GridType=\"Uniform\">'+\"\\n\") XMFfile.write(r' <Time Value=\"'+str(step)+'\"", "run\", action=\"store\", type=\"int\", dest=\"size\", default=1) parser.add_option(\"-s\",\"--stride\", help=\"stride for solution output\",", "DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename + ':/p</DataItem>'+\"\\n\")", "XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"phid\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\"", "tmp.name == \"phid\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"phid\">'+\"\\n\") XMFfile.write (r'", "?> <!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []> <Xdmf Version=\"2.0\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"> <Domain>\"\"\"+\"\\n\")", "def H5toXMF(basename,size,start,finaltime,stride): # Open XMF files for step in range(start,finaltime+1,stride):", "numpy #import os #from xml.etree.ElementTree import * import tables #from", "'\" Format=\"HDF\" Precision=\"8\">' + filename + ':/phid</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") f1.close()", "parser = OptionParser(usage=usage) parser.add_option(\"-n\",\"--size\", help=\"number of processors for run\", action=\"store\",", "if tmp.name == \"u\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"u\">'+\"\\n\") XMFfile.write", "+ filename + ':/phid</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") f1.close() XMFfile.write(' </Grid>'+\"\\n\") XMFfile.write('", "+str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename + ':/w</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\")", "GridType=\"Collection\" CollectionType=\"Spatial\">'+\"\\n\") for proc in range(0,size): filename=\"solution.p\"+str(proc)+\".\"+str(step)+\".h5\" print filename f1", "for step in range(start,finaltime+1,stride): XMFfile = open(basename+\".\"+str(step)+\".xmf\",\"w\") XMFfile.write(r\"\"\"<?xml version=\"1.0\" ?>", "Format=\"HDF\" Precision=\"8\">' + filename + ':/w</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name", "tmp.name == \"p\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"p\">'+\"\\n\") XMFfile.write (r'", "Format=\"HDF\">' + filename + ':/elements</DataItem>'+\"\\n\") XMFfile.write (r'</Topology>'+\"\\n\") if tmp.name ==", "type=\"string\", dest=\"filebase\", default=\"solution\") (opts,args) = parser.parse_args() start = 0 if", "step in range(start,finaltime+1,stride): XMFfile = open(basename+\".\"+str(step)+\".xmf\",\"w\") XMFfile.write(r\"\"\"<?xml version=\"1.0\" ?> <!DOCTYPE", "dest=\"filebase\", default=\"solution\") (opts,args) = parser.parse_args() start = 0 if opts.stride", "dest=\"size\", default=1) parser.add_option(\"-s\",\"--stride\", help=\"stride for solution output\", action=\"store\", type=\"int\", dest=\"stride\",", "XMFfile.write(' </Grid>'+\"\\n\") XMFfile.write(' </Domain>'+\"\\n\") XMFfile.write(' </Xdmf>'+\"\\n\") XMFfile.close() if __name__ ==", "range(0,size): filename=\"solution.p\"+str(proc)+\".\"+str(step)+\".h5\" print filename f1 = tables.openFile(filename) XMFfile.write (r'<Grid GridType=\"Uniform\">'+\"\\n\")", "tables #from Xdmf import * def H5toXMF(basename,size,start,finaltime,stride): # Open XMF", "for proc in range(0,size): filename=\"solution.p\"+str(proc)+\".\"+str(step)+\".h5\" print filename f1 = tables.openFile(filename)", "if tmp.name == \"nodes\": XMFfile.write (r'<Geometry Type=\"XYZ\">'+\"\\n\") XMFfile.write (r' <DataItem", "Open XMF files for step in range(start,finaltime+1,stride): XMFfile = open(basename+\".\"+str(step)+\".xmf\",\"w\")", "Precision=\"8\">' + filename + ':/nodes</DataItem>'+\"\\n\") XMFfile.write (r'</Geometry>'+\"\\n\") if tmp.name ==", "type=\"int\", dest=\"stride\", default=0) parser.add_option(\"-t\",\"--finaltime\", help=\"finaltime\", action=\"store\", type=\"int\", dest=\"finaltime\", default=1000) parser.add_option(\"-f\",\"--filebase_flow\",", "if tmp.name == \"v\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"v\">'+\"\\n\") XMFfile.write", "XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"v\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\"", "optparse import OptionParser usage = \"\" parser = OptionParser(usage=usage) parser.add_option(\"-n\",\"--size\",", "<Domain>\"\"\"+\"\\n\") XMFfile.write(r' <Grid GridType=\"Collection\" CollectionType=\"Spatial\">'+\"\\n\") for proc in range(0,size): filename=\"solution.p\"+str(proc)+\".\"+str(step)+\".h5\"", "+str(len(tmp[:]))+ ' 4\" Format=\"HDF\">' + filename + ':/elements</DataItem>'+\"\\n\") XMFfile.write (r'</Topology>'+\"\\n\")", "import OptionParser usage = \"\" parser = OptionParser(usage=usage) parser.add_option(\"-n\",\"--size\", help=\"number", "XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"u\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"'", "</Xdmf>'+\"\\n\") XMFfile.close() if __name__ == '__main__': from optparse import OptionParser", "dest=\"finaltime\", default=1000) parser.add_option(\"-f\",\"--filebase_flow\", help=\"base name for storage files\", action=\"store\", type=\"string\",", "AttributeType=\"Scalar\" Center=\"Node\" Name=\"p\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\"", "help=\"base name for storage files\", action=\"store\", type=\"string\", dest=\"filebase\", default=\"solution\") (opts,args)", "DataType=\"Int\" Dimensions=\"' +str(len(tmp[:]))+ ' 4\" Format=\"HDF\">' + filename + ':/elements</DataItem>'+\"\\n\")", "== \"w\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"w\">'+\"\\n\") XMFfile.write (r' <DataItem", "+ ':/elements</DataItem>'+\"\\n\") XMFfile.write (r'</Topology>'+\"\\n\") if tmp.name == \"nodes\": XMFfile.write (r'<Geometry", "tmp.name == \"u\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"u\">'+\"\\n\") XMFfile.write (r'", "+str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename + ':/p</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\")", "start = 0 if opts.stride == 0 : start =", "for storage files\", action=\"store\", type=\"string\", dest=\"filebase\", default=\"solution\") (opts,args) = parser.parse_args()", "'\" Format=\"HDF\" Precision=\"8\">' + filename + ':/v</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if", "Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename + ':/p</DataItem>'+\"\\n\") XMFfile.write", "XMFfile.write(' </Domain>'+\"\\n\") XMFfile.write(' </Xdmf>'+\"\\n\") XMFfile.close() if __name__ == '__main__': from", "+ filename + ':/elements</DataItem>'+\"\\n\") XMFfile.write (r'</Topology>'+\"\\n\") if tmp.name == \"nodes\":", "for solution output\", action=\"store\", type=\"int\", dest=\"stride\", default=0) parser.add_option(\"-t\",\"--finaltime\", help=\"finaltime\", action=\"store\",", "Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename + ':/v</DataItem>'+\"\\n\") XMFfile.write", "0 if opts.stride == 0 : start = opts.finaltime opts.stride", "if tmp.name == \"p\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"p\">'+\"\\n\") XMFfile.write", "default=1) parser.add_option(\"-s\",\"--stride\", help=\"stride for solution output\", action=\"store\", type=\"int\", dest=\"stride\", default=0)", "NumberOfElements=\"' +str(len(tmp[:]))+ '\" Type=\"Tetrahedron\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Int\" Dimensions=\"' +str(len(tmp[:]))+", "filename + ':/v</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"w\": XMFfile.write", "SYSTEM \"Xdmf.dtd\" []> <Xdmf Version=\"2.0\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"> <Domain>\"\"\"+\"\\n\") XMFfile.write(r' <Grid GridType=\"Collection\"", "action=\"store\", type=\"int\", dest=\"finaltime\", default=1000) parser.add_option(\"-f\",\"--filebase_flow\", help=\"base name for storage files\",", "XMFfile.write(' </Grid>'+\"\\n\") XMFfile.write(' </Grid>'+\"\\n\") XMFfile.write(' </Domain>'+\"\\n\") XMFfile.write(' </Xdmf>'+\"\\n\") XMFfile.close() if", "# Open XMF files for step in range(start,finaltime+1,stride): XMFfile =", "<DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ ' 3\" Format=\"HDF\" Precision=\"8\">' + filename", "import * def H5toXMF(basename,size,start,finaltime,stride): # Open XMF files for step", "XMFfile.write(r' <Time Value=\"'+str(step)+'\" />'+\"\\n\") for tmp in f1.root: if tmp.name", "3\" Format=\"HDF\" Precision=\"8\">' + filename + ':/nodes</DataItem>'+\"\\n\") XMFfile.write (r'</Geometry>'+\"\\n\") if", "'\" Format=\"HDF\" Precision=\"8\">' + filename + ':/w</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if", "= parser.parse_args() start = 0 if opts.stride == 0 :", "print filename f1 = tables.openFile(filename) XMFfile.write (r'<Grid GridType=\"Uniform\">'+\"\\n\") XMFfile.write(r' <Time", "default=0) parser.add_option(\"-t\",\"--finaltime\", help=\"finaltime\", action=\"store\", type=\"int\", dest=\"finaltime\", default=1000) parser.add_option(\"-f\",\"--filebase_flow\", help=\"base name", "import tables #from Xdmf import * def H5toXMF(basename,size,start,finaltime,stride): # Open", "XMFfile.write (r'</Attribute>'+\"\\n\") f1.close() XMFfile.write(' </Grid>'+\"\\n\") XMFfile.write(' </Grid>'+\"\\n\") XMFfile.write(' </Domain>'+\"\\n\") XMFfile.write('", "Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename + ':/u</DataItem>'+\"\\n\") XMFfile.write", "DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename + ':/phid</DataItem>'+\"\\n\")", "#from Xdmf import * def H5toXMF(basename,size,start,finaltime,stride): # Open XMF files", "Format=\"HDF\" Precision=\"8\">' + filename + ':/phid</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") f1.close() XMFfile.write('", "parser.add_option(\"-s\",\"--stride\", help=\"stride for solution output\", action=\"store\", type=\"int\", dest=\"stride\", default=0) parser.add_option(\"-t\",\"--finaltime\",", "XMFfile.write(r\"\"\"<?xml version=\"1.0\" ?> <!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []> <Xdmf Version=\"2.0\"", "for run\", action=\"store\", type=\"int\", dest=\"size\", default=1) parser.add_option(\"-s\",\"--stride\", help=\"stride for solution", "output\", action=\"store\", type=\"int\", dest=\"stride\", default=0) parser.add_option(\"-t\",\"--finaltime\", help=\"finaltime\", action=\"store\", type=\"int\", dest=\"finaltime\",", "':/p</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"phid\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\"", "(r'<Grid GridType=\"Uniform\">'+\"\\n\") XMFfile.write(r' <Time Value=\"'+str(step)+'\" />'+\"\\n\") for tmp in f1.root:", "XMFfile.write (r'<Topology NumberOfElements=\"' +str(len(tmp[:]))+ '\" Type=\"Tetrahedron\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Int\"", "\"p\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"p\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\"", "Precision=\"8\">' + filename + ':/phid</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") f1.close() XMFfile.write(' </Grid>'+\"\\n\")", "</Grid>'+\"\\n\") XMFfile.write(' </Grid>'+\"\\n\") XMFfile.write(' </Domain>'+\"\\n\") XMFfile.write(' </Xdmf>'+\"\\n\") XMFfile.close() if __name__", "<Xdmf Version=\"2.0\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"> <Domain>\"\"\"+\"\\n\") XMFfile.write(r' <Grid GridType=\"Collection\" CollectionType=\"Spatial\">'+\"\\n\") for proc", "== \"u\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"u\">'+\"\\n\") XMFfile.write (r' <DataItem", "':/u</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"v\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\"", "XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"p\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"'", "from optparse import OptionParser usage = \"\" parser = OptionParser(usage=usage)", "xml.etree.ElementTree import * import tables #from Xdmf import * def", "* import tables #from Xdmf import * def H5toXMF(basename,size,start,finaltime,stride): #", "(r'</Attribute>'+\"\\n\") if tmp.name == \"phid\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"phid\">'+\"\\n\")", "':/phid</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") f1.close() XMFfile.write(' </Grid>'+\"\\n\") XMFfile.write(' </Grid>'+\"\\n\") XMFfile.write(' </Domain>'+\"\\n\")", "help=\"number of processors for run\", action=\"store\", type=\"int\", dest=\"size\", default=1) parser.add_option(\"-s\",\"--stride\",", "XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' +", "filename + ':/nodes</DataItem>'+\"\\n\") XMFfile.write (r'</Geometry>'+\"\\n\") if tmp.name == \"u\": XMFfile.write", "\"w\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"w\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\"", "tmp.name == \"elements\": XMFfile.write (r'<Topology NumberOfElements=\"' +str(len(tmp[:]))+ '\" Type=\"Tetrahedron\">'+\"\\n\") XMFfile.write", "in f1.root: if tmp.name == \"elements\": XMFfile.write (r'<Topology NumberOfElements=\"' +str(len(tmp[:]))+", "'\" Type=\"Tetrahedron\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Int\" Dimensions=\"' +str(len(tmp[:]))+ ' 4\"", "filename + ':/elements</DataItem>'+\"\\n\") XMFfile.write (r'</Topology>'+\"\\n\") if tmp.name == \"nodes\": XMFfile.write", "Center=\"Node\" Name=\"u\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\"", "default=\"solution\") (opts,args) = parser.parse_args() start = 0 if opts.stride ==", "+ ':/p</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"phid\": XMFfile.write (r'<Attribute", "Value=\"'+str(step)+'\" />'+\"\\n\") for tmp in f1.root: if tmp.name == \"elements\":", "\"u\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"u\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\"", "XMFfile.write(r' <Grid GridType=\"Collection\" CollectionType=\"Spatial\">'+\"\\n\") for proc in range(0,size): filename=\"solution.p\"+str(proc)+\".\"+str(step)+\".h5\" print", "(r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"v\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+", "Type=\"XYZ\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ ' 3\" Format=\"HDF\"", "tmp.name == \"v\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"v\">'+\"\\n\") XMFfile.write (r'", "action=\"store\", type=\"int\", dest=\"size\", default=1) parser.add_option(\"-s\",\"--stride\", help=\"stride for solution output\", action=\"store\",", "Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">' + filename + ':/phid</DataItem>'+\"\\n\") XMFfile.write", "AttributeType=\"Scalar\" Center=\"Node\" Name=\"phid\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\"", "== 0 : start = opts.finaltime opts.stride = 1 H5toXMF(opts.filebase,opts.size,start,opts.finaltime,opts.stride)", "parser.add_option(\"-t\",\"--finaltime\", help=\"finaltime\", action=\"store\", type=\"int\", dest=\"finaltime\", default=1000) parser.add_option(\"-f\",\"--filebase_flow\", help=\"base name for", "Name=\"u\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">'", "Dimensions=\"' +str(len(tmp[:]))+ ' 3\" Format=\"HDF\" Precision=\"8\">' + filename + ':/nodes</DataItem>'+\"\\n\")", "<Grid GridType=\"Collection\" CollectionType=\"Spatial\">'+\"\\n\") for proc in range(0,size): filename=\"solution.p\"+str(proc)+\".\"+str(step)+\".h5\" print filename", "Name=\"v\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">'", "\"v\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"v\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\"", "' 3\" Format=\"HDF\" Precision=\"8\">' + filename + ':/nodes</DataItem>'+\"\\n\") XMFfile.write (r'</Geometry>'+\"\\n\")", "parser.add_option(\"-f\",\"--filebase_flow\", help=\"base name for storage files\", action=\"store\", type=\"string\", dest=\"filebase\", default=\"solution\")", "Version=\"2.0\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"> <Domain>\"\"\"+\"\\n\") XMFfile.write(r' <Grid GridType=\"Collection\" CollectionType=\"Spatial\">'+\"\\n\") for proc in", "xmlns:xi=\"http://www.w3.org/2001/XInclude\"> <Domain>\"\"\"+\"\\n\") XMFfile.write(r' <Grid GridType=\"Collection\" CollectionType=\"Spatial\">'+\"\\n\") for proc in range(0,size):", "XMFfile.write (r'<Grid GridType=\"Uniform\">'+\"\\n\") XMFfile.write(r' <Time Value=\"'+str(step)+'\" />'+\"\\n\") for tmp in", "help=\"finaltime\", action=\"store\", type=\"int\", dest=\"finaltime\", default=1000) parser.add_option(\"-f\",\"--filebase_flow\", help=\"base name for storage", "(r'</Topology>'+\"\\n\") if tmp.name == \"nodes\": XMFfile.write (r'<Geometry Type=\"XYZ\">'+\"\\n\") XMFfile.write (r'", "AttributeType=\"Scalar\" Center=\"Node\" Name=\"u\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\"", "filename=\"solution.p\"+str(proc)+\".\"+str(step)+\".h5\" print filename f1 = tables.openFile(filename) XMFfile.write (r'<Grid GridType=\"Uniform\">'+\"\\n\") XMFfile.write(r'", "== \"v\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"v\">'+\"\\n\") XMFfile.write (r' <DataItem", "Center=\"Node\" Name=\"phid\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\"", "Center=\"Node\" Name=\"w\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\"", "+str(len(tmp[:]))+ ' 3\" Format=\"HDF\" Precision=\"8\">' + filename + ':/nodes</DataItem>'+\"\\n\") XMFfile.write", "tmp.name == \"nodes\": XMFfile.write (r'<Geometry Type=\"XYZ\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\"", "<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []> <Xdmf Version=\"2.0\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"> <Domain>\"\"\"+\"\\n\") XMFfile.write(r'", "XMFfile.write(' </Xdmf>'+\"\\n\") XMFfile.close() if __name__ == '__main__': from optparse import", "+ ':/u</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"v\": XMFfile.write (r'<Attribute", "XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"phid\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"'", "AttributeType=\"Scalar\" Center=\"Node\" Name=\"w\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\"", "+ ':/v</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"w\": XMFfile.write (r'<Attribute", "Center=\"Node\" Name=\"p\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\"", "== \"p\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"p\">'+\"\\n\") XMFfile.write (r' <DataItem", "f1.root: if tmp.name == \"elements\": XMFfile.write (r'<Topology NumberOfElements=\"' +str(len(tmp[:]))+ '\"", "'__main__': from optparse import OptionParser usage = \"\" parser =", "Xdmf SYSTEM \"Xdmf.dtd\" []> <Xdmf Version=\"2.0\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"> <Domain>\"\"\"+\"\\n\") XMFfile.write(r' <Grid", "dest=\"stride\", default=0) parser.add_option(\"-t\",\"--finaltime\", help=\"finaltime\", action=\"store\", type=\"int\", dest=\"finaltime\", default=1000) parser.add_option(\"-f\",\"--filebase_flow\", help=\"base", "XMFfile.write (r' <DataItem DataType=\"Int\" Dimensions=\"' +str(len(tmp[:]))+ ' 4\" Format=\"HDF\">' +", "(r'<Geometry Type=\"XYZ\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ ' 3\"", "parser.parse_args() start = 0 if opts.stride == 0 : start", "tables.openFile(filename) XMFfile.write (r'<Grid GridType=\"Uniform\">'+\"\\n\") XMFfile.write(r' <Time Value=\"'+str(step)+'\" />'+\"\\n\") for tmp", "':/nodes</DataItem>'+\"\\n\") XMFfile.write (r'</Geometry>'+\"\\n\") if tmp.name == \"u\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\"", "== \"nodes\": XMFfile.write (r'<Geometry Type=\"XYZ\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"'", "+str(len(tmp[:]))+ '\" Type=\"Tetrahedron\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Int\" Dimensions=\"' +str(len(tmp[:]))+ '", "proc in range(0,size): filename=\"solution.p\"+str(proc)+\".\"+str(step)+\".h5\" print filename f1 = tables.openFile(filename) XMFfile.write", "processors for run\", action=\"store\", type=\"int\", dest=\"size\", default=1) parser.add_option(\"-s\",\"--stride\", help=\"stride for", "import * import tables #from Xdmf import * def H5toXMF(basename,size,start,finaltime,stride):", "\"\" parser = OptionParser(usage=usage) parser.add_option(\"-n\",\"--size\", help=\"number of processors for run\",", "/>'+\"\\n\") for tmp in f1.root: if tmp.name == \"elements\": XMFfile.write", "AttributeType=\"Scalar\" Center=\"Node\" Name=\"v\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\"", "type=\"int\", dest=\"size\", default=1) parser.add_option(\"-s\",\"--stride\", help=\"stride for solution output\", action=\"store\", type=\"int\",", "(r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"u\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+", "help=\"stride for solution output\", action=\"store\", type=\"int\", dest=\"stride\", default=0) parser.add_option(\"-t\",\"--finaltime\", help=\"finaltime\",", "\"Xdmf.dtd\" []> <Xdmf Version=\"2.0\" xmlns:xi=\"http://www.w3.org/2001/XInclude\"> <Domain>\"\"\"+\"\\n\") XMFfile.write(r' <Grid GridType=\"Collection\" CollectionType=\"Spatial\">'+\"\\n\")", "(r'</Geometry>'+\"\\n\") if tmp.name == \"u\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"u\">'+\"\\n\")", "== \"elements\": XMFfile.write (r'<Topology NumberOfElements=\"' +str(len(tmp[:]))+ '\" Type=\"Tetrahedron\">'+\"\\n\") XMFfile.write (r'", "Center=\"Node\" Name=\"v\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\"", "XMFfile.write (r'</Attribute>'+\"\\n\") if tmp.name == \"w\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\"", "Name=\"phid\">'+\"\\n\") XMFfile.write (r' <DataItem DataType=\"Float\" Dimensions=\"' +str(len(tmp[:]))+ '\" Format=\"HDF\" Precision=\"8\">'", "'\" Format=\"HDF\" Precision=\"8\">' + filename + ':/u</DataItem>'+\"\\n\") XMFfile.write (r'</Attribute>'+\"\\n\") if", "(r'</Attribute>'+\"\\n\") if tmp.name == \"v\": XMFfile.write (r'<Attribute AttributeType=\"Scalar\" Center=\"Node\" Name=\"v\">'+\"\\n\")" ]
[ "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "# # Licensed under the Apache License, Version 2.0 (the", "compliance with the License. # You may obtain a copy", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "2.0 (the \"License\"); # you may not use this file", "agreed to in writing, software # distributed under the License", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Unless required by applicable law or agreed to in writing,", "under the License. # # ------------------------------------------------------------------------------ \"\"\"This test module contains", "def test__generate_item_file_exists(self, *mocks): \"\"\"Test for fetch_agent_locally method positive result.\"\"\" ctx_mock", "distributed under the License is distributed on an \"AS IS\"", "utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited", "# ------------------------------------------------------------------------------ \"\"\"This test module contains the tests for the", "# # Copyright 2018-2019 Fetch.AI Limited # # Licensed under", "the specific language governing permissions and # limitations under the", "_raise_file_exists) class GenerateItemTestCase(TestCase): \"\"\"Test case for fetch_agent_locally method.\"\"\" def test__generate_item_file_exists(self,", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "from tests.test_cli.tools_for_testing import ContextMock def _raise_file_exists(self, *args, **kwargs): raise FileExistsError()", "*args, **kwargs): raise FileExistsError() @mock.patch(\"builtins.open\", mock.mock_open()) @mock.patch(\"aea.cli.generate.ConfigLoader\") @mock.patch(\"aea.cli.generate.os.path.join\", return_value=\"joined-path\") @mock.patch(\"aea.cli.generate.ProtocolGenerator.generate\",", "express or implied. # See the License for the specific", "applicable law or agreed to in writing, software # distributed", "except in compliance with the License. # You may obtain", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "not use this file except in compliance with the License.", "Fetch.AI Limited # # Licensed under the Apache License, Version", "tests for the aea.cli.generate sub-module.\"\"\" from unittest import TestCase, mock", "writing, software # distributed under the License is distributed on", "in writing, software # distributed under the License is distributed", "governing permissions and # limitations under the License. # #", "for the aea.cli.generate sub-module.\"\"\" from unittest import TestCase, mock from", "you may not use this file except in compliance with", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "-*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited #", "Copyright 2018-2019 Fetch.AI Limited # # Licensed under the Apache", "# limitations under the License. # # ------------------------------------------------------------------------------ \"\"\"This test", "use this file except in compliance with the License. #", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "fetch_agent_locally method positive result.\"\"\" ctx_mock = ContextMock() with self.assertRaises(SystemExit): _generate_item(ctx_mock,", "*mocks): \"\"\"Test for fetch_agent_locally method positive result.\"\"\" ctx_mock = ContextMock()", "\"\"\"Test case for fetch_agent_locally method.\"\"\" def test__generate_item_file_exists(self, *mocks): \"\"\"Test for", "CONDITIONS OF ANY KIND, either express or implied. # See", "aea.cli.generate sub-module.\"\"\" from unittest import TestCase, mock from aea.cli.generate import", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "or implied. # See the License for the specific language", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "the tests for the aea.cli.generate sub-module.\"\"\" from unittest import TestCase,", "module contains the tests for the aea.cli.generate sub-module.\"\"\" from unittest", "License. # You may obtain a copy of the License", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "License, Version 2.0 (the \"License\"); # you may not use", "# You may obtain a copy of the License at", "case for fetch_agent_locally method.\"\"\" def test__generate_item_file_exists(self, *mocks): \"\"\"Test for fetch_agent_locally", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "return_value=\"joined-path\") @mock.patch(\"aea.cli.generate.ProtocolGenerator.generate\", _raise_file_exists) class GenerateItemTestCase(TestCase): \"\"\"Test case for fetch_agent_locally method.\"\"\"", "License. # # ------------------------------------------------------------------------------ \"\"\"This test module contains the tests", "-*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019", "under the License is distributed on an \"AS IS\" BASIS,", "def _raise_file_exists(self, *args, **kwargs): raise FileExistsError() @mock.patch(\"builtins.open\", mock.mock_open()) @mock.patch(\"aea.cli.generate.ConfigLoader\") @mock.patch(\"aea.cli.generate.os.path.join\",", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "License for the specific language governing permissions and # limitations", "import TestCase, mock from aea.cli.generate import _generate_item from tests.test_cli.tools_for_testing import", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "mock from aea.cli.generate import _generate_item from tests.test_cli.tools_for_testing import ContextMock def", "sub-module.\"\"\" from unittest import TestCase, mock from aea.cli.generate import _generate_item", "for fetch_agent_locally method.\"\"\" def test__generate_item_file_exists(self, *mocks): \"\"\"Test for fetch_agent_locally method", "the License for the specific language governing permissions and #", "(the \"License\"); # you may not use this file except", "@mock.patch(\"aea.cli.generate.ConfigLoader\") @mock.patch(\"aea.cli.generate.os.path.join\", return_value=\"joined-path\") @mock.patch(\"aea.cli.generate.ProtocolGenerator.generate\", _raise_file_exists) class GenerateItemTestCase(TestCase): \"\"\"Test case for", "Apache License, Version 2.0 (the \"License\"); # you may not", "# you may not use this file except in compliance", "\"\"\"Test for fetch_agent_locally method positive result.\"\"\" ctx_mock = ContextMock() with", "either express or implied. # See the License for the", "# ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # #", "OR CONDITIONS OF ANY KIND, either express or implied. #", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # Licensed", "Limited # # Licensed under the Apache License, Version 2.0", "the License is distributed on an \"AS IS\" BASIS, #", "in compliance with the License. # You may obtain a", "# Copyright 2018-2019 Fetch.AI Limited # # Licensed under the", "software # distributed under the License is distributed on an", "limitations under the License. # # ------------------------------------------------------------------------------ \"\"\"This test module", "aea.cli.generate import _generate_item from tests.test_cli.tools_for_testing import ContextMock def _raise_file_exists(self, *args,", "**kwargs): raise FileExistsError() @mock.patch(\"builtins.open\", mock.mock_open()) @mock.patch(\"aea.cli.generate.ConfigLoader\") @mock.patch(\"aea.cli.generate.os.path.join\", return_value=\"joined-path\") @mock.patch(\"aea.cli.generate.ProtocolGenerator.generate\", _raise_file_exists)", "positive result.\"\"\" ctx_mock = ContextMock() with self.assertRaises(SystemExit): _generate_item(ctx_mock, \"protocol\", \"path\")", "test__generate_item_file_exists(self, *mocks): \"\"\"Test for fetch_agent_locally method positive result.\"\"\" ctx_mock =", "fetch_agent_locally method.\"\"\" def test__generate_item_file_exists(self, *mocks): \"\"\"Test for fetch_agent_locally method positive", "# # Unless required by applicable law or agreed to", "TestCase, mock from aea.cli.generate import _generate_item from tests.test_cli.tools_for_testing import ContextMock", "permissions and # limitations under the License. # # ------------------------------------------------------------------------------", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "\"\"\"This test module contains the tests for the aea.cli.generate sub-module.\"\"\"", "method positive result.\"\"\" ctx_mock = ContextMock() with self.assertRaises(SystemExit): _generate_item(ctx_mock, \"protocol\",", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "------------------------------------------------------------------------------ \"\"\"This test module contains the tests for the aea.cli.generate", "coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI", "Version 2.0 (the \"License\"); # you may not use this", "_raise_file_exists(self, *args, **kwargs): raise FileExistsError() @mock.patch(\"builtins.open\", mock.mock_open()) @mock.patch(\"aea.cli.generate.ConfigLoader\") @mock.patch(\"aea.cli.generate.os.path.join\", return_value=\"joined-path\")", "law or agreed to in writing, software # distributed under", "import _generate_item from tests.test_cli.tools_for_testing import ContextMock def _raise_file_exists(self, *args, **kwargs):", "class GenerateItemTestCase(TestCase): \"\"\"Test case for fetch_agent_locally method.\"\"\" def test__generate_item_file_exists(self, *mocks):", "unittest import TestCase, mock from aea.cli.generate import _generate_item from tests.test_cli.tools_for_testing", "import ContextMock def _raise_file_exists(self, *args, **kwargs): raise FileExistsError() @mock.patch(\"builtins.open\", mock.mock_open())", "contains the tests for the aea.cli.generate sub-module.\"\"\" from unittest import", "2018-2019 Fetch.AI Limited # # Licensed under the Apache License,", "the aea.cli.generate sub-module.\"\"\" from unittest import TestCase, mock from aea.cli.generate", "mock.mock_open()) @mock.patch(\"aea.cli.generate.ConfigLoader\") @mock.patch(\"aea.cli.generate.os.path.join\", return_value=\"joined-path\") @mock.patch(\"aea.cli.generate.ProtocolGenerator.generate\", _raise_file_exists) class GenerateItemTestCase(TestCase): \"\"\"Test case", "implied. # See the License for the specific language governing", "under the Apache License, Version 2.0 (the \"License\"); # you", "_generate_item from tests.test_cli.tools_for_testing import ContextMock def _raise_file_exists(self, *args, **kwargs): raise", "\"License\"); # you may not use this file except in", "from unittest import TestCase, mock from aea.cli.generate import _generate_item from", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "ContextMock def _raise_file_exists(self, *args, **kwargs): raise FileExistsError() @mock.patch(\"builtins.open\", mock.mock_open()) @mock.patch(\"aea.cli.generate.ConfigLoader\")", "# # ------------------------------------------------------------------------------ \"\"\"This test module contains the tests for", "for fetch_agent_locally method positive result.\"\"\" ctx_mock = ContextMock() with self.assertRaises(SystemExit):", "by applicable law or agreed to in writing, software #", "# distributed under the License is distributed on an \"AS", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "raise FileExistsError() @mock.patch(\"builtins.open\", mock.mock_open()) @mock.patch(\"aea.cli.generate.ConfigLoader\") @mock.patch(\"aea.cli.generate.os.path.join\", return_value=\"joined-path\") @mock.patch(\"aea.cli.generate.ProtocolGenerator.generate\", _raise_file_exists) class", "FileExistsError() @mock.patch(\"builtins.open\", mock.mock_open()) @mock.patch(\"aea.cli.generate.ConfigLoader\") @mock.patch(\"aea.cli.generate.os.path.join\", return_value=\"joined-path\") @mock.patch(\"aea.cli.generate.ProtocolGenerator.generate\", _raise_file_exists) class GenerateItemTestCase(TestCase):", "may obtain a copy of the License at # #", "# Unless required by applicable law or agreed to in", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "tests.test_cli.tools_for_testing import ContextMock def _raise_file_exists(self, *args, **kwargs): raise FileExistsError() @mock.patch(\"builtins.open\",", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "to in writing, software # distributed under the License is", "@mock.patch(\"builtins.open\", mock.mock_open()) @mock.patch(\"aea.cli.generate.ConfigLoader\") @mock.patch(\"aea.cli.generate.os.path.join\", return_value=\"joined-path\") @mock.patch(\"aea.cli.generate.ProtocolGenerator.generate\", _raise_file_exists) class GenerateItemTestCase(TestCase): \"\"\"Test", "and # limitations under the License. # # ------------------------------------------------------------------------------ \"\"\"This", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "# See the License for the specific language governing permissions", "You may obtain a copy of the License at #", "language governing permissions and # limitations under the License. #", "may not use this file except in compliance with the", "or agreed to in writing, software # distributed under the", "required by applicable law or agreed to in writing, software", "@mock.patch(\"aea.cli.generate.ProtocolGenerator.generate\", _raise_file_exists) class GenerateItemTestCase(TestCase): \"\"\"Test case for fetch_agent_locally method.\"\"\" def", "GenerateItemTestCase(TestCase): \"\"\"Test case for fetch_agent_locally method.\"\"\" def test__generate_item_file_exists(self, *mocks): \"\"\"Test", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "the License. # # ------------------------------------------------------------------------------ \"\"\"This test module contains the", "with the License. # You may obtain a copy of", "this file except in compliance with the License. # You", "test module contains the tests for the aea.cli.generate sub-module.\"\"\" from", "the Apache License, Version 2.0 (the \"License\"); # you may", "# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright", "@mock.patch(\"aea.cli.generate.os.path.join\", return_value=\"joined-path\") @mock.patch(\"aea.cli.generate.ProtocolGenerator.generate\", _raise_file_exists) class GenerateItemTestCase(TestCase): \"\"\"Test case for fetch_agent_locally", "method.\"\"\" def test__generate_item_file_exists(self, *mocks): \"\"\"Test for fetch_agent_locally method positive result.\"\"\"", "from aea.cli.generate import _generate_item from tests.test_cli.tools_for_testing import ContextMock def _raise_file_exists(self," ]
[ "it has a docstring \\\"\\\"\\\" pass def _skipped(self): # This", "Config: \"\"\"Sphinx napoleon extension settings in `conf.py`. Listed below are", "Also -------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_ivar : :obj:`bool` (Defaults to False) True", "---------- arg1 : str Description of `arg1` arg2 : int,", "for all the keywords. This behaves similarly to :attr:`napoleon_use_param`. Note", "and is_member: cls_is_owner = False if what == 'class' or", "(False, 'env'), 'napoleon_use_ivar': (False, 'env'), 'napoleon_use_param': (True, 'env'), 'napoleon_use_rtype': (True,", "(Sphinx) -> Dict[str, Any] \"\"\"Sphinx extension setup function. When the", "a tuple/list/indexed container, the first entry is the name of", "# Napoleon settings napoleon_google_docstring = True napoleon_numpy_docstring = True napoleon_include_init_with_doc", "This behaves similarly to :attr:`napoleon_use_param`. Note unlike docutils, ``:keyword:`` and", "generic section. If the entry is a tuple/list/indexed container, the", "``_membername``) with docstrings in the documentation. False to fall back", ":obj:`bool` (Defaults to True) True to use a ``:keyword:`` role", "# This will NOT be included in the docs pass", "a header for a generic section. If the entry is", "_NumPy style: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt Attributes ---------- napoleon_google_docstring : :obj:`bool` (Defaults to", "the decision options : sphinx.ext.autodoc.Options The options given to the", "name of the section, the second is the section key", "(False, 'env'), 'napoleon_use_param': (True, 'env'), 'napoleon_use_rtype': (True, 'env'), 'napoleon_use_keyword': (True,", "the docs because it has a docstring \\\"\\\"\\\" def __init__(self):", "PyTypedField except ImportError: pass else: import sphinx.domains.python from sphinx.locale import", "of `attr1` **If True**:: :ivar attr1: Description of `attr1` :vartype", "None \"\"\"Process the docstring for a given python object. Called", "This will be included in the docs because it has", ".. rubric:: Example This is just a quick example napoleon_use_admonition_for_notes", "name of the member. obj : module, class, exception, function,", "Parameters ---------- arg1 : str Description of `arg1` arg2 :", "-- True if successful, False otherwise napoleon_custom_sections : :obj:`list` (Defaults", "if name != '__weakref__' and has_doc and is_member: cls_is_owner =", "'napoleon_use_admonition_for_notes': (False, 'env'), 'napoleon_use_admonition_for_references': (False, 'env'), 'napoleon_use_ivar': (False, 'env'), 'napoleon_use_param':", "just pass a string. * To create an alias for", "of the object to which the member belongs. Valid values:", "name, default) for name, value in settings.items(): setattr(self, name, value)", "follows:: Example ------- This is just a quick example **If", "is the name of the section, the second is the", "if private and special class members are included in docs.", "List # NOQA class Config: \"\"\"Sphinx napoleon extension settings in", "The name of the member. obj : module, class, exception,", "and their default values. These settings can be changed in", "from the class docstring. False to fall back to Sphinx's", "use the ``.. admonition::`` directive for the **Example** and **Examples**", "bool \"\"\"Determine if private and special class members are included", "**Examples** sections. False to use the ``.. rubric::`` directive instead.", "in conf.py control what styles of docstrings will be parsed:", "`_skip_member` does not override the decision options : sphinx.ext.autodoc.Options The", "docstring.lines() lines[:] = result_lines[:] def _skip_member(app, what, name, obj, skip,", "rubric::`` directive instead. One may look better than the other", "== 'exception' or what == 'module') if name != '__weakref__'", "str, str, Any, bool, Any) -> bool \"\"\"Determine if private", "Tutorial <http://sphinx-doc.org/extdev/tutorial.html>`_ `The Extension API <http://sphinx-doc.org/extdev/appapi.html>`_ \"\"\" if not isinstance(app,", "bool A boolean indicating if autodoc will skip this member", "of the section, the second is the section key to", "be treated the same way - there will be a", "((is_special and inc_special) or (is_private and inc_private) or (is_init and", "(Defaults to False) True to include special members (like ``__membername__``)", "# type: () -> None try: from sphinx.domains.python import PyTypedField", "= True napoleon_use_rtype = True napoleon_use_keyword = True napoleon_custom_sections =", "Description of `arg1` * **arg2** (*int, optional*) -- Description of", "options) result_lines = docstring.lines() if app.config.napoleon_google_docstring: docstring = GoogleDocstring(result_lines, app.config,", "else: cls = obj.__globals__[cls_path] except Exception: cls_is_owner = False else:", "False**:: :returns: *bool* -- True if successful, False otherwise napoleon_custom_sections", "'napoleon_use_keyword': (True, 'env'), 'napoleon_custom_sections': (None, 'env') } def __init__(self, **settings):", "used. This `NumPy style`_ snippet will be converted as follows::", "(False, 'env'), 'napoleon_use_admonition_for_examples': (False, 'env'), 'napoleon_use_admonition_for_notes': (False, 'env'), 'napoleon_use_admonition_for_references': (False,", "Valid values: \"module\", \"class\", \"exception\", \"function\", \"method\", \"attribute\". name :", "in the docs napoleon_include_private_with_doc : :obj:`bool` (Defaults to False) True", "'argument') break sphinx.domains.python.PyObject.doc_field_types.append( PyTypedField('keyword', label=_('Keyword Arguments'), names=('keyword', 'kwarg', 'kwparam'), typerolename='obj',", "values: \"module\", \"class\", \"exception\", \"function\", \"method\", \"attribute\". name : str", "and has_doc and is_member: cls_is_owner = False if what ==", "False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = True", "True**:: def __init__(self): \\\"\\\"\\\" This will be included in the", "included in the docs napoleon_include_private_with_doc : :obj:`bool` (Defaults to False)", "special class members are included in docs. The following settings", "False otherwise napoleon_custom_sections : :obj:`list` (Defaults to None) Add a", "docs. \"\"\" has_doc = getattr(obj, '__doc__', False) is_member = (what", "instead. See Also -------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_ivar : :obj:`bool` (Defaults to", "`Google style`_ docstrings. False to disable support for Google style", "`_process_docstring` modifies in place to change what Sphinx outputs. The", "**If False**:: :returns: *bool* -- True if successful, False otherwise", "will be a separate \"Keyword Arguments\" section, rendered in the", "Sphinx documentation on Extensions <http://sphinx-doc.org/extensions.html>`_ `The Extension Tutorial <http://sphinx-doc.org/extdev/tutorial.html>`_ `The", "and not is_special and name.startswith('_')) inc_init = app.config.napoleon_include_init_with_doc inc_special =", "member. obj : module, class, exception, function, method, or attribute.", "'exception' or what == 'module') if name != '__weakref__' and", "be a separate \"Keyword Arguments\" section, rendered in the same", "docstrings. napoleon_numpy_docstring : :obj:`bool` (Defaults to True) True to parse", "a custom \"generic\" section, just pass a string. * To", "(Defaults to True) True to use the ``:rtype:`` role for", "special members if they have docstrings Parameters ---------- app :", "have docstrings * ``napoleon_include_special_with_doc`` -- include special members if they", "(True, 'env'), 'napoleon_custom_sections': (None, 'env') } def __init__(self, **settings): #", "docstring \\\"\\\"\\\" return unicode(self).encode('utf-8') def __unicode__(self): # This will NOT", "(default, rebuild) in self._config_values.items(): setattr(self, name, default) for name, value", "what == 'exception': qualname = getattr(obj, '__qualname__', '') cls_path, _,", "what Sphinx outputs. The following settings in conf.py control what", "in the generated documentation: * ``napoleon_include_init_with_doc`` -- include init methods", "This `NumPy style`_ snippet will be converted as follows:: Example", "everything the extension offers. Parameters ---------- app : sphinx.application.Sphinx Application", "options): # type: (Sphinx, str, str, Any, bool, Any) ->", "# For type annotation from typing import Any, Dict, List", "False napoleon_use_param = True napoleon_use_rtype = True napoleon_use_keyword = True", "== 'class' or what == 'exception': qualname = getattr(obj, '__qualname__',", "the original, in that order. If an entry is just", "Sphinx process. what : str A string specifying the type", "be strings or tuples, depending on the intention: * To", "the object. obj : module, class, exception, function, method, or", "sections. False to use the ``.. rubric::`` directive instead. See", "a ``:keyword:`` role for each function keyword argument. False to", "-> None for name, (default, rebuild) in self._config_values.items(): setattr(self, name,", "the docstring belongs. options : sphinx.ext.autodoc.Options The options given to", "members are included in docs. The following settings in conf.py", "Sphinx extension module names here, as strings extensions = ['sphinx.ext.napoleon']", "directive for **Notes** sections. False to use the ``.. rubric::``", "a given python object. Called when autodoc has read and", "considers the ``__init___`` docstring as part of the class documentation.", "is_init = (name == '__init__') is_special = (not is_init and", "``napoleon_include_special_with_doc`` -- include special members if they have docstrings Parameters", "napoleon_include_private_with_doc = False napoleon_include_special_with_doc = False napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes", ":param arg2: Description of `arg2`, defaults to 0 :type arg2:", "quick example **If True**:: .. admonition:: Example This is just", "a string, it is interpreted as a header for a", "are True if the flag option of same name was", "typerolename='obj', typenames=('paramtype', 'kwtype'), can_collapse=True)) def _process_docstring(app, what, name, obj, options,", "docstring, see above. .. note:: `lines` is modified *in place*", "True to parse `NumPy style`_ docstrings. False to disable support", "setattr(self, name, default) for name, value in settings.items(): setattr(self, name,", "the first entry is the name of the section, the", "(Defaults to False) True to include private members (like ``_membername``)", "-> bool \"\"\"Determine if private and special class members are", "-- include private members if they have docstrings * ``napoleon_include_special_with_doc``", "(not is_init and not is_special and name.startswith('_')) inc_init = app.config.napoleon_include_init_with_doc", "_process_docstring(app, what, name, obj, options, lines): # type: (Sphinx, str,", "* **arg1** (*str*) -- Description of `arg1` * **arg2** (*int,", "'kwarg', 'kwparam'), typerolename='obj', typenames=('paramtype', 'kwtype'), can_collapse=True)) def _process_docstring(app, what, name,", "(Sphinx, str, str, Any, bool, Any) -> bool \"\"\"Determine if", "-- include special members if they have docstrings Parameters ----------", "section will always be converted to a ``.. note::`` directive.", "cls_path: try: if '.' in cls_path: import importlib import functools", "single ``:parameters:`` role for all the parameters. This `NumPy style`_", "the list of parsed sections. The entries can either be", "private and special class members are included in docs. The", "the second is the section key to emulate. \"\"\" _config_values", "same name was given to the auto directive. lines :", "because it has a docstring \\\"\\\"\\\" def __init__(self): # This", "members if they have docstrings * ``napoleon_include_special_with_doc`` -- include special", "(False, 'env'), 'napoleon_use_admonition_for_notes': (False, 'env'), 'napoleon_use_admonition_for_references': (False, 'env'), 'napoleon_use_ivar': (False,", "napoleon_include_special_with_doc = False napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references", "See Also -------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_ivar : :obj:`bool` (Defaults to False)", "rebuild) in self._config_values.items(): setattr(self, name, default) for name, value in", "similarly to :attr:`napoleon_use_param`. Note unlike docutils, ``:keyword:`` and ``:param:`` will", "= app.config.napoleon_include_init_with_doc inc_special = app.config.napoleon_include_special_with_doc inc_private = app.config.napoleon_include_private_with_doc if ((is_special", "False to disable support for Google style docstrings. napoleon_numpy_docstring :", "containing the alias name and the original, in that order.", "(False, 'env'), 'napoleon_use_admonition_for_references': (False, 'env'), 'napoleon_use_ivar': (False, 'env'), 'napoleon_use_param': (True,", "the Sphinx process See Also -------- `The Sphinx documentation on", "False if it should be included in the docs. \"\"\"", "treated the same way - there will be a separate", "to include, expanding the list of parsed sections. The entries", "are all the settings used by napoleon and their default", "__unicode__(self): # This will NOT be included in the docs", "setup function. When the extension is loaded, Sphinx imports this", "obj, options) result_lines = docstring.lines() if app.config.napoleon_google_docstring: docstring = GoogleDocstring(result_lines,", "Extensions <http://sphinx-doc.org/extensions.html>`_ `The Extension Tutorial <http://sphinx-doc.org/extdev/tutorial.html>`_ `The Extension API <http://sphinx-doc.org/extdev/appapi.html>`_", "return {'version': __version__, 'parallel_read_safe': True} _patch_python_domain() app.setup_extension('sphinx.ext.autodoc') app.connect('autodoc-process-docstring', _process_docstring) app.connect('autodoc-skip-member',", "``.. rubric::`` directive instead. See Also -------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_ivar :", "unicode(self.__class__.__name__) napoleon_use_admonition_for_examples : :obj:`bool` (Defaults to False) True to use", "list of parsed sections. The entries can either be strings", "docs. The following settings in conf.py determine if private and", "in the docs because it has a docstring \\\"\\\"\\\" return", "in the docs because it has a docstring \\\"\\\"\\\" def", "sure that \"sphinx.ext.napoleon\" is enabled in `conf.py`:: # conf.py #", "napoleon_google_docstring = True napoleon_numpy_docstring = True napoleon_include_init_with_doc = False napoleon_include_private_with_doc", "<http://sphinx-doc.org/extensions.html>`_ `The Extension Tutorial <http://sphinx-doc.org/extdev/tutorial.html>`_ `The Extension API <http://sphinx-doc.org/extdev/appapi.html>`_ \"\"\"", "``.. admonition::`` directive for **Notes** sections. False to use the", "support for NumPy style docstrings. napoleon_include_init_with_doc : :obj:`bool` (Defaults to", "and name.startswith('__') and name.endswith('__')) is_private = (not is_init and not", "it is interpreted as a header for a generic section.", "{'version': __version__, 'parallel_read_safe': True} _patch_python_domain() app.setup_extension('sphinx.ext.autodoc') app.connect('autodoc-process-docstring', _process_docstring) app.connect('autodoc-skip-member', _skip_member)", "quick example napoleon_use_admonition_for_notes : :obj:`bool` (Defaults to False) True to", "admonition:: Example This is just a quick example **If False**::", "is the __init__ method of class A, then `obj` will", "can be changed in the Sphinx `conf.py` file. Make sure", "'napoleon_numpy_docstring': (True, 'env'), 'napoleon_include_init_with_doc': (False, 'env'), 'napoleon_include_private_with_doc': (False, 'env'), 'napoleon_include_special_with_doc':", "the docs pass napoleon_include_special_with_doc : :obj:`bool` (Defaults to False) True", "True to use the ``:rtype:`` role for the return type.", "a list of custom sections to include, expanding the list", "modified *in place* \"\"\" result_lines = lines docstring = None", "defaults to 0 napoleon_use_keyword : :obj:`bool` (Defaults to True) True", "disable support for NumPy style docstrings. napoleon_include_init_with_doc : :obj:`bool` (Defaults", "= qualname.rpartition('.') if cls_path: try: if '.' in cls_path: import", "lines[:] = result_lines[:] def _skip_member(app, what, name, obj, skip, options):", "If an entry is just a string, it is interpreted", "rubric::`` directive instead. See Also -------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_ivar : :obj:`bool`", "settings used by napoleon and their default values. These settings", "cls_is_owner = (cls and hasattr(cls, name) and # type: ignore", "`conf.py` file. Make sure that \"sphinx.ext.napoleon\" is enabled in `conf.py`::", "`lines` is a list of docstring lines that `_process_docstring` modifies", "modifies in place to change what Sphinx outputs. The following", "of the class documentation. **If True**:: def __init__(self): \\\"\\\"\\\" This", "directive. Returns ------- bool True if the member should be", "name, value in settings.items(): setattr(self, name, value) def setup(app): #", "of the docstring, see above. .. note:: `lines` is modified", "use the ``.. rubric::`` directive instead. See Also -------- :attr:`napoleon_use_admonition_for_examples`", "of the member. obj : module, class, exception, function, method,", "the section key to emulate. \"\"\" _config_values = { 'napoleon_google_docstring':", "of `arg2`, defaults to 0 **If True**:: :param arg1: Description", "offers. Parameters ---------- app : sphinx.application.Sphinx Application object representing the", "import Any, Dict, List # NOQA class Config: \"\"\"Sphinx napoleon", "just a quick example napoleon_use_admonition_for_notes : :obj:`bool` (Defaults to False)", "is a list of docstring lines that `_process_docstring` modifies in", "else: cls_is_owner = False if what == 'module' or cls_is_owner:", "the ``.. attribute::`` directive instead. This `NumPy style`_ snippet will", "\"\"\" has_doc = getattr(obj, '__doc__', False) is_member = (what ==", ":ivar attr1: Description of `attr1` :vartype attr1: int **If False**::", "Sphinx from sphinx.ext.napoleon.docstring import GoogleDocstring, NumpyDocstring if False: # For", "lines docstring = None # type: GoogleDocstring if app.config.napoleon_numpy_docstring: docstring", "The object to which the docstring belongs. options : sphinx.ext.autodoc.Options", "strings extensions = ['sphinx.ext.napoleon'] # Napoleon settings napoleon_google_docstring = True", "if doc_field.name == 'parameter': doc_field.names = ('param', 'parameter', 'arg', 'argument')", "the docs, False if it should be included in the", "PyTypedField('keyword', label=_('Keyword Arguments'), names=('keyword', 'kwarg', 'kwparam'), typerolename='obj', typenames=('paramtype', 'kwtype'), can_collapse=True))", "HTML theme is used. This `NumPy style`_ snippet will be", "`NumPy style`_ snippet will be converted as follows:: Attributes ----------", "int napoleon_use_param : :obj:`bool` (Defaults to True) True to use", "to include special members (like ``__membername__``) with docstrings in the", "``.. rubric::`` directive instead. One may look better than the", "use a single ``:parameters:`` role for all the parameters. This", "if they have docstrings * ``napoleon_include_private_with_doc`` -- include private members", "Sphinx of everything the extension offers. Parameters ---------- app :", "**Example** and **Examples** sections. False to use the ``.. rubric::``", "attribute. For example, if the member is the __init__ method", "place* \"\"\" result_lines = lines docstring = None # type:", "def __init__(self, **settings): # type: (Any) -> None for name,", "'class' or what == 'exception' or what == 'module') if", "value) def setup(app): # type: (Sphinx) -> Dict[str, Any] \"\"\"Sphinx", "== 'exception': qualname = getattr(obj, '__qualname__', '') cls_path, _, _", "functools.reduce(getattr, mod_path, mod) else: cls = obj.__globals__[cls_path] except Exception: cls_is_owner", "`attr1` :vartype attr1: int **If False**:: .. attribute:: attr1 Description", "napoleon_use_keyword : :obj:`bool` (Defaults to True) True to use a", "napoleon_numpy_docstring = True napoleon_include_init_with_doc = False napoleon_include_private_with_doc = False napoleon_include_special_with_doc", "what, name, obj, options, lines): # type: (Sphinx, str, str,", "name : str The fully qualified name of the object.", "directive instead. One may look better than the other depending", "to which the member belongs. Valid values: \"module\", \"class\", \"exception\",", ".. note:: `lines` is modified *in place* \"\"\" result_lines =", "note:: `lines` is modified *in place* \"\"\" result_lines = lines", "obj, options, lines): # type: (Sphinx, str, str, Any, Any,", "= functools.reduce(getattr, mod_path, mod) else: cls = obj.__globals__[cls_path] except Exception:", "'module') if name != '__weakref__' and has_doc and is_member: cls_is_owner", "unicode(self).encode('utf-8') def __unicode__(self): # This will NOT be included in", "directive instead. Note ---- The singular **Note** section will always", "``setup()`` function, which in turn notifies Sphinx of everything the", "given to the auto directive. Returns ------- bool True if", "None for name, (default, rebuild) in self._config_values.items(): setattr(self, name, default)", "'napoleon_custom_sections': (None, 'env') } def __init__(self, **settings): # type: (Any)", "the class docstring. False to fall back to Sphinx's default", "str A string specifying the type of the object to", "it should be included in the docs. \"\"\" has_doc =", "type: (Any) -> None for name, (default, rebuild) in self._config_values.items():", "NumPy and Google style docstrings. :copyright: Copyright 2007-2018 by the", "to Sphinx's default behavior. **If True**:: def _included(self): \\\"\\\"\\\" This", "---------- attr1 : int Description of `attr1` **If True**:: :ivar", "be skipped during creation of the docs, False if it", "has read and processed a docstring. `lines` is a list", "will not be treated the same way - there will", "str The lines of the docstring, see above. .. note::", "Any, Dict, List # NOQA class Config: \"\"\"Sphinx napoleon extension", "default, rebuild) return {'version': __version__, 'parallel_read_safe': True} def _patch_python_domain(): #", "\"\"\"Sphinx extension setup function. When the extension is loaded, Sphinx", "belongs. Valid values: \"module\", \"class\", \"exception\", \"function\", \"method\", \"attribute\". name", "napoleon_include_special_with_doc : :obj:`bool` (Defaults to False) True to include special", "obj.__globals__[cls_path] except Exception: cls_is_owner = False else: cls_is_owner = (cls", "by napoleon and their default values. These settings can be", "= False napoleon_use_ivar = False napoleon_use_param = True napoleon_use_rtype =", "def _skipped(self): # This will NOT be included in the", "sphinx.application.Sphinx Application object representing the Sphinx process See Also --------", "List[str]) -> None \"\"\"Process the docstring for a given python", "to None) Add a list of custom sections to include,", "in place to change what Sphinx outputs. The following settings", "method, or attribute. For example, if the member is the", "function keyword argument. False to use a single ``:keyword arguments:``", "------- bool True if the member should be skipped during", "and **Examples** sections. False to use the ``.. rubric::`` directive", "intention: * To create a custom \"generic\" section, just pass", "See Also -------- `The Sphinx documentation on Extensions <http://sphinx-doc.org/extensions.html>`_ `The", "included in the docs. \"\"\" has_doc = getattr(obj, '__doc__', False)", "include private members if they have docstrings * ``napoleon_include_special_with_doc`` --", "<http://sphinx-doc.org/extdev/appapi.html>`_ \"\"\" if not isinstance(app, Sphinx): # probably called by", "the parameters. This `NumPy style`_ snippet will be converted as", "members or init methods are included in the generated documentation:", ":returns: True if successful, False otherwise :rtype: bool **If False**::", "'napoleon_use_param': (True, 'env'), 'napoleon_use_rtype': (True, 'env'), 'napoleon_use_keyword': (True, 'env'), 'napoleon_custom_sections':", "are included in the generated documentation: * ``napoleon_include_init_with_doc`` -- include", "NumPy style docstrings Parameters ---------- app : sphinx.application.Sphinx Application object", "will be converted as follows:: Example ------- This is just", "the ``:rtype:`` role for the return type. False to output", "key to emulate. \"\"\" _config_values = { 'napoleon_google_docstring': (True, 'env'),", "if the member is the __init__ method of class A,", "importlib.import_module(obj.__module__) mod_path = cls_path.split('.') cls = functools.reduce(getattr, mod_path, mod) else:", "(like ``__membername__``) with docstrings in the documentation. False to fall", "type: GoogleDocstring if app.config.napoleon_numpy_docstring: docstring = NumpyDocstring(result_lines, app.config, app, what,", "notifies Sphinx of everything the extension offers. Parameters ---------- app", "all the settings used by napoleon and their default values.", "the docstring, see above. .. note:: `lines` is modified *in", "the auto directive. lines : list of str The lines", ": :obj:`bool` (Defaults to True) True to use the ``:rtype:``", "in the docs because it has a docstring \\\"\\\"\\\" pass", "function, method, or attribute The object to which the docstring", "for an existing section, pass a tuple containing the alias", "to False) True to include special members (like ``__membername__``) with", "**If False**:: :parameters: * **arg1** (*str*) -- Description of `arg1`", "change what Sphinx outputs. The following settings in conf.py control", "**If False**:: .. rubric:: Example This is just a quick", "for name, (default, rebuild) in self._config_values.items(): setattr(self, name, default) for", "list of custom sections to include, expanding the list of", "auto directive. lines : list of str The lines of", "following settings in conf.py determine if private and special class", "container, the first entry is the name of the section,", "_included(self): \\\"\\\"\\\" This will be included in the docs because", "'env'), 'napoleon_use_ivar': (False, 'env'), 'napoleon_use_param': (True, 'env'), 'napoleon_use_rtype': (True, 'env'),", "role for all the parameters. This `NumPy style`_ snippet will", "Listed below are all the settings used by napoleon and", "back to Sphinx's default behavior, which considers the ``__init___`` docstring", "typenames=('paramtype', 'kwtype'), can_collapse=True)) def _process_docstring(app, what, name, obj, options, lines):", "# type: GoogleDocstring if app.config.napoleon_numpy_docstring: docstring = NumpyDocstring(result_lines, app.config, app,", "AUTHORS. :license: BSD, see LICENSE for details. \"\"\" from sphinx", "int **If False**:: .. attribute:: attr1 Description of `attr1` :type:", "directive instead. See Also -------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_ivar : :obj:`bool` (Defaults", "docstring for a given python object. Called when autodoc has", "False to disable support for NumPy style docstrings. napoleon_include_init_with_doc :", "for the **Example** and **Examples** sections. False to use the", "be included in the docs pass napoleon_include_special_with_doc : :obj:`bool` (Defaults", "extension is loaded, Sphinx imports this module and executes the", "process. what : str A string specifying the type of", "`The Extension API <http://sphinx-doc.org/extdev/appapi.html>`_ \"\"\" if not isinstance(app, Sphinx): #", "True**:: .. admonition:: Example This is just a quick example", "auto directive. Returns ------- bool True if the member should", "given python object. Called when autodoc has read and processed", "tests return {'version': __version__, 'parallel_read_safe': True} _patch_python_domain() app.setup_extension('sphinx.ext.autodoc') app.connect('autodoc-process-docstring', _process_docstring)", "type of the object to which the docstring belongs. Valid", "back to Sphinx's default behavior. **If True**:: def _included(self): \\\"\\\"\\\"", ": :obj:`bool` (Defaults to False) True to list ``__init___`` docstrings", "undoc_members, show_inheritance and noindex that are True if the flag", "the type of the object to which the member belongs.", "'kwparam'), typerolename='obj', typenames=('paramtype', 'kwtype'), can_collapse=True)) def _process_docstring(app, what, name, obj,", "indicating if autodoc will skip this member if `_skip_member` does", "which in turn notifies Sphinx of everything the extension offers.", "for NumPy style docstrings. napoleon_include_init_with_doc : :obj:`bool` (Defaults to False)", "converted to a ``.. note::`` directive. See Also -------- :attr:`napoleon_use_admonition_for_examples`", "name) and # type: ignore name in cls.__dict__) else: cls_is_owner", "style: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt Attributes ---------- napoleon_google_docstring : :obj:`bool` (Defaults to True)", "style docstrings Parameters ---------- app : sphinx.application.Sphinx Application object representing", "is_private = (not is_init and not is_special and name.startswith('_')) inc_init", "object representing the Sphinx process See Also -------- `The Sphinx", "(Defaults to True) True to use a ``:param:`` role for", "'parameter', 'arg', 'argument') break sphinx.domains.python.PyObject.doc_field_types.append( PyTypedField('keyword', label=_('Keyword Arguments'), names=('keyword', 'kwarg',", "it has a docstring \\\"\\\"\\\" def __init__(self): # This will", "be converted as follows:: Returns ------- bool True if successful,", "defaults to 0 **If True**:: :param arg1: Description of `arg1`", "_process_docstring) app.connect('autodoc-skip-member', _skip_member) for name, (default, rebuild) in Config._config_values.items(): app.add_config_value(name,", "has a docstring \\\"\\\"\\\" return unicode(self).encode('utf-8') def __unicode__(self): # This", "possible) See Also -------- :attr:`napoleon_use_param` napoleon_use_rtype : :obj:`bool` (Defaults to", "_Google style: https://google.github.io/styleguide/pyguide.html .. _NumPy style: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt Attributes ---------- napoleon_google_docstring", "to True) True to parse `NumPy style`_ docstrings. False to", "imports this module and executes the ``setup()`` function, which in", "the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for", "app.connect('autodoc-skip-member', _skip_member) for name, (default, rebuild) in Config._config_values.items(): app.add_config_value(name, default,", "True if successful, False otherwise napoleon_custom_sections : :obj:`list` (Defaults to", "rendered in the same fashion as \"Parameters\" section (type links", ": :obj:`bool` (Defaults to True) True to parse `Google style`_", "`NumPy style`_ docstrings. False to disable support for NumPy style", "skip this member if `_skip_member` does not override the decision", "what == 'module' or cls_is_owner: is_init = (name == '__init__')", "qualname.rpartition('.') if cls_path: try: if '.' in cls_path: import importlib", "-- include init methods if they have docstrings * ``napoleon_include_private_with_doc``", "an alias for an existing section, pass a tuple containing", "section, pass a tuple containing the alias name and the", "include special members (like ``__membername__``) with docstrings in the documentation.", "representing the Sphinx process. what : str A string specifying", "``napoleon_numpy_docstring`` -- parse NumPy style docstrings Parameters ---------- app :", "which the docstring belongs. options : sphinx.ext.autodoc.Options The options given", "app.config.napoleon_numpy_docstring: docstring = NumpyDocstring(result_lines, app.config, app, what, name, obj, options)", "if '.' in cls_path: import importlib import functools mod =", "init methods if they have docstrings * ``napoleon_include_private_with_doc`` -- include", "attributes inherited_members, undoc_members, show_inheritance and noindex that are True if", ":attr:`napoleon_use_admonition_for_examples` napoleon_use_admonition_for_references : :obj:`bool` (Defaults to False) True to use", ": str Description of `arg1` arg2 : int, optional Description", "the class documentation. **If True**:: def __init__(self): \\\"\\\"\\\" This will", "the extension is loaded, Sphinx imports this module and executes", ":rtype: bool **If False**:: :returns: *bool* -- True if successful,", "For example, if the member is the __init__ method of", "for Google style docstrings. napoleon_numpy_docstring : :obj:`bool` (Defaults to True)", "== 'module' or cls_is_owner: is_init = (name == '__init__') is_special", "cls_is_owner: is_init = (name == '__init__') is_special = (not is_init", "(type links created if possible) See Also -------- :attr:`napoleon_use_param` napoleon_use_rtype", "'napoleon_include_private_with_doc': (False, 'env'), 'napoleon_include_special_with_doc': (False, 'env'), 'napoleon_use_admonition_for_examples': (False, 'env'), 'napoleon_use_admonition_for_notes':", "Also -------- :attr:`napoleon_use_param` napoleon_use_rtype : :obj:`bool` (Defaults to True) True", "inline with the description. This `NumPy style`_ snippet will be", "napoleon extension settings in `conf.py`. Listed below are all the", "False) True to use the ``.. admonition::`` directive for **References**", "as follows:: Returns ------- bool True if successful, False otherwise", ":returns: *bool* -- True if successful, False otherwise napoleon_custom_sections :", "create an alias for an existing section, pass a tuple", "Arguments\" section, rendered in the same fashion as \"Parameters\" section", "False) is_member = (what == 'class' or what == 'exception'", "for a generic section. If the entry is a tuple/list/indexed", "0 napoleon_use_keyword : :obj:`bool` (Defaults to True) True to use", "docs because it has a docstring \\\"\\\"\\\" def __init__(self): #", "Parameters ---------- app : sphinx.application.Sphinx Application object representing the Sphinx", "Description of `arg2`, defaults to 0 **If True**:: :param arg1:", "---------- app : sphinx.application.Sphinx Application object representing the Sphinx process", "~~~~~~~~~~~~~~~~~~~ Support for NumPy and Google style docstrings. :copyright: Copyright", "for NumPy and Google style docstrings. :copyright: Copyright 2007-2018 by", "on what HTML theme is used. This `NumPy style`_ snippet", "following settings in conf.py control what styles of docstrings will", "app.config, app, what, name, obj, options) result_lines = docstring.lines() if", "False if what == 'class' or what == 'exception': qualname", "a quick example **If False**:: .. rubric:: Example This is", "napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param", "sphinx.ext.autodoc.Options The options given to the directive: an object with", "of class A, then `obj` will be `A.__init__`. skip :", "True to parse `Google style`_ docstrings. False to disable support", "or attribute. For example, if the member is the __init__", "Sphinx process See Also -------- `The Sphinx documentation on Extensions", "member is the __init__ method of class A, then `obj`", "with docstrings in the documentation. False to fall back to", "``:param:`` role for each function parameter. False to use a", "docstrings * ``napoleon_include_private_with_doc`` -- include private members if they have", "specifying the type of the object to which the docstring", "def _patch_python_domain(): # type: () -> None try: from sphinx.domains.python", "the member. obj : module, class, exception, function, method, or", "is_init and not is_special and name.startswith('_')) inc_init = app.config.napoleon_include_init_with_doc inc_special", "or (is_private and inc_private) or (is_init and inc_init)): return False", "fashion as \"Parameters\" section (type links created if possible) See", "what, name, obj, skip, options): # type: (Sphinx, str, str,", "---- The singular **Note** section will always be converted to", "NOT be included in the docs return unicode(self.__class__.__name__) napoleon_use_admonition_for_examples :", "name.startswith('__') and name.endswith('__')) is_private = (not is_init and not is_special", "arg2: Description of `arg2`, defaults to 0 :type arg2: int,", "# Add any Sphinx extension module names here, as strings", ": list of str The lines of the docstring, see", "docstrings * ``napoleon_include_special_with_doc`` -- include special members if they have", "False napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False", "created if possible) See Also -------- :attr:`napoleon_use_param` napoleon_use_rtype : :obj:`bool`", "was given to the auto directive. lines : list of", "-- parse Google style docstrings * ``napoleon_numpy_docstring`` -- parse NumPy", "name, obj, skip, options): # type: (Sphinx, str, str, Any,", "converted as follows:: Parameters ---------- arg1 : str Description of", "True napoleon_use_rtype = True napoleon_use_keyword = True napoleon_custom_sections = None", "\"method\", \"attribute\". name : str The name of the member.", "creation of the docs, False if it should be included", "False to fall back to Sphinx's default behavior, which considers", "to change what Sphinx outputs. The following settings in conf.py", "as follows:: Parameters ---------- arg1 : str Description of `arg1`", "'env'), 'napoleon_use_param': (True, 'env'), 'napoleon_use_rtype': (True, 'env'), 'napoleon_use_keyword': (True, 'env'),", "a quick example napoleon_use_admonition_for_notes : :obj:`bool` (Defaults to False) True", "Description of `arg2`, defaults to 0 :type arg2: int, optional", "_, _ = qualname.rpartition('.') if cls_path: try: if '.' in", "except Exception: cls_is_owner = False else: cls_is_owner = (cls and", "options, lines): # type: (Sphinx, str, str, Any, Any, List[str])", ": bool A boolean indicating if autodoc will skip this", "False napoleon_include_private_with_doc = False napoleon_include_special_with_doc = False napoleon_use_admonition_for_examples = False", "attribute The object to which the docstring belongs. options :", "A, then `obj` will be `A.__init__`. skip : bool A", "to parse `NumPy style`_ docstrings. False to disable support for", "= ['sphinx.ext.napoleon'] # Napoleon settings napoleon_google_docstring = True napoleon_numpy_docstring =", "that order. If an entry is just a string, it", "or cls_is_owner: is_init = (name == '__init__') is_special = (not", "def __init__(self): \\\"\\\"\\\" This will be included in the docs", "methods are included in the generated documentation: * ``napoleon_include_init_with_doc`` --", "'.' in cls_path: import importlib import functools mod = importlib.import_module(obj.__module__)", "'env'), 'napoleon_use_admonition_for_examples': (False, 'env'), 'napoleon_use_admonition_for_notes': (False, 'env'), 'napoleon_use_admonition_for_references': (False, 'env'),", "__init__(self): \\\"\\\"\\\" This will be included in the docs because", "entry is just a string, it is interpreted as a", "False to use a single ``:keyword arguments:`` role for all", "'__init__') is_special = (not is_init and name.startswith('__') and name.endswith('__')) is_private", "documentation: * ``napoleon_include_init_with_doc`` -- include init methods if they have", "the object to which the member belongs. Valid values: \"module\",", "name, value) def setup(app): # type: (Sphinx) -> Dict[str, Any]", "docs napoleon_include_private_with_doc : :obj:`bool` (Defaults to False) True to include", "A string specifying the type of the object to which", "= importlib.import_module(obj.__module__) mod_path = cls_path.split('.') cls = functools.reduce(getattr, mod_path, mod)", "documentation on Extensions <http://sphinx-doc.org/extensions.html>`_ `The Extension Tutorial <http://sphinx-doc.org/extdev/tutorial.html>`_ `The Extension", "successful, False otherwise napoleon_custom_sections : :obj:`list` (Defaults to None) Add", "determine if private and special class members or init methods", "style docstrings. napoleon_include_init_with_doc : :obj:`bool` (Defaults to False) True to", "str The name of the member. obj : module, class,", "docstring \\\"\\\"\\\" def __init__(self): # This will NOT be included", "False**:: .. rubric:: Example This is just a quick example", "which the member belongs. Valid values: \"module\", \"class\", \"exception\", \"function\",", "``__membername__``) with docstrings in the documentation. False to fall back", "-> Dict[str, Any] \"\"\"Sphinx extension setup function. When the extension", "docstring as part of the class documentation. **If True**:: def", "__version__, 'parallel_read_safe': True} def _patch_python_domain(): # type: () -> None", "for details. \"\"\" from sphinx import __display_version__ as __version__ from", "with attributes inherited_members, undoc_members, show_inheritance and noindex that are True", "init methods are included in the generated documentation: * ``napoleon_include_init_with_doc``", ":attr:`napoleon_use_admonition_for_examples` napoleon_use_ivar : :obj:`bool` (Defaults to False) True to use", "'napoleon_include_init_with_doc': (False, 'env'), 'napoleon_include_private_with_doc': (False, 'env'), 'napoleon_include_special_with_doc': (False, 'env'), 'napoleon_use_admonition_for_examples':", "`arg1` arg2 : int, optional Description of `arg2`, defaults to", "by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE", "docstrings in the documentation. False to fall back to Sphinx's", "depending on the intention: * To create a custom \"generic\"", "custom sections to include, expanding the list of parsed sections.", "role for each function parameter. False to use a single", ":license: BSD, see LICENSE for details. \"\"\" from sphinx import", "details. \"\"\" from sphinx import __display_version__ as __version__ from sphinx.application", "type: () -> None try: from sphinx.domains.python import PyTypedField except", "# type: ignore name in cls.__dict__) else: cls_is_owner = False", "# type: (Any) -> None for name, (default, rebuild) in", "**If False**:: .. attribute:: attr1 Description of `attr1` :type: int", "return unicode(self).encode('utf-8') def __unicode__(self): # This will NOT be included", "that `_process_docstring` modifies in place to change what Sphinx outputs.", "def _skip_member(app, what, name, obj, skip, options): # type: (Sphinx,", "= False napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param =", "above. .. note:: `lines` is modified *in place* \"\"\" result_lines", "if successful, False otherwise napoleon_custom_sections : :obj:`list` (Defaults to None)", "__init__ method of class A, then `obj` will be `A.__init__`.", "admonition::`` directive for **References** sections. False to use the ``..", "in settings.items(): setattr(self, name, value) def setup(app): # type: (Sphinx)", "docstrings. False to disable support for NumPy style docstrings. napoleon_include_init_with_doc", "default behavior. **If True**:: def __str__(self): \\\"\\\"\\\" This will be", "be converted to a ``.. note::`` directive. See Also --------", "= NumpyDocstring(result_lines, app.config, app, what, name, obj, options) result_lines =", "separately from the class docstring. False to fall back to", "the same way - there will be a separate \"Keyword", "default behavior. **If True**:: def _included(self): \\\"\\\"\\\" This will be", "is just a quick example **If True**:: .. admonition:: Example", "have docstrings Parameters ---------- app : sphinx.application.Sphinx Application object representing", "be converted as follows:: Example ------- This is just a", "True to include private members (like ``_membername``) with docstrings in", "int Description of `attr1` **If True**:: :ivar attr1: Description of", ":obj:`bool` (Defaults to False) True to use the ``.. admonition::``", "in the documentation. False to fall back to Sphinx's default", "use the ``.. rubric::`` directive instead. Note ---- The singular", "to which the docstring belongs. Valid values: \"module\", \"class\", \"exception\",", "Note ---- The singular **Note** section will always be converted", "a ``:param:`` role for each function parameter. False to use", "str Description of `arg1` arg2 : int, optional Description of", "napoleon_use_admonition_for_references : :obj:`bool` (Defaults to False) True to use the", "``:keyword:`` role for each function keyword argument. False to use", "result_lines = lines docstring = None # type: GoogleDocstring if", "object with attributes inherited_members, undoc_members, show_inheritance and noindex that are", "cls.__dict__) else: cls_is_owner = False if what == 'module' or", "arguments:`` role for all the keywords. This behaves similarly to", "Description of `attr1` **If True**:: :ivar attr1: Description of `attr1`", "This `NumPy style`_ snippet will be converted as follows:: Attributes", "napoleon_custom_sections = None .. _Google style: https://google.github.io/styleguide/pyguide.html .. _NumPy style:", "can_collapse=True)) def _process_docstring(app, what, name, obj, options, lines): # type:", "object. Called when autodoc has read and processed a docstring.", "to use a ``:param:`` role for each function parameter. False", "(Sphinx, str, str, Any, Any, List[str]) -> None \"\"\"Process the", "to parse `Google style`_ docstrings. False to disable support for", "links created if possible) See Also -------- :attr:`napoleon_use_param` napoleon_use_rtype :", "cls_is_owner = False else: cls_is_owner = (cls and hasattr(cls, name)", "it has a docstring \\\"\\\"\\\" return unicode(self).encode('utf-8') def __unicode__(self): #", "Example ------- This is just a quick example **If True**::", "the ``.. admonition::`` directive for **Notes** sections. False to use", "instead. This `NumPy style`_ snippet will be converted as follows::", "parse NumPy style docstrings Parameters ---------- app : sphinx.application.Sphinx Application", "of same name was given to the auto directive. Returns", "control what styles of docstrings will be parsed: * ``napoleon_google_docstring``", "they have docstrings * ``napoleon_include_private_with_doc`` -- include private members if", "``.. admonition::`` directive for the **Example** and **Examples** sections. False", "style`_ docstrings. False to disable support for NumPy style docstrings.", "settings napoleon_google_docstring = True napoleon_numpy_docstring = True napoleon_include_init_with_doc = False", "(name == '__init__') is_special = (not is_init and name.startswith('__') and", "True napoleon_include_init_with_doc = False napoleon_include_private_with_doc = False napoleon_include_special_with_doc = False", "sphinx.domains.python.PyObject.doc_field_types: if doc_field.name == 'parameter': doc_field.names = ('param', 'parameter', 'arg',", "the docstring belongs. Valid values: \"module\", \"class\", \"exception\", \"function\", \"method\",", "the __init__ method of class A, then `obj` will be", "mod) else: cls = obj.__globals__[cls_path] except Exception: cls_is_owner = False", "header for a generic section. If the entry is a", "the docs because it has a docstring \\\"\\\"\\\" pass def", "to 0 :type arg2: int, optional **If False**:: :parameters: *", "name was given to the auto directive. lines : list", "== 'parameter': doc_field.names = ('param', 'parameter', 'arg', 'argument') break sphinx.domains.python.PyObject.doc_field_types.append(", "from sphinx.ext.napoleon.docstring import GoogleDocstring, NumpyDocstring if False: # For type", "def __unicode__(self): # This will NOT be included in the", "emulate. \"\"\" _config_values = { 'napoleon_google_docstring': (True, 'env'), 'napoleon_numpy_docstring': (True,", "This will NOT be included in the docs pass napoleon_include_special_with_doc", "to use the ``.. admonition::`` directive for **Notes** sections. False", "*bool* -- True if successful, False otherwise napoleon_custom_sections : :obj:`list`", "import GoogleDocstring, NumpyDocstring if False: # For type annotation from", "False to use a single ``:parameters:`` role for all the", "the **Example** and **Examples** sections. False to use the ``..", "if app.config.napoleon_google_docstring: docstring = GoogleDocstring(result_lines, app.config, app, what, name, obj,", "just a quick example **If True**:: .. admonition:: Example This", "docstrings will be parsed: * ``napoleon_google_docstring`` -- parse Google style", "``:keyword arguments:`` role for all the keywords. This behaves similarly", "object. obj : module, class, exception, function, method, or attribute", "**Note** section will always be converted to a ``.. note::``", "options) result_lines = docstring.lines() lines[:] = result_lines[:] def _skip_member(app, what,", "NOT be included in the docs napoleon_include_private_with_doc : :obj:`bool` (Defaults", "is just a quick example napoleon_use_admonition_for_notes : :obj:`bool` (Defaults to", ": :obj:`bool` (Defaults to True) True to use a ``:keyword:``", "string, it is interpreted as a header for a generic", "'env'), 'napoleon_custom_sections': (None, 'env') } def __init__(self, **settings): # type:", "``.. note::`` directive. See Also -------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_admonition_for_references : :obj:`bool`", "in the docs. \"\"\" has_doc = getattr(obj, '__doc__', False) is_member", "the keywords. This behaves similarly to :attr:`napoleon_use_param`. Note unlike docutils,", "see above. .. note:: `lines` is modified *in place* \"\"\"", "behaves similarly to :attr:`napoleon_use_param`. Note unlike docutils, ``:keyword:`` and ``:param:``", "`arg2`, defaults to 0 napoleon_use_keyword : :obj:`bool` (Defaults to True)", "True**:: :ivar attr1: Description of `attr1` :vartype attr1: int **If", "if autodoc will skip this member if `_skip_member` does not", "docstring belongs. Valid values: \"module\", \"class\", \"exception\", \"function\", \"method\", \"attribute\".", "\"\"\" if not isinstance(app, Sphinx): # probably called by tests", "(True, 'env'), 'napoleon_include_init_with_doc': (False, 'env'), 'napoleon_include_private_with_doc': (False, 'env'), 'napoleon_include_special_with_doc': (False,", "support for Google style docstrings. napoleon_numpy_docstring : :obj:`bool` (Defaults to", "= app.config.napoleon_include_special_with_doc inc_private = app.config.napoleon_include_private_with_doc if ((is_special and inc_special) or", "as __version__ from sphinx.application import Sphinx from sphinx.ext.napoleon.docstring import GoogleDocstring,", "alias for an existing section, pass a tuple containing the", "NOT be included in the docs pass napoleon_include_special_with_doc : :obj:`bool`", "= False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar =", "docstrings * ``napoleon_numpy_docstring`` -- parse NumPy style docstrings Parameters ----------", "This is just a quick example **If False**:: .. rubric::", "= lines docstring = None # type: GoogleDocstring if app.config.napoleon_numpy_docstring:", "pass napoleon_include_special_with_doc : :obj:`bool` (Defaults to False) True to include", "parsed: * ``napoleon_google_docstring`` -- parse Google style docstrings * ``napoleon_numpy_docstring``", "parsed sections. The entries can either be strings or tuples,", "getattr(obj, '__qualname__', '') cls_path, _, _ = qualname.rpartition('.') if cls_path:", "(*str*) -- Description of `arg1` * **arg2** (*int, optional*) --", "be included in the docs return unicode(self.__class__.__name__) napoleon_use_admonition_for_examples : :obj:`bool`", "members (like ``_membername``) with docstrings in the documentation. False to", "second is the section key to emulate. \"\"\" _config_values =", "for the return type. False to output the return type", "'env') } def __init__(self, **settings): # type: (Any) -> None", "of `arg1` :type arg1: str :param arg2: Description of `arg2`,", "* ``napoleon_include_private_with_doc`` -- include private members if they have docstrings", "to disable support for NumPy style docstrings. napoleon_include_init_with_doc : :obj:`bool`", "= None # type: GoogleDocstring if app.config.napoleon_numpy_docstring: docstring = NumpyDocstring(result_lines,", "True to list ``__init___`` docstrings separately from the class docstring.", "pass def _skipped(self): # This will NOT be included in", "Description of `attr1` :vartype attr1: int **If False**:: .. attribute::", "-- Description of `arg1` * **arg2** (*int, optional*) -- Description", "Any] \"\"\"Sphinx extension setup function. When the extension is loaded,", "True**:: def __str__(self): \\\"\\\"\\\" This will be included in the", "**If True**:: def __str__(self): \\\"\\\"\\\" This will be included in", "which the docstring belongs. Valid values: \"module\", \"class\", \"exception\", \"function\",", "is_member = (what == 'class' or what == 'exception' or", "will be converted as follows:: Returns ------- bool True if", "private members if they have docstrings * ``napoleon_include_special_with_doc`` -- include", "_config_values = { 'napoleon_google_docstring': (True, 'env'), 'napoleon_numpy_docstring': (True, 'env'), 'napoleon_include_init_with_doc':", "directive instead. This `NumPy style`_ snippet will be converted as", ": :obj:`bool` (Defaults to False) True to use the ``:ivar:``", "cls = obj.__globals__[cls_path] except Exception: cls_is_owner = False else: cls_is_owner", "https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt Attributes ---------- napoleon_google_docstring : :obj:`bool` (Defaults to True) True", "Application object representing the Sphinx process what : str A", "False) True to use the ``:ivar:`` role for instance variables.", ".. _NumPy style: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt Attributes ---------- napoleon_google_docstring : :obj:`bool` (Defaults", "\"attribute\". name : str The fully qualified name of the", "changed in the Sphinx `conf.py` file. Make sure that \"sphinx.ext.napoleon\"", "processed a docstring. `lines` is a list of docstring lines", "-------- :attr:`napoleon_use_param` napoleon_use_rtype : :obj:`bool` (Defaults to True) True to", "role for all the keywords. This behaves similarly to :attr:`napoleon_use_param`.", "`arg2`, defaults to 0 **If True**:: :param arg1: Description of", "= True napoleon_numpy_docstring = True napoleon_include_init_with_doc = False napoleon_include_private_with_doc =", "- there will be a separate \"Keyword Arguments\" section, rendered", "arg1 : str Description of `arg1` arg2 : int, optional", "``napoleon_include_init_with_doc`` -- include init methods if they have docstrings *", "style`_ docstrings. False to disable support for Google style docstrings.", "what == 'module') if name != '__weakref__' and has_doc and", "and special class members are included in docs. The following", "private and special class members or init methods are included", "if what == 'class' or what == 'exception': qualname =", "if successful, False otherwise :rtype: bool **If False**:: :returns: *bool*", "Example This is just a quick example napoleon_use_admonition_for_notes : :obj:`bool`", "self._config_values.items(): setattr(self, name, default) for name, value in settings.items(): setattr(self,", "example napoleon_use_admonition_for_notes : :obj:`bool` (Defaults to False) True to use", "Description of `arg1` arg2 : int, optional Description of `arg2`,", "alias name and the original, in that order. If an", "is_init and name.startswith('__') and name.endswith('__')) is_private = (not is_init and", "section, the second is the section key to emulate. \"\"\"", "boolean indicating if autodoc will skip this member if `_skip_member`", "admonition::`` directive for **Notes** sections. False to use the ``..", "'env'), 'napoleon_use_rtype': (True, 'env'), 'napoleon_use_keyword': (True, 'env'), 'napoleon_custom_sections': (None, 'env')", "they have docstrings Parameters ---------- app : sphinx.application.Sphinx Application object", "import importlib import functools mod = importlib.import_module(obj.__module__) mod_path = cls_path.split('.')", "== '__init__') is_special = (not is_init and name.startswith('__') and name.endswith('__'))", "as part of the class documentation. **If True**:: def __init__(self):", "The following settings in conf.py determine if private and special", "be `A.__init__`. skip : bool A boolean indicating if autodoc", "instead. One may look better than the other depending on", "the member belongs. Valid values: \"module\", \"class\", \"exception\", \"function\", \"method\",", "app.config.napoleon_include_special_with_doc inc_private = app.config.napoleon_include_private_with_doc if ((is_special and inc_special) or (is_private", "theme is used. This `NumPy style`_ snippet will be converted", "for each function parameter. False to use a single ``:parameters:``", "False napoleon_use_ivar = False napoleon_use_param = True napoleon_use_rtype = True", "doc_field.name == 'parameter': doc_field.names = ('param', 'parameter', 'arg', 'argument') break", "# This will NOT be included in the docs return", "cls_path.split('.') cls = functools.reduce(getattr, mod_path, mod) else: cls = obj.__globals__[cls_path]", "docutils, ``:keyword:`` and ``:param:`` will not be treated the same", "name in cls.__dict__) else: cls_is_owner = False if what ==", "'') cls_path, _, _ = qualname.rpartition('.') if cls_path: try: if", "True if the flag option of same name was given", "function. When the extension is loaded, Sphinx imports this module", "NumpyDocstring if False: # For type annotation from typing import", "is just a string, it is interpreted as a header", "str The fully qualified name of the object. obj :", "(Defaults to False) True to use the ``.. admonition::`` directive", "name != '__weakref__' and has_doc and is_member: cls_is_owner = False", "if what == 'module' or cls_is_owner: is_init = (name ==", "False else: cls_is_owner = (cls and hasattr(cls, name) and #", "cls_is_owner = False if what == 'module' or cls_is_owner: is_init", "def __init__(self): # This will NOT be included in the", "= False napoleon_use_param = True napoleon_use_rtype = True napoleon_use_keyword =", "cls_is_owner = False if what == 'class' or what ==", "\"class\", \"exception\", \"function\", \"method\", \"attribute\". name : str The name", "Description of `arg1` :type arg1: str :param arg2: Description of", "def setup(app): # type: (Sphinx) -> Dict[str, Any] \"\"\"Sphinx extension", "read and processed a docstring. `lines` is a list of", "and name.startswith('_')) inc_init = app.config.napoleon_include_init_with_doc inc_special = app.config.napoleon_include_special_with_doc inc_private =", "(Defaults to True) True to use a ``:keyword:`` role for", "``.. admonition::`` directive for **References** sections. False to use the", "Attributes ---------- attr1 : int Description of `attr1` **If True**::", "object to which the member belongs. Valid values: \"module\", \"class\",", "class, exception, function, method, or attribute. For example, if the", "has_doc and is_member: cls_is_owner = False if what == 'class'", "(True, 'env'), 'napoleon_numpy_docstring': (True, 'env'), 'napoleon_include_init_with_doc': (False, 'env'), 'napoleon_include_private_with_doc': (False,", "to True) True to use the ``:rtype:`` role for the", "order. If an entry is just a string, it is", "'parallel_read_safe': True} _patch_python_domain() app.setup_extension('sphinx.ext.autodoc') app.connect('autodoc-process-docstring', _process_docstring) app.connect('autodoc-skip-member', _skip_member) for name,", "True if successful, False otherwise **If True**:: :returns: True if", "extension module names here, as strings extensions = ['sphinx.ext.napoleon'] #", "(None, 'env') } def __init__(self, **settings): # type: (Any) ->", "* ``napoleon_include_init_with_doc`` -- include init methods if they have docstrings", "False) True to include private members (like ``_membername``) with docstrings", "variables. False to use the ``.. attribute::`` directive instead. This", "mod_path, mod) else: cls = obj.__globals__[cls_path] except Exception: cls_is_owner =", "napoleon_use_ivar : :obj:`bool` (Defaults to False) True to use the", "* ``napoleon_google_docstring`` -- parse Google style docstrings * ``napoleon_numpy_docstring`` --", "!= '__weakref__' and has_doc and is_member: cls_is_owner = False if", "\"\"\" from sphinx import __display_version__ as __version__ from sphinx.application import", "obj, options) result_lines = docstring.lines() lines[:] = result_lines[:] def _skip_member(app,", "__init__(self): # This will NOT be included in the docs", "option of same name was given to the auto directive.", "'env'), 'napoleon_use_admonition_for_notes': (False, 'env'), 'napoleon_use_admonition_for_references': (False, 'env'), 'napoleon_use_ivar': (False, 'env'),", "if app.config.napoleon_numpy_docstring: docstring = NumpyDocstring(result_lines, app.config, app, what, name, obj,", "import Sphinx from sphinx.ext.napoleon.docstring import GoogleDocstring, NumpyDocstring if False: #", "mod = importlib.import_module(obj.__module__) mod_path = cls_path.split('.') cls = functools.reduce(getattr, mod_path,", "'module' or cls_is_owner: is_init = (name == '__init__') is_special =", "= (name == '__init__') is_special = (not is_init and name.startswith('__')", "False) True to list ``__init___`` docstrings separately from the class", "just a string, it is interpreted as a header for", "style`_ snippet will be converted as follows:: Returns ------- bool", "directive for **References** sections. False to use the ``.. rubric::``", "docstrings separately from the class docstring. False to fall back", "of the object to which the docstring belongs. Valid values:", "True to use the ``.. admonition::`` directive for **Notes** sections.", "fully qualified name of the object. obj : module, class,", "True} def _patch_python_domain(): # type: () -> None try: from", "of `arg1` * **arg2** (*int, optional*) -- Description of `arg2`,", "either be strings or tuples, depending on the intention: *", "docstring.lines() if app.config.napoleon_google_docstring: docstring = GoogleDocstring(result_lines, app.config, app, what, name,", "\"\"\" result_lines = lines docstring = None # type: GoogleDocstring", "Also -------- `The Sphinx documentation on Extensions <http://sphinx-doc.org/extensions.html>`_ `The Extension", "has a docstring \\\"\\\"\\\" pass def _skipped(self): # This will", "name of the object. obj : module, class, exception, function,", "functools mod = importlib.import_module(obj.__module__) mod_path = cls_path.split('.') cls = functools.reduce(getattr,", "docstring = NumpyDocstring(result_lines, app.config, app, what, name, obj, options) result_lines", "*in place* \"\"\" result_lines = lines docstring = None #", "disable support for Google style docstrings. napoleon_numpy_docstring : :obj:`bool` (Defaults", "same fashion as \"Parameters\" section (type links created if possible)", "skip : bool A boolean indicating if autodoc will skip", "of parsed sections. The entries can either be strings or", "sections. False to use the ``.. rubric::`` directive instead. One", "to False) True to include private members (like ``_membername``) with", "custom \"generic\" section, just pass a string. * To create", "name, (default, rebuild) in self._config_values.items(): setattr(self, name, default) for name,", "with the description. This `NumPy style`_ snippet will be converted", "style`_ snippet will be converted as follows:: Attributes ---------- attr1", "'parallel_read_safe': True} def _patch_python_domain(): # type: () -> None try:", "(is_private and inc_private) or (is_init and inc_init)): return False return", "be parsed: * ``napoleon_google_docstring`` -- parse Google style docstrings *", "in that order. If an entry is just a string,", "Config._config_values.items(): app.add_config_value(name, default, rebuild) return {'version': __version__, 'parallel_read_safe': True} def", "the docs napoleon_include_private_with_doc : :obj:`bool` (Defaults to False) True to", "is a tuple/list/indexed container, the first entry is the name", "skipped during creation of the docs, False if it should", "sphinx.domains.python.PyObject.doc_field_types.append( PyTypedField('keyword', label=_('Keyword Arguments'), names=('keyword', 'kwarg', 'kwparam'), typerolename='obj', typenames=('paramtype', 'kwtype'),", "import sphinx.domains.python from sphinx.locale import _ for doc_field in sphinx.domains.python.PyObject.doc_field_types:", "snippet will be converted as follows:: Attributes ---------- attr1 :", "other depending on what HTML theme is used. This `NumPy", "app.config.napoleon_google_docstring: docstring = GoogleDocstring(result_lines, app.config, app, what, name, obj, options)", "when autodoc has read and processed a docstring. `lines` is", "should be included in the docs. \"\"\" has_doc = getattr(obj,", "style`_ snippet will be converted as follows:: Parameters ---------- arg1", "styles of docstrings will be parsed: * ``napoleon_google_docstring`` -- parse", "---------- app : sphinx.application.Sphinx Application object representing the Sphinx process.", "None) Add a list of custom sections to include, expanding", "name was given to the auto directive. Returns ------- bool", ":obj:`bool` (Defaults to False) True to include private members (like", "() -> None try: from sphinx.domains.python import PyTypedField except ImportError:", "napoleon_use_param : :obj:`bool` (Defaults to True) True to use a", "attr1: Description of `attr1` :vartype attr1: int **If False**:: ..", "The singular **Note** section will always be converted to a", "**If True**:: :param arg1: Description of `arg1` :type arg1: str", ": :obj:`bool` (Defaults to False) True to include private members", "not override the decision options : sphinx.ext.autodoc.Options The options given", "__display_version__ as __version__ from sphinx.application import Sphinx from sphinx.ext.napoleon.docstring import", "(Defaults to None) Add a list of custom sections to", "the object to which the docstring belongs. Valid values: \"module\",", "= { 'napoleon_google_docstring': (True, 'env'), 'napoleon_numpy_docstring': (True, 'env'), 'napoleon_include_init_with_doc': (False,", "__version__ from sphinx.application import Sphinx from sphinx.ext.napoleon.docstring import GoogleDocstring, NumpyDocstring", "role for instance variables. False to use the ``.. attribute::``", "Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details.", "False to fall back to Sphinx's default behavior. **If True**::", "== 'module') if name != '__weakref__' and has_doc and is_member:", "from sphinx.application import Sphinx from sphinx.ext.napoleon.docstring import GoogleDocstring, NumpyDocstring if", "Sphinx imports this module and executes the ``setup()`` function, which", "to the auto directive. lines : list of str The", "'napoleon_use_admonition_for_examples': (False, 'env'), 'napoleon_use_admonition_for_notes': (False, 'env'), 'napoleon_use_admonition_for_references': (False, 'env'), 'napoleon_use_ivar':", "**Notes** sections. False to use the ``.. rubric::`` directive instead.", "return {'version': __version__, 'parallel_read_safe': True} def _patch_python_domain(): # type: ()", "function, method, or attribute. For example, if the member is", "type: (Sphinx, str, str, Any, Any, List[str]) -> None \"\"\"Process", "if False: # For type annotation from typing import Any,", "\"attribute\". name : str The name of the member. obj", "tuples, depending on the intention: * To create a custom", "from sphinx import __display_version__ as __version__ from sphinx.application import Sphinx", "than the other depending on what HTML theme is used.", ":attr:`napoleon_use_param` napoleon_use_rtype : :obj:`bool` (Defaults to True) True to use", "parse `NumPy style`_ docstrings. False to disable support for NumPy", "section. If the entry is a tuple/list/indexed container, the first", "None .. _Google style: https://google.github.io/styleguide/pyguide.html .. _NumPy style: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt Attributes", "= False napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references =", "name : str The name of the member. obj :", "if they have docstrings Parameters ---------- app : sphinx.application.Sphinx Application", "Also -------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_admonition_for_references : :obj:`bool` (Defaults to False) True", "first entry is the name of the section, the second", "napoleon_use_rtype = True napoleon_use_keyword = True napoleon_custom_sections = None ..", "behavior. **If True**:: def _included(self): \\\"\\\"\\\" This will be included", "as follows:: Example ------- This is just a quick example", "'__weakref__' and has_doc and is_member: cls_is_owner = False if what", "keyword argument. False to use a single ``:keyword arguments:`` role", "``__init___`` docstring as part of the class documentation. **If True**::", "that \"sphinx.ext.napoleon\" is enabled in `conf.py`:: # conf.py # Add", "\"\"\" _config_values = { 'napoleon_google_docstring': (True, 'env'), 'napoleon_numpy_docstring': (True, 'env'),", "break sphinx.domains.python.PyObject.doc_field_types.append( PyTypedField('keyword', label=_('Keyword Arguments'), names=('keyword', 'kwarg', 'kwparam'), typerolename='obj', typenames=('paramtype',", "string. * To create an alias for an existing section,", "mod_path = cls_path.split('.') cls = functools.reduce(getattr, mod_path, mod) else: cls", "include, expanding the list of parsed sections. The entries can", "an existing section, pass a tuple containing the alias name", "settings in `conf.py`. Listed below are all the settings used", "to False) True to list ``__init___`` docstrings separately from the", "the type of the object to which the docstring belongs.", "for all the parameters. This `NumPy style`_ snippet will be", "in turn notifies Sphinx of everything the extension offers. Parameters", ": sphinx.application.Sphinx Application object representing the Sphinx process what :", "ImportError: pass else: import sphinx.domains.python from sphinx.locale import _ for", "(not is_init and name.startswith('__') and name.endswith('__')) is_private = (not is_init", "app.add_config_value(name, default, rebuild) return {'version': __version__, 'parallel_read_safe': True} def _patch_python_domain():", "Dict[str, Any] \"\"\"Sphinx extension setup function. When the extension is", "may look better than the other depending on what HTML", "(Any) -> None for name, (default, rebuild) in self._config_values.items(): setattr(self,", ": :obj:`bool` (Defaults to True) True to parse `NumPy style`_", "parse `Google style`_ docstrings. False to disable support for Google", "is_member: cls_is_owner = False if what == 'class' or what", "to fall back to Sphinx's default behavior. **If True**:: def", "arg1: str :param arg2: Description of `arg2`, defaults to 0", ".. _Google style: https://google.github.io/styleguide/pyguide.html .. _NumPy style: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt Attributes ----------", "given to the directive: an object with attributes inherited_members, undoc_members,", "_ = qualname.rpartition('.') if cls_path: try: if '.' in cls_path:", "Note unlike docutils, ``:keyword:`` and ``:param:`` will not be treated", "lines that `_process_docstring` modifies in place to change what Sphinx", "inc_private = app.config.napoleon_include_private_with_doc if ((is_special and inc_special) or (is_private and", "because it has a docstring \\\"\\\"\\\" return unicode(self).encode('utf-8') def __unicode__(self):", "False if what == 'module' or cls_is_owner: is_init = (name", ".. attribute:: attr1 Description of `attr1` :type: int napoleon_use_param :", "-------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_ivar : :obj:`bool` (Defaults to False) True to", "docstrings. :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.", "\"sphinx.ext.napoleon\" is enabled in `conf.py`:: # conf.py # Add any", "pass a tuple containing the alias name and the original,", "class members or init methods are included in the generated", "For type annotation from typing import Any, Dict, List #", "= False if what == 'class' or what == 'exception':", "to True) True to use a ``:keyword:`` role for each", "extension offers. Parameters ---------- app : sphinx.application.Sphinx Application object representing", "('param', 'parameter', 'arg', 'argument') break sphinx.domains.python.PyObject.doc_field_types.append( PyTypedField('keyword', label=_('Keyword Arguments'), names=('keyword',", "object representing the Sphinx process. what : str A string", ": int, optional Description of `arg2`, defaults to 0 **If", "False to use the ``.. rubric::`` directive instead. See Also", "that are True if the flag option of same name", "to the directive: an object with attributes inherited_members, undoc_members, show_inheritance", "depending on what HTML theme is used. This `NumPy style`_", "to False) True to use the ``.. admonition::`` directive for", "to True) True to use a ``:param:`` role for each", "to False) True to use the ``:ivar:`` role for instance", "`attr1` **If True**:: :ivar attr1: Description of `attr1` :vartype attr1:", "entries can either be strings or tuples, depending on the", "False to use the ``.. attribute::`` directive instead. This `NumPy", "inherited_members, undoc_members, show_inheritance and noindex that are True if the", "\"\"\" sphinx.ext.napoleon ~~~~~~~~~~~~~~~~~~~ Support for NumPy and Google style docstrings.", "\"Parameters\" section (type links created if possible) See Also --------", "snippet will be converted as follows:: Example ------- This is", "or what == 'module') if name != '__weakref__' and has_doc", "**If True**:: def _included(self): \\\"\\\"\\\" This will be included in", "for a given python object. Called when autodoc has read", "qualified name of the object. obj : module, class, exception,", "will be `A.__init__`. skip : bool A boolean indicating if", "team, see AUTHORS. :license: BSD, see LICENSE for details. \"\"\"", ".. admonition:: Example This is just a quick example **If", "BSD, see LICENSE for details. \"\"\" from sphinx import __display_version__", "Sphinx process what : str A string specifying the type", "parameters. This `NumPy style`_ snippet will be converted as follows::", "== 'class' or what == 'exception' or what == 'module')", "Google style docstrings. napoleon_numpy_docstring : :obj:`bool` (Defaults to True) True", "rebuild) in Config._config_values.items(): app.add_config_value(name, default, rebuild) return {'version': __version__, 'parallel_read_safe':", "which considers the ``__init___`` docstring as part of the class", "role for each function keyword argument. False to use a", "this module and executes the ``setup()`` function, which in turn", "the flag option of same name was given to the", "docs, False if it should be included in the docs.", "converted as follows:: Example ------- This is just a quick", "will be included in the docs because it has a", "lines : list of str The lines of the docstring,", "output the return type inline with the description. This `NumPy", "special class members or init methods are included in the", "directive: an object with attributes inherited_members, undoc_members, show_inheritance and noindex", "have docstrings * ``napoleon_include_private_with_doc`` -- include private members if they", "in the same fashion as \"Parameters\" section (type links created", "of the object. obj : module, class, exception, function, method,", "loaded, Sphinx imports this module and executes the ``setup()`` function,", "a docstring \\\"\\\"\\\" def __init__(self): # This will NOT be", "doc_field in sphinx.domains.python.PyObject.doc_field_types: if doc_field.name == 'parameter': doc_field.names = ('param',", ": str The name of the member. obj : module,", "a single ``:keyword arguments:`` role for all the keywords. This", "str, Any, bool, Any) -> bool \"\"\"Determine if private and", "be converted as follows:: Parameters ---------- arg1 : str Description", "return type. False to output the return type inline with", "their default values. These settings can be changed in the", "**arg1** (*str*) -- Description of `arg1` * **arg2** (*int, optional*)", "Sphinx): # probably called by tests return {'version': __version__, 'parallel_read_safe':", "enabled in `conf.py`:: # conf.py # Add any Sphinx extension", "behavior, which considers the ``__init___`` docstring as part of the", "given to the auto directive. lines : list of str", "if cls_path: try: if '.' in cls_path: import importlib import", "there will be a separate \"Keyword Arguments\" section, rendered in", "if successful, False otherwise **If True**:: :returns: True if successful,", "Any, bool, Any) -> bool \"\"\"Determine if private and special", "docstring belongs. options : sphinx.ext.autodoc.Options The options given to the", "and the original, in that order. If an entry is", "or what == 'exception' or what == 'module') if name", "inc_special = app.config.napoleon_include_special_with_doc inc_private = app.config.napoleon_include_private_with_doc if ((is_special and inc_special)", "to use the ``:ivar:`` role for instance variables. False to", "instead. Note ---- The singular **Note** section will always be", "can either be strings or tuples, depending on the intention:", "fall back to Sphinx's default behavior. **If True**:: def __str__(self):", "app.config, app, what, name, obj, options) result_lines = docstring.lines() lines[:]", "str :param arg2: Description of `arg2`, defaults to 0 :type", "argument. False to use a single ``:keyword arguments:`` role for", "is enabled in `conf.py`:: # conf.py # Add any Sphinx", "= False if what == 'module' or cls_is_owner: is_init =", "lines of the docstring, see above. .. note:: `lines` is", "\"\"\"Process the docstring for a given python object. Called when", "here, as strings extensions = ['sphinx.ext.napoleon'] # Napoleon settings napoleon_google_docstring", "the name of the section, the second is the section", "representing the Sphinx process what : str A string specifying", "unlike docutils, ``:keyword:`` and ``:param:`` will not be treated the", "label=_('Keyword Arguments'), names=('keyword', 'kwarg', 'kwparam'), typerolename='obj', typenames=('paramtype', 'kwtype'), can_collapse=True)) def", "\"Keyword Arguments\" section, rendered in the same fashion as \"Parameters\"", "---------- napoleon_google_docstring : :obj:`bool` (Defaults to True) True to parse", ":parameters: * **arg1** (*str*) -- Description of `arg1` * **arg2**", "\"generic\" section, just pass a string. * To create an", "= result_lines[:] def _skip_member(app, what, name, obj, skip, options): #", "# type: (Sphinx, str, str, Any, bool, Any) -> bool", ": :obj:`list` (Defaults to None) Add a list of custom", "**If True**:: .. admonition:: Example This is just a quick", "member if `_skip_member` does not override the decision options :", "and # type: ignore name in cls.__dict__) else: cls_is_owner =", "of `attr1` :vartype attr1: int **If False**:: .. attribute:: attr1", "called by tests return {'version': __version__, 'parallel_read_safe': True} _patch_python_domain() app.setup_extension('sphinx.ext.autodoc')", "members (like ``__membername__``) with docstrings in the documentation. False to", "name, (default, rebuild) in Config._config_values.items(): app.add_config_value(name, default, rebuild) return {'version':", "to output the return type inline with the description. This", "import _ for doc_field in sphinx.domains.python.PyObject.doc_field_types: if doc_field.name == 'parameter':", "as \"Parameters\" section (type links created if possible) See Also", "will be converted as follows:: Attributes ---------- attr1 : int", "Application object representing the Sphinx process. what : str A", "This is just a quick example napoleon_use_admonition_for_notes : :obj:`bool` (Defaults", "always be converted to a ``.. note::`` directive. See Also", "Any, Any, List[str]) -> None \"\"\"Process the docstring for a", "in cls.__dict__) else: cls_is_owner = False if what == 'module'", "= getattr(obj, '__doc__', False) is_member = (what == 'class' or", "documentation. False to fall back to Sphinx's default behavior. **If", "int, optional **If False**:: :parameters: * **arg1** (*str*) -- Description", "`A.__init__`. skip : bool A boolean indicating if autodoc will", "extension setup function. When the extension is loaded, Sphinx imports", "`conf.py`. Listed below are all the settings used by napoleon", "the directive: an object with attributes inherited_members, undoc_members, show_inheritance and", "parse Google style docstrings * ``napoleon_numpy_docstring`` -- parse NumPy style", "be converted as follows:: Attributes ---------- attr1 : int Description", ": str The fully qualified name of the object. obj", "private members (like ``_membername``) with docstrings in the documentation. False", "see AUTHORS. :license: BSD, see LICENSE for details. \"\"\" from", "def __str__(self): \\\"\\\"\\\" This will be included in the docs", "['sphinx.ext.napoleon'] # Napoleon settings napoleon_google_docstring = True napoleon_numpy_docstring = True", "the other depending on what HTML theme is used. This", "settings.items(): setattr(self, name, value) def setup(app): # type: (Sphinx) ->", "Example This is just a quick example **If False**:: ..", "extensions = ['sphinx.ext.napoleon'] # Napoleon settings napoleon_google_docstring = True napoleon_numpy_docstring", "of `arg2`, defaults to 0 napoleon_use_keyword : :obj:`bool` (Defaults to", "members if they have docstrings Parameters ---------- app : sphinx.application.Sphinx", "True) True to use a ``:keyword:`` role for each function", "Sphinx outputs. The following settings in conf.py control what styles", "\"class\", \"exception\", \"function\", \"method\", \"attribute\". name : str The fully", "snippet will be converted as follows:: Returns ------- bool True", "to the auto directive. Returns ------- bool True if the", "representing the Sphinx process See Also -------- `The Sphinx documentation", "the documentation. False to fall back to Sphinx's default behavior.", ":obj:`list` (Defaults to None) Add a list of custom sections", "name.endswith('__')) is_private = (not is_init and not is_special and name.startswith('_'))", "the ``__init___`` docstring as part of the class documentation. **If", "a docstring. `lines` is a list of docstring lines that", "if the flag option of same name was given to", "`arg1` * **arg2** (*int, optional*) -- Description of `arg2`, defaults", "`NumPy style`_ snippet will be converted as follows:: Returns -------", "pass else: import sphinx.domains.python from sphinx.locale import _ for doc_field", "arg1: Description of `arg1` :type arg1: str :param arg2: Description", "hasattr(cls, name) and # type: ignore name in cls.__dict__) else:", "of `attr1` :type: int napoleon_use_param : :obj:`bool` (Defaults to True)", "an object with attributes inherited_members, undoc_members, show_inheritance and noindex that", "napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar", "to use the ``.. admonition::`` directive for the **Example** and", ": sphinx.application.Sphinx Application object representing the Sphinx process See Also", "include special members if they have docstrings Parameters ---------- app", "class, exception, function, method, or attribute The object to which", "sections. The entries can either be strings or tuples, depending", "be included in the docs because it has a docstring", "original, in that order. If an entry is just a", "a tuple containing the alias name and the original, in", "to include private members (like ``_membername``) with docstrings in the", "__str__(self): \\\"\\\"\\\" This will be included in the docs because", "will be converted as follows:: Parameters ---------- arg1 : str", "the Sphinx `conf.py` file. Make sure that \"sphinx.ext.napoleon\" is enabled", "= (not is_init and not is_special and name.startswith('_')) inc_init =", "* ``napoleon_numpy_docstring`` -- parse NumPy style docstrings Parameters ---------- app", "None try: from sphinx.domains.python import PyTypedField except ImportError: pass else:", "Google style docstrings. :copyright: Copyright 2007-2018 by the Sphinx team,", "has a docstring \\\"\\\"\\\" def __init__(self): # This will NOT", "`lines` is modified *in place* \"\"\" result_lines = lines docstring", "method, or attribute The object to which the docstring belongs.", "If the entry is a tuple/list/indexed container, the first entry", "separate \"Keyword Arguments\" section, rendered in the same fashion as", "to :attr:`napoleon_use_param`. Note unlike docutils, ``:keyword:`` and ``:param:`` will not", "admonition::`` directive for the **Example** and **Examples** sections. False to", "behavior. **If True**:: def __str__(self): \\\"\\\"\\\" This will be included", "module, class, exception, function, method, or attribute The object to", "if `_skip_member` does not override the decision options : sphinx.ext.autodoc.Options", "try: if '.' in cls_path: import importlib import functools mod", "This will NOT be included in the docs return unicode(self.__class__.__name__)", "'napoleon_use_admonition_for_references': (False, 'env'), 'napoleon_use_ivar': (False, 'env'), 'napoleon_use_param': (True, 'env'), 'napoleon_use_rtype':", "is loaded, Sphinx imports this module and executes the ``setup()``", "to 0 **If True**:: :param arg1: Description of `arg1` :type", "use the ``.. attribute::`` directive instead. This `NumPy style`_ snippet", "style: https://google.github.io/styleguide/pyguide.html .. _NumPy style: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt Attributes ---------- napoleon_google_docstring :", "same name was given to the auto directive. Returns -------", "This is just a quick example **If True**:: .. admonition::", "napoleon_include_init_with_doc : :obj:`bool` (Defaults to False) True to list ``__init___``", "conf.py control what styles of docstrings will be parsed: *", "docstrings. False to disable support for Google style docstrings. napoleon_numpy_docstring", "way - there will be a separate \"Keyword Arguments\" section,", "'napoleon_use_ivar': (False, 'env'), 'napoleon_use_param': (True, 'env'), 'napoleon_use_rtype': (True, 'env'), 'napoleon_use_keyword':", "tuple containing the alias name and the original, in that", "in sphinx.domains.python.PyObject.doc_field_types: if doc_field.name == 'parameter': doc_field.names = ('param', 'parameter',", "to Sphinx's default behavior. **If True**:: def __str__(self): \\\"\\\"\\\" This", "of `arg1` arg2 : int, optional Description of `arg2`, defaults", "type. False to output the return type inline with the", "type of the object to which the member belongs. Valid", "is the section key to emulate. \"\"\" _config_values = {", "is modified *in place* \"\"\" result_lines = lines docstring =", ": sphinx.ext.autodoc.Options The options given to the directive: an object", "None # type: GoogleDocstring if app.config.napoleon_numpy_docstring: docstring = NumpyDocstring(result_lines, app.config,", "True napoleon_custom_sections = None .. _Google style: https://google.github.io/styleguide/pyguide.html .. _NumPy", "to list ``__init___`` docstrings separately from the class docstring. False", "parameter. False to use a single ``:parameters:`` role for all", "**References** sections. False to use the ``.. rubric::`` directive instead.", "app, what, name, obj, options) result_lines = docstring.lines() lines[:] =", "= (what == 'class' or what == 'exception' or what", "use a single ``:keyword arguments:`` role for all the keywords.", "= (cls and hasattr(cls, name) and # type: ignore name", "(False, 'env'), 'napoleon_include_special_with_doc': (False, 'env'), 'napoleon_use_admonition_for_examples': (False, 'env'), 'napoleon_use_admonition_for_notes': (False,", "else: cls_is_owner = (cls and hasattr(cls, name) and # type:", "should be skipped during creation of the docs, False if", "string specifying the type of the object to which the", "\\\"\\\"\\\" pass def _skipped(self): # This will NOT be included", "NumpyDocstring(result_lines, app.config, app, what, name, obj, options) result_lines = docstring.lines()", "the entry is a tuple/list/indexed container, the first entry is", "'__qualname__', '') cls_path, _, _ = qualname.rpartition('.') if cls_path: try:", "defaults to 0 :type arg2: int, optional **If False**:: :parameters:", "follows:: Returns ------- bool True if successful, False otherwise **If", "settings can be changed in the Sphinx `conf.py` file. Make", "The lines of the docstring, see above. .. note:: `lines`", "docstrings Parameters ---------- app : sphinx.application.Sphinx Application object representing the", "for instance variables. False to use the ``.. attribute::`` directive", "and Google style docstrings. :copyright: Copyright 2007-2018 by the Sphinx", "if ((is_special and inc_special) or (is_private and inc_private) or (is_init", "a docstring \\\"\\\"\\\" return unicode(self).encode('utf-8') def __unicode__(self): # This will", "role for the return type. False to output the return", "to use the ``.. attribute::`` directive instead. This `NumPy style`_", "docs because it has a docstring \\\"\\\"\\\" return unicode(self).encode('utf-8') def", "result_lines[:] def _skip_member(app, what, name, obj, skip, options): # type:", "app : sphinx.application.Sphinx Application object representing the Sphinx process what", "`arg2`, defaults to 0 :type arg2: int, optional **If False**::", "all the parameters. This `NumPy style`_ snippet will be converted", "(what == 'class' or what == 'exception' or what ==", "importlib import functools mod = importlib.import_module(obj.__module__) mod_path = cls_path.split('.') cls", "Called when autodoc has read and processed a docstring. `lines`", "docstring = GoogleDocstring(result_lines, app.config, app, what, name, obj, options) result_lines", "{ 'napoleon_google_docstring': (True, 'env'), 'napoleon_numpy_docstring': (True, 'env'), 'napoleon_include_init_with_doc': (False, 'env'),", "decision options : sphinx.ext.autodoc.Options The options given to the directive:", "except ImportError: pass else: import sphinx.domains.python from sphinx.locale import _", "in the docs return unicode(self.__class__.__name__) napoleon_use_admonition_for_examples : :obj:`bool` (Defaults to", "app, what, name, obj, options) result_lines = docstring.lines() if app.config.napoleon_google_docstring:", "One may look better than the other depending on what", "Returns ------- bool True if successful, False otherwise **If True**::", "style docstrings. napoleon_numpy_docstring : :obj:`bool` (Defaults to True) True to", "be included in the docs napoleon_include_private_with_doc : :obj:`bool` (Defaults to", "app.config.napoleon_include_init_with_doc inc_special = app.config.napoleon_include_special_with_doc inc_private = app.config.napoleon_include_private_with_doc if ((is_special and", "0 **If True**:: :param arg1: Description of `arg1` :type arg1:", "napoleon_use_rtype : :obj:`bool` (Defaults to True) True to use the", "# type: (Sphinx) -> Dict[str, Any] \"\"\"Sphinx extension setup function.", "bool **If False**:: :returns: *bool* -- True if successful, False", "_skipped(self): # This will NOT be included in the docs", "Dict, List # NOQA class Config: \"\"\"Sphinx napoleon extension settings", "entry is the name of the section, the second is", "``:param:`` will not be treated the same way - there", "Any, List[str]) -> None \"\"\"Process the docstring for a given", "function parameter. False to use a single ``:parameters:`` role for", "'__doc__', False) is_member = (what == 'class' or what ==", "names here, as strings extensions = ['sphinx.ext.napoleon'] # Napoleon settings", "section key to emulate. \"\"\" _config_values = { 'napoleon_google_docstring': (True,", "the ``.. rubric::`` directive instead. See Also -------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_ivar", "description. This `NumPy style`_ snippet will be converted as follows::", "bool, Any) -> bool \"\"\"Determine if private and special class", "an entry is just a string, it is interpreted as", "probably called by tests return {'version': __version__, 'parallel_read_safe': True} _patch_python_domain()", "True to use a ``:param:`` role for each function parameter.", "if not isinstance(app, Sphinx): # probably called by tests return", ": :obj:`bool` (Defaults to False) True to include special members", "function, which in turn notifies Sphinx of everything the extension", "------- bool True if successful, False otherwise **If True**:: :returns:", "existing section, pass a tuple containing the alias name and", "= docstring.lines() lines[:] = result_lines[:] def _skip_member(app, what, name, obj,", "= True napoleon_include_init_with_doc = False napoleon_include_private_with_doc = False napoleon_include_special_with_doc =", "------- This is just a quick example **If True**:: ..", "(*int, optional*) -- Description of `arg2`, defaults to 0 napoleon_use_keyword", "docstring lines that `_process_docstring` modifies in place to change what", "on the intention: * To create a custom \"generic\" section,", "True) True to parse `NumPy style`_ docstrings. False to disable", "`NumPy style`_ snippet will be converted as follows:: Example -------", "not isinstance(app, Sphinx): # probably called by tests return {'version':", "what, name, obj, options) result_lines = docstring.lines() if app.config.napoleon_google_docstring: docstring", "default behavior, which considers the ``__init___`` docstring as part of", "of the docs, False if it should be included in", "what, name, obj, options) result_lines = docstring.lines() lines[:] = result_lines[:]", "True napoleon_numpy_docstring = True napoleon_include_init_with_doc = False napoleon_include_private_with_doc = False", "show_inheritance and noindex that are True if the flag option", "section (type links created if possible) See Also -------- :attr:`napoleon_use_param`", "= GoogleDocstring(result_lines, app.config, app, what, name, obj, options) result_lines =", "True} _patch_python_domain() app.setup_extension('sphinx.ext.autodoc') app.connect('autodoc-process-docstring', _process_docstring) app.connect('autodoc-skip-member', _skip_member) for name, (default,", "to disable support for Google style docstrings. napoleon_numpy_docstring : :obj:`bool`", "``:parameters:`` role for all the parameters. This `NumPy style`_ snippet", "expanding the list of parsed sections. The entries can either", "will be parsed: * ``napoleon_google_docstring`` -- parse Google style docstrings", "'env'), 'napoleon_numpy_docstring': (True, 'env'), 'napoleon_include_init_with_doc': (False, 'env'), 'napoleon_include_private_with_doc': (False, 'env'),", "{'version': __version__, 'parallel_read_safe': True} def _patch_python_domain(): # type: () ->", "Exception: cls_is_owner = False else: cls_is_owner = (cls and hasattr(cls,", "This will NOT be included in the docs napoleon_include_private_with_doc :", "the member should be skipped during creation of the docs,", "napoleon_include_init_with_doc = False napoleon_include_private_with_doc = False napoleon_include_special_with_doc = False napoleon_use_admonition_for_examples", "a quick example **If True**:: .. admonition:: Example This is", "bool True if the member should be skipped during creation", "arg2 : int, optional Description of `arg2`, defaults to 0", "the extension offers. Parameters ---------- app : sphinx.application.Sphinx Application object", "to use a single ``:keyword arguments:`` role for all the", "example **If True**:: .. admonition:: Example This is just a", "napoleon_use_keyword = True napoleon_custom_sections = None .. _Google style: https://google.github.io/styleguide/pyguide.html", "``:ivar:`` role for instance variables. False to use the ``..", "_skip_member) for name, (default, rebuild) in Config._config_values.items(): app.add_config_value(name, default, rebuild)", "API <http://sphinx-doc.org/extdev/appapi.html>`_ \"\"\" if not isinstance(app, Sphinx): # probably called", "not be treated the same way - there will be", "be changed in the Sphinx `conf.py` file. Make sure that", "type: (Sphinx) -> Dict[str, Any] \"\"\"Sphinx extension setup function. When", "class A, then `obj` will be `A.__init__`. skip : bool", "the docs because it has a docstring \\\"\\\"\\\" return unicode(self).encode('utf-8')", "optional **If False**:: :parameters: * **arg1** (*str*) -- Description of", "**If True**:: :returns: True if successful, False otherwise :rtype: bool", "style docstrings * ``napoleon_numpy_docstring`` -- parse NumPy style docstrings Parameters", "values. These settings can be changed in the Sphinx `conf.py`", "or init methods are included in the generated documentation: *", "name and the original, in that order. If an entry", "use a ``:keyword:`` role for each function keyword argument. False", "(Defaults to True) True to parse `Google style`_ docstrings. False", "This `NumPy style`_ snippet will be converted as follows:: Returns", "inc_special) or (is_private and inc_private) or (is_init and inc_init)): return", "False otherwise :rtype: bool **If False**:: :returns: *bool* -- True", "directive for the **Example** and **Examples** sections. False to use", "bool True if successful, False otherwise **If True**:: :returns: True", "str, Any, Any, List[str]) -> None \"\"\"Process the docstring for", "_skip_member(app, what, name, obj, skip, options): # type: (Sphinx, str,", "True) True to use a ``:param:`` role for each function", "Sphinx `conf.py` file. Make sure that \"sphinx.ext.napoleon\" is enabled in", "napoleon_include_private_with_doc : :obj:`bool` (Defaults to False) True to include private", "example, if the member is the __init__ method of class", "inc_init = app.config.napoleon_include_init_with_doc inc_special = app.config.napoleon_include_special_with_doc inc_private = app.config.napoleon_include_private_with_doc if", "default) for name, value in settings.items(): setattr(self, name, value) def", "getattr(obj, '__doc__', False) is_member = (what == 'class' or what", "attr1 Description of `attr1` :type: int napoleon_use_param : :obj:`bool` (Defaults", "Support for NumPy and Google style docstrings. :copyright: Copyright 2007-2018", "app : sphinx.application.Sphinx Application object representing the Sphinx process. what", "Any) -> bool \"\"\"Determine if private and special class members", "default values. These settings can be changed in the Sphinx", "will skip this member if `_skip_member` does not override the", "the Sphinx process what : str A string specifying the", "obj : module, class, exception, function, method, or attribute. For", "will NOT be included in the docs return unicode(self.__class__.__name__) napoleon_use_admonition_for_examples", "list of str The lines of the docstring, see above.", "Application object representing the Sphinx process See Also -------- `The", "converted as follows:: Returns ------- bool True if successful, False", "**settings): # type: (Any) -> None for name, (default, rebuild)", "will NOT be included in the docs napoleon_include_private_with_doc : :obj:`bool`", "'arg', 'argument') break sphinx.domains.python.PyObject.doc_field_types.append( PyTypedField('keyword', label=_('Keyword Arguments'), names=('keyword', 'kwarg', 'kwparam'),", "`The Extension Tutorial <http://sphinx-doc.org/extdev/tutorial.html>`_ `The Extension API <http://sphinx-doc.org/extdev/appapi.html>`_ \"\"\" if", "during creation of the docs, False if it should be", "used by napoleon and their default values. These settings can", "(default, rebuild) in Config._config_values.items(): app.add_config_value(name, default, rebuild) return {'version': __version__,", "Arguments'), names=('keyword', 'kwarg', 'kwparam'), typerolename='obj', typenames=('paramtype', 'kwtype'), can_collapse=True)) def _process_docstring(app,", "python object. Called when autodoc has read and processed a", "autodoc will skip this member if `_skip_member` does not override", "they have docstrings * ``napoleon_include_special_with_doc`` -- include special members if", "_patch_python_domain(): # type: () -> None try: from sphinx.domains.python import", "_patch_python_domain() app.setup_extension('sphinx.ext.autodoc') app.connect('autodoc-process-docstring', _process_docstring) app.connect('autodoc-skip-member', _skip_member) for name, (default, rebuild)", "exception, function, method, or attribute. For example, if the member", "look better than the other depending on what HTML theme", "napoleon_google_docstring : :obj:`bool` (Defaults to True) True to parse `Google", "'env'), 'napoleon_use_admonition_for_references': (False, 'env'), 'napoleon_use_ivar': (False, 'env'), 'napoleon_use_param': (True, 'env'),", "`obj` will be `A.__init__`. skip : bool A boolean indicating", "The entries can either be strings or tuples, depending on", "each function parameter. False to use a single ``:parameters:`` role", "napoleon_numpy_docstring : :obj:`bool` (Defaults to True) True to parse `NumPy", "obj, skip, options): # type: (Sphinx, str, str, Any, bool,", "for **References** sections. False to use the ``.. rubric::`` directive", "and processed a docstring. `lines` is a list of docstring", "will NOT be included in the docs pass napoleon_include_special_with_doc :", "for doc_field in sphinx.domains.python.PyObject.doc_field_types: if doc_field.name == 'parameter': doc_field.names =", "method of class A, then `obj` will be `A.__init__`. skip", "successful, False otherwise :rtype: bool **If False**:: :returns: *bool* --", "Add any Sphinx extension module names here, as strings extensions", "instance variables. False to use the ``.. attribute::`` directive instead.", "When the extension is loaded, Sphinx imports this module and", "the description. This `NumPy style`_ snippet will be converted as", "to use a ``:keyword:`` role for each function keyword argument.", "note::`` directive. See Also -------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_admonition_for_references : :obj:`bool` (Defaults", "_ for doc_field in sphinx.domains.python.PyObject.doc_field_types: if doc_field.name == 'parameter': doc_field.names", "= False napoleon_include_special_with_doc = False napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes =", "then `obj` will be `A.__init__`. skip : bool A boolean", "for name, (default, rebuild) in Config._config_values.items(): app.add_config_value(name, default, rebuild) return", "names=('keyword', 'kwarg', 'kwparam'), typerolename='obj', typenames=('paramtype', 'kwtype'), can_collapse=True)) def _process_docstring(app, what,", "directive. lines : list of str The lines of the", "to which the docstring belongs. options : sphinx.ext.autodoc.Options The options", "Google style docstrings * ``napoleon_numpy_docstring`` -- parse NumPy style docstrings", "'napoleon_google_docstring': (True, 'env'), 'napoleon_numpy_docstring': (True, 'env'), 'napoleon_include_init_with_doc': (False, 'env'), 'napoleon_include_private_with_doc':", "**If True**:: :ivar attr1: Description of `attr1` :vartype attr1: int", "int, optional Description of `arg2`, defaults to 0 **If True**::", "False napoleon_include_special_with_doc = False napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False", "process what : str A string specifying the type of", "``napoleon_include_private_with_doc`` -- include private members if they have docstrings *", "= (not is_init and name.startswith('__') and name.endswith('__')) is_private = (not", "class documentation. **If True**:: def __init__(self): \\\"\\\"\\\" This will be", "name, obj, options) result_lines = docstring.lines() if app.config.napoleon_google_docstring: docstring =", "* **arg2** (*int, optional*) -- Description of `arg2`, defaults to", "-- Description of `arg2`, defaults to 0 napoleon_use_keyword : :obj:`bool`", "outputs. The following settings in conf.py control what styles of", ":attr:`napoleon_use_param`. Note unlike docutils, ``:keyword:`` and ``:param:`` will not be", "name, obj, options) result_lines = docstring.lines() lines[:] = result_lines[:] def", "because it has a docstring \\\"\\\"\\\" pass def _skipped(self): #", "of docstrings will be parsed: * ``napoleon_google_docstring`` -- parse Google", "try: from sphinx.domains.python import PyTypedField except ImportError: pass else: import", "for **Notes** sections. False to use the ``.. rubric::`` directive", "on Extensions <http://sphinx-doc.org/extensions.html>`_ `The Extension Tutorial <http://sphinx-doc.org/extdev/tutorial.html>`_ `The Extension API", "a ``.. note::`` directive. See Also -------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_admonition_for_references :", "'class' or what == 'exception': qualname = getattr(obj, '__qualname__', '')", "* To create an alias for an existing section, pass", "style docstrings. :copyright: Copyright 2007-2018 by the Sphinx team, see", "False**:: .. attribute:: attr1 Description of `attr1` :type: int napoleon_use_param", "sphinx.application.Sphinx Application object representing the Sphinx process what : str", "included in the generated documentation: * ``napoleon_include_init_with_doc`` -- include init", ":type: int napoleon_use_param : :obj:`bool` (Defaults to True) True to", "was given to the auto directive. Returns ------- bool True", "True) True to parse `Google style`_ docstrings. False to disable", "= docstring.lines() if app.config.napoleon_google_docstring: docstring = GoogleDocstring(result_lines, app.config, app, what,", "type inline with the description. This `NumPy style`_ snippet will", "\"method\", \"attribute\". name : str The fully qualified name of", "the docs return unicode(self.__class__.__name__) napoleon_use_admonition_for_examples : :obj:`bool` (Defaults to False)", "generated documentation: * ``napoleon_include_init_with_doc`` -- include init methods if they", "a list of docstring lines that `_process_docstring` modifies in place", "from sphinx.domains.python import PyTypedField except ImportError: pass else: import sphinx.domains.python", "cls_path: import importlib import functools mod = importlib.import_module(obj.__module__) mod_path =", "is just a quick example **If False**:: .. rubric:: Example", "= ('param', 'parameter', 'arg', 'argument') break sphinx.domains.python.PyObject.doc_field_types.append( PyTypedField('keyword', label=_('Keyword Arguments'),", "Description of `arg2`, defaults to 0 napoleon_use_keyword : :obj:`bool` (Defaults", "the alias name and the original, in that order. If", "(cls and hasattr(cls, name) and # type: ignore name in", "result_lines = docstring.lines() if app.config.napoleon_google_docstring: docstring = GoogleDocstring(result_lines, app.config, app,", "sphinx.domains.python from sphinx.locale import _ for doc_field in sphinx.domains.python.PyObject.doc_field_types: if", "qualname = getattr(obj, '__qualname__', '') cls_path, _, _ = qualname.rpartition('.')", "name.startswith('_')) inc_init = app.config.napoleon_include_init_with_doc inc_special = app.config.napoleon_include_special_with_doc inc_private = app.config.napoleon_include_private_with_doc", "as a header for a generic section. If the entry", "to use the ``.. rubric::`` directive instead. See Also --------", "a single ``:parameters:`` role for all the parameters. This `NumPy", "**If True**:: def __init__(self): \\\"\\\"\\\" This will be included in", ": int Description of `attr1` **If True**:: :ivar attr1: Description", "if private and special class members or init methods are", "True to include special members (like ``__membername__``) with docstrings in", "included in the docs return unicode(self.__class__.__name__) napoleon_use_admonition_for_examples : :obj:`bool` (Defaults", "sphinx.application.Sphinx Application object representing the Sphinx process. what : str", "else: import sphinx.domains.python from sphinx.locale import _ for doc_field in", "object to which the docstring belongs. Valid values: \"module\", \"class\",", "(True, 'env'), 'napoleon_use_rtype': (True, 'env'), 'napoleon_use_keyword': (True, 'env'), 'napoleon_custom_sections': (None,", "to use the ``.. admonition::`` directive for **References** sections. False", "from sphinx.locale import _ for doc_field in sphinx.domains.python.PyObject.doc_field_types: if doc_field.name", "converted as follows:: Attributes ---------- attr1 : int Description of", "The following settings in conf.py control what styles of docstrings", "list ``__init___`` docstrings separately from the class docstring. False to", "\"\"\"Sphinx napoleon extension settings in `conf.py`. Listed below are all", "for name, value in settings.items(): setattr(self, name, value) def setup(app):", "'env'), 'napoleon_include_private_with_doc': (False, 'env'), 'napoleon_include_special_with_doc': (False, 'env'), 'napoleon_use_admonition_for_examples': (False, 'env'),", "interpreted as a header for a generic section. If the", "(like ``_membername``) with docstrings in the documentation. False to fall", "back to Sphinx's default behavior. **If True**:: def __str__(self): \\\"\\\"\\\"", ":obj:`bool` (Defaults to True) True to parse `Google style`_ docstrings.", "app : sphinx.application.Sphinx Application object representing the Sphinx process See", "-> None \"\"\"Process the docstring for a given python object.", "options given to the directive: an object with attributes inherited_members,", "napoleon_use_ivar = False napoleon_use_param = True napoleon_use_rtype = True napoleon_use_keyword", "the section, the second is the section key to emulate.", "(False, 'env'), 'napoleon_include_private_with_doc': (False, 'env'), 'napoleon_include_special_with_doc': (False, 'env'), 'napoleon_use_admonition_for_examples': (False,", "sphinx import __display_version__ as __version__ from sphinx.application import Sphinx from", "True to use a ``:keyword:`` role for each function keyword", "docs because it has a docstring \\\"\\\"\\\" pass def _skipped(self):", "Sphinx's default behavior. **If True**:: def __str__(self): \\\"\\\"\\\" This will", ": module, class, exception, function, method, or attribute. For example,", "any Sphinx extension module names here, as strings extensions =", "* To create a custom \"generic\" section, just pass a", "use the ``:rtype:`` role for the return type. False to", "settings in conf.py control what styles of docstrings will be", "use a ``:param:`` role for each function parameter. False to", "has_doc = getattr(obj, '__doc__', False) is_member = (what == 'class'", "docstring = None # type: GoogleDocstring if app.config.napoleon_numpy_docstring: docstring =", "value in settings.items(): setattr(self, name, value) def setup(app): # type:", "to True) True to parse `Google style`_ docstrings. False to", "successful, False otherwise **If True**:: :returns: True if successful, False", "**arg2** (*int, optional*) -- Description of `arg2`, defaults to 0", "True) True to use the ``:rtype:`` role for the return", "object to which the docstring belongs. options : sphinx.ext.autodoc.Options The", "`arg1` :type arg1: str :param arg2: Description of `arg2`, defaults", "from typing import Any, Dict, List # NOQA class Config:", "NOQA class Config: \"\"\"Sphinx napoleon extension settings in `conf.py`. Listed", "as strings extensions = ['sphinx.ext.napoleon'] # Napoleon settings napoleon_google_docstring =", "docstring. False to fall back to Sphinx's default behavior, which", ": :obj:`bool` (Defaults to True) True to use a ``:param:``", "the settings used by napoleon and their default values. These", "what HTML theme is used. This `NumPy style`_ snippet will", "options : sphinx.ext.autodoc.Options The options given to the directive: an", "result_lines = docstring.lines() lines[:] = result_lines[:] def _skip_member(app, what, name,", "the auto directive. Returns ------- bool True if the member", "be included in the docs. \"\"\" has_doc = getattr(obj, '__doc__',", "the same fashion as \"Parameters\" section (type links created if", "True napoleon_use_keyword = True napoleon_custom_sections = None .. _Google style:", "\"exception\", \"function\", \"method\", \"attribute\". name : str The fully qualified", "or what == 'exception': qualname = getattr(obj, '__qualname__', '') cls_path,", "\"\"\"Determine if private and special class members are included in", "app.setup_extension('sphinx.ext.autodoc') app.connect('autodoc-process-docstring', _process_docstring) app.connect('autodoc-skip-member', _skip_member) for name, (default, rebuild) in", ":param arg1: Description of `arg1` :type arg1: str :param arg2:", "See Also -------- :attr:`napoleon_use_param` napoleon_use_rtype : :obj:`bool` (Defaults to True)", "isinstance(app, Sphinx): # probably called by tests return {'version': __version__,", "arg2: int, optional **If False**:: :parameters: * **arg1** (*str*) --", "the return type inline with the description. This `NumPy style`_", "the return type. False to output the return type inline", "the generated documentation: * ``napoleon_include_init_with_doc`` -- include init methods if", "= getattr(obj, '__qualname__', '') cls_path, _, _ = qualname.rpartition('.') if", "False otherwise **If True**:: :returns: True if successful, False otherwise", "noindex that are True if the flag option of same", "for each function keyword argument. False to use a single", "type: (Sphinx, str, str, Any, bool, Any) -> bool \"\"\"Determine", "app.connect('autodoc-process-docstring', _process_docstring) app.connect('autodoc-skip-member', _skip_member) for name, (default, rebuild) in Config._config_values.items():", "``:rtype:`` role for the return type. False to output the", "flag option of same name was given to the auto", "class members are included in docs. The following settings in", "cls_path, _, _ = qualname.rpartition('.') if cls_path: try: if '.'", "sphinx.application import Sphinx from sphinx.ext.napoleon.docstring import GoogleDocstring, NumpyDocstring if False:", "the docstring for a given python object. Called when autodoc", "<http://sphinx-doc.org/extdev/tutorial.html>`_ `The Extension API <http://sphinx-doc.org/extdev/appapi.html>`_ \"\"\" if not isinstance(app, Sphinx):", "if possible) See Also -------- :attr:`napoleon_use_param` napoleon_use_rtype : :obj:`bool` (Defaults", "'napoleon_use_rtype': (True, 'env'), 'napoleon_use_keyword': (True, 'env'), 'napoleon_custom_sections': (None, 'env') }", "to use the ``.. rubric::`` directive instead. One may look", "optional*) -- Description of `arg2`, defaults to 0 napoleon_use_keyword :", "if it should be included in the docs. \"\"\" has_doc", "is used. This `NumPy style`_ snippet will be converted as", "The options given to the directive: an object with attributes", "# This will NOT be included in the docs napoleon_include_private_with_doc", "keywords. This behaves similarly to :attr:`napoleon_use_param`. Note unlike docutils, ``:keyword:``", "the ``.. rubric::`` directive instead. One may look better than", "object representing the Sphinx process what : str A string", "quick example **If False**:: .. rubric:: Example This is just", "False: # For type annotation from typing import Any, Dict,", "if the member should be skipped during creation of the", "example **If False**:: .. rubric:: Example This is just a", "of docstring lines that `_process_docstring` modifies in place to change", "\\\"\\\"\\\" This will be included in the docs because it", "str, str, Any, Any, List[str]) -> None \"\"\"Process the docstring", "`NumPy style`_ snippet will be converted as follows:: Parameters ----------", "settings in conf.py determine if private and special class members", "use the ``.. rubric::`` directive instead. One may look better", "class docstring. False to fall back to Sphinx's default behavior,", "follows:: Parameters ---------- arg1 : str Description of `arg1` arg2", "to 0 napoleon_use_keyword : :obj:`bool` (Defaults to True) True to", "better than the other depending on what HTML theme is", "attribute:: attr1 Description of `attr1` :type: int napoleon_use_param : :obj:`bool`", "module names here, as strings extensions = ['sphinx.ext.napoleon'] # Napoleon", "True if successful, False otherwise :rtype: bool **If False**:: :returns:", "LICENSE for details. \"\"\" from sphinx import __display_version__ as __version__", "Copyright 2007-2018 by the Sphinx team, see AUTHORS. :license: BSD,", "the ``:ivar:`` role for instance variables. False to use the", "This `NumPy style`_ snippet will be converted as follows:: Parameters", "= True napoleon_custom_sections = None .. _Google style: https://google.github.io/styleguide/pyguide.html ..", "(Defaults to True) True to parse `NumPy style`_ docstrings. False", "False) True to include special members (like ``__membername__``) with docstrings", "setattr(self, name, value) def setup(app): # type: (Sphinx) -> Dict[str,", "\"exception\", \"function\", \"method\", \"attribute\". name : str The name of", "or attribute The object to which the docstring belongs. options", "see LICENSE for details. \"\"\" from sphinx import __display_version__ as", "__init__(self, **settings): # type: (Any) -> None for name, (default,", "sphinx.locale import _ for doc_field in sphinx.domains.python.PyObject.doc_field_types: if doc_field.name ==", "\"module\", \"class\", \"exception\", \"function\", \"method\", \"attribute\". name : str The", "attr1 : int Description of `attr1` **If True**:: :ivar attr1:", "specifying the type of the object to which the member", "if they have docstrings * ``napoleon_include_special_with_doc`` -- include special members", "fall back to Sphinx's default behavior, which considers the ``__init___``", "otherwise **If True**:: :returns: True if successful, False otherwise :rtype:", "docs return unicode(self.__class__.__name__) napoleon_use_admonition_for_examples : :obj:`bool` (Defaults to False) True", "type annotation from typing import Any, Dict, List # NOQA", "annotation from typing import Any, Dict, List # NOQA class", "'parameter': doc_field.names = ('param', 'parameter', 'arg', 'argument') break sphinx.domains.python.PyObject.doc_field_types.append( PyTypedField('keyword',", "= True napoleon_use_keyword = True napoleon_custom_sections = None .. _Google", "sections. False to use the ``.. rubric::`` directive instead. Note", "-------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_admonition_for_references : :obj:`bool` (Defaults to False) True to", "single ``:keyword arguments:`` role for all the keywords. This behaves", "the ``.. admonition::`` directive for the **Example** and **Examples** sections.", "lines): # type: (Sphinx, str, str, Any, Any, List[str]) ->", "True**:: def _included(self): \\\"\\\"\\\" This will be included in the", "\\\"\\\"\\\" return unicode(self).encode('utf-8') def __unicode__(self): # This will NOT be", "`attr1` :type: int napoleon_use_param : :obj:`bool` (Defaults to True) True", "will always be converted to a ``.. note::`` directive. See", "of `arg2`, defaults to 0 :type arg2: int, optional **If", "style`_ snippet will be converted as follows:: Example ------- This", "True to use the ``.. admonition::`` directive for the **Example**", "belongs. options : sphinx.ext.autodoc.Options The options given to the directive:", "name, obj, options, lines): # type: (Sphinx, str, str, Any,", ":obj:`bool` (Defaults to False) True to include special members (like", "Extension API <http://sphinx-doc.org/extdev/appapi.html>`_ \"\"\" if not isinstance(app, Sphinx): # probably", ":obj:`bool` (Defaults to True) True to use the ``:rtype:`` role", "in `conf.py`. Listed below are all the settings used by", "# NOQA class Config: \"\"\"Sphinx napoleon extension settings in `conf.py`.", "executes the ``setup()`` function, which in turn notifies Sphinx of", "and inc_special) or (is_private and inc_private) or (is_init and inc_init)):", "what == 'class' or what == 'exception': qualname = getattr(obj,", "Description of `attr1` :type: int napoleon_use_param : :obj:`bool` (Defaults to", "and inc_private) or (is_init and inc_init)): return False return None", "otherwise :rtype: bool **If False**:: :returns: *bool* -- True if", "override the decision options : sphinx.ext.autodoc.Options The options given to", "process See Also -------- `The Sphinx documentation on Extensions <http://sphinx-doc.org/extensions.html>`_", "section, just pass a string. * To create an alias", "fall back to Sphinx's default behavior. **If True**:: def _included(self):", "rubric:: Example This is just a quick example napoleon_use_admonition_for_notes :", "= app.config.napoleon_include_private_with_doc if ((is_special and inc_special) or (is_private and inc_private)", "included in the docs pass napoleon_include_special_with_doc : :obj:`bool` (Defaults to", "attribute::`` directive instead. This `NumPy style`_ snippet will be converted", "= False napoleon_include_private_with_doc = False napoleon_include_special_with_doc = False napoleon_use_admonition_for_examples =", "special members (like ``__membername__``) with docstrings in the documentation. False", "to emulate. \"\"\" _config_values = { 'napoleon_google_docstring': (True, 'env'), 'napoleon_numpy_docstring':", "is interpreted as a header for a generic section. If", "singular **Note** section will always be converted to a ``..", "optional Description of `arg2`, defaults to 0 **If True**:: :param", "as follows:: Attributes ---------- attr1 : int Description of `attr1`", "turn notifies Sphinx of everything the extension offers. Parameters ----------", "docstring \\\"\\\"\\\" pass def _skipped(self): # This will NOT be", "True to use the ``.. admonition::`` directive for **References** sections.", "all the keywords. This behaves similarly to :attr:`napoleon_use_param`. Note unlike", "return type inline with the description. This `NumPy style`_ snippet", "in self._config_values.items(): setattr(self, name, default) for name, value in settings.items():", "cls = functools.reduce(getattr, mod_path, mod) else: cls = obj.__globals__[cls_path] except", "'napoleon_include_special_with_doc': (False, 'env'), 'napoleon_use_admonition_for_examples': (False, 'env'), 'napoleon_use_admonition_for_notes': (False, 'env'), 'napoleon_use_admonition_for_references':", "typing import Any, Dict, List # NOQA class Config: \"\"\"Sphinx", "``__init___`` docstrings separately from the class docstring. False to fall", ": module, class, exception, function, method, or attribute The object", "= None .. _Google style: https://google.github.io/styleguide/pyguide.html .. _NumPy style: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt", "napoleon_custom_sections : :obj:`list` (Defaults to None) Add a list of", "} def __init__(self, **settings): # type: (Any) -> None for", "https://google.github.io/styleguide/pyguide.html .. _NumPy style: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt Attributes ---------- napoleon_google_docstring : :obj:`bool`", "and hasattr(cls, name) and # type: ignore name in cls.__dict__)", "methods if they have docstrings * ``napoleon_include_private_with_doc`` -- include private", "to fall back to Sphinx's default behavior, which considers the", ":vartype attr1: int **If False**:: .. attribute:: attr1 Description of", "and special class members or init methods are included in", "GoogleDocstring(result_lines, app.config, app, what, name, obj, options) result_lines = docstring.lines()", "what styles of docstrings will be parsed: * ``napoleon_google_docstring`` --", "A boolean indicating if autodoc will skip this member if", "napoleon_use_param = True napoleon_use_rtype = True napoleon_use_keyword = True napoleon_custom_sections", ":obj:`bool` (Defaults to True) True to parse `NumPy style`_ docstrings.", "'kwtype'), can_collapse=True)) def _process_docstring(app, what, name, obj, options, lines): #", "is_special and name.startswith('_')) inc_init = app.config.napoleon_include_init_with_doc inc_special = app.config.napoleon_include_special_with_doc inc_private", "False) True to use the ``.. admonition::`` directive for the", "module, class, exception, function, method, or attribute. For example, if", "False to use the ``.. rubric::`` directive instead. One may", "sphinx.ext.napoleon.docstring import GoogleDocstring, NumpyDocstring if False: # For type annotation", "the ``.. rubric::`` directive instead. Note ---- The singular **Note**", "autodoc has read and processed a docstring. `lines` is a", "rebuild) return {'version': __version__, 'parallel_read_safe': True} def _patch_python_domain(): # type:", "and ``:param:`` will not be treated the same way -", "of str The lines of the docstring, see above. ..", ":obj:`bool` (Defaults to False) True to use the ``:ivar:`` role", "`conf.py`:: # conf.py # Add any Sphinx extension module names", "import __display_version__ as __version__ from sphinx.application import Sphinx from sphinx.ext.napoleon.docstring", "just a quick example **If False**:: .. rubric:: Example This", "below are all the settings used by napoleon and their", "does not override the decision options : sphinx.ext.autodoc.Options The options", "in `conf.py`:: # conf.py # Add any Sphinx extension module", "in the docs pass napoleon_include_special_with_doc : :obj:`bool` (Defaults to False)", "'exception': qualname = getattr(obj, '__qualname__', '') cls_path, _, _ =", "napoleon_use_admonition_for_notes : :obj:`bool` (Defaults to False) True to use the", "sections to include, expanding the list of parsed sections. The", "pass a string. * To create an alias for an", "`The Sphinx documentation on Extensions <http://sphinx-doc.org/extensions.html>`_ `The Extension Tutorial <http://sphinx-doc.org/extdev/tutorial.html>`_", "what == 'exception' or what == 'module') if name !=", "a string. * To create an alias for an existing", "# type: (Sphinx, str, str, Any, Any, List[str]) -> None", "to use the ``.. rubric::`` directive instead. Note ---- The", "member belongs. Valid values: \"module\", \"class\", \"exception\", \"function\", \"method\", \"attribute\".", "class Config: \"\"\"Sphinx napoleon extension settings in `conf.py`. Listed below", "(Defaults to False) True to use the ``:ivar:`` role for", "'env'), 'napoleon_include_special_with_doc': (False, 'env'), 'napoleon_use_admonition_for_examples': (False, 'env'), 'napoleon_use_admonition_for_notes': (False, 'env'),", "The fully qualified name of the object. obj : module,", "file. Make sure that \"sphinx.ext.napoleon\" is enabled in `conf.py`:: #", "To create an alias for an existing section, pass a", ": :obj:`bool` (Defaults to False) True to use the ``..", "the ``setup()`` function, which in turn notifies Sphinx of everything", "conf.py determine if private and special class members or init", "doc_field.names = ('param', 'parameter', 'arg', 'argument') break sphinx.domains.python.PyObject.doc_field_types.append( PyTypedField('keyword', label=_('Keyword", "to use a single ``:parameters:`` role for all the parameters.", "Sphinx's default behavior. **If True**:: def _included(self): \\\"\\\"\\\" This will", "False to use the ``.. rubric::`` directive instead. Note ----", "-- parse NumPy style docstrings Parameters ---------- app : sphinx.application.Sphinx", "True**:: :returns: True if successful, False otherwise :rtype: bool **If", "in conf.py determine if private and special class members or", "directive. See Also -------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_admonition_for_references : :obj:`bool` (Defaults to", "a generic section. If the entry is a tuple/list/indexed container,", "# probably called by tests return {'version': __version__, 'parallel_read_safe': True}", "documentation. **If True**:: def __init__(self): \\\"\\\"\\\" This will be included", "included in docs. The following settings in conf.py determine if", "False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = False", "the docs. \"\"\" has_doc = getattr(obj, '__doc__', False) is_member =", "entry is a tuple/list/indexed container, the first entry is the", "Napoleon settings napoleon_google_docstring = True napoleon_numpy_docstring = True napoleon_include_init_with_doc =", "in the Sphinx `conf.py` file. Make sure that \"sphinx.ext.napoleon\" is", "a separate \"Keyword Arguments\" section, rendered in the same fashion", "def _process_docstring(app, what, name, obj, options, lines): # type: (Sphinx,", "= False else: cls_is_owner = (cls and hasattr(cls, name) and", "sphinx.domains.python import PyTypedField except ImportError: pass else: import sphinx.domains.python from", "Returns ------- bool True if the member should be skipped", "sphinx.ext.napoleon ~~~~~~~~~~~~~~~~~~~ Support for NumPy and Google style docstrings. :copyright:", "place to change what Sphinx outputs. The following settings in", "True**:: :param arg1: Description of `arg1` :type arg1: str :param", ":type arg1: str :param arg2: Description of `arg2`, defaults to", "rubric::`` directive instead. Note ---- The singular **Note** section will", "the intention: * To create a custom \"generic\" section, just", "= obj.__globals__[cls_path] except Exception: cls_is_owner = False else: cls_is_owner =", "type: ignore name in cls.__dict__) else: cls_is_owner = False if", "same way - there will be a separate \"Keyword Arguments\"", "Extension Tutorial <http://sphinx-doc.org/extdev/tutorial.html>`_ `The Extension API <http://sphinx-doc.org/extdev/appapi.html>`_ \"\"\" if not", ": str A string specifying the type of the object", "the Sphinx process. what : str A string specifying the", "use the ``:ivar:`` role for instance variables. False to use", "False to output the return type inline with the description.", "import functools mod = importlib.import_module(obj.__module__) mod_path = cls_path.split('.') cls =", "2007-2018 by the Sphinx team, see AUTHORS. :license: BSD, see", "member should be skipped during creation of the docs, False", "obj : module, class, exception, function, method, or attribute The", "not is_special and name.startswith('_')) inc_init = app.config.napoleon_include_init_with_doc inc_special = app.config.napoleon_include_special_with_doc", "follows:: Attributes ---------- attr1 : int Description of `attr1` **If", "and name.endswith('__')) is_private = (not is_init and not is_special and", "module and executes the ``setup()`` function, which in turn notifies", "0 :type arg2: int, optional **If False**:: :parameters: * **arg1**", "True to use the ``:ivar:`` role for instance variables. False", "def _included(self): \\\"\\\"\\\" This will be included in the docs", "in Config._config_values.items(): app.add_config_value(name, default, rebuild) return {'version': __version__, 'parallel_read_safe': True}", "extension settings in `conf.py`. Listed below are all the settings", "to a ``.. note::`` directive. See Also -------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_admonition_for_references", "To create a custom \"generic\" section, just pass a string.", "False**:: :parameters: * **arg1** (*str*) -- Description of `arg1` *", "exception, function, method, or attribute The object to which the", "tuple/list/indexed container, the first entry is the name of the", "snippet will be converted as follows:: Parameters ---------- arg1 :", "create a custom \"generic\" section, just pass a string. *", "and noindex that are True if the flag option of", "= cls_path.split('.') cls = functools.reduce(getattr, mod_path, mod) else: cls =", "the member is the __init__ method of class A, then", "conf.py # Add any Sphinx extension module names here, as", "a docstring \\\"\\\"\\\" pass def _skipped(self): # This will NOT", "section, rendered in the same fashion as \"Parameters\" section (type", "napoleon_use_admonition_for_examples : :obj:`bool` (Defaults to False) True to use the", "``.. attribute::`` directive instead. This `NumPy style`_ snippet will be", "included in the docs because it has a docstring \\\"\\\"\\\"", "use the ``.. admonition::`` directive for **References** sections. False to", ":obj:`bool` (Defaults to False) True to list ``__init___`` docstrings separately", "of custom sections to include, expanding the list of parsed", "strings or tuples, depending on the intention: * To create", ": sphinx.application.Sphinx Application object representing the Sphinx process. what :", "use the ``.. admonition::`` directive for **Notes** sections. False to", ":type arg2: int, optional **If False**:: :parameters: * **arg1** (*str*)", "Make sure that \"sphinx.ext.napoleon\" is enabled in `conf.py`:: # conf.py", "what : str A string specifying the type of the", "list of docstring lines that `_process_docstring` modifies in place to", "part of the class documentation. **If True**:: def __init__(self): \\\"\\\"\\\"", "\"function\", \"method\", \"attribute\". name : str The fully qualified name", "app.config.napoleon_include_private_with_doc if ((is_special and inc_special) or (is_private and inc_private) or", "These settings can be changed in the Sphinx `conf.py` file.", "docstring. `lines` is a list of docstring lines that `_process_docstring`", "\\\"\\\"\\\" def __init__(self): # This will NOT be included in", "to use the ``:rtype:`` role for the return type. False", "are included in docs. The following settings in conf.py determine", "is_special = (not is_init and name.startswith('__') and name.endswith('__')) is_private =", "NumPy style docstrings. napoleon_include_init_with_doc : :obj:`bool` (Defaults to False) True", "* ``napoleon_include_special_with_doc`` -- include special members if they have docstrings", "'env'), 'napoleon_include_init_with_doc': (False, 'env'), 'napoleon_include_private_with_doc': (False, 'env'), 'napoleon_include_special_with_doc': (False, 'env'),", "\"function\", \"method\", \"attribute\". name : str The name of the", "``napoleon_google_docstring`` -- parse Google style docstrings * ``napoleon_numpy_docstring`` -- parse", "``:keyword:`` and ``:param:`` will not be treated the same way", "Attributes ---------- napoleon_google_docstring : :obj:`bool` (Defaults to True) True to", "docs pass napoleon_include_special_with_doc : :obj:`bool` (Defaults to False) True to", "# conf.py # Add any Sphinx extension module names here,", "this member if `_skip_member` does not override the decision options", "the ``.. admonition::`` directive for **References** sections. False to use", ":copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. :license:", "by tests return {'version': __version__, 'parallel_read_safe': True} _patch_python_domain() app.setup_extension('sphinx.ext.autodoc') app.connect('autodoc-process-docstring',", "napoleon_use_admonition_for_references = False napoleon_use_ivar = False napoleon_use_param = True napoleon_use_rtype", "True if the member should be skipped during creation of", "include private members (like ``_membername``) with docstrings in the documentation.", "of everything the extension offers. Parameters ---------- app : sphinx.application.Sphinx", "(True, 'env'), 'napoleon_use_keyword': (True, 'env'), 'napoleon_custom_sections': (None, 'env') } def", "-------- `The Sphinx documentation on Extensions <http://sphinx-doc.org/extensions.html>`_ `The Extension Tutorial", "import PyTypedField except ImportError: pass else: import sphinx.domains.python from sphinx.locale", "Add a list of custom sections to include, expanding the", "in docs. The following settings in conf.py determine if private", "attr1: int **If False**:: .. attribute:: attr1 Description of `attr1`", "docstrings. napoleon_include_init_with_doc : :obj:`bool` (Defaults to False) True to list", "'env'), 'napoleon_use_keyword': (True, 'env'), 'napoleon_custom_sections': (None, 'env') } def __init__(self,", "napoleon and their default values. These settings can be changed", "Sphinx's default behavior, which considers the ``__init___`` docstring as part", ":obj:`bool` (Defaults to True) True to use a ``:param:`` role", "to Sphinx's default behavior, which considers the ``__init___`` docstring as", "-> None try: from sphinx.domains.python import PyTypedField except ImportError: pass", "``.. rubric::`` directive instead. Note ---- The singular **Note** section", "ignore name in cls.__dict__) else: cls_is_owner = False if what", "setup(app): # type: (Sphinx) -> Dict[str, Any] \"\"\"Sphinx extension setup", "otherwise napoleon_custom_sections : :obj:`list` (Defaults to None) Add a list", "in cls_path: import importlib import functools mod = importlib.import_module(obj.__module__) mod_path", "skip, options): # type: (Sphinx, str, str, Any, bool, Any)", "or tuples, depending on the intention: * To create a", "(Defaults to False) True to list ``__init___`` docstrings separately from", "each function keyword argument. False to use a single ``:keyword", "of same name was given to the auto directive. lines", "GoogleDocstring if app.config.napoleon_numpy_docstring: docstring = NumpyDocstring(result_lines, app.config, app, what, name,", "and executes the ``setup()`` function, which in turn notifies Sphinx", "include init methods if they have docstrings * ``napoleon_include_private_with_doc`` --", "False) True to use the ``.. admonition::`` directive for **Notes**", "See Also -------- :attr:`napoleon_use_admonition_for_examples` napoleon_use_admonition_for_references : :obj:`bool` (Defaults to False)", "GoogleDocstring, NumpyDocstring if False: # For type annotation from typing", "return unicode(self.__class__.__name__) napoleon_use_admonition_for_examples : :obj:`bool` (Defaults to False) True to", "__version__, 'parallel_read_safe': True} _patch_python_domain() app.setup_extension('sphinx.ext.autodoc') app.connect('autodoc-process-docstring', _process_docstring) app.connect('autodoc-skip-member', _skip_member) for" ]
[ "vector @staticmethod def _compute_similarity(left, right): return DataStructs.TanimotoSimilarity(left, right) def get_metadata(self)", "= False self._compute_and_write_similarity(query_item, database_item) def _write_separator_if_needed(self): if not self.first_entry: self.stream.write(\",\")", "self.counter = 0 self.first_entry = False def execute(self, files): query", "True for query_item in query: for database_item in database: self._write_separator_if_needed()", "json.load(stream)[\"data\"]] @staticmethod def _as_sparse_vector(data): # Use max integer value as", "right) def get_metadata(self) -> object: return { \"id\": \"rdkit/tanimoto\" }", "= False def execute(self, files): query = LbvsEntry._load_file(files[\"query_file\"]) database =", "= LbvsEntry._load_file(files[\"database_file\"]) with open(files[\"output_file\"], \"w\") as stream: self.stream = stream", "self._write_separator_if_needed() self.first_entry = False self._compute_and_write_similarity(query_item, database_item) def _write_separator_if_needed(self): if not", "in query: for database_item in database: self._write_separator_if_needed() self.first_entry = False", "item[\"id\"], \"value\": similarity }, self.stream) @staticmethod def _load_file(path): with open(path)", "for database_item in database: self._write_separator_if_needed() self.first_entry = False self._compute_and_write_similarity(query_item, database_item)", "# Use max integer value as a size. vector =", "integer value as a size. vector = DataStructs.cDataStructs.IntSparseIntVect(8388608) for key", "with open(files[\"output_file\"], \"w\") as stream: self.stream = stream self.write_output_header() self.compute_and_write_similarities_for_items(query,", "LbvsEntry(plugin_api.PluginInterface): \"\"\" Compute Tanimoto similarity. \"\"\" def __init__(self): self.stream =", "stream: self.stream = stream self.write_output_header() self.compute_and_write_similarities_for_items(query, database) self.write_output_footer() def write_output_header(self):", "from rdkit import DataStructs import plugin_api __license__ = \"X11\" class", "write_output_footer(self): self.stream.write(']}') def compute_and_write_similarities_for_items(self, query, database): self.first_entry = True for", "a size. vector = DataStructs.cDataStructs.IntSparseIntVect(8388608) for key in data: vector[(int)(key)]", "rdkit import DataStructs import plugin_api __license__ = \"X11\" class LbvsEntry(plugin_api.PluginInterface):", "query[\"value\"], item[\"value\"]) json.dump({ \"query\": query[\"id\"], \"id\": item[\"id\"], \"value\": similarity },", "import DataStructs import plugin_api __license__ = \"X11\" class LbvsEntry(plugin_api.PluginInterface): \"\"\"", "self.write_output_footer() def write_output_header(self): self.stream.write('{\"data\":[') def write_output_footer(self): self.stream.write(']}') def compute_and_write_similarities_for_items(self, query,", "as stream: return [{ \"id\": item[\"id\"], \"value\": LbvsEntry._as_sparse_vector(item[\"value\"]) } for", "python # -*- coding: utf-8 -*- import json from rdkit", "similarity = LbvsEntry._compute_similarity( query[\"value\"], item[\"value\"]) json.dump({ \"query\": query[\"id\"], \"id\": item[\"id\"],", "self.stream = None self.counter = 0 self.first_entry = False def", "\"value\": LbvsEntry._as_sparse_vector(item[\"value\"]) } for item in json.load(stream)[\"data\"]] @staticmethod def _as_sparse_vector(data):", "database) self.write_output_footer() def write_output_header(self): self.stream.write('{\"data\":[') def write_output_footer(self): self.stream.write(']}') def compute_and_write_similarities_for_items(self,", "@staticmethod def _as_sparse_vector(data): # Use max integer value as a", "def write_output_footer(self): self.stream.write(']}') def compute_and_write_similarities_for_items(self, query, database): self.first_entry = True", "json from rdkit import DataStructs import plugin_api __license__ = \"X11\"", "def execute(self, files): query = LbvsEntry._load_file(files[\"query_file\"]) database = LbvsEntry._load_file(files[\"database_file\"]) with", "LbvsEntry._compute_similarity( query[\"value\"], item[\"value\"]) json.dump({ \"query\": query[\"id\"], \"id\": item[\"id\"], \"value\": similarity", "self.stream.write(']}') def compute_and_write_similarities_for_items(self, query, database): self.first_entry = True for query_item", "database): self.first_entry = True for query_item in query: for database_item", "= True for query_item in query: for database_item in database:", "def __init__(self): self.stream = None self.counter = 0 self.first_entry =", "data: vector[(int)(key)] = (int)(data[key]) return vector @staticmethod def _compute_similarity(left, right):", "= 0 self.first_entry = False def execute(self, files): query =", "@staticmethod def _load_file(path): with open(path) as stream: return [{ \"id\":", "_write_separator_if_needed(self): if not self.first_entry: self.stream.write(\",\") def _compute_and_write_similarity(self, query, item): similarity", "with open(path) as stream: return [{ \"id\": item[\"id\"], \"value\": LbvsEntry._as_sparse_vector(item[\"value\"])", "database = LbvsEntry._load_file(files[\"database_file\"]) with open(files[\"output_file\"], \"w\") as stream: self.stream =", "item in json.load(stream)[\"data\"]] @staticmethod def _as_sparse_vector(data): # Use max integer", "for key in data: vector[(int)(key)] = (int)(data[key]) return vector @staticmethod", "similarity }, self.stream) @staticmethod def _load_file(path): with open(path) as stream:", "= LbvsEntry._compute_similarity( query[\"value\"], item[\"value\"]) json.dump({ \"query\": query[\"id\"], \"id\": item[\"id\"], \"value\":", "query, database): self.first_entry = True for query_item in query: for", "self.first_entry: self.stream.write(\",\") def _compute_and_write_similarity(self, query, item): similarity = LbvsEntry._compute_similarity( query[\"value\"],", "json.dump({ \"query\": query[\"id\"], \"id\": item[\"id\"], \"value\": similarity }, self.stream) @staticmethod", "\"id\": item[\"id\"], \"value\": LbvsEntry._as_sparse_vector(item[\"value\"]) } for item in json.load(stream)[\"data\"]] @staticmethod", "DataStructs.cDataStructs.IntSparseIntVect(8388608) for key in data: vector[(int)(key)] = (int)(data[key]) return vector", "_compute_similarity(left, right): return DataStructs.TanimotoSimilarity(left, right) def get_metadata(self) -> object: return", "self.stream.write(\",\") def _compute_and_write_similarity(self, query, item): similarity = LbvsEntry._compute_similarity( query[\"value\"], item[\"value\"])", "self.compute_and_write_similarities_for_items(query, database) self.write_output_footer() def write_output_header(self): self.stream.write('{\"data\":[') def write_output_footer(self): self.stream.write(']}') def", "LbvsEntry._as_sparse_vector(item[\"value\"]) } for item in json.load(stream)[\"data\"]] @staticmethod def _as_sparse_vector(data): #", "import json from rdkit import DataStructs import plugin_api __license__ =", "= stream self.write_output_header() self.compute_and_write_similarities_for_items(query, database) self.write_output_footer() def write_output_header(self): self.stream.write('{\"data\":[') def", "return [{ \"id\": item[\"id\"], \"value\": LbvsEntry._as_sparse_vector(item[\"value\"]) } for item in", "import plugin_api __license__ = \"X11\" class LbvsEntry(plugin_api.PluginInterface): \"\"\" Compute Tanimoto", "query, item): similarity = LbvsEntry._compute_similarity( query[\"value\"], item[\"value\"]) json.dump({ \"query\": query[\"id\"],", "= LbvsEntry._load_file(files[\"query_file\"]) database = LbvsEntry._load_file(files[\"database_file\"]) with open(files[\"output_file\"], \"w\") as stream:", "in json.load(stream)[\"data\"]] @staticmethod def _as_sparse_vector(data): # Use max integer value", "-*- import json from rdkit import DataStructs import plugin_api __license__", "\"w\") as stream: self.stream = stream self.write_output_header() self.compute_and_write_similarities_for_items(query, database) self.write_output_footer()", "def _compute_similarity(left, right): return DataStructs.TanimotoSimilarity(left, right) def get_metadata(self) -> object:", "self.stream.write('{\"data\":[') def write_output_footer(self): self.stream.write(']}') def compute_and_write_similarities_for_items(self, query, database): self.first_entry =", "database_item in database: self._write_separator_if_needed() self.first_entry = False self._compute_and_write_similarity(query_item, database_item) def", "@staticmethod def _compute_similarity(left, right): return DataStructs.TanimotoSimilarity(left, right) def get_metadata(self) ->", "self.stream = stream self.write_output_header() self.compute_and_write_similarities_for_items(query, database) self.write_output_footer() def write_output_header(self): self.stream.write('{\"data\":[')", "#!/usr/bin/env python # -*- coding: utf-8 -*- import json from", "= (int)(data[key]) return vector @staticmethod def _compute_similarity(left, right): return DataStructs.TanimotoSimilarity(left,", "def _write_separator_if_needed(self): if not self.first_entry: self.stream.write(\",\") def _compute_and_write_similarity(self, query, item):", "not self.first_entry: self.stream.write(\",\") def _compute_and_write_similarity(self, query, item): similarity = LbvsEntry._compute_similarity(", "for query_item in query: for database_item in database: self._write_separator_if_needed() self.first_entry", "database_item) def _write_separator_if_needed(self): if not self.first_entry: self.stream.write(\",\") def _compute_and_write_similarity(self, query,", "query[\"id\"], \"id\": item[\"id\"], \"value\": similarity }, self.stream) @staticmethod def _load_file(path):", "utf-8 -*- import json from rdkit import DataStructs import plugin_api", "item[\"id\"], \"value\": LbvsEntry._as_sparse_vector(item[\"value\"]) } for item in json.load(stream)[\"data\"]] @staticmethod def", "\"\"\" def __init__(self): self.stream = None self.counter = 0 self.first_entry", "\"query\": query[\"id\"], \"id\": item[\"id\"], \"value\": similarity }, self.stream) @staticmethod def", "False def execute(self, files): query = LbvsEntry._load_file(files[\"query_file\"]) database = LbvsEntry._load_file(files[\"database_file\"])", "Use max integer value as a size. vector = DataStructs.cDataStructs.IntSparseIntVect(8388608)", "open(path) as stream: return [{ \"id\": item[\"id\"], \"value\": LbvsEntry._as_sparse_vector(item[\"value\"]) }", "}, self.stream) @staticmethod def _load_file(path): with open(path) as stream: return", "as a size. vector = DataStructs.cDataStructs.IntSparseIntVect(8388608) for key in data:", "None self.counter = 0 self.first_entry = False def execute(self, files):", "def _load_file(path): with open(path) as stream: return [{ \"id\": item[\"id\"],", "files): query = LbvsEntry._load_file(files[\"query_file\"]) database = LbvsEntry._load_file(files[\"database_file\"]) with open(files[\"output_file\"], \"w\")", "__license__ = \"X11\" class LbvsEntry(plugin_api.PluginInterface): \"\"\" Compute Tanimoto similarity. \"\"\"", "execute(self, files): query = LbvsEntry._load_file(files[\"query_file\"]) database = LbvsEntry._load_file(files[\"database_file\"]) with open(files[\"output_file\"],", "for item in json.load(stream)[\"data\"]] @staticmethod def _as_sparse_vector(data): # Use max", "DataStructs.TanimotoSimilarity(left, right) def get_metadata(self) -> object: return { \"id\": \"rdkit/tanimoto\"", "vector[(int)(key)] = (int)(data[key]) return vector @staticmethod def _compute_similarity(left, right): return", "right): return DataStructs.TanimotoSimilarity(left, right) def get_metadata(self) -> object: return {", "_compute_and_write_similarity(self, query, item): similarity = LbvsEntry._compute_similarity( query[\"value\"], item[\"value\"]) json.dump({ \"query\":", "\"\"\" Compute Tanimoto similarity. \"\"\" def __init__(self): self.stream = None", "def _as_sparse_vector(data): # Use max integer value as a size.", "size. vector = DataStructs.cDataStructs.IntSparseIntVect(8388608) for key in data: vector[(int)(key)] =", "plugin_api __license__ = \"X11\" class LbvsEntry(plugin_api.PluginInterface): \"\"\" Compute Tanimoto similarity.", "stream self.write_output_header() self.compute_and_write_similarities_for_items(query, database) self.write_output_footer() def write_output_header(self): self.stream.write('{\"data\":[') def write_output_footer(self):", "(int)(data[key]) return vector @staticmethod def _compute_similarity(left, right): return DataStructs.TanimotoSimilarity(left, right)", "as stream: self.stream = stream self.write_output_header() self.compute_and_write_similarities_for_items(query, database) self.write_output_footer() def", "vector = DataStructs.cDataStructs.IntSparseIntVect(8388608) for key in data: vector[(int)(key)] = (int)(data[key])", "query = LbvsEntry._load_file(files[\"query_file\"]) database = LbvsEntry._load_file(files[\"database_file\"]) with open(files[\"output_file\"], \"w\") as", "compute_and_write_similarities_for_items(self, query, database): self.first_entry = True for query_item in query:", "write_output_header(self): self.stream.write('{\"data\":[') def write_output_footer(self): self.stream.write(']}') def compute_and_write_similarities_for_items(self, query, database): self.first_entry", "\"value\": similarity }, self.stream) @staticmethod def _load_file(path): with open(path) as", "coding: utf-8 -*- import json from rdkit import DataStructs import", "class LbvsEntry(plugin_api.PluginInterface): \"\"\" Compute Tanimoto similarity. \"\"\" def __init__(self): self.stream", "} for item in json.load(stream)[\"data\"]] @staticmethod def _as_sparse_vector(data): # Use", "= DataStructs.cDataStructs.IntSparseIntVect(8388608) for key in data: vector[(int)(key)] = (int)(data[key]) return", "\"id\": item[\"id\"], \"value\": similarity }, self.stream) @staticmethod def _load_file(path): with", "self.first_entry = False self._compute_and_write_similarity(query_item, database_item) def _write_separator_if_needed(self): if not self.first_entry:", "DataStructs import plugin_api __license__ = \"X11\" class LbvsEntry(plugin_api.PluginInterface): \"\"\" Compute", "= \"X11\" class LbvsEntry(plugin_api.PluginInterface): \"\"\" Compute Tanimoto similarity. \"\"\" def", "stream: return [{ \"id\": item[\"id\"], \"value\": LbvsEntry._as_sparse_vector(item[\"value\"]) } for item", "[{ \"id\": item[\"id\"], \"value\": LbvsEntry._as_sparse_vector(item[\"value\"]) } for item in json.load(stream)[\"data\"]]", "LbvsEntry._load_file(files[\"query_file\"]) database = LbvsEntry._load_file(files[\"database_file\"]) with open(files[\"output_file\"], \"w\") as stream: self.stream", "query: for database_item in database: self._write_separator_if_needed() self.first_entry = False self._compute_and_write_similarity(query_item,", "-*- coding: utf-8 -*- import json from rdkit import DataStructs", "self.stream) @staticmethod def _load_file(path): with open(path) as stream: return [{", "def write_output_header(self): self.stream.write('{\"data\":[') def write_output_footer(self): self.stream.write(']}') def compute_and_write_similarities_for_items(self, query, database):", "open(files[\"output_file\"], \"w\") as stream: self.stream = stream self.write_output_header() self.compute_and_write_similarities_for_items(query, database)", "similarity. \"\"\" def __init__(self): self.stream = None self.counter = 0", "Tanimoto similarity. \"\"\" def __init__(self): self.stream = None self.counter =", "return vector @staticmethod def _compute_similarity(left, right): return DataStructs.TanimotoSimilarity(left, right) def", "Compute Tanimoto similarity. \"\"\" def __init__(self): self.stream = None self.counter", "\"X11\" class LbvsEntry(plugin_api.PluginInterface): \"\"\" Compute Tanimoto similarity. \"\"\" def __init__(self):", "item[\"value\"]) json.dump({ \"query\": query[\"id\"], \"id\": item[\"id\"], \"value\": similarity }, self.stream)", "database: self._write_separator_if_needed() self.first_entry = False self._compute_and_write_similarity(query_item, database_item) def _write_separator_if_needed(self): if", "return DataStructs.TanimotoSimilarity(left, right) def get_metadata(self) -> object: return { \"id\":", "item): similarity = LbvsEntry._compute_similarity( query[\"value\"], item[\"value\"]) json.dump({ \"query\": query[\"id\"], \"id\":", "in database: self._write_separator_if_needed() self.first_entry = False self._compute_and_write_similarity(query_item, database_item) def _write_separator_if_needed(self):", "def compute_and_write_similarities_for_items(self, query, database): self.first_entry = True for query_item in", "self._compute_and_write_similarity(query_item, database_item) def _write_separator_if_needed(self): if not self.first_entry: self.stream.write(\",\") def _compute_and_write_similarity(self,", "def _compute_and_write_similarity(self, query, item): similarity = LbvsEntry._compute_similarity( query[\"value\"], item[\"value\"]) json.dump({", "__init__(self): self.stream = None self.counter = 0 self.first_entry = False", "False self._compute_and_write_similarity(query_item, database_item) def _write_separator_if_needed(self): if not self.first_entry: self.stream.write(\",\") def", "value as a size. vector = DataStructs.cDataStructs.IntSparseIntVect(8388608) for key in", "self.write_output_header() self.compute_and_write_similarities_for_items(query, database) self.write_output_footer() def write_output_header(self): self.stream.write('{\"data\":[') def write_output_footer(self): self.stream.write(']}')", "in data: vector[(int)(key)] = (int)(data[key]) return vector @staticmethod def _compute_similarity(left,", "max integer value as a size. vector = DataStructs.cDataStructs.IntSparseIntVect(8388608) for", "# -*- coding: utf-8 -*- import json from rdkit import", "self.first_entry = False def execute(self, files): query = LbvsEntry._load_file(files[\"query_file\"]) database", "LbvsEntry._load_file(files[\"database_file\"]) with open(files[\"output_file\"], \"w\") as stream: self.stream = stream self.write_output_header()", "_as_sparse_vector(data): # Use max integer value as a size. vector", "= None self.counter = 0 self.first_entry = False def execute(self,", "_load_file(path): with open(path) as stream: return [{ \"id\": item[\"id\"], \"value\":", "0 self.first_entry = False def execute(self, files): query = LbvsEntry._load_file(files[\"query_file\"])", "if not self.first_entry: self.stream.write(\",\") def _compute_and_write_similarity(self, query, item): similarity =", "query_item in query: for database_item in database: self._write_separator_if_needed() self.first_entry =", "key in data: vector[(int)(key)] = (int)(data[key]) return vector @staticmethod def", "self.first_entry = True for query_item in query: for database_item in" ]
[ "= ['https://' + item['ip'] + ':' + item['port'] for item", "item in result: ip = item['IP'] port = str(item['Port']) url", "= global_config.s_proxy_dict[username] url = 'https://' + proxy['ip'] + ':' +", "global_config.s_proxy_dict[username] def get_static_proxy(self, username): if not global_config.static_proxy: return None proxy", "global_config.static_proxy_dict[username] def get_proxy(self): if len(self.proxies_list) < self.LOW_WATER_MARK: for i in", "proxies_list = ['https://' + item['ip'] + ':' + item['port'] for", "return { 'https': url } def get_origin_static_proxy(self, username): if not", "= str(item['Port']) url = 'https://' + ip + ':' +", "+ port if url not in self.proxies_set: self.proxies_set.add(url) self.proxies_list.append(url) def", "= global_config.static_proxy_dict[username] if proxy['username'] and proxy['password']: url = 'https://' +", "return None return global_config.static_proxy_dict[username] def get_proxy(self): if len(self.proxies_list) < self.LOW_WATER_MARK:", "'https://' + ip + ':' + port if url not", "ip = item['IP'] port = str(item['Port']) url = 'https://' +", "'https://' + proxy['ip'] + ':' + proxy['port'] return { 'https':", "':' + proxy['port'] return { 'https': url } def get_origin_s_proxy(self,", "+ ip + ':' + port if url not in", "return { 'https': url } def get_origin_s_proxy(self, username): return global_config.s_proxy_dict[username]", "not global_config.static_proxy: return None return global_config.static_proxy_dict[username] def get_proxy(self): if len(self.proxies_list)", "'https://' + proxy['username'] + ':' + proxy['password'] + '@' +", "item in global_config.s_proxy] LOW_WATER_MARK = 5 proxy_fetch_url = \"http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&qty=1&time=1&pro=&city=&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=\" def", "if url not in self.proxies_set: self.proxies_set.add(url) self.proxies_list.append(url) def remove_proxy(self, url,", "return global_config.static_proxy_dict[username] def get_proxy(self): if len(self.proxies_list) < self.LOW_WATER_MARK: for i", "context = Context() action = DirectProxyAction() action.execute(context=context) result = context.get(Context.KEY_PROXY_RESULT,", "+ item['port'] for item in global_config.s_proxy] LOW_WATER_MARK = 5 proxy_fetch_url", "global_config.static_proxy_dict[username] if proxy['username'] and proxy['password']: url = 'https://' + proxy['username']", "{ 'https': url } def get_origin_static_proxy(self, username): if not global_config.static_proxy:", "= None class ProxyService(object): proxies_set = set() proxies_list = ['https://'", "+ proxy['username'] + ':' + proxy['password'] + '@' + proxy['ip']", "ip + ':' + port if url not in self.proxies_set:", "global_config.static_proxy: return None proxy = global_config.static_proxy_dict[username] if proxy['username'] and proxy['password']:", "len(self.proxies_list)): self.fetch_proxy() time.sleep(2) proxy = self.proxies_list[self._counter % len(self.proxies_list)] self._counter +=", "proxy_fetch_url = \"http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&qty=1&time=1&pro=&city=&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=\" def __init__(self) -> None: super().__init__() self._counter =", "proxy['username'] + ':' + proxy['password'] + '@' + proxy['ip'] +", "url = 'https://' + proxy['username'] + ':' + proxy['password'] +", "item['IP'] port = str(item['Port']) url = 'https://' + ip +", "url = 'https://' + proxy['ip'] + ':' + proxy['port'] return", "config.config_loader import global_config from mall_spider.spiders.actions.context import Context from mall_spider.spiders.actions.direct_proxy_action import", "import global_config from mall_spider.spiders.actions.context import Context from mall_spider.spiders.actions.direct_proxy_action import DirectProxyAction", "= set() proxies_list = ['https://' + item['ip'] + ':' +", "get_proxy(self): if len(self.proxies_list) < self.LOW_WATER_MARK: for i in range(0, int(self.LOW_WATER_MARK", "import time from config.config_loader import global_config from mall_spider.spiders.actions.context import Context", "def get_static_proxy(self, username): if not global_config.static_proxy: return None proxy =", "force=False): if force: self.proxies_set.remove(url) self.proxies_list.remove(url) def get_proxy_service(): global __proxy_service if", "{ 'https': proxy } def fetch_proxy(self): context = Context() action", "super().__init__() self._counter = 0 def get_s_proxy(self, username): proxy = global_config.s_proxy_dict[username]", "mall_spider.spiders.actions.direct_proxy_action import DirectProxyAction __proxy_service = None class ProxyService(object): proxies_set =", "+ ':' + proxy['port'] return { 'https': url } def", "+ ':' + item['port'] for item in global_config.s_proxy] LOW_WATER_MARK =", "item['port'] for item in global_config.s_proxy] LOW_WATER_MARK = 5 proxy_fetch_url =", "global_config.s_proxy] LOW_WATER_MARK = 5 proxy_fetch_url = \"http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&qty=1&time=1&pro=&city=&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=\" def __init__(self) ->", "not global_config.static_proxy: return None proxy = global_config.static_proxy_dict[username] if proxy['username'] and", "= DirectProxyAction() action.execute(context=context) result = context.get(Context.KEY_PROXY_RESULT, []) if result: for", "':' + proxy['password'] + '@' + proxy['ip'] + ':' +", "DirectProxyAction __proxy_service = None class ProxyService(object): proxies_set = set() proxies_list", "__init__(self) -> None: super().__init__() self._counter = 0 def get_s_proxy(self, username):", "self.LOW_WATER_MARK: for i in range(0, int(self.LOW_WATER_MARK * 1) - len(self.proxies_list)):", "username): proxy = global_config.s_proxy_dict[username] url = 'https://' + proxy['ip'] +", "fetch_proxy(self): context = Context() action = DirectProxyAction() action.execute(context=context) result =", "get_origin_s_proxy(self, username): return global_config.s_proxy_dict[username] def get_static_proxy(self, username): if not global_config.static_proxy:", "port if url not in self.proxies_set: self.proxies_set.add(url) self.proxies_list.append(url) def remove_proxy(self,", "ProxyService(object): proxies_set = set() proxies_list = ['https://' + item['ip'] +", "in range(0, int(self.LOW_WATER_MARK * 1) - len(self.proxies_list)): self.fetch_proxy() time.sleep(2) proxy", "+ '@' + proxy['ip'] + ':' + proxy['port'] else: url", "proxies_set = set() proxies_list = ['https://' + item['ip'] + ':'", "':' + port if url not in self.proxies_set: self.proxies_set.add(url) self.proxies_list.append(url)", "self.proxies_set.add(url) self.proxies_list.append(url) def remove_proxy(self, url, force=False): if force: self.proxies_set.remove(url) self.proxies_list.remove(url)", "':' + proxy['port'] else: url = 'https://' + proxy['ip'] +", "- len(self.proxies_list)): self.fetch_proxy() time.sleep(2) proxy = self.proxies_list[self._counter % len(self.proxies_list)] self._counter", "return { 'https': proxy } def fetch_proxy(self): context = Context()", "Context() action = DirectProxyAction() action.execute(context=context) result = context.get(Context.KEY_PROXY_RESULT, []) if", "return None proxy = global_config.static_proxy_dict[username] if proxy['username'] and proxy['password']: url", "= item['IP'] port = str(item['Port']) url = 'https://' + ip", "proxy['port'] else: url = 'https://' + proxy['ip'] + ':' +", "['https://' + item['ip'] + ':' + item['port'] for item in", "# coding: utf-8 import time from config.config_loader import global_config from", "None: super().__init__() self._counter = 0 def get_s_proxy(self, username): proxy =", "from mall_spider.spiders.actions.context import Context from mall_spider.spiders.actions.direct_proxy_action import DirectProxyAction __proxy_service =", "+ proxy['port'] return { 'https': url } def get_origin_static_proxy(self, username):", "proxy['password']: url = 'https://' + proxy['username'] + ':' + proxy['password']", "if not global_config.static_proxy: return None return global_config.static_proxy_dict[username] def get_proxy(self): if", "proxy } def fetch_proxy(self): context = Context() action = DirectProxyAction()", "for item in result: ip = item['IP'] port = str(item['Port'])", "-> None: super().__init__() self._counter = 0 def get_s_proxy(self, username): proxy", "} def get_origin_static_proxy(self, username): if not global_config.static_proxy: return None return", "= Context() action = DirectProxyAction() action.execute(context=context) result = context.get(Context.KEY_PROXY_RESULT, [])", "proxy['username'] and proxy['password']: url = 'https://' + proxy['username'] + ':'", "if len(self.proxies_list) < self.LOW_WATER_MARK: for i in range(0, int(self.LOW_WATER_MARK *", "time.sleep(2) proxy = self.proxies_list[self._counter % len(self.proxies_list)] self._counter += 1 return", "remove_proxy(self, url, force=False): if force: self.proxies_set.remove(url) self.proxies_list.remove(url) def get_proxy_service(): global", "+= 1 return { 'https': proxy } def fetch_proxy(self): context", "import Context from mall_spider.spiders.actions.direct_proxy_action import DirectProxyAction __proxy_service = None class", "% len(self.proxies_list)] self._counter += 1 return { 'https': proxy }", "url } def get_origin_static_proxy(self, username): if not global_config.static_proxy: return None", "range(0, int(self.LOW_WATER_MARK * 1) - len(self.proxies_list)): self.fetch_proxy() time.sleep(2) proxy =", "int(self.LOW_WATER_MARK * 1) - len(self.proxies_list)): self.fetch_proxy() time.sleep(2) proxy = self.proxies_list[self._counter", "in result: ip = item['IP'] port = str(item['Port']) url =", "for i in range(0, int(self.LOW_WATER_MARK * 1) - len(self.proxies_list)): self.fetch_proxy()", "self.proxies_list.append(url) def remove_proxy(self, url, force=False): if force: self.proxies_set.remove(url) self.proxies_list.remove(url) def", "result: ip = item['IP'] port = str(item['Port']) url = 'https://'", "i in range(0, int(self.LOW_WATER_MARK * 1) - len(self.proxies_list)): self.fetch_proxy() time.sleep(2)", "url } def get_origin_s_proxy(self, username): return global_config.s_proxy_dict[username] def get_static_proxy(self, username):", "= context.get(Context.KEY_PROXY_RESULT, []) if result: for item in result: ip", "context.get(Context.KEY_PROXY_RESULT, []) if result: for item in result: ip =", "if result: for item in result: ip = item['IP'] port", "from config.config_loader import global_config from mall_spider.spiders.actions.context import Context from mall_spider.spiders.actions.direct_proxy_action", "proxy['port'] return { 'https': url } def get_origin_s_proxy(self, username): return", "'@' + proxy['ip'] + ':' + proxy['port'] else: url =", "DirectProxyAction() action.execute(context=context) result = context.get(Context.KEY_PROXY_RESULT, []) if result: for item", "LOW_WATER_MARK = 5 proxy_fetch_url = \"http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&qty=1&time=1&pro=&city=&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=\" def __init__(self) -> None:", "str(item['Port']) url = 'https://' + ip + ':' + port", "def __init__(self) -> None: super().__init__() self._counter = 0 def get_s_proxy(self,", "'https': proxy } def fetch_proxy(self): context = Context() action =", "= 'https://' + proxy['username'] + ':' + proxy['password'] + '@'", "coding: utf-8 import time from config.config_loader import global_config from mall_spider.spiders.actions.context", "from mall_spider.spiders.actions.direct_proxy_action import DirectProxyAction __proxy_service = None class ProxyService(object): proxies_set", "global_config.s_proxy_dict[username] url = 'https://' + proxy['ip'] + ':' + proxy['port']", "proxy['port'] return { 'https': url } def get_origin_static_proxy(self, username): if", "global __proxy_service if not __proxy_service: __proxy_service = ProxyService() return __proxy_service", "+ ':' + proxy['port'] else: url = 'https://' + proxy['ip']", "def fetch_proxy(self): context = Context() action = DirectProxyAction() action.execute(context=context) result", "url = 'https://' + ip + ':' + port if", "get_static_proxy(self, username): if not global_config.static_proxy: return None proxy = global_config.static_proxy_dict[username]", "self.proxies_list.remove(url) def get_proxy_service(): global __proxy_service if not __proxy_service: __proxy_service =", "proxy = self.proxies_list[self._counter % len(self.proxies_list)] self._counter += 1 return {", "Context from mall_spider.spiders.actions.direct_proxy_action import DirectProxyAction __proxy_service = None class ProxyService(object):", "+ proxy['port'] return { 'https': url } def get_origin_s_proxy(self, username):", "in global_config.s_proxy] LOW_WATER_MARK = 5 proxy_fetch_url = \"http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&qty=1&time=1&pro=&city=&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=\" def __init__(self)", "None return global_config.static_proxy_dict[username] def get_proxy(self): if len(self.proxies_list) < self.LOW_WATER_MARK: for", "result: for item in result: ip = item['IP'] port =", "utf-8 import time from config.config_loader import global_config from mall_spider.spiders.actions.context import", "force: self.proxies_set.remove(url) self.proxies_list.remove(url) def get_proxy_service(): global __proxy_service if not __proxy_service:", "class ProxyService(object): proxies_set = set() proxies_list = ['https://' + item['ip']", "def get_proxy(self): if len(self.proxies_list) < self.LOW_WATER_MARK: for i in range(0,", "for item in global_config.s_proxy] LOW_WATER_MARK = 5 proxy_fetch_url = \"http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&qty=1&time=1&pro=&city=&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=\"", "= 0 def get_s_proxy(self, username): proxy = global_config.s_proxy_dict[username] url =", "username): if not global_config.static_proxy: return None proxy = global_config.static_proxy_dict[username] if", "if proxy['username'] and proxy['password']: url = 'https://' + proxy['username'] +", "\"http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&qty=1&time=1&pro=&city=&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=\" def __init__(self) -> None: super().__init__() self._counter = 0 def", "5 proxy_fetch_url = \"http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&qty=1&time=1&pro=&city=&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=\" def __init__(self) -> None: super().__init__() self._counter", "0 def get_s_proxy(self, username): proxy = global_config.s_proxy_dict[username] url = 'https://'", "proxy['password'] + '@' + proxy['ip'] + ':' + proxy['port'] else:", "'https': url } def get_origin_s_proxy(self, username): return global_config.s_proxy_dict[username] def get_static_proxy(self,", "} def fetch_proxy(self): context = Context() action = DirectProxyAction() action.execute(context=context)", "url, force=False): if force: self.proxies_set.remove(url) self.proxies_list.remove(url) def get_proxy_service(): global __proxy_service", "def get_origin_s_proxy(self, username): return global_config.s_proxy_dict[username] def get_static_proxy(self, username): if not", "self._counter = 0 def get_s_proxy(self, username): proxy = global_config.s_proxy_dict[username] url", "= 5 proxy_fetch_url = \"http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&qty=1&time=1&pro=&city=&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=\" def __init__(self) -> None: super().__init__()", "def get_origin_static_proxy(self, username): if not global_config.static_proxy: return None return global_config.static_proxy_dict[username]", "__proxy_service = None class ProxyService(object): proxies_set = set() proxies_list =", "return global_config.s_proxy_dict[username] def get_static_proxy(self, username): if not global_config.static_proxy: return None", "+ ':' + port if url not in self.proxies_set: self.proxies_set.add(url)", "self.proxies_set: self.proxies_set.add(url) self.proxies_list.append(url) def remove_proxy(self, url, force=False): if force: self.proxies_set.remove(url)", "global_config from mall_spider.spiders.actions.context import Context from mall_spider.spiders.actions.direct_proxy_action import DirectProxyAction __proxy_service", "':' + item['port'] for item in global_config.s_proxy] LOW_WATER_MARK = 5", "+ proxy['ip'] + ':' + proxy['port'] else: url = 'https://'", "+ item['ip'] + ':' + item['port'] for item in global_config.s_proxy]", "} def get_origin_s_proxy(self, username): return global_config.s_proxy_dict[username] def get_static_proxy(self, username): if", "else: url = 'https://' + proxy['ip'] + ':' + proxy['port']", "= self.proxies_list[self._counter % len(self.proxies_list)] self._counter += 1 return { 'https':", "+ proxy['ip'] + ':' + proxy['port'] return { 'https': url", "get_origin_static_proxy(self, username): if not global_config.static_proxy: return None return global_config.static_proxy_dict[username] def", "not in self.proxies_set: self.proxies_set.add(url) self.proxies_list.append(url) def remove_proxy(self, url, force=False): if", "def remove_proxy(self, url, force=False): if force: self.proxies_set.remove(url) self.proxies_list.remove(url) def get_proxy_service():", "1 return { 'https': proxy } def fetch_proxy(self): context =", "get_proxy_service(): global __proxy_service if not __proxy_service: __proxy_service = ProxyService() return", "item['ip'] + ':' + item['port'] for item in global_config.s_proxy] LOW_WATER_MARK", "url not in self.proxies_set: self.proxies_set.add(url) self.proxies_list.append(url) def remove_proxy(self, url, force=False):", "port = str(item['Port']) url = 'https://' + ip + ':'", "if force: self.proxies_set.remove(url) self.proxies_list.remove(url) def get_proxy_service(): global __proxy_service if not", "= \"http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=1&fa=0&fetch_key=&qty=1&time=1&pro=&city=&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=\" def __init__(self) -> None: super().__init__() self._counter = 0", "+ proxy['password'] + '@' + proxy['ip'] + ':' + proxy['port']", "len(self.proxies_list) < self.LOW_WATER_MARK: for i in range(0, int(self.LOW_WATER_MARK * 1)", "mall_spider.spiders.actions.context import Context from mall_spider.spiders.actions.direct_proxy_action import DirectProxyAction __proxy_service = None", "username): return global_config.s_proxy_dict[username] def get_static_proxy(self, username): if not global_config.static_proxy: return", "and proxy['password']: url = 'https://' + proxy['username'] + ':' +", "self._counter += 1 return { 'https': proxy } def fetch_proxy(self):", "= 'https://' + ip + ':' + port if url", "proxy = global_config.static_proxy_dict[username] if proxy['username'] and proxy['password']: url = 'https://'", "[]) if result: for item in result: ip = item['IP']", "result = context.get(Context.KEY_PROXY_RESULT, []) if result: for item in result:", "global_config.static_proxy: return None return global_config.static_proxy_dict[username] def get_proxy(self): if len(self.proxies_list) <", "':' + proxy['port'] return { 'https': url } def get_origin_static_proxy(self,", "if not global_config.static_proxy: return None proxy = global_config.static_proxy_dict[username] if proxy['username']", "get_s_proxy(self, username): proxy = global_config.s_proxy_dict[username] url = 'https://' + proxy['ip']", "self.proxies_list[self._counter % len(self.proxies_list)] self._counter += 1 return { 'https': proxy", "self.fetch_proxy() time.sleep(2) proxy = self.proxies_list[self._counter % len(self.proxies_list)] self._counter += 1", "None proxy = global_config.static_proxy_dict[username] if proxy['username'] and proxy['password']: url =", "proxy = global_config.s_proxy_dict[username] url = 'https://' + proxy['ip'] + ':'", "+ proxy['port'] else: url = 'https://' + proxy['ip'] + ':'", "1) - len(self.proxies_list)): self.fetch_proxy() time.sleep(2) proxy = self.proxies_list[self._counter % len(self.proxies_list)]", "action = DirectProxyAction() action.execute(context=context) result = context.get(Context.KEY_PROXY_RESULT, []) if result:", "'https': url } def get_origin_static_proxy(self, username): if not global_config.static_proxy: return", "len(self.proxies_list)] self._counter += 1 return { 'https': proxy } def", "* 1) - len(self.proxies_list)): self.fetch_proxy() time.sleep(2) proxy = self.proxies_list[self._counter %", "time from config.config_loader import global_config from mall_spider.spiders.actions.context import Context from", "username): if not global_config.static_proxy: return None return global_config.static_proxy_dict[username] def get_proxy(self):", "set() proxies_list = ['https://' + item['ip'] + ':' + item['port']", "< self.LOW_WATER_MARK: for i in range(0, int(self.LOW_WATER_MARK * 1) -", "None class ProxyService(object): proxies_set = set() proxies_list = ['https://' +", "in self.proxies_set: self.proxies_set.add(url) self.proxies_list.append(url) def remove_proxy(self, url, force=False): if force:", "proxy['ip'] + ':' + proxy['port'] else: url = 'https://' +", "action.execute(context=context) result = context.get(Context.KEY_PROXY_RESULT, []) if result: for item in", "def get_proxy_service(): global __proxy_service if not __proxy_service: __proxy_service = ProxyService()", "import DirectProxyAction __proxy_service = None class ProxyService(object): proxies_set = set()", "self.proxies_set.remove(url) self.proxies_list.remove(url) def get_proxy_service(): global __proxy_service if not __proxy_service: __proxy_service", "def get_s_proxy(self, username): proxy = global_config.s_proxy_dict[username] url = 'https://' +", "= 'https://' + proxy['ip'] + ':' + proxy['port'] return {", "<gh_stars>10-100 # coding: utf-8 import time from config.config_loader import global_config", "{ 'https': url } def get_origin_s_proxy(self, username): return global_config.s_proxy_dict[username] def", "proxy['ip'] + ':' + proxy['port'] return { 'https': url }", "+ ':' + proxy['password'] + '@' + proxy['ip'] + ':'" ]
[ "datetime import unittest import tempfile class WeatherTestCase(unittest.TestCase): def setUp(self): self.db_fd,", "no entries.\"\"\" rv = self.app.get('/') assert 'Nothing logged yet.' in", "import tempfile class WeatherTestCase(unittest.TestCase): def setUp(self): self.db_fd, weather.app.config['DATABASE'] = tempfile.mkstemp()", "self.db_fd, weather.app.config['DATABASE'] = tempfile.mkstemp() weather.app.config['TESTING'] = True self.app = weather.app.test_client()", "self.app = weather.app.test_client() weather.init_db() def tearDown(self): os.close(self.db_fd) os.unlink(weather.app.config['DATABASE']) def test_empty_db(self):", "reporting weather\"\"\" rv = self.app.get('/report/11210/63/23', follow_redirects=True) assert b'11210' in rv.data", "\"\"\"Test reporting weather\"\"\" rv = self.app.get('/', follow_redirects=True) assert b'11210' in", "'Nothing logged yet.' in rv.data def test_report(self): \"\"\"Test reporting weather\"\"\"", "os.unlink(weather.app.config['DATABASE']) def test_empty_db(self): \"\"\"Test empty database with no entries.\"\"\" rv", "logged yet.' in rv.data def test_report(self): \"\"\"Test reporting weather\"\"\" rv", "test_report(self): \"\"\"Test reporting weather\"\"\" rv = self.app.get('/report/11210/63/23', follow_redirects=True) assert b'11210'", "self.app.get('/') assert 'Nothing logged yet.' in rv.data def test_report(self): \"\"\"Test", "def test_full_db(self): \"\"\"Test reporting weather\"\"\" rv = self.app.get('/', follow_redirects=True) assert", "tempfile.mkstemp() weather.app.config['TESTING'] = True self.app = weather.app.test_client() weather.init_db() def tearDown(self):", "rv.data def test_report(self): \"\"\"Test reporting weather\"\"\" rv = self.app.get('/report/11210/63/23', follow_redirects=True)", "= self.app.get('/report/11210/63/23', follow_redirects=True) assert b'11210' in rv.data def test_full_db(self): \"\"\"Test", "tearDown(self): os.close(self.db_fd) os.unlink(weather.app.config['DATABASE']) def test_empty_db(self): \"\"\"Test empty database with no", "test_full_db(self): \"\"\"Test reporting weather\"\"\" rv = self.app.get('/', follow_redirects=True) assert b'11210'", "\"\"\"Test reporting weather\"\"\" rv = self.app.get('/report/11210/63/23', follow_redirects=True) assert b'11210' in", "tempfile class WeatherTestCase(unittest.TestCase): def setUp(self): self.db_fd, weather.app.config['DATABASE'] = tempfile.mkstemp() weather.app.config['TESTING']", "= True self.app = weather.app.test_client() weather.init_db() def tearDown(self): os.close(self.db_fd) os.unlink(weather.app.config['DATABASE'])", "os import weather import datetime import unittest import tempfile class", "import unittest import tempfile class WeatherTestCase(unittest.TestCase): def setUp(self): self.db_fd, weather.app.config['DATABASE']", "def tearDown(self): os.close(self.db_fd) os.unlink(weather.app.config['DATABASE']) def test_empty_db(self): \"\"\"Test empty database with", "self.app.get('/', follow_redirects=True) assert b'11210' in rv.data if __name__ == '__main__':", "class WeatherTestCase(unittest.TestCase): def setUp(self): self.db_fd, weather.app.config['DATABASE'] = tempfile.mkstemp() weather.app.config['TESTING'] =", "def test_report(self): \"\"\"Test reporting weather\"\"\" rv = self.app.get('/report/11210/63/23', follow_redirects=True) assert", "b'11210' in rv.data def test_full_db(self): \"\"\"Test reporting weather\"\"\" rv =", "weather.app.test_client() weather.init_db() def tearDown(self): os.close(self.db_fd) os.unlink(weather.app.config['DATABASE']) def test_empty_db(self): \"\"\"Test empty", "def test_empty_db(self): \"\"\"Test empty database with no entries.\"\"\" rv =", "in rv.data def test_full_db(self): \"\"\"Test reporting weather\"\"\" rv = self.app.get('/',", "assert b'11210' in rv.data def test_full_db(self): \"\"\"Test reporting weather\"\"\" rv", "unittest import tempfile class WeatherTestCase(unittest.TestCase): def setUp(self): self.db_fd, weather.app.config['DATABASE'] =", "rv = self.app.get('/') assert 'Nothing logged yet.' in rv.data def", "= weather.app.test_client() weather.init_db() def tearDown(self): os.close(self.db_fd) os.unlink(weather.app.config['DATABASE']) def test_empty_db(self): \"\"\"Test", "weather.init_db() def tearDown(self): os.close(self.db_fd) os.unlink(weather.app.config['DATABASE']) def test_empty_db(self): \"\"\"Test empty database", "setUp(self): self.db_fd, weather.app.config['DATABASE'] = tempfile.mkstemp() weather.app.config['TESTING'] = True self.app =", "weather.app.config['TESTING'] = True self.app = weather.app.test_client() weather.init_db() def tearDown(self): os.close(self.db_fd)", "rv = self.app.get('/', follow_redirects=True) assert b'11210' in rv.data if __name__", "weather import datetime import unittest import tempfile class WeatherTestCase(unittest.TestCase): def", "def setUp(self): self.db_fd, weather.app.config['DATABASE'] = tempfile.mkstemp() weather.app.config['TESTING'] = True self.app", "in rv.data def test_report(self): \"\"\"Test reporting weather\"\"\" rv = self.app.get('/report/11210/63/23',", "weather\"\"\" rv = self.app.get('/', follow_redirects=True) assert b'11210' in rv.data if", "import weather import datetime import unittest import tempfile class WeatherTestCase(unittest.TestCase):", "empty database with no entries.\"\"\" rv = self.app.get('/') assert 'Nothing", "reporting weather\"\"\" rv = self.app.get('/', follow_redirects=True) assert b'11210' in rv.data", "weather.app.config['DATABASE'] = tempfile.mkstemp() weather.app.config['TESTING'] = True self.app = weather.app.test_client() weather.init_db()", "= self.app.get('/', follow_redirects=True) assert b'11210' in rv.data if __name__ ==", "database with no entries.\"\"\" rv = self.app.get('/') assert 'Nothing logged", "= self.app.get('/') assert 'Nothing logged yet.' in rv.data def test_report(self):", "follow_redirects=True) assert b'11210' in rv.data def test_full_db(self): \"\"\"Test reporting weather\"\"\"", "assert 'Nothing logged yet.' in rv.data def test_report(self): \"\"\"Test reporting", "self.app.get('/report/11210/63/23', follow_redirects=True) assert b'11210' in rv.data def test_full_db(self): \"\"\"Test reporting", "import os import weather import datetime import unittest import tempfile", "rv.data def test_full_db(self): \"\"\"Test reporting weather\"\"\" rv = self.app.get('/', follow_redirects=True)", "= tempfile.mkstemp() weather.app.config['TESTING'] = True self.app = weather.app.test_client() weather.init_db() def", "with no entries.\"\"\" rv = self.app.get('/') assert 'Nothing logged yet.'", "os.close(self.db_fd) os.unlink(weather.app.config['DATABASE']) def test_empty_db(self): \"\"\"Test empty database with no entries.\"\"\"", "test_empty_db(self): \"\"\"Test empty database with no entries.\"\"\" rv = self.app.get('/')", "WeatherTestCase(unittest.TestCase): def setUp(self): self.db_fd, weather.app.config['DATABASE'] = tempfile.mkstemp() weather.app.config['TESTING'] = True", "True self.app = weather.app.test_client() weather.init_db() def tearDown(self): os.close(self.db_fd) os.unlink(weather.app.config['DATABASE']) def", "entries.\"\"\" rv = self.app.get('/') assert 'Nothing logged yet.' in rv.data", "yet.' in rv.data def test_report(self): \"\"\"Test reporting weather\"\"\" rv =", "weather\"\"\" rv = self.app.get('/report/11210/63/23', follow_redirects=True) assert b'11210' in rv.data def", "follow_redirects=True) assert b'11210' in rv.data if __name__ == '__main__': unittest.main()", "\"\"\"Test empty database with no entries.\"\"\" rv = self.app.get('/') assert", "rv = self.app.get('/report/11210/63/23', follow_redirects=True) assert b'11210' in rv.data def test_full_db(self):", "import datetime import unittest import tempfile class WeatherTestCase(unittest.TestCase): def setUp(self):" ]
[ "class Activator: def __init__(self, name, packet_stream=None): self.ps = None self.name", "and self.future and pkt[0] == 0: self.future.set_result(1) def set_packet_stream(self, ps):", "0 self.state = '' if packet_stream: self.set_packet_stream(packet_stream) @_core.module_cmd def wait_activator(self):", "print('checking act') if self.data: self.future.set_result(1) else: self.state = 'check_chinch' print('checking", "= 'chinch_ready' print('waiting for activator') if self.state == 'chinch_ready' and", "self.data: self.future.set_result(1) else: self.state = 'check_chinch' print('checking for chinch') def", "for chinch') def export_cmds(self): _core.export_cmd('wait_activator', self.wait_activator) _core.export_cmd('check_activator', self.check_activator) def on_recv(self,", "pkt): if self.state == 'check_chinch' and self.future and pkt[0] ==", "= None self.data = 0 self.state = '' if packet_stream:", "if self.state == 'chinch_ready' and self.future and pkt[0] == 0:", "self.future.set_result(1) self.state = 'chinch_ready' print('waiting for activator') if self.state ==", "pass @_core.module_cmd def check_activator(self): print('checking act') if self.data: self.future.set_result(1) else:", "self.future = None self.data = 0 self.state = '' if", "if self.data: self.future.set_result(1) else: self.state = 'check_chinch' print('checking for chinch')", "and self.future and pkt[0] == 1: self.future.set_result(1) self.state = 'chinch_ready'", "== 'check_chinch' and self.future and pkt[0] == 1: self.future.set_result(1) self.state", "= None self.name = name self.future = None self.data =", "None self.name = name self.future = None self.data = 0", "== 1: self.future.set_result(1) self.state = 'chinch_ready' print('waiting for activator') if", "'check_chinch' and self.future and pkt[0] == 1: self.future.set_result(1) self.state =", "def check_activator(self): print('checking act') if self.data: self.future.set_result(1) else: self.state =", "def export_cmds(self): _core.export_cmd('wait_activator', self.wait_activator) _core.export_cmd('check_activator', self.check_activator) def on_recv(self, pkt): if", "export_cmds(self): _core.export_cmd('wait_activator', self.wait_activator) _core.export_cmd('check_activator', self.check_activator) def on_recv(self, pkt): if self.state", "and pkt[0] == 1: self.future.set_result(1) self.state = 'chinch_ready' print('waiting for", "'' if packet_stream: self.set_packet_stream(packet_stream) @_core.module_cmd def wait_activator(self): pass @_core.module_cmd def", "activator') if self.state == 'chinch_ready' and self.future and pkt[0] ==", "act') if self.data: self.future.set_result(1) else: self.state = 'check_chinch' print('checking for", "self.check_activator) def on_recv(self, pkt): if self.state == 'check_chinch' and self.future", "self.state = 'check_chinch' print('checking for chinch') def export_cmds(self): _core.export_cmd('wait_activator', self.wait_activator)", "packet_stream: self.set_packet_stream(packet_stream) @_core.module_cmd def wait_activator(self): pass @_core.module_cmd def check_activator(self): print('checking", "= 'check_chinch' print('checking for chinch') def export_cmds(self): _core.export_cmd('wait_activator', self.wait_activator) _core.export_cmd('check_activator',", "on_recv(self, pkt): if self.state == 'check_chinch' and self.future and pkt[0]", "= 0 self.state = '' if packet_stream: self.set_packet_stream(packet_stream) @_core.module_cmd def", "self.wait_activator) _core.export_cmd('check_activator', self.check_activator) def on_recv(self, pkt): if self.state == 'check_chinch'", "self.name = name self.future = None self.data = 0 self.state", "self.state == 'chinch_ready' and self.future and pkt[0] == 0: self.future.set_result(1)", "== 0: self.future.set_result(1) def set_packet_stream(self, ps): ps.recv = self.on_recv self.ps", "print('waiting for activator') if self.state == 'chinch_ready' and self.future and", "self.future.set_result(1) def set_packet_stream(self, ps): ps.recv = self.on_recv self.ps = ps", "= name self.future = None self.data = 0 self.state =", "self.set_packet_stream(packet_stream) @_core.module_cmd def wait_activator(self): pass @_core.module_cmd def check_activator(self): print('checking act')", "pkt[0] == 0: self.future.set_result(1) def set_packet_stream(self, ps): ps.recv = self.on_recv", "print('checking for chinch') def export_cmds(self): _core.export_cmd('wait_activator', self.wait_activator) _core.export_cmd('check_activator', self.check_activator) def", "if packet_stream: self.set_packet_stream(packet_stream) @_core.module_cmd def wait_activator(self): pass @_core.module_cmd def check_activator(self):", "'check_chinch' print('checking for chinch') def export_cmds(self): _core.export_cmd('wait_activator', self.wait_activator) _core.export_cmd('check_activator', self.check_activator)", "def wait_activator(self): pass @_core.module_cmd def check_activator(self): print('checking act') if self.data:", "_core.export_cmd('check_activator', self.check_activator) def on_recv(self, pkt): if self.state == 'check_chinch' and", "self.state = '' if packet_stream: self.set_packet_stream(packet_stream) @_core.module_cmd def wait_activator(self): pass", "def __init__(self, name, packet_stream=None): self.ps = None self.name = name", "self.future.set_result(1) else: self.state = 'check_chinch' print('checking for chinch') def export_cmds(self):", "wait_activator(self): pass @_core.module_cmd def check_activator(self): print('checking act') if self.data: self.future.set_result(1)", "_core.export_cmd('wait_activator', self.wait_activator) _core.export_cmd('check_activator', self.check_activator) def on_recv(self, pkt): if self.state ==", "== 'chinch_ready' and self.future and pkt[0] == 0: self.future.set_result(1) def", "asyncio class Activator: def __init__(self, name, packet_stream=None): self.ps = None", "0: self.future.set_result(1) def set_packet_stream(self, ps): ps.recv = self.on_recv self.ps =", "__init__(self, name, packet_stream=None): self.ps = None self.name = name self.future", "check_activator(self): print('checking act') if self.data: self.future.set_result(1) else: self.state = 'check_chinch'", "@_core.module_cmd def check_activator(self): print('checking act') if self.data: self.future.set_result(1) else: self.state", "name, packet_stream=None): self.ps = None self.name = name self.future =", "self.state = 'chinch_ready' print('waiting for activator') if self.state == 'chinch_ready'", "'chinch_ready' and self.future and pkt[0] == 0: self.future.set_result(1) def set_packet_stream(self,", "self.future and pkt[0] == 1: self.future.set_result(1) self.state = 'chinch_ready' print('waiting", "import asyncio class Activator: def __init__(self, name, packet_stream=None): self.ps =", "Activator: def __init__(self, name, packet_stream=None): self.ps = None self.name =", "name self.future = None self.data = 0 self.state = ''", "packet_stream=None): self.ps = None self.name = name self.future = None", "chinch') def export_cmds(self): _core.export_cmd('wait_activator', self.wait_activator) _core.export_cmd('check_activator', self.check_activator) def on_recv(self, pkt):", "'chinch_ready' print('waiting for activator') if self.state == 'chinch_ready' and self.future", "None self.data = 0 self.state = '' if packet_stream: self.set_packet_stream(packet_stream)", "for activator') if self.state == 'chinch_ready' and self.future and pkt[0]", "1: self.future.set_result(1) self.state = 'chinch_ready' print('waiting for activator') if self.state", "self.data = 0 self.state = '' if packet_stream: self.set_packet_stream(packet_stream) @_core.module_cmd", "@_core.module_cmd def wait_activator(self): pass @_core.module_cmd def check_activator(self): print('checking act') if", "else: self.state = 'check_chinch' print('checking for chinch') def export_cmds(self): _core.export_cmd('wait_activator',", "pkt[0] == 1: self.future.set_result(1) self.state = 'chinch_ready' print('waiting for activator')", "self.future and pkt[0] == 0: self.future.set_result(1) def set_packet_stream(self, ps): ps.recv", "def on_recv(self, pkt): if self.state == 'check_chinch' and self.future and", "= '' if packet_stream: self.set_packet_stream(packet_stream) @_core.module_cmd def wait_activator(self): pass @_core.module_cmd", "self.state == 'check_chinch' and self.future and pkt[0] == 1: self.future.set_result(1)", "and pkt[0] == 0: self.future.set_result(1) def set_packet_stream(self, ps): ps.recv =", "if self.state == 'check_chinch' and self.future and pkt[0] == 1:", "self.ps = None self.name = name self.future = None self.data" ]
[ "<NAME>, <NAME>, (https://github.com/AdeDZY/DeepCT) model_url = \"http://boston.lti.cs.cmu.edu/appendices/arXiv2019-DeepCT-Zhuyun-Dai/outputs/marco.zip\" out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\")", "350 # Provide Max Sequence Length used for consideration. (Max:", "more details on DeepCT, refer here: https://arxiv.org/abs/1910.10687 The original DeepCT", "beir/pyserini-fastapi #### #### Locally run the docker Image + FastAPI", "checkpoint file. run_deepct.FLAGS.max_seq_length = 350 # Provide Max Sequence Length", "-it --rm pyserini-fastapi Usage: python evaluate_deepct.py \"\"\" from DeepCT.deepct import", "3. Configure Params for DeepCT inference #### ################################################## # We", "Provide Max Sequence Length used for consideration. (Max: 512) run_deepct.FLAGS.train_batch_size", "#### docker_beir_pyserini = \"http://127.0.0.1:8000\" #### Upload Multipart-encoded files #### with", "Length used for consideration. (Max: 512) run_deepct.FLAGS.train_batch_size = 128 #", "follow the steps below to install DeepCT: 1. git clone", "FastAPI #### docker_beir_pyserini = \"http://127.0.0.1:8000\" #### Upload Multipart-encoded files ####", "installation, please follow the steps below to get docker container", "#### Index documents to Pyserini ##### index_name = \"beir/you-index-name\" #", "params={\"index_name\": index_name}) ###################################### #### 2. Pyserini-Retrieval (BM25) #### ###################################### ####", "-p 8000:8000 -it --rm pyserini-fastapi Usage: python evaluate_deepct.py \"\"\" from", "dataset and unzip the dataset dataset = \"scifact\" url =", "to delete terms. # Runs DeepCT model on the corpus.jsonl", "more Memory but faster! run_deepct.FLAGS.output_dir = data_path # Output directory,", "We only want to use the code for inference. run_deepct.FLAGS.do_eval", "(using Anserini) in BEIR. For more details on DeepCT, refer", "Output file for storing final DeepCT produced corpus. run_deepct.FLAGS.m =", "= sorted(scores_dict.items(), key=lambda item: item[1], reverse=True) for rank in range(10):", "here: https://docs.docker.com/get-docker/ After docker installation, please follow the steps below", "TF 2.X! if not os.path.isfile(os.path.join(data_path, \"deepct.jsonl\")): ################################ #### Command-Line Arugments", "logging.info(\"Retriever evaluation for k in: {}\".format(retriever.k_values)) ndcg, _map, recall, precision", "= os.path.join(checkpoint_dir, \"model.ckpt-65816\") # Provide DeepCT MSMARCO model (bert-base-uncased) checkpoint", "Pyserini-Retrieval (BM25) #### ###################################### #### Retrieve documents from Pyserini #####", "Image + FastAPI #### docker_beir_pyserini = \"http://127.0.0.1:8000\" #### Upload Multipart-encoded", "python evaluate_deepct.py \"\"\" from DeepCT.deepct import run_deepct # git clone", "faster! run_deepct.FLAGS.output_dir = data_path # Output directory, this will contain", "not allow DeepCT to delete terms. # Runs DeepCT model", "#### ################################################## # We cannot use the original Repo (https://github.com/AdeDZY/DeepCT)", "DeepCT to delete terms. # Runs DeepCT model on the", "Tensorflow latest (2.x). We do not change the core-prediction code,", "Docker Image beir/pyserini-fastapi #### #### Locally run the docker Image", "Anserini uses Java-11, we would advise you to use docker", "unzip the dataset dataset = \"scifact\" url = \"https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/{}.zip\".format(dataset) out_dir", "as fIn: r = requests.post(docker_beir_pyserini + \"/upload/\", files={\"file\": fIn}, verify=False)", "the core-prediction code, only few input/output file format and structure", "128 # Inference batch size, Larger more Memory but faster!", "from beir.datasets.data_loader import GenericDataLoader from beir.retrieval.evaluation import EvaluateRetrieval from beir.generation.models", "util, LoggingHandler from beir.datasets.data_loader import GenericDataLoader from beir.retrieval.evaluation import EvaluateRetrieval", "= util.download_and_unzip(url, out_dir) corpus, queries, qrels = GenericDataLoader(data_path).load(split=\"test\") #### 1.", "Evaluate your retrieval using NDCG@k, MAP@K ... logging.info(\"Retriever evaluation for", "verify=False) #### Index documents to Pyserini ##### index_name = \"beir/you-index-name\"", "run_deepct.FLAGS.m = 100 # Scaling parameter for DeepCT weights: scaling", "#### Download Docker Image beir/pyserini-fastapi #### #### Locally run the", "For more details on DeepCT, refer here: https://arxiv.org/abs/1910.10687 The original", "##### retriever = EvaluateRetrieval() qids = list(queries) query_texts = [queries[qid]", "bert_base_dir = util.download_and_unzip(base_model_url, out_dir) #### 2. Download DeepCT MSMARCO Trained", "retrieval using NDCG@k, MAP@K ... logging.info(\"Retriever evaluation for k in:", "files: deepct.jsonl (output-file) and predict.tf_record run_deepct.FLAGS.output_file = \"deepct.jsonl\" # Output", "evaluate_deepct.py \"\"\" from DeepCT.deepct import run_deepct # git clone https://github.com/NThakur20/DeepCT.git", "from beir.retrieval.evaluation import EvaluateRetrieval from beir.generation.models import QGenModel from tqdm.autonotebook", "DeepCT MSMARCO Trained BERT checkpoint #### # Credits to DeepCT", "r = requests.post(docker_beir_pyserini + \"/upload/\", files={\"file\": fIn}, verify=False) #### Index", "= util.download_and_unzip(model_url, out_dir) ################################################## #### 3. Configure Params for DeepCT", "in DeepCT. Check out run_deepct. run_deepct.FLAGS.do_train = False # We", "vocabulary. run_deepct.FLAGS.bert_config_file = os.path.join(bert_base_dir, \"bert_config.json\") # Provide bert-base-uncased config.json file.", "information to stdout logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO, handlers=[LoggingHandler()])", "range(10): doc_id = scores[rank][0] logging.info(\"Doc %d: %s [%s] - %s\\n\"", "Do not allow DeepCT to delete terms. # Runs DeepCT", "data_path # Output directory, this will contain two files: deepct.jsonl", "#### Retrieve RM3 expanded pyserini results (format of results is", "use docker for running Pyserini. To be able to run", "sqrt to smooth weights. DeepCT Paper uses None. run_deepct.FLAGS.keep_all_terms =", "Java-11, we would advise you to use docker for running", "True # Do not allow DeepCT to delete terms. #", "%d: %s [%s] - %s\\n\" % (rank+1, doc_id, corpus[doc_id].get(\"title\"), corpus[doc_id].get(\"text\")))", "from DeepCT.deepct import run_deepct # git clone https://github.com/NThakur20/DeepCT.git from beir", "and only works with Tensorflow 1.x (1.15). We modified the", "check: https://github.com/NThakur20/DeepCT and compare it with original repo! Please follow", "results = json.loads(requests.post(docker_beir_pyserini + \"/lexical/rm3/batch_search/\", json=payload).text)[\"results\"] #### Evaluate your retrieval", "latest (2.x). We do not change the core-prediction code, only", "scores_dict = random.choice(list(results.items())) logging.info(\"Query : %s\\n\" % queries[query_id]) scores =", "doc_id = scores[rank][0] logging.info(\"Doc %d: %s [%s] - %s\\n\" %", "formats. For more details on changes, check: https://github.com/NThakur20/DeepCT and compare", "authors: <NAME>, <NAME>, (https://github.com/AdeDZY/DeepCT) model_url = \"http://boston.lti.cs.cmu.edu/appendices/arXiv2019-DeepCT-Zhuyun-Dai/outputs/marco.zip\" out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(),", "from tqdm.autonotebook import trange import pathlib, os, json import logging", "#### #### Locally run the docker Image + FastAPI ####", "random #### Just some code to print debug information to", "it with original repo! Please follow the steps below to", "refer here: https://arxiv.org/abs/1910.10687 The original DeepCT repository is not modularised", "scifact.zip dataset and unzip the dataset dataset = \"scifact\" url", "#### 3. Configure Params for DeepCT inference #### ################################################## #", "steps below to get docker container up and running: 1.", "run the docker Image + FastAPI #### docker_beir_pyserini = \"http://127.0.0.1:8000\"", "\"\"\" from DeepCT.deepct import run_deepct # git clone https://github.com/NThakur20/DeepCT.git from", "only prediction. run_deepct.FLAGS.data_dir = os.path.join(data_path, \"corpus.jsonl\") # Provide original path", "Uncased model #### # Ref: https://github.com/google-research/bert base_model_url = \"https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip\" out_dir", "import trange import pathlib, os, json import logging import requests", "################################################## #### 3. Configure Params for DeepCT inference #### ##################################################", "below to get docker container up and running: 1. docker", "and compare it with original repo! Please follow the steps", "to install DeepCT: 1. git clone https://github.com/NThakur20/DeepCT.git Since Anserini uses", "made it working with latest TF 2.X! if not os.path.isfile(os.path.join(data_path,", "to get docker container up and running: 1. docker pull", "os.path.join(bert_base_dir, \"bert_config.json\") # Provide bert-base-uncased config.json file. run_deepct.FLAGS.init_checkpoint = os.path.join(checkpoint_dir,", "uses None. run_deepct.FLAGS.keep_all_terms = True # Do not allow DeepCT", "Image beir/pyserini-fastapi #### #### Locally run the docker Image +", "working with latest TF 2.X! if not os.path.isfile(os.path.join(data_path, \"deepct.jsonl\")): ################################", "Provide bert-base-uncased model vocabulary. run_deepct.FLAGS.bert_config_file = os.path.join(bert_base_dir, \"bert_config.json\") # Provide", "\"/lexical/batch_search/\", json=payload).text)[\"results\"] #### Retrieve RM3 expanded pyserini results (format of", "from beir import util, LoggingHandler from beir.datasets.data_loader import GenericDataLoader from", "run_deepct.FLAGS.do_train = False # We only want to use the", "format. run_deepct.FLAGS.vocab_file = os.path.join(bert_base_dir, \"vocab.txt\") # Provide bert-base-uncased model vocabulary.", "repo! Please follow the steps below to install DeepCT: 1.", "structure to adapt to BEIR formats. For more details on", "= data_path # Output directory, this will contain two files:", "# Output file for storing final DeepCT produced corpus. run_deepct.FLAGS.m", "#### Upload Multipart-encoded files #### with open(os.path.join(data_path, \"deepct.jsonl\"), \"rb\") as", "Provide bert-base-uncased config.json file. run_deepct.FLAGS.init_checkpoint = os.path.join(checkpoint_dir, \"model.ckpt-65816\") # Provide", "################################################## # We cannot use the original Repo (https://github.com/AdeDZY/DeepCT) as", "\"beir/you-index-name\" # beir/scifact r = requests.get(docker_beir_pyserini + \"/index/\", params={\"index_name\": index_name})", "beir.datasets.data_loader import GenericDataLoader from beir.retrieval.evaluation import EvaluateRetrieval from beir.generation.models import", "stdout logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO, handlers=[LoggingHandler()]) #### /print", "2.X! if not os.path.isfile(os.path.join(data_path, \"deepct.jsonl\")): ################################ #### Command-Line Arugments ####", "index_name}) ###################################### #### 2. Pyserini-Retrieval (BM25) #### ###################################### #### Retrieve", "container up and running: 1. docker pull docker pull beir/pyserini-fastapi", "not change the core-prediction code, only few input/output file format", "TF 1.15. # We reformatted the code (https://github.com/NThakur20/DeepCT) and made", "= \"sqrt\" # Use sqrt to smooth weights. DeepCT Paper", "advise you to use docker for running Pyserini. To be", "os.path.isfile(os.path.join(data_path, \"deepct.jsonl\")): ################################ #### Command-Line Arugments #### ################################ run_deepct.FLAGS.task_name =", "to use the code for inference. run_deepct.FLAGS.do_eval = False #", "results = json.loads(requests.post(docker_beir_pyserini + \"/lexical/batch_search/\", json=payload).text)[\"results\"] #### Retrieve RM3 expanded", "from Pyserini ##### retriever = EvaluateRetrieval() qids = list(queries) query_texts", "item: item[1], reverse=True) for rank in range(10): doc_id = scores[rank][0]", "you to use docker for running Pyserini. To be able", "changes, check: https://github.com/NThakur20/DeepCT and compare it with original repo! Please", "reformatted the code (https://github.com/NThakur20/DeepCT) and made it working with latest", "use DeepCT model for only prediction. run_deepct.FLAGS.data_dir = os.path.join(data_path, \"corpus.jsonl\")", "Please follow the steps below to install DeepCT: 1. git", "Runs DeepCT model on the corpus.jsonl run_deepct.main() #### Download Docker", "your local machine, please refer here: https://docs.docker.com/get-docker/ After docker installation,", "# Defined a seperate BEIR task in DeepCT. Check out", "trange import pathlib, os, json import logging import requests import", "import pathlib, os, json import logging import requests import random", "Multipart-encoded files #### with open(os.path.join(data_path, \"deepct.jsonl\"), \"rb\") as fIn: r", "qrels) results = json.loads(requests.post(docker_beir_pyserini + \"/lexical/batch_search/\", json=payload).text)[\"results\"] #### Retrieve RM3", "refer here: https://docs.docker.com/get-docker/ After docker installation, please follow the steps", "task in DeepCT. Check out run_deepct. run_deepct.FLAGS.do_train = False #", "1.0}, \"bm25\": {\"k1\": 18, \"b\": 0.7}} #### Retrieve pyserini results", "original DeepCT repository is not modularised and only works with", "json=payload).text)[\"results\"] #### Evaluate your retrieval using NDCG@k, MAP@K ... logging.info(\"Retriever", "random.choice(list(results.items())) logging.info(\"Query : %s\\n\" % queries[query_id]) scores = sorted(scores_dict.items(), key=lambda", "= os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\") bert_base_dir = util.download_and_unzip(base_model_url, out_dir) #### 2. Download", "code below you must have docker locally installed in your", "fIn}, verify=False) #### Index documents to Pyserini ##### index_name =", "= 128 # Inference batch size, Larger more Memory but", "evaluation. run_deepct.FLAGS.do_predict = True # True, as we would use", "run_deepct.FLAGS.output_dir = data_path # Output directory, this will contain two", "# git clone https://github.com/NThakur20/DeepCT.git from beir import util, LoggingHandler from", "below you must have docker locally installed in your machine.", "Inference batch size, Larger more Memory but faster! run_deepct.FLAGS.output_dir =", "DeepCT repository is not modularised and only works with Tensorflow", "for consideration. (Max: 512) run_deepct.FLAGS.train_batch_size = 128 # Inference batch", "#### query_id, scores_dict = random.choice(list(results.items())) logging.info(\"Query : %s\\n\" % queries[query_id])", "not modularised and only works with Tensorflow 1.x (1.15). We", "install docker on your local machine, please refer here: https://docs.docker.com/get-docker/", "seperate BEIR task in DeepCT. Check out run_deepct. run_deepct.FLAGS.do_train =", "it working with latest TF 2.X! if not os.path.isfile(os.path.join(data_path, \"deepct.jsonl\")):", "#### Locally run the docker Image + FastAPI #### docker_beir_pyserini", "# True, as we would use DeepCT model for only", "# Credits to DeepCT authors: <NAME>, <NAME>, (https://github.com/AdeDZY/DeepCT) model_url =", "DeepCT authors: <NAME>, <NAME>, (https://github.com/AdeDZY/DeepCT) model_url = \"http://boston.lti.cs.cmu.edu/appendices/arXiv2019-DeepCT-Zhuyun-Dai/outputs/marco.zip\" out_dir =", "reverse=True) for rank in range(10): doc_id = scores[rank][0] logging.info(\"Doc %d:", "DeepCT MSMARCO model (bert-base-uncased) checkpoint file. run_deepct.FLAGS.max_seq_length = 350 #", "here: https://arxiv.org/abs/1910.10687 The original DeepCT repository is not modularised and", "100 # Scaling parameter for DeepCT weights: scaling parameter >", "RM3 expanded pyserini results (format of results is identical to", "docker for running Pyserini. To be able to run the", "to stdout logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO, handlers=[LoggingHandler()]) ####", "scores = sorted(scores_dict.items(), key=lambda item: item[1], reverse=True) for rank in", "pathlib, os, json import logging import requests import random ####", "results, retriever.k_values) #### Retrieval Example #### query_id, scores_dict = random.choice(list(results.items()))", "runs with TF 1.15. # We reformatted the code (https://github.com/NThakur20/DeepCT)", "batch size, Larger more Memory but faster! run_deepct.FLAGS.output_dir = data_path", "= list(queries) query_texts = [queries[qid] for qid in qids] payload", "for inference. run_deepct.FLAGS.do_eval = False # No evaluation. run_deepct.FLAGS.do_predict =", "directory, this will contain two files: deepct.jsonl (output-file) and predict.tf_record", "We do not change the core-prediction code, only few input/output", "\"/lexical/rm3/batch_search/\", json=payload).text)[\"results\"] #### Evaluate your retrieval using NDCG@k, MAP@K ...", "results is identical to qrels) # results = json.loads(requests.post(docker_beir_pyserini +", "documents to Pyserini ##### index_name = \"beir/you-index-name\" # beir/scifact r", "we would advise you to use docker for running Pyserini.", "use the code for inference. run_deepct.FLAGS.do_eval = False # No", "item[1], reverse=True) for rank in range(10): doc_id = scores[rank][0] logging.info(\"Doc", "r = requests.get(docker_beir_pyserini + \"/index/\", params={\"index_name\": index_name}) ###################################### #### 2.", "out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\") checkpoint_dir = util.download_and_unzip(model_url, out_dir) ################################################## ####", "= os.path.join(pathlib.Path(__file__).parent.absolute(), \"datasets\") data_path = util.download_and_unzip(url, out_dir) corpus, queries, qrels", "expanded pyserini results (format of results is identical to qrels)", "# We cannot use the original Repo (https://github.com/AdeDZY/DeepCT) as it", "evaluate DeepCT (using Anserini) in BEIR. For more details on", "{\"k1\": 18, \"b\": 0.7}} #### Retrieve pyserini results (format of", "shows how to evaluate DeepCT (using Anserini) in BEIR. For", "Download scifact.zip dataset and unzip the dataset dataset = \"scifact\"", "Index documents to Pyserini ##### index_name = \"beir/you-index-name\" # beir/scifact", "query_texts = [queries[qid] for qid in qids] payload = {\"queries\":", "to work with Tensorflow latest (2.x). We do not change", "allow DeepCT to delete terms. # Runs DeepCT model on", "run_deepct.main() #### Download Docker Image beir/pyserini-fastapi #### #### Locally run", "fIn: r = requests.post(docker_beir_pyserini + \"/upload/\", files={\"file\": fIn}, verify=False) ####", "Memory but faster! run_deepct.FLAGS.output_dir = data_path # Output directory, this", "docker_beir_pyserini = \"http://127.0.0.1:8000\" #### Upload Multipart-encoded files #### with open(os.path.join(data_path,", "#### 2. Pyserini-Retrieval (BM25) #### ###################################### #### Retrieve documents from", "# Scaling parameter for DeepCT weights: scaling parameter > 0,", "consideration. (Max: 512) run_deepct.FLAGS.train_batch_size = 128 # Inference batch size,", "queries[query_id]) scores = sorted(scores_dict.items(), key=lambda item: item[1], reverse=True) for rank", "run_deepct.FLAGS.data_dir = os.path.join(data_path, \"corpus.jsonl\") # Provide original path to corpus", "Retrieve pyserini results (format of results is identical to qrels)", "able to run the code below you must have docker", "# We only want to use the code for inference.", "%(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO, handlers=[LoggingHandler()]) #### /print debug information to", "= EvaluateRetrieval() qids = list(queries) query_texts = [queries[qid] for qid", "queries, qrels = GenericDataLoader(data_path).load(split=\"test\") #### 1. Download Google BERT-BASE, Uncased", "#### Evaluate your retrieval using NDCG@k, MAP@K ... logging.info(\"Retriever evaluation", "original path to corpus data, follow beir format. run_deepct.FLAGS.vocab_file =", "code for inference. run_deepct.FLAGS.do_eval = False # No evaluation. run_deepct.FLAGS.do_predict", "Download Google BERT-BASE, Uncased model #### # Ref: https://github.com/google-research/bert base_model_url", "with Tensorflow 1.x (1.15). We modified the DeepCT repository to", "\"http://boston.lti.cs.cmu.edu/appendices/arXiv2019-DeepCT-Zhuyun-Dai/outputs/marco.zip\" out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\") checkpoint_dir = util.download_and_unzip(model_url, out_dir) ##################################################", "the dataset dataset = \"scifact\" url = \"https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/{}.zip\".format(dataset) out_dir =", "################################ run_deepct.FLAGS.task_name = \"beir\" # Defined a seperate BEIR task", "retriever = EvaluateRetrieval() qids = list(queries) query_texts = [queries[qid] for", "beir/pyserini-fastapi 2. docker build -t pyserini-fastapi . 3. docker run", "steps below to install DeepCT: 1. git clone https://github.com/NThakur20/DeepCT.git Since", "in qids] payload = {\"queries\": query_texts, \"qids\": qids, \"k\": max(retriever.k_values),", "False # We only want to use the code for", "\"deepct.jsonl\")): ################################ #### Command-Line Arugments #### ################################ run_deepct.FLAGS.task_name = \"beir\"", "beir.generation.models import QGenModel from tqdm.autonotebook import trange import pathlib, os,", "requests.post(docker_beir_pyserini + \"/upload/\", files={\"file\": fIn}, verify=False) #### Index documents to", "get docker container up and running: 1. docker pull docker", "dataset = \"scifact\" url = \"https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/{}.zip\".format(dataset) out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"datasets\")", "BEIR formats. For more details on changes, check: https://github.com/NThakur20/DeepCT and", "as we would use DeepCT model for only prediction. run_deepct.FLAGS.data_dir", "query_id, scores_dict = random.choice(list(results.items())) logging.info(\"Query : %s\\n\" % queries[query_id]) scores", "Example #### query_id, scores_dict = random.choice(list(results.items())) logging.info(\"Query : %s\\n\" %", "Command-Line Arugments #### ################################ run_deepct.FLAGS.task_name = \"beir\" # Defined a", "util.download_and_unzip(base_model_url, out_dir) #### 2. Download DeepCT MSMARCO Trained BERT checkpoint", "#### Retrieve pyserini results (format of results is identical to", "(https://github.com/NThakur20/DeepCT) and made it working with latest TF 2.X! if", "the code (https://github.com/NThakur20/DeepCT) and made it working with latest TF", "recommend 100 run_deepct.FLAGS.smoothing = \"sqrt\" # Use sqrt to smooth", "uses Java-11, we would advise you to use docker for", "for k in: {}\".format(retriever.k_values)) ndcg, _map, recall, precision = retriever.evaluate(qrels,", "for running Pyserini. To be able to run the code", "on DeepCT, refer here: https://arxiv.org/abs/1910.10687 The original DeepCT repository is", "the code below you must have docker locally installed in", "util.download_and_unzip(model_url, out_dir) ################################################## #### 3. Configure Params for DeepCT inference", "# Provide Max Sequence Length used for consideration. (Max: 512)", "##### index_name = \"beir/you-index-name\" # beir/scifact r = requests.get(docker_beir_pyserini +", "model_url = \"http://boston.lti.cs.cmu.edu/appendices/arXiv2019-DeepCT-Zhuyun-Dai/outputs/marco.zip\" out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\") checkpoint_dir = util.download_and_unzip(model_url,", "pyserini-fastapi Usage: python evaluate_deepct.py \"\"\" from DeepCT.deepct import run_deepct #", "works with Tensorflow 1.x (1.15). We modified the DeepCT repository", "modularised and only works with Tensorflow 1.x (1.15). We modified", "(bert-base-uncased) checkpoint file. run_deepct.FLAGS.max_seq_length = 350 # Provide Max Sequence", "run -p 8000:8000 -it --rm pyserini-fastapi Usage: python evaluate_deepct.py \"\"\"", "512) run_deepct.FLAGS.train_batch_size = 128 # Inference batch size, Larger more", "= json.loads(requests.post(docker_beir_pyserini + \"/lexical/rm3/batch_search/\", json=payload).text)[\"results\"] #### Evaluate your retrieval using", "8000:8000 -it --rm pyserini-fastapi Usage: python evaluate_deepct.py \"\"\" from DeepCT.deepct", "We cannot use the original Repo (https://github.com/AdeDZY/DeepCT) as it only", "Use sqrt to smooth weights. DeepCT Paper uses None. run_deepct.FLAGS.keep_all_terms", "run_deepct.FLAGS.keep_all_terms = True # Do not allow DeepCT to delete", "out_dir) ################################################## #### 3. Configure Params for DeepCT inference ####", "run_deepct # git clone https://github.com/NThakur20/DeepCT.git from beir import util, LoggingHandler", "+ \"/upload/\", files={\"file\": fIn}, verify=False) #### Index documents to Pyserini", "Larger more Memory but faster! run_deepct.FLAGS.output_dir = data_path # Output", "and unzip the dataset dataset = \"scifact\" url = \"https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/{}.zip\".format(dataset)", "max(retriever.k_values), \"fields\": {\"contents\": 1.0}, \"bm25\": {\"k1\": 18, \"b\": 0.7}} ####", "files={\"file\": fIn}, verify=False) #### Index documents to Pyserini ##### index_name", "be able to run the code below you must have", "and predict.tf_record run_deepct.FLAGS.output_file = \"deepct.jsonl\" # Output file for storing", "inference. run_deepct.FLAGS.do_eval = False # No evaluation. run_deepct.FLAGS.do_predict = True", "requests.get(docker_beir_pyserini + \"/index/\", params={\"index_name\": index_name}) ###################################### #### 2. Pyserini-Retrieval (BM25)", "sorted(scores_dict.items(), key=lambda item: item[1], reverse=True) for rank in range(10): doc_id", "qids = list(queries) query_texts = [queries[qid] for qid in qids]", "follow beir format. run_deepct.FLAGS.vocab_file = os.path.join(bert_base_dir, \"vocab.txt\") # Provide bert-base-uncased", "1.x (1.15). We modified the DeepCT repository to work with", "18, \"b\": 0.7}} #### Retrieve pyserini results (format of results", "os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\") bert_base_dir = util.download_and_unzip(base_model_url, out_dir) #### 2. Download DeepCT", "will contain two files: deepct.jsonl (output-file) and predict.tf_record run_deepct.FLAGS.output_file =", "the code for inference. run_deepct.FLAGS.do_eval = False # No evaluation.", "os.path.join(bert_base_dir, \"vocab.txt\") # Provide bert-base-uncased model vocabulary. run_deepct.FLAGS.bert_config_file = os.path.join(bert_base_dir,", "\"qids\": qids, \"k\": max(retriever.k_values), \"fields\": {\"contents\": 1.0}, \"bm25\": {\"k1\": 18,", "1. git clone https://github.com/NThakur20/DeepCT.git Since Anserini uses Java-11, we would", "= random.choice(list(results.items())) logging.info(\"Query : %s\\n\" % queries[query_id]) scores = sorted(scores_dict.items(),", "LoggingHandler from beir.datasets.data_loader import GenericDataLoader from beir.retrieval.evaluation import EvaluateRetrieval from", "2. Pyserini-Retrieval (BM25) #### ###################################### #### Retrieve documents from Pyserini", "Upload Multipart-encoded files #### with open(os.path.join(data_path, \"deepct.jsonl\"), \"rb\") as fIn:", ": %s\\n\" % queries[query_id]) scores = sorted(scores_dict.items(), key=lambda item: item[1],", "- %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO, handlers=[LoggingHandler()]) #### /print debug information", "delete terms. # Runs DeepCT model on the corpus.jsonl run_deepct.main()", "\"vocab.txt\") # Provide bert-base-uncased model vocabulary. run_deepct.FLAGS.bert_config_file = os.path.join(bert_base_dir, \"bert_config.json\")", "Defined a seperate BEIR task in DeepCT. Check out run_deepct.", "of results is identical to qrels) # results = json.loads(requests.post(docker_beir_pyserini", "k in: {}\".format(retriever.k_values)) ndcg, _map, recall, precision = retriever.evaluate(qrels, results,", "is identical to qrels) # results = json.loads(requests.post(docker_beir_pyserini + \"/lexical/rm3/batch_search/\",", "DeepCT (using Anserini) in BEIR. For more details on DeepCT,", "retriever.evaluate(qrels, results, retriever.k_values) #### Retrieval Example #### query_id, scores_dict =", "= True # True, as we would use DeepCT model", "To install docker on your local machine, please refer here:", "format and structure to adapt to BEIR formats. For more", "#### Retrieval Example #### query_id, scores_dict = random.choice(list(results.items())) logging.info(\"Query :", "for DeepCT inference #### ################################################## # We cannot use the", "https://github.com/NThakur20/DeepCT and compare it with original repo! Please follow the", "weights: scaling parameter > 0, recommend 100 run_deepct.FLAGS.smoothing = \"sqrt\"", "rank in range(10): doc_id = scores[rank][0] logging.info(\"Doc %d: %s [%s]", "\"rb\") as fIn: r = requests.post(docker_beir_pyserini + \"/upload/\", files={\"file\": fIn},", "results (format of results is identical to qrels) results =", "# Provide bert-base-uncased model vocabulary. run_deepct.FLAGS.bert_config_file = os.path.join(bert_base_dir, \"bert_config.json\") #", "pull docker pull beir/pyserini-fastapi 2. docker build -t pyserini-fastapi .", "run the code below you must have docker locally installed", "The original DeepCT repository is not modularised and only works", "#### # Credits to DeepCT authors: <NAME>, <NAME>, (https://github.com/AdeDZY/DeepCT) model_url", "scores[rank][0] logging.info(\"Doc %d: %s [%s] - %s\\n\" % (rank+1, doc_id,", "please refer here: https://docs.docker.com/get-docker/ After docker installation, please follow the", "evaluation for k in: {}\".format(retriever.k_values)) ndcg, _map, recall, precision =", "path to corpus data, follow beir format. run_deepct.FLAGS.vocab_file = os.path.join(bert_base_dir,", "3. docker run -p 8000:8000 -it --rm pyserini-fastapi Usage: python", "tqdm.autonotebook import trange import pathlib, os, json import logging import", "code to print debug information to stdout logging.basicConfig(format='%(asctime)s - %(message)s',", "run_deepct. run_deepct.FLAGS.do_train = False # We only want to use", "Download Docker Image beir/pyserini-fastapi #### #### Locally run the docker", "the docker Image + FastAPI #### docker_beir_pyserini = \"http://127.0.0.1:8000\" ####", "in range(10): doc_id = scores[rank][0] logging.info(\"Doc %d: %s [%s] -", "BERT-BASE, Uncased model #### # Ref: https://github.com/google-research/bert base_model_url = \"https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip\"", "results is identical to qrels) results = json.loads(requests.post(docker_beir_pyserini + \"/lexical/batch_search/\",", "DeepCT, refer here: https://arxiv.org/abs/1910.10687 The original DeepCT repository is not", "Google BERT-BASE, Uncased model #### # Ref: https://github.com/google-research/bert base_model_url =", "= \"beir/you-index-name\" # beir/scifact r = requests.get(docker_beir_pyserini + \"/index/\", params={\"index_name\":", "documents from Pyserini ##### retriever = EvaluateRetrieval() qids = list(queries)", "running: 1. docker pull docker pull beir/pyserini-fastapi 2. docker build", "two files: deepct.jsonl (output-file) and predict.tf_record run_deepct.FLAGS.output_file = \"deepct.jsonl\" #", "\"deepct.jsonl\"), \"rb\") as fIn: r = requests.post(docker_beir_pyserini + \"/upload/\", files={\"file\":", "out_dir) #### 2. Download DeepCT MSMARCO Trained BERT checkpoint ####", "2. Download DeepCT MSMARCO Trained BERT checkpoint #### # Credits", "the corpus.jsonl run_deepct.main() #### Download Docker Image beir/pyserini-fastapi #### ####", "stdout #### Download scifact.zip dataset and unzip the dataset dataset", "out run_deepct. run_deepct.FLAGS.do_train = False # We only want to", "NDCG@k, MAP@K ... logging.info(\"Retriever evaluation for k in: {}\".format(retriever.k_values)) ndcg,", "Locally run the docker Image + FastAPI #### docker_beir_pyserini =", "= \"https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip\" out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\") bert_base_dir = util.download_and_unzip(base_model_url, out_dir)", "\"corpus.jsonl\") # Provide original path to corpus data, follow beir", "below to install DeepCT: 1. git clone https://github.com/NThakur20/DeepCT.git Since Anserini", "and structure to adapt to BEIR formats. For more details", "ndcg, _map, recall, precision = retriever.evaluate(qrels, results, retriever.k_values) #### Retrieval", "identical to qrels) # results = json.loads(requests.post(docker_beir_pyserini + \"/lexical/rm3/batch_search/\", json=payload).text)[\"results\"]", "#### 1. Download Google BERT-BASE, Uncased model #### # Ref:", "results (format of results is identical to qrels) # results", "run_deepct.FLAGS.output_file = \"deepct.jsonl\" # Output file for storing final DeepCT", "= [queries[qid] for qid in qids] payload = {\"queries\": query_texts,", "only runs with TF 1.15. # We reformatted the code", "= False # We only want to use the code", "clone https://github.com/NThakur20/DeepCT.git from beir import util, LoggingHandler from beir.datasets.data_loader import", "for rank in range(10): doc_id = scores[rank][0] logging.info(\"Doc %d: %s", "MAP@K ... logging.info(\"Retriever evaluation for k in: {}\".format(retriever.k_values)) ndcg, _map,", "EvaluateRetrieval() qids = list(queries) query_texts = [queries[qid] for qid in", "out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"datasets\") data_path = util.download_and_unzip(url, out_dir) corpus, queries,", "\"http://127.0.0.1:8000\" #### Upload Multipart-encoded files #### with open(os.path.join(data_path, \"deepct.jsonl\"), \"rb\")", "json.loads(requests.post(docker_beir_pyserini + \"/lexical/batch_search/\", json=payload).text)[\"results\"] #### Retrieve RM3 expanded pyserini results", "if not os.path.isfile(os.path.join(data_path, \"deepct.jsonl\")): ################################ #### Command-Line Arugments #### ################################", "code, only few input/output file format and structure to adapt", "(1.15). We modified the DeepCT repository to work with Tensorflow", "the steps below to install DeepCT: 1. git clone https://github.com/NThakur20/DeepCT.git", "the original Repo (https://github.com/AdeDZY/DeepCT) as it only runs with TF", "0.7}} #### Retrieve pyserini results (format of results is identical", "print debug information to stdout logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S',", "logging import requests import random #### Just some code to", "up and running: 1. docker pull docker pull beir/pyserini-fastapi 2.", "DeepCT model for only prediction. run_deepct.FLAGS.data_dir = os.path.join(data_path, \"corpus.jsonl\") #", "Scaling parameter for DeepCT weights: scaling parameter > 0, recommend", "requests import random #### Just some code to print debug", "DeepCT Paper uses None. run_deepct.FLAGS.keep_all_terms = True # Do not", "docker installation, please follow the steps below to get docker", "DeepCT: 1. git clone https://github.com/NThakur20/DeepCT.git Since Anserini uses Java-11, we", "predict.tf_record run_deepct.FLAGS.output_file = \"deepct.jsonl\" # Output file for storing final", "url = \"https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/{}.zip\".format(dataset) out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"datasets\") data_path = util.download_and_unzip(url,", "query_texts, \"qids\": qids, \"k\": max(retriever.k_values), \"fields\": {\"contents\": 1.0}, \"bm25\": {\"k1\":", "\"datasets\") data_path = util.download_and_unzip(url, out_dir) corpus, queries, qrels = GenericDataLoader(data_path).load(split=\"test\")", "repository to work with Tensorflow latest (2.x). We do not", "Anserini) in BEIR. For more details on DeepCT, refer here:", "deepct.jsonl (output-file) and predict.tf_record run_deepct.FLAGS.output_file = \"deepct.jsonl\" # Output file", "= \"http://boston.lti.cs.cmu.edu/appendices/arXiv2019-DeepCT-Zhuyun-Dai/outputs/marco.zip\" out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\") checkpoint_dir = util.download_and_unzip(model_url, out_dir)", "\"\"\" This example shows how to evaluate DeepCT (using Anserini)", "After docker installation, please follow the steps below to get", "data, follow beir format. run_deepct.FLAGS.vocab_file = os.path.join(bert_base_dir, \"vocab.txt\") # Provide", "run_deepct.FLAGS.vocab_file = os.path.join(bert_base_dir, \"vocab.txt\") # Provide bert-base-uncased model vocabulary. run_deepct.FLAGS.bert_config_file", "with open(os.path.join(data_path, \"deepct.jsonl\"), \"rb\") as fIn: r = requests.post(docker_beir_pyserini +", "file format and structure to adapt to BEIR formats. For", "to smooth weights. DeepCT Paper uses None. run_deepct.FLAGS.keep_all_terms = True", "corpus. run_deepct.FLAGS.m = 100 # Scaling parameter for DeepCT weights:", "#### Just some code to print debug information to stdout", "compare it with original repo! Please follow the steps below", "import util, LoggingHandler from beir.datasets.data_loader import GenericDataLoader from beir.retrieval.evaluation import", "Just some code to print debug information to stdout logging.basicConfig(format='%(asctime)s", "bert-base-uncased model vocabulary. run_deepct.FLAGS.bert_config_file = os.path.join(bert_base_dir, \"bert_config.json\") # Provide bert-base-uncased", "to evaluate DeepCT (using Anserini) in BEIR. For more details", "# Inference batch size, Larger more Memory but faster! run_deepct.FLAGS.output_dir", "Ref: https://github.com/google-research/bert base_model_url = \"https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip\" out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\") bert_base_dir", "We modified the DeepCT repository to work with Tensorflow latest", "retriever.k_values) #### Retrieval Example #### query_id, scores_dict = random.choice(list(results.items())) logging.info(\"Query", "(format of results is identical to qrels) # results =", "on changes, check: https://github.com/NThakur20/DeepCT and compare it with original repo!", "1.15. # We reformatted the code (https://github.com/NThakur20/DeepCT) and made it", "################################ #### Command-Line Arugments #### ################################ run_deepct.FLAGS.task_name = \"beir\" #", "MSMARCO Trained BERT checkpoint #### # Credits to DeepCT authors:", "your retrieval using NDCG@k, MAP@K ... logging.info(\"Retriever evaluation for k", "/print debug information to stdout #### Download scifact.zip dataset and", "(https://github.com/AdeDZY/DeepCT) model_url = \"http://boston.lti.cs.cmu.edu/appendices/arXiv2019-DeepCT-Zhuyun-Dai/outputs/marco.zip\" out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\") checkpoint_dir =", "Check out run_deepct. run_deepct.FLAGS.do_train = False # We only want", "# Provide original path to corpus data, follow beir format.", "Retrieve documents from Pyserini ##### retriever = EvaluateRetrieval() qids =", "= scores[rank][0] logging.info(\"Doc %d: %s [%s] - %s\\n\" % (rank+1,", "docker container up and running: 1. docker pull docker pull", "using NDCG@k, MAP@K ... logging.info(\"Retriever evaluation for k in: {}\".format(retriever.k_values))", "= 350 # Provide Max Sequence Length used for consideration.", "corpus.jsonl run_deepct.main() #### Download Docker Image beir/pyserini-fastapi #### #### Locally", "= {\"queries\": query_texts, \"qids\": qids, \"k\": max(retriever.k_values), \"fields\": {\"contents\": 1.0},", "docker run -p 8000:8000 -it --rm pyserini-fastapi Usage: python evaluate_deepct.py", "https://arxiv.org/abs/1910.10687 The original DeepCT repository is not modularised and only", "= 100 # Scaling parameter for DeepCT weights: scaling parameter", "\"models\") checkpoint_dir = util.download_and_unzip(model_url, out_dir) ################################################## #### 3. Configure Params", "\"models\") bert_base_dir = util.download_and_unzip(base_model_url, out_dir) #### 2. Download DeepCT MSMARCO", "= \"http://127.0.0.1:8000\" #### Upload Multipart-encoded files #### with open(os.path.join(data_path, \"deepct.jsonl\"),", "install DeepCT: 1. git clone https://github.com/NThakur20/DeepCT.git Since Anserini uses Java-11,", "original repo! Please follow the steps below to install DeepCT:", "docker pull docker pull beir/pyserini-fastapi 2. docker build -t pyserini-fastapi", "# results = json.loads(requests.post(docker_beir_pyserini + \"/lexical/rm3/batch_search/\", json=payload).text)[\"results\"] #### Evaluate your", "DeepCT produced corpus. run_deepct.FLAGS.m = 100 # Scaling parameter for", "to qrels) results = json.loads(requests.post(docker_beir_pyserini + \"/lexical/batch_search/\", json=payload).text)[\"results\"] #### Retrieve", "few input/output file format and structure to adapt to BEIR", "to adapt to BEIR formats. For more details on changes,", "contain two files: deepct.jsonl (output-file) and predict.tf_record run_deepct.FLAGS.output_file = \"deepct.jsonl\"", "docker locally installed in your machine. To install docker on", "is not modularised and only works with Tensorflow 1.x (1.15).", "# Output directory, this will contain two files: deepct.jsonl (output-file)", "100 run_deepct.FLAGS.smoothing = \"sqrt\" # Use sqrt to smooth weights.", "###################################### #### Retrieve documents from Pyserini ##### retriever = EvaluateRetrieval()", "json.loads(requests.post(docker_beir_pyserini + \"/lexical/rm3/batch_search/\", json=payload).text)[\"results\"] #### Evaluate your retrieval using NDCG@k,", "\"https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/{}.zip\".format(dataset) out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"datasets\") data_path = util.download_and_unzip(url, out_dir) corpus,", "https://github.com/google-research/bert base_model_url = \"https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip\" out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\") bert_base_dir =", "with original repo! Please follow the steps below to install", "Retrieval Example #### query_id, scores_dict = random.choice(list(results.items())) logging.info(\"Query : %s\\n\"", "(Max: 512) run_deepct.FLAGS.train_batch_size = 128 # Inference batch size, Larger", "= True # Do not allow DeepCT to delete terms.", "beir format. run_deepct.FLAGS.vocab_file = os.path.join(bert_base_dir, \"vocab.txt\") # Provide bert-base-uncased model", "docker pull beir/pyserini-fastapi 2. docker build -t pyserini-fastapi . 3.", "how to evaluate DeepCT (using Anserini) in BEIR. For more", "\"beir\" # Defined a seperate BEIR task in DeepCT. Check", "run_deepct.FLAGS.init_checkpoint = os.path.join(checkpoint_dir, \"model.ckpt-65816\") # Provide DeepCT MSMARCO model (bert-base-uncased)", "#### ###################################### #### Retrieve documents from Pyserini ##### retriever =", "qid in qids] payload = {\"queries\": query_texts, \"qids\": qids, \"k\":", "DeepCT repository to work with Tensorflow latest (2.x). We do", "--rm pyserini-fastapi Usage: python evaluate_deepct.py \"\"\" from DeepCT.deepct import run_deepct", "run_deepct.FLAGS.bert_config_file = os.path.join(bert_base_dir, \"bert_config.json\") # Provide bert-base-uncased config.json file. run_deepct.FLAGS.init_checkpoint", "import logging import requests import random #### Just some code", "EvaluateRetrieval from beir.generation.models import QGenModel from tqdm.autonotebook import trange import", "code (https://github.com/NThakur20/DeepCT) and made it working with latest TF 2.X!", "\"sqrt\" # Use sqrt to smooth weights. DeepCT Paper uses", "cannot use the original Repo (https://github.com/AdeDZY/DeepCT) as it only runs", "json=payload).text)[\"results\"] #### Retrieve RM3 expanded pyserini results (format of results", "only works with Tensorflow 1.x (1.15). We modified the DeepCT", "run_deepct.FLAGS.max_seq_length = 350 # Provide Max Sequence Length used for", "level=logging.INFO, handlers=[LoggingHandler()]) #### /print debug information to stdout #### Download", "= requests.get(docker_beir_pyserini + \"/index/\", params={\"index_name\": index_name}) ###################################### #### 2. Pyserini-Retrieval", "os, json import logging import requests import random #### Just", "would advise you to use docker for running Pyserini. To", "follow the steps below to get docker container up and", "prediction. run_deepct.FLAGS.data_dir = os.path.join(data_path, \"corpus.jsonl\") # Provide original path to", "beir/scifact r = requests.get(docker_beir_pyserini + \"/index/\", params={\"index_name\": index_name}) ###################################### ####", "beir.retrieval.evaluation import EvaluateRetrieval from beir.generation.models import QGenModel from tqdm.autonotebook import", "\"b\": 0.7}} #### Retrieve pyserini results (format of results is", "Tensorflow 1.x (1.15). We modified the DeepCT repository to work", "Trained BERT checkpoint #### # Credits to DeepCT authors: <NAME>,", "original Repo (https://github.com/AdeDZY/DeepCT) as it only runs with TF 1.15.", "Credits to DeepCT authors: <NAME>, <NAME>, (https://github.com/AdeDZY/DeepCT) model_url = \"http://boston.lti.cs.cmu.edu/appendices/arXiv2019-DeepCT-Zhuyun-Dai/outputs/marco.zip\"", "dataset dataset = \"scifact\" url = \"https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/{}.zip\".format(dataset) out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(),", "= \"deepct.jsonl\" # Output file for storing final DeepCT produced", "= \"https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/{}.zip\".format(dataset) out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"datasets\") data_path = util.download_and_unzip(url, out_dir)", "+ FastAPI #### docker_beir_pyserini = \"http://127.0.0.1:8000\" #### Upload Multipart-encoded files", "{\"contents\": 1.0}, \"bm25\": {\"k1\": 18, \"b\": 0.7}} #### Retrieve pyserini", "_map, recall, precision = retriever.evaluate(qrels, results, retriever.k_values) #### Retrieval Example", "https://github.com/NThakur20/DeepCT.git Since Anserini uses Java-11, we would advise you to", "to Pyserini ##### index_name = \"beir/you-index-name\" # beir/scifact r =", "import requests import random #### Just some code to print", "GenericDataLoader(data_path).load(split=\"test\") #### 1. Download Google BERT-BASE, Uncased model #### #", "size, Larger more Memory but faster! run_deepct.FLAGS.output_dir = data_path #", "this will contain two files: deepct.jsonl (output-file) and predict.tf_record run_deepct.FLAGS.output_file", "= os.path.join(data_path, \"corpus.jsonl\") # Provide original path to corpus data,", "True, as we would use DeepCT model for only prediction.", "Pyserini. To be able to run the code below you", "\"k\": max(retriever.k_values), \"fields\": {\"contents\": 1.0}, \"bm25\": {\"k1\": 18, \"b\": 0.7}}", "want to use the code for inference. run_deepct.FLAGS.do_eval = False", "machine. To install docker on your local machine, please refer", "= \"beir\" # Defined a seperate BEIR task in DeepCT.", "corpus data, follow beir format. run_deepct.FLAGS.vocab_file = os.path.join(bert_base_dir, \"vocab.txt\") #", "(output-file) and predict.tf_record run_deepct.FLAGS.output_file = \"deepct.jsonl\" # Output file for", "%s\\n\" % queries[query_id]) scores = sorted(scores_dict.items(), key=lambda item: item[1], reverse=True)", "storing final DeepCT produced corpus. run_deepct.FLAGS.m = 100 # Scaling", "= util.download_and_unzip(base_model_url, out_dir) #### 2. Download DeepCT MSMARCO Trained BERT", "to print debug information to stdout logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d", "to use docker for running Pyserini. To be able to", "DeepCT. Check out run_deepct. run_deepct.FLAGS.do_train = False # We only", "scaling parameter > 0, recommend 100 run_deepct.FLAGS.smoothing = \"sqrt\" #", "adapt to BEIR formats. For more details on changes, check:", "(2.x). We do not change the core-prediction code, only few", "weights. DeepCT Paper uses None. run_deepct.FLAGS.keep_all_terms = True # Do", "please follow the steps below to get docker container up", "DeepCT.deepct import run_deepct # git clone https://github.com/NThakur20/DeepCT.git from beir import", "2. docker build -t pyserini-fastapi . 3. docker run -p", "GenericDataLoader from beir.retrieval.evaluation import EvaluateRetrieval from beir.generation.models import QGenModel from", "the steps below to get docker container up and running:", "#### Retrieve documents from Pyserini ##### retriever = EvaluateRetrieval() qids", "to run the code below you must have docker locally", "some code to print debug information to stdout logging.basicConfig(format='%(asctime)s -", "in BEIR. For more details on DeepCT, refer here: https://arxiv.org/abs/1910.10687", "import QGenModel from tqdm.autonotebook import trange import pathlib, os, json", "DeepCT inference #### ################################################## # We cannot use the original", "###################################### #### 2. Pyserini-Retrieval (BM25) #### ###################################### #### Retrieve documents", "-t pyserini-fastapi . 3. docker run -p 8000:8000 -it --rm", "only want to use the code for inference. run_deepct.FLAGS.do_eval =", "= \"scifact\" url = \"https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/{}.zip\".format(dataset) out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"datasets\") data_path", "docker build -t pyserini-fastapi . 3. docker run -p 8000:8000", "<gh_stars>10-100 \"\"\" This example shows how to evaluate DeepCT (using", "model (bert-base-uncased) checkpoint file. run_deepct.FLAGS.max_seq_length = 350 # Provide Max", "index_name = \"beir/you-index-name\" # beir/scifact r = requests.get(docker_beir_pyserini + \"/index/\",", "Sequence Length used for consideration. (Max: 512) run_deepct.FLAGS.train_batch_size = 128", "Pyserini ##### index_name = \"beir/you-index-name\" # beir/scifact r = requests.get(docker_beir_pyserini", "= os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\") checkpoint_dir = util.download_and_unzip(model_url, out_dir) ################################################## #### 3.", "Provide original path to corpus data, follow beir format. run_deepct.FLAGS.vocab_file", "run_deepct.FLAGS.train_batch_size = 128 # Inference batch size, Larger more Memory", "Params for DeepCT inference #### ################################################## # We cannot use", "and made it working with latest TF 2.X! if not", "bert-base-uncased config.json file. run_deepct.FLAGS.init_checkpoint = os.path.join(checkpoint_dir, \"model.ckpt-65816\") # Provide DeepCT", "input/output file format and structure to adapt to BEIR formats.", "clone https://github.com/NThakur20/DeepCT.git Since Anserini uses Java-11, we would advise you", "handlers=[LoggingHandler()]) #### /print debug information to stdout #### Download scifact.zip", "We reformatted the code (https://github.com/NThakur20/DeepCT) and made it working with", "machine, please refer here: https://docs.docker.com/get-docker/ After docker installation, please follow", "\"/upload/\", files={\"file\": fIn}, verify=False) #### Index documents to Pyserini #####", "and running: 1. docker pull docker pull beir/pyserini-fastapi 2. docker", "Download DeepCT MSMARCO Trained BERT checkpoint #### # Credits to", "model #### # Ref: https://github.com/google-research/bert base_model_url = \"https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip\" out_dir =", "it only runs with TF 1.15. # We reformatted the", "file. run_deepct.FLAGS.init_checkpoint = os.path.join(checkpoint_dir, \"model.ckpt-65816\") # Provide DeepCT MSMARCO model", "do not change the core-prediction code, only few input/output file", "\"bm25\": {\"k1\": 18, \"b\": 0.7}} #### Retrieve pyserini results (format", "to qrels) # results = json.loads(requests.post(docker_beir_pyserini + \"/lexical/rm3/batch_search/\", json=payload).text)[\"results\"] ####", "out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\") bert_base_dir = util.download_and_unzip(base_model_url, out_dir) #### 2.", "list(queries) query_texts = [queries[qid] for qid in qids] payload =", "git clone https://github.com/NThakur20/DeepCT.git Since Anserini uses Java-11, we would advise", "1. docker pull docker pull beir/pyserini-fastapi 2. docker build -t", "\"https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip\" out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\") bert_base_dir = util.download_and_unzip(base_model_url, out_dir) ####", "work with Tensorflow latest (2.x). We do not change the", "\"model.ckpt-65816\") # Provide DeepCT MSMARCO model (bert-base-uncased) checkpoint file. run_deepct.FLAGS.max_seq_length", "= json.loads(requests.post(docker_beir_pyserini + \"/lexical/batch_search/\", json=payload).text)[\"results\"] #### Retrieve RM3 expanded pyserini", "to BEIR formats. For more details on changes, check: https://github.com/NThakur20/DeepCT", "build -t pyserini-fastapi . 3. docker run -p 8000:8000 -it", "docker Image + FastAPI #### docker_beir_pyserini = \"http://127.0.0.1:8000\" #### Upload", "QGenModel from tqdm.autonotebook import trange import pathlib, os, json import", "have docker locally installed in your machine. To install docker", "[queries[qid] for qid in qids] payload = {\"queries\": query_texts, \"qids\":", "in your machine. To install docker on your local machine,", "details on changes, check: https://github.com/NThakur20/DeepCT and compare it with original", "# Provide DeepCT MSMARCO model (bert-base-uncased) checkpoint file. run_deepct.FLAGS.max_seq_length =", "<NAME>, (https://github.com/AdeDZY/DeepCT) model_url = \"http://boston.lti.cs.cmu.edu/appendices/arXiv2019-DeepCT-Zhuyun-Dai/outputs/marco.zip\" out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\") checkpoint_dir", "\"bert_config.json\") # Provide bert-base-uncased config.json file. run_deepct.FLAGS.init_checkpoint = os.path.join(checkpoint_dir, \"model.ckpt-65816\")", "logging.info(\"Query : %s\\n\" % queries[query_id]) scores = sorted(scores_dict.items(), key=lambda item:", "util.download_and_unzip(url, out_dir) corpus, queries, qrels = GenericDataLoader(data_path).load(split=\"test\") #### 1. Download", "for storing final DeepCT produced corpus. run_deepct.FLAGS.m = 100 #", "logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO, handlers=[LoggingHandler()]) #### /print debug", "> 0, recommend 100 run_deepct.FLAGS.smoothing = \"sqrt\" # Use sqrt", "details on DeepCT, refer here: https://arxiv.org/abs/1910.10687 The original DeepCT repository", "example shows how to evaluate DeepCT (using Anserini) in BEIR.", "with Tensorflow latest (2.x). We do not change the core-prediction", "information to stdout #### Download scifact.zip dataset and unzip the", "# Do not allow DeepCT to delete terms. # Runs", "pyserini results (format of results is identical to qrels) #", "# We reformatted the code (https://github.com/NThakur20/DeepCT) and made it working", "import GenericDataLoader from beir.retrieval.evaluation import EvaluateRetrieval from beir.generation.models import QGenModel", "\"/index/\", params={\"index_name\": index_name}) ###################################### #### 2. Pyserini-Retrieval (BM25) #### ######################################", "parameter for DeepCT weights: scaling parameter > 0, recommend 100", "os.path.join(pathlib.Path(__file__).parent.absolute(), \"datasets\") data_path = util.download_and_unzip(url, out_dir) corpus, queries, qrels =", "MSMARCO model (bert-base-uncased) checkpoint file. run_deepct.FLAGS.max_seq_length = 350 # Provide", "smooth weights. DeepCT Paper uses None. run_deepct.FLAGS.keep_all_terms = True #", "repository is not modularised and only works with Tensorflow 1.x", "must have docker locally installed in your machine. To install", "Arugments #### ################################ run_deepct.FLAGS.task_name = \"beir\" # Defined a seperate", "a seperate BEIR task in DeepCT. Check out run_deepct. run_deepct.FLAGS.do_train", "produced corpus. run_deepct.FLAGS.m = 100 # Scaling parameter for DeepCT", "#### Download scifact.zip dataset and unzip the dataset dataset =", "identical to qrels) results = json.loads(requests.post(docker_beir_pyserini + \"/lexical/batch_search/\", json=payload).text)[\"results\"] ####", "BEIR. For more details on DeepCT, refer here: https://arxiv.org/abs/1910.10687 The", "data_path = util.download_and_unzip(url, out_dir) corpus, queries, qrels = GenericDataLoader(data_path).load(split=\"test\") ####", "{\"queries\": query_texts, \"qids\": qids, \"k\": max(retriever.k_values), \"fields\": {\"contents\": 1.0}, \"bm25\":", "0, recommend 100 run_deepct.FLAGS.smoothing = \"sqrt\" # Use sqrt to", "logging.info(\"Doc %d: %s [%s] - %s\\n\" % (rank+1, doc_id, corpus[doc_id].get(\"title\"),", "config.json file. run_deepct.FLAGS.init_checkpoint = os.path.join(checkpoint_dir, \"model.ckpt-65816\") # Provide DeepCT MSMARCO", "file. run_deepct.FLAGS.max_seq_length = 350 # Provide Max Sequence Length used", "modified the DeepCT repository to work with Tensorflow latest (2.x).", "qids] payload = {\"queries\": query_texts, \"qids\": qids, \"k\": max(retriever.k_values), \"fields\":", "False # No evaluation. run_deepct.FLAGS.do_predict = True # True, as", "Max Sequence Length used for consideration. (Max: 512) run_deepct.FLAGS.train_batch_size =", "more details on changes, check: https://github.com/NThakur20/DeepCT and compare it with", "of results is identical to qrels) results = json.loads(requests.post(docker_beir_pyserini +", "+ \"/lexical/batch_search/\", json=payload).text)[\"results\"] #### Retrieve RM3 expanded pyserini results (format", "pull beir/pyserini-fastapi 2. docker build -t pyserini-fastapi . 3. docker", "out_dir) corpus, queries, qrels = GenericDataLoader(data_path).load(split=\"test\") #### 1. Download Google", "Configure Params for DeepCT inference #### ################################################## # We cannot", "qrels) # results = json.loads(requests.post(docker_beir_pyserini + \"/lexical/rm3/batch_search/\", json=payload).text)[\"results\"] #### Evaluate", "# beir/scifact r = requests.get(docker_beir_pyserini + \"/index/\", params={\"index_name\": index_name}) ######################################", "= GenericDataLoader(data_path).load(split=\"test\") #### 1. Download Google BERT-BASE, Uncased model ####", "Provide DeepCT MSMARCO model (bert-base-uncased) checkpoint file. run_deepct.FLAGS.max_seq_length = 350", "checkpoint_dir = util.download_and_unzip(model_url, out_dir) ################################################## #### 3. Configure Params for", "# No evaluation. run_deepct.FLAGS.do_predict = True # True, as we", "parameter > 0, recommend 100 run_deepct.FLAGS.smoothing = \"sqrt\" # Use", "to DeepCT authors: <NAME>, <NAME>, (https://github.com/AdeDZY/DeepCT) model_url = \"http://boston.lti.cs.cmu.edu/appendices/arXiv2019-DeepCT-Zhuyun-Dai/outputs/marco.zip\" out_dir", "run_deepct.FLAGS.do_predict = True # True, as we would use DeepCT", "\"deepct.jsonl\" # Output file for storing final DeepCT produced corpus.", "import run_deepct # git clone https://github.com/NThakur20/DeepCT.git from beir import util,", "would use DeepCT model for only prediction. run_deepct.FLAGS.data_dir = os.path.join(data_path,", "your machine. To install docker on your local machine, please", "# Provide bert-base-uncased config.json file. run_deepct.FLAGS.init_checkpoint = os.path.join(checkpoint_dir, \"model.ckpt-65816\") #", "installed in your machine. To install docker on your local", "# Ref: https://github.com/google-research/bert base_model_url = \"https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip\" out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\")", "inference #### ################################################## # We cannot use the original Repo", "run_deepct.FLAGS.do_eval = False # No evaluation. run_deepct.FLAGS.do_predict = True #", "import EvaluateRetrieval from beir.generation.models import QGenModel from tqdm.autonotebook import trange", "for only prediction. run_deepct.FLAGS.data_dir = os.path.join(data_path, \"corpus.jsonl\") # Provide original", "git clone https://github.com/NThakur20/DeepCT.git from beir import util, LoggingHandler from beir.datasets.data_loader", "debug information to stdout logging.basicConfig(format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO,", "qids, \"k\": max(retriever.k_values), \"fields\": {\"contents\": 1.0}, \"bm25\": {\"k1\": 18, \"b\":", "only few input/output file format and structure to adapt to", "running Pyserini. To be able to run the code below", "model on the corpus.jsonl run_deepct.main() #### Download Docker Image beir/pyserini-fastapi", "terms. # Runs DeepCT model on the corpus.jsonl run_deepct.main() ####", "you must have docker locally installed in your machine. To", "BERT checkpoint #### # Credits to DeepCT authors: <NAME>, <NAME>,", "but faster! run_deepct.FLAGS.output_dir = data_path # Output directory, this will", "for DeepCT weights: scaling parameter > 0, recommend 100 run_deepct.FLAGS.smoothing", "key=lambda item: item[1], reverse=True) for rank in range(10): doc_id =", "json import logging import requests import random #### Just some", "For more details on changes, check: https://github.com/NThakur20/DeepCT and compare it", "files #### with open(os.path.join(data_path, \"deepct.jsonl\"), \"rb\") as fIn: r =", "on your local machine, please refer here: https://docs.docker.com/get-docker/ After docker", "on the corpus.jsonl run_deepct.main() #### Download Docker Image beir/pyserini-fastapi ####", "model vocabulary. run_deepct.FLAGS.bert_config_file = os.path.join(bert_base_dir, \"bert_config.json\") # Provide bert-base-uncased config.json", "None. run_deepct.FLAGS.keep_all_terms = True # Do not allow DeepCT to", "pyserini results (format of results is identical to qrels) results", "os.path.join(data_path, \"corpus.jsonl\") # Provide original path to corpus data, follow", "docker on your local machine, please refer here: https://docs.docker.com/get-docker/ After", "BEIR task in DeepCT. Check out run_deepct. run_deepct.FLAGS.do_train = False", "True # True, as we would use DeepCT model for", "with TF 1.15. # We reformatted the code (https://github.com/NThakur20/DeepCT) and", "not os.path.isfile(os.path.join(data_path, \"deepct.jsonl\")): ################################ #### Command-Line Arugments #### ################################ run_deepct.FLAGS.task_name", "#### # Ref: https://github.com/google-research/bert base_model_url = \"https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip\" out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(),", "\"fields\": {\"contents\": 1.0}, \"bm25\": {\"k1\": 18, \"b\": 0.7}} #### Retrieve", "Retrieve RM3 expanded pyserini results (format of results is identical", "Paper uses None. run_deepct.FLAGS.keep_all_terms = True # Do not allow", "Pyserini ##### retriever = EvaluateRetrieval() qids = list(queries) query_texts =", "= os.path.join(bert_base_dir, \"bert_config.json\") # Provide bert-base-uncased config.json file. run_deepct.FLAGS.init_checkpoint =", "from beir.generation.models import QGenModel from tqdm.autonotebook import trange import pathlib,", "DeepCT model on the corpus.jsonl run_deepct.main() #### Download Docker Image", "1. Download Google BERT-BASE, Uncased model #### # Ref: https://github.com/google-research/bert", "to stdout #### Download scifact.zip dataset and unzip the dataset", "#### with open(os.path.join(data_path, \"deepct.jsonl\"), \"rb\") as fIn: r = requests.post(docker_beir_pyserini", "with latest TF 2.X! if not os.path.isfile(os.path.join(data_path, \"deepct.jsonl\")): ################################ ####", "DeepCT weights: scaling parameter > 0, recommend 100 run_deepct.FLAGS.smoothing =", "Repo (https://github.com/AdeDZY/DeepCT) as it only runs with TF 1.15. #", "... logging.info(\"Retriever evaluation for k in: {}\".format(retriever.k_values)) ndcg, _map, recall,", "final DeepCT produced corpus. run_deepct.FLAGS.m = 100 # Scaling parameter", "\"scifact\" url = \"https://public.ukp.informatik.tu-darmstadt.de/thakur/BEIR/datasets/{}.zip\".format(dataset) out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"datasets\") data_path =", "as it only runs with TF 1.15. # We reformatted", "os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\") checkpoint_dir = util.download_and_unzip(model_url, out_dir) ################################################## #### 3. Configure", "debug information to stdout #### Download scifact.zip dataset and unzip", "import random #### Just some code to print debug information", "(BM25) #### ###################################### #### Retrieve documents from Pyserini ##### retriever", "beir import util, LoggingHandler from beir.datasets.data_loader import GenericDataLoader from beir.retrieval.evaluation", "the DeepCT repository to work with Tensorflow latest (2.x). We", "checkpoint #### # Credits to DeepCT authors: <NAME>, <NAME>, (https://github.com/AdeDZY/DeepCT)", "%H:%M:%S', level=logging.INFO, handlers=[LoggingHandler()]) #### /print debug information to stdout ####", "# Runs DeepCT model on the corpus.jsonl run_deepct.main() #### Download", "Usage: python evaluate_deepct.py \"\"\" from DeepCT.deepct import run_deepct # git", "(https://github.com/AdeDZY/DeepCT) as it only runs with TF 1.15. # We", "use the original Repo (https://github.com/AdeDZY/DeepCT) as it only runs with", "(format of results is identical to qrels) results = json.loads(requests.post(docker_beir_pyserini", "for qid in qids] payload = {\"queries\": query_texts, \"qids\": qids,", "os.path.join(checkpoint_dir, \"model.ckpt-65816\") # Provide DeepCT MSMARCO model (bert-base-uncased) checkpoint file.", "+ \"/lexical/rm3/batch_search/\", json=payload).text)[\"results\"] #### Evaluate your retrieval using NDCG@k, MAP@K", "we would use DeepCT model for only prediction. run_deepct.FLAGS.data_dir =", "run_deepct.FLAGS.task_name = \"beir\" # Defined a seperate BEIR task in", "locally installed in your machine. To install docker on your", "payload = {\"queries\": query_texts, \"qids\": qids, \"k\": max(retriever.k_values), \"fields\": {\"contents\":", "qrels = GenericDataLoader(data_path).load(split=\"test\") #### 1. Download Google BERT-BASE, Uncased model", "https://github.com/NThakur20/DeepCT.git from beir import util, LoggingHandler from beir.datasets.data_loader import GenericDataLoader", "base_model_url = \"https://storage.googleapis.com/bert_models/2018_10_18/uncased_L-12_H-768_A-12.zip\" out_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), \"models\") bert_base_dir = util.download_and_unzip(base_model_url,", "Since Anserini uses Java-11, we would advise you to use", "#### ################################ run_deepct.FLAGS.task_name = \"beir\" # Defined a seperate BEIR", "Output directory, this will contain two files: deepct.jsonl (output-file) and", "open(os.path.join(data_path, \"deepct.jsonl\"), \"rb\") as fIn: r = requests.post(docker_beir_pyserini + \"/upload/\",", "= os.path.join(bert_base_dir, \"vocab.txt\") # Provide bert-base-uncased model vocabulary. run_deepct.FLAGS.bert_config_file =", "To be able to run the code below you must", "corpus, queries, qrels = GenericDataLoader(data_path).load(split=\"test\") #### 1. Download Google BERT-BASE,", "run_deepct.FLAGS.smoothing = \"sqrt\" # Use sqrt to smooth weights. DeepCT", "= False # No evaluation. run_deepct.FLAGS.do_predict = True # True,", "#### 2. Download DeepCT MSMARCO Trained BERT checkpoint #### #", "file for storing final DeepCT produced corpus. run_deepct.FLAGS.m = 100", "change the core-prediction code, only few input/output file format and", "core-prediction code, only few input/output file format and structure to", "precision = retriever.evaluate(qrels, results, retriever.k_values) #### Retrieval Example #### query_id,", "+ \"/index/\", params={\"index_name\": index_name}) ###################################### #### 2. Pyserini-Retrieval (BM25) ####", "latest TF 2.X! if not os.path.isfile(os.path.join(data_path, \"deepct.jsonl\")): ################################ #### Command-Line", "used for consideration. (Max: 512) run_deepct.FLAGS.train_batch_size = 128 # Inference", "#### /print debug information to stdout #### Download scifact.zip dataset", "No evaluation. run_deepct.FLAGS.do_predict = True # True, as we would", "to corpus data, follow beir format. run_deepct.FLAGS.vocab_file = os.path.join(bert_base_dir, \"vocab.txt\")", ". 3. docker run -p 8000:8000 -it --rm pyserini-fastapi Usage:", "pyserini-fastapi . 3. docker run -p 8000:8000 -it --rm pyserini-fastapi", "datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO, handlers=[LoggingHandler()]) #### /print debug information to stdout", "in: {}\".format(retriever.k_values)) ndcg, _map, recall, precision = retriever.evaluate(qrels, results, retriever.k_values)", "This example shows how to evaluate DeepCT (using Anserini) in", "#### Command-Line Arugments #### ################################ run_deepct.FLAGS.task_name = \"beir\" # Defined", "model for only prediction. run_deepct.FLAGS.data_dir = os.path.join(data_path, \"corpus.jsonl\") # Provide", "= retriever.evaluate(qrels, results, retriever.k_values) #### Retrieval Example #### query_id, scores_dict", "= requests.post(docker_beir_pyserini + \"/upload/\", files={\"file\": fIn}, verify=False) #### Index documents", "https://docs.docker.com/get-docker/ After docker installation, please follow the steps below to", "is identical to qrels) results = json.loads(requests.post(docker_beir_pyserini + \"/lexical/batch_search/\", json=payload).text)[\"results\"]", "% queries[query_id]) scores = sorted(scores_dict.items(), key=lambda item: item[1], reverse=True) for", "{}\".format(retriever.k_values)) ndcg, _map, recall, precision = retriever.evaluate(qrels, results, retriever.k_values) ####", "local machine, please refer here: https://docs.docker.com/get-docker/ After docker installation, please", "recall, precision = retriever.evaluate(qrels, results, retriever.k_values) #### Retrieval Example ####", "# Use sqrt to smooth weights. DeepCT Paper uses None." ]
[ "# Because the members in this example are nearly rigid,", "this example are nearly rigid, there will be virtually no", "100, 100, 100, 100, 100) truss.AddMember('BC', 'B', 'C', E, 100,", "Mechanics: Statics, 4th Edition # <NAME> # Problem 6.64 #", "False, True, True) truss.DefineReleases('BD', False, False, False, False, True, True,", "very large value E = 99999999 truss.AddMember('AB', 'A', 'B', E,", "100, 100) truss.AddMember('BE', 'B', 'E', E, 100, 100, 100, 100,", "be virtually no deformation. The deformed shape won't be rendered.", "used # To make all the members act rigid, the", "the members to make truss members truss.DefineReleases('AC', False, False, False,", "a very large value E = 99999999 truss.AddMember('AB', 'A', 'B',", "1, 0, 0) truss.AddNode('C', 0, 0, 0.6) truss.AddNode('D', 0, 0,", "rigid, there will be virtually no deformation. The deformed shape", "from PyNite import FEModel3D from PyNite import Visualization # Create", "0, 0) truss.AddNode('C', 0, 0, 0.6) truss.AddNode('D', 0, 0, -0.4)", "str(truss.GetMember('BD').MaxAxial())) print('Member BD expected axial force: 45.2 Tension') print('Member BE", "45.2 Tension') print('Member BE calculated axial force: ' + str(truss.GetMember('BE').MaxAxial()))", "a default load case 'Case 1' and a default load", "axial force: ' + str(truss.GetMember('BE').MaxAxial())) print('Member BE expected axial force:", "the modulus of elasticity will be set to a very", "True, True, \\ False, False, False, False, True, True) truss.DefineReleases('BE',", "'Case 1' and a default load combo 'Combo 1' since", "100, 100) truss.AddMember('BC', 'B', 'C', E, 100, 100, 100, 100,", "str(truss.GetMember('BE').MaxAxial())) print('Member BE expected axial force: 112.1 Compression') # Render", "FEModel3D from PyNite import Visualization # Create a new model", "make truss members truss.DefineReleases('AC', False, False, False, False, True, True,", "'FEModel3D' and 'Visualization' from 'PyNite' from PyNite import FEModel3D from", "BC calculated axial force: ' + str(truss.GetMember('BC').MaxAxial())) print('Member BC expected", "will be used # To make all the members act", "100) truss.AddMember('BD', 'B', 'D', E, 100, 100, 100, 100, 100)", "the model truss.Analyze() # Print results print('Member BC calculated axial", "'Visualization' from 'PyNite' from PyNite import FEModel3D from PyNite import", "rendered. # The program has created a default load case", "truss.AddNode('C', 0, 0, 0.6) truss.AddNode('D', 0, 0, -0.4) truss.AddNode('E', 0,", "set to 50 mm. # Because the members in this", "BE calculated axial force: ' + str(truss.GetMember('BE').MaxAxial())) print('Member BE expected", "-0.4) truss.AddNode('E', 0, 0.8, 0) # Define the supports truss.DefineSupport('C',", "False, False, False, True, True) truss.DefineReleases('BC', False, False, False, False,", "Load.py # Engineering Mechanics: Statics, 4th Edition # <NAME> #", "\\ False, False, False, False, True, True) truss.DefineReleases('AD', False, False,", "+ str(truss.GetMember('BD').MaxAxial())) print('Member BD expected axial force: 45.2 Tension') print('Member", "The deformed shape won't be rendered. # The program has", "100, 100, 100) truss.AddMember('AD', 'A', 'D', E, 100, 100, 100,", "be set to a very large value E = 99999999", "100, 100, 100) truss.AddMember('BC', 'B', 'C', E, 100, 100, 100,", "E, 100, 100, 100, 100, 100) truss.AddMember('AC', 'A', 'C', E,", "this problem, so assumed values will be used # To", "The program has created a default load case 'Case 1'", "large value E = 99999999 truss.AddMember('AB', 'A', 'B', E, 100,", "'FY', 60) truss.AddNodeLoad('A', 'FZ', 20) # Analyze the model truss.Analyze()", "100, 100, 100, 100) truss.AddMember('AC', 'A', 'C', E, 100, 100,", "100, 100, 100, 100) # Release the moments at the", "10) truss.AddNodeLoad('A', 'FY', 60) truss.AddNodeLoad('A', 'FZ', 20) # Analyze the", "and 'Visualization' from 'PyNite' from PyNite import FEModel3D from PyNite", "'B', 'C', E, 100, 100, 100, 100, 100) truss.AddMember('BD', 'B',", "0, 0, -0.4) truss.AddNode('E', 0, 0.8, 0) # Define the", "60) truss.AddNodeLoad('A', 'FZ', 20) # Analyze the model truss.Analyze() #", "PyNite import Visualization # Create a new model truss =", "100) # Release the moments at the ends of the", "False, False, True, True) truss.DefineReleases('BE', False, False, False, False, True,", "has created a default load case 'Case 1' and a", "'D', E, 100, 100, 100, 100, 100) truss.AddMember('BE', 'B', 'E',", "expected axial force: 112.1 Compression') # Render the model for", "Analyze the model truss.Analyze() # Print results print('Member BC calculated", "Edition # <NAME> # Problem 6.64 # Units for this", "didn't specify any. We'll display 'Case 1'. Visualization.RenderModel(truss, text_height=0.05, render_loads=True,", "E, 100, 100, 100, 100, 100) truss.AddMember('BC', 'B', 'C', E,", "truss.AddNodeLoad('A', 'FY', 60) truss.AddNodeLoad('A', 'FZ', 20) # Analyze the model", "100, 100, 100, 100) truss.AddMember('BD', 'B', 'D', E, 100, 100,", "False, False, False, False, True, True) truss.DefineReleases('BE', False, False, False,", "calculated axial force: ' + str(truss.GetMember('BC').MaxAxial())) print('Member BC expected axial", "model truss.Analyze() # Print results print('Member BC calculated axial force:", "Truss - Nodal Load.py # Engineering Mechanics: Statics, 4th Edition", "value E = 99999999 truss.AddMember('AB', 'A', 'B', E, 100, 100,", "Nodal Load.py # Engineering Mechanics: Statics, 4th Edition # <NAME>", "truss.DefineReleases('BD', False, False, False, False, True, True, \\ False, False,", "force: 112.1 Compression') # Render the model for viewing. The", "Render the model for viewing. The text height will be", "# Units for this model are meters and kilonewtons #", "the members in this example are nearly rigid, there will", "in this example are nearly rigid, there will be virtually", "100, 100, 100, 100, 100) # Release the moments at", "members truss.DefineReleases('AC', False, False, False, False, True, True, \\ False,", "truss.DefineReleases('BC', False, False, False, False, True, True, \\ False, False,", "False, False, True, True, \\ False, False, False, False, True,", "= FEModel3D() # Define the nodes truss.AddNode('A', 1.1, -0.4, 0)", "True, \\ False, False, False, False, True, True) # Add", "and kilonewtons # Import 'FEModel3D' and 'Visualization' from 'PyNite' from", "# Print results print('Member BC calculated axial force: ' +", "assumed values will be used # To make all the", "' + str(truss.GetMember('BC').MaxAxial())) print('Member BC expected axial force: 32.7 Tension')", "the members act rigid, the modulus of elasticity will be", "-0.4, 0) truss.AddNode('B', 1, 0, 0) truss.AddNode('C', 0, 0, 0.6)", "viewing. The text height will be set to 50 mm.", "truss.DefineSupport('D', True, True, True, True, True, True) truss.DefineSupport('E', True, True,", "False, False, True, True) truss.DefineReleases('BC', False, False, False, False, True,", "truss.DefineReleases('BE', False, False, False, False, True, True, \\ False, False,", "for this problem, so assumed values will be used #", "112.1 Compression') # Render the model for viewing. The text", "False, True, True) # Add nodal loads truss.AddNodeLoad('A', 'FX', 10)", "50 mm. # Because the members in this example are", "'A', 'C', E, 100, 100, 100, 100, 100) truss.AddMember('AD', 'A',", "Units for this model are meters and kilonewtons # Import", "E, 100, 100, 100, 100, 100) truss.AddMember('BE', 'B', 'E', E,", "# Problem 6.64 # Units for this model are meters", "4th Edition # <NAME> # Problem 6.64 # Units for", "axial force: ' + str(truss.GetMember('BC').MaxAxial())) print('Member BC expected axial force:", "Visualization # Create a new model truss = FEModel3D() #", "given for this problem, so assumed values will be used", "created a default load case 'Case 1' and a default", "# <NAME> # Problem 6.64 # Units for this model", "be used # To make all the members act rigid,", "load combo 'Combo 1' since we didn't specify any. We'll", "True, True, True, True, True, True) truss.DefineSupport('D', True, True, True,", "100) truss.AddMember('BE', 'B', 'E', E, 100, 100, 100, 100, 100)", "False, False, False, True, True) # Add nodal loads truss.AddNodeLoad('A',", "truss.DefineReleases('AD', False, False, False, False, True, True, \\ False, False,", "set to a very large value E = 99999999 truss.AddMember('AB',", "# Engineering Mechanics: Statics, 4th Edition # <NAME> # Problem", "True, True) truss.DefineSupport('D', True, True, True, True, True, True) truss.DefineSupport('E',", "truss members truss.DefineReleases('AC', False, False, False, False, True, True, \\", "False, False, True, True) # Add nodal loads truss.AddNodeLoad('A', 'FX',", "Print results print('Member BC calculated axial force: ' + str(truss.GetMember('BC').MaxAxial()))", "members act rigid, the modulus of elasticity will be set", "nearly rigid, there will be virtually no deformation. The deformed", "True, True, True, True) # Create members # Member properties", "any. We'll display 'Case 1'. Visualization.RenderModel(truss, text_height=0.05, render_loads=True, case='Case 1')", "print('Member BE expected axial force: 112.1 Compression') # Render the", "False, False, True, True) truss.DefineReleases('AD', False, False, False, False, True,", "E, 100, 100, 100, 100, 100) truss.AddMember('AD', 'A', 'D', E,", "True, True, True, True, True) # Create members # Member", "1.1, -0.4, 0) truss.AddNode('B', 1, 0, 0) truss.AddNode('C', 0, 0,", "100, 100, 100, 100) truss.AddMember('BC', 'B', 'C', E, 100, 100,", "0) # Define the supports truss.DefineSupport('C', True, True, True, True,", "'D', E, 100, 100, 100, 100, 100) truss.AddMember('BC', 'B', 'C',", "False, False, False, True, True) truss.DefineReleases('AD', False, False, False, False,", "str(truss.GetMember('BC').MaxAxial())) print('Member BC expected axial force: 32.7 Tension') print('Member BD", "100, 100, 100) # Release the moments at the ends", "'Combo 1' since we didn't specify any. We'll display 'Case", "rigid, the modulus of elasticity will be set to a", "to make truss members truss.DefineReleases('AC', False, False, False, False, True,", "# Define the supports truss.DefineSupport('C', True, True, True, True, True,", "# Import 'FEModel3D' and 'Visualization' from 'PyNite' from PyNite import", "modulus of elasticity will be set to a very large", "False, False, False, True, True) truss.DefineReleases('BE', False, False, False, False,", "BC expected axial force: 32.7 Tension') print('Member BD calculated axial", "to 50 mm. # Because the members in this example", "FEModel3D() # Define the nodes truss.AddNode('A', 1.1, -0.4, 0) truss.AddNode('B',", "Compression') # Render the model for viewing. The text height", "print('Member BD calculated axial force: ' + str(truss.GetMember('BD').MaxAxial())) print('Member BD", "ends of the members to make truss members truss.DefineReleases('AC', False,", "True) # Add nodal loads truss.AddNodeLoad('A', 'FX', 10) truss.AddNodeLoad('A', 'FY',", "members # Member properties were not given for this problem,", "Engineering Mechanics: Statics, 4th Edition # <NAME> # Problem 6.64", "members to make truss members truss.DefineReleases('AC', False, False, False, False,", "Tension') print('Member BE calculated axial force: ' + str(truss.GetMember('BE').MaxAxial())) print('Member", "there will be virtually no deformation. The deformed shape won't", "'B', E, 100, 100, 100, 100, 100) truss.AddMember('AC', 'A', 'C',", "of elasticity will be set to a very large value", "make all the members act rigid, the modulus of elasticity", "force: 45.2 Tension') print('Member BE calculated axial force: ' +", "True, True, True) truss.DefineSupport('D', True, True, True, True, True, True)", "truss.AddMember('BC', 'B', 'C', E, 100, 100, 100, 100, 100) truss.AddMember('BD',", "Define the nodes truss.AddNode('A', 1.1, -0.4, 0) truss.AddNode('B', 1, 0,", "from 'PyNite' from PyNite import FEModel3D from PyNite import Visualization", "False, False, False, False, True, True) truss.DefineReleases('BC', False, False, False,", "100, 100, 100, 100, 100) truss.AddMember('AD', 'A', 'D', E, 100,", "force: ' + str(truss.GetMember('BD').MaxAxial())) print('Member BD expected axial force: 45.2", "default load combo 'Combo 1' since we didn't specify any.", "act rigid, the modulus of elasticity will be set to", "100) truss.AddMember('AD', 'A', 'D', E, 100, 100, 100, 100, 100)", "truss.AddNode('B', 1, 0, 0) truss.AddNode('C', 0, 0, 0.6) truss.AddNode('D', 0,", "\\ False, False, False, False, True, True) truss.DefineReleases('BD', False, False,", "True, \\ False, False, False, False, True, True) truss.DefineReleases('AD', False,", "truss.AddNode('E', 0, 0.8, 0) # Define the supports truss.DefineSupport('C', True,", "' + str(truss.GetMember('BD').MaxAxial())) print('Member BD expected axial force: 45.2 Tension')", "force: ' + str(truss.GetMember('BC').MaxAxial())) print('Member BC expected axial force: 32.7", "are nearly rigid, there will be virtually no deformation. The", "for this model are meters and kilonewtons # Import 'FEModel3D'", "0.6) truss.AddNode('D', 0, 0, -0.4) truss.AddNode('E', 0, 0.8, 0) #", "True, True) # Create members # Member properties were not", "truss.AddMember('BD', 'B', 'D', E, 100, 100, 100, 100, 100) truss.AddMember('BE',", "Create members # Member properties were not given for this", "' + str(truss.GetMember('BE').MaxAxial())) print('Member BE expected axial force: 112.1 Compression')", "PyNite import FEModel3D from PyNite import Visualization # Create a", "calculated axial force: ' + str(truss.GetMember('BE').MaxAxial())) print('Member BE expected axial", "False, False, True, True) truss.DefineReleases('BD', False, False, False, False, True,", "# Define the nodes truss.AddNode('A', 1.1, -0.4, 0) truss.AddNode('B', 1,", "properties were not given for this problem, so assumed values", "'B', 'D', E, 100, 100, 100, 100, 100) truss.AddMember('BE', 'B',", "32.7 Tension') print('Member BD calculated axial force: ' + str(truss.GetMember('BD').MaxAxial()))", "specify any. We'll display 'Case 1'. Visualization.RenderModel(truss, text_height=0.05, render_loads=True, case='Case", "# To make all the members act rigid, the modulus", "To make all the members act rigid, the modulus of", "deformed shape won't be rendered. # The program has created", "a default load combo 'Combo 1' since we didn't specify", "\\ False, False, False, False, True, True) # Add nodal", "'B', 'E', E, 100, 100, 100, 100, 100) # Release", "False, False, False, True, True, \\ False, False, False, False,", "0) truss.AddNode('B', 1, 0, 0) truss.AddNode('C', 0, 0, 0.6) truss.AddNode('D',", "True, True, True) truss.DefineSupport('E', True, True, True, True, True, True)", "be rendered. # The program has created a default load", "True, \\ False, False, False, False, True, True) truss.DefineReleases('BD', False,", "True) truss.DefineSupport('E', True, True, True, True, True, True) # Create", "False, False, False, False, True, True) truss.DefineReleases('AD', False, False, False,", "'C', E, 100, 100, 100, 100, 100) truss.AddMember('AD', 'A', 'D',", "truss.Analyze() # Print results print('Member BC calculated axial force: '", "Define the supports truss.DefineSupport('C', True, True, True, True, True, True)", "True, True, True, True) truss.DefineSupport('E', True, True, True, True, True,", "+ str(truss.GetMember('BC').MaxAxial())) print('Member BC expected axial force: 32.7 Tension') print('Member", "truss.AddMember('BE', 'B', 'E', E, 100, 100, 100, 100, 100) #", "print('Member BC expected axial force: 32.7 Tension') print('Member BD calculated", "values will be used # To make all the members", "100, 100) truss.AddMember('BD', 'B', 'D', E, 100, 100, 100, 100,", "True, True, True) # Create members # Member properties were", "True, True) truss.DefineReleases('BE', False, False, False, False, True, True, \\", "Because the members in this example are nearly rigid, there", "were not given for this problem, so assumed values will", "a new model truss = FEModel3D() # Define the nodes", "truss.DefineSupport('C', True, True, True, True, True, True) truss.DefineSupport('D', True, True,", "text height will be set to 50 mm. # Because", "the supports truss.DefineSupport('C', True, True, True, True, True, True) truss.DefineSupport('D',", "deformation. The deformed shape won't be rendered. # The program", "100, 100, 100, 100, 100) truss.AddMember('AC', 'A', 'C', E, 100,", "'A', 'D', E, 100, 100, 100, 100, 100) truss.AddMember('BC', 'B',", "0, 0, 0.6) truss.AddNode('D', 0, 0, -0.4) truss.AddNode('E', 0, 0.8,", "'E', E, 100, 100, 100, 100, 100) # Release the", "Problem 6.64 # Units for this model are meters and", "# The program has created a default load case 'Case", "the ends of the members to make truss members truss.DefineReleases('AC',", "members in this example are nearly rigid, there will be", "True) truss.DefineSupport('D', True, True, True, True, True, True) truss.DefineSupport('E', True,", "truss.AddNode('D', 0, 0, -0.4) truss.AddNode('E', 0, 0.8, 0) # Define", "True, True, True, True, True, True) # Create members #", "we didn't specify any. We'll display 'Case 1'. Visualization.RenderModel(truss, text_height=0.05,", "True, True) truss.DefineReleases('AD', False, False, False, False, True, True, \\", "<filename>Examples/Space Truss - Nodal Load.py # Engineering Mechanics: Statics, 4th", "will be set to 50 mm. # Because the members", "True) truss.DefineReleases('BD', False, False, False, False, True, True, \\ False,", "# Create members # Member properties were not given for", "expected axial force: 45.2 Tension') print('Member BE calculated axial force:", "True, \\ False, False, False, False, True, True) truss.DefineReleases('BC', False,", "100) truss.AddMember('AC', 'A', 'C', E, 100, 100, 100, 100, 100)", "new model truss = FEModel3D() # Define the nodes truss.AddNode('A',", "'C', E, 100, 100, 100, 100, 100) truss.AddMember('BD', 'B', 'D',", "False, True, True) truss.DefineReleases('BE', False, False, False, False, True, True,", "and a default load combo 'Combo 1' since we didn't", "100, 100) truss.AddMember('AD', 'A', 'D', E, 100, 100, 100, 100,", "Tension') print('Member BD calculated axial force: ' + str(truss.GetMember('BD').MaxAxial())) print('Member", "100, 100, 100, 100, 100) truss.AddMember('BD', 'B', 'D', E, 100,", "no deformation. The deformed shape won't be rendered. # The", "'PyNite' from PyNite import FEModel3D from PyNite import Visualization #", "truss.AddMember('AD', 'A', 'D', E, 100, 100, 100, 100, 100) truss.AddMember('BC',", "not given for this problem, so assumed values will be", "+ str(truss.GetMember('BE').MaxAxial())) print('Member BE expected axial force: 112.1 Compression') #", "\\ False, False, False, False, True, True) truss.DefineReleases('BC', False, False,", "meters and kilonewtons # Import 'FEModel3D' and 'Visualization' from 'PyNite'", "0.8, 0) # Define the supports truss.DefineSupport('C', True, True, True,", "the moments at the ends of the members to make", "import FEModel3D from PyNite import Visualization # Create a new", "print('Member BC calculated axial force: ' + str(truss.GetMember('BC').MaxAxial())) print('Member BC", "0, 0.6) truss.AddNode('D', 0, 0, -0.4) truss.AddNode('E', 0, 0.8, 0)", "import Visualization # Create a new model truss = FEModel3D()", "True, \\ False, False, False, False, True, True) truss.DefineReleases('BE', False,", "truss.DefineSupport('E', True, True, True, True, True, True) # Create members", "= 99999999 truss.AddMember('AB', 'A', 'B', E, 100, 100, 100, 100,", "BD expected axial force: 45.2 Tension') print('Member BE calculated axial", "False, False, False, False, True, True, \\ False, False, False,", "expected axial force: 32.7 Tension') print('Member BD calculated axial force:", "results print('Member BC calculated axial force: ' + str(truss.GetMember('BC').MaxAxial())) print('Member", "False, False, False, False, True, True) # Add nodal loads", "example are nearly rigid, there will be virtually no deformation.", "100, 100, 100) truss.AddMember('BD', 'B', 'D', E, 100, 100, 100,", "100, 100, 100, 100) truss.AddMember('BE', 'B', 'E', E, 100, 100,", "True, True, \\ False, False, False, False, True, True) #", "# Create a new model truss = FEModel3D() # Define", "True, True) truss.DefineSupport('E', True, True, True, True, True, True) #", "100, 100, 100, 100) truss.AddMember('AD', 'A', 'D', E, 100, 100,", "0, -0.4) truss.AddNode('E', 0, 0.8, 0) # Define the supports", "problem, so assumed values will be used # To make", "0, 0.8, 0) # Define the supports truss.DefineSupport('C', True, True,", "nodes truss.AddNode('A', 1.1, -0.4, 0) truss.AddNode('B', 1, 0, 0) truss.AddNode('C',", "BD calculated axial force: ' + str(truss.GetMember('BD').MaxAxial())) print('Member BD expected", "1' and a default load combo 'Combo 1' since we", "load case 'Case 1' and a default load combo 'Combo", "will be set to a very large value E =", "100, 100) # Release the moments at the ends of", "print('Member BD expected axial force: 45.2 Tension') print('Member BE calculated", "calculated axial force: ' + str(truss.GetMember('BD').MaxAxial())) print('Member BD expected axial", "truss.AddMember('AC', 'A', 'C', E, 100, 100, 100, 100, 100) truss.AddMember('AD',", "BE expected axial force: 112.1 Compression') # Render the model", "'FX', 10) truss.AddNodeLoad('A', 'FY', 60) truss.AddNodeLoad('A', 'FZ', 20) # Analyze", "nodal loads truss.AddNodeLoad('A', 'FX', 10) truss.AddNodeLoad('A', 'FY', 60) truss.AddNodeLoad('A', 'FZ',", "True, True) truss.DefineReleases('BC', False, False, False, False, True, True, \\", "won't be rendered. # The program has created a default", "E, 100, 100, 100, 100, 100) # Release the moments", "of the members to make truss members truss.DefineReleases('AC', False, False,", "all the members act rigid, the modulus of elasticity will", "True) truss.DefineReleases('AD', False, False, False, False, True, True, \\ False,", "False, False, False, True, True) truss.DefineReleases('BD', False, False, False, False,", "'FZ', 20) # Analyze the model truss.Analyze() # Print results", "default load case 'Case 1' and a default load combo", "height will be set to 50 mm. # Because the", "model truss = FEModel3D() # Define the nodes truss.AddNode('A', 1.1,", "# Analyze the model truss.Analyze() # Print results print('Member BC", "True, True, True, True, True) truss.DefineSupport('E', True, True, True, True,", "combo 'Combo 1' since we didn't specify any. We'll display", "100, 100, 100) truss.AddMember('AC', 'A', 'C', E, 100, 100, 100,", "True, True, \\ False, False, False, False, True, True) truss.DefineReleases('AD',", "axial force: 112.1 Compression') # Render the model for viewing.", "99999999 truss.AddMember('AB', 'A', 'B', E, 100, 100, 100, 100, 100)", "truss.DefineReleases('AC', False, False, False, False, True, True, \\ False, False,", "since we didn't specify any. We'll display 'Case 1'. Visualization.RenderModel(truss,", "E, 100, 100, 100, 100, 100) truss.AddMember('BD', 'B', 'D', E,", "force: 32.7 Tension') print('Member BD calculated axial force: ' +", "# Release the moments at the ends of the members", "Add nodal loads truss.AddNodeLoad('A', 'FX', 10) truss.AddNodeLoad('A', 'FY', 60) truss.AddNodeLoad('A',", "mm. # Because the members in this example are nearly", "truss.AddNodeLoad('A', 'FZ', 20) # Analyze the model truss.Analyze() # Print", "\\ False, False, False, False, True, True) truss.DefineReleases('BE', False, False,", "The text height will be set to 50 mm. #", "loads truss.AddNodeLoad('A', 'FX', 10) truss.AddNodeLoad('A', 'FY', 60) truss.AddNodeLoad('A', 'FZ', 20)", "are meters and kilonewtons # Import 'FEModel3D' and 'Visualization' from", "True) # Create members # Member properties were not given", "program has created a default load case 'Case 1' and", "True, True) truss.DefineReleases('BD', False, False, False, False, True, True, \\", "truss.AddNodeLoad('A', 'FX', 10) truss.AddNodeLoad('A', 'FY', 60) truss.AddNodeLoad('A', 'FZ', 20) #", "Import 'FEModel3D' and 'Visualization' from 'PyNite' from PyNite import FEModel3D", "0) truss.AddNode('C', 0, 0, 0.6) truss.AddNode('D', 0, 0, -0.4) truss.AddNode('E',", "# Member properties were not given for this problem, so", "supports truss.DefineSupport('C', True, True, True, True, True, True) truss.DefineSupport('D', True,", "True, True) # Add nodal loads truss.AddNodeLoad('A', 'FX', 10) truss.AddNodeLoad('A',", "1' since we didn't specify any. We'll display 'Case 1'.", "Create a new model truss = FEModel3D() # Define the", "'A', 'B', E, 100, 100, 100, 100, 100) truss.AddMember('AC', 'A',", "True) truss.DefineReleases('BC', False, False, False, False, True, True, \\ False,", "at the ends of the members to make truss members", "Statics, 4th Edition # <NAME> # Problem 6.64 # Units", "- Nodal Load.py # Engineering Mechanics: Statics, 4th Edition #", "True) truss.DefineReleases('BE', False, False, False, False, True, True, \\ False,", "<NAME> # Problem 6.64 # Units for this model are", "from PyNite import Visualization # Create a new model truss", "model for viewing. The text height will be set to", "case 'Case 1' and a default load combo 'Combo 1'", "100) truss.AddMember('BC', 'B', 'C', E, 100, 100, 100, 100, 100)", "the model for viewing. The text height will be set", "will be virtually no deformation. The deformed shape won't be", "False, True, True) truss.DefineReleases('AD', False, False, False, False, True, True,", "6.64 # Units for this model are meters and kilonewtons", "truss.AddMember('AB', 'A', 'B', E, 100, 100, 100, 100, 100) truss.AddMember('AC',", "so assumed values will be used # To make all", "True, True, \\ False, False, False, False, True, True) truss.DefineReleases('BC',", "# Render the model for viewing. The text height will", "virtually no deformation. The deformed shape won't be rendered. #", "this model are meters and kilonewtons # Import 'FEModel3D' and", "False, False, False, False, True, True) truss.DefineReleases('BD', False, False, False,", "True, True, True, True, True, True) truss.DefineSupport('E', True, True, True,", "print('Member BE calculated axial force: ' + str(truss.GetMember('BE').MaxAxial())) print('Member BE", "truss.AddNode('A', 1.1, -0.4, 0) truss.AddNode('B', 1, 0, 0) truss.AddNode('C', 0,", "kilonewtons # Import 'FEModel3D' and 'Visualization' from 'PyNite' from PyNite", "moments at the ends of the members to make truss", "# Add nodal loads truss.AddNodeLoad('A', 'FX', 10) truss.AddNodeLoad('A', 'FY', 60)", "E = 99999999 truss.AddMember('AB', 'A', 'B', E, 100, 100, 100,", "True, True, \\ False, False, False, False, True, True) truss.DefineReleases('BD',", "for viewing. The text height will be set to 50", "be set to 50 mm. # Because the members in", "Member properties were not given for this problem, so assumed", "False, True, True) truss.DefineReleases('BC', False, False, False, False, True, True,", "axial force: 45.2 Tension') print('Member BE calculated axial force: '", "axial force: ' + str(truss.GetMember('BD').MaxAxial())) print('Member BD expected axial force:", "elasticity will be set to a very large value E", "100, 100) truss.AddMember('AC', 'A', 'C', E, 100, 100, 100, 100,", "True, True, True, True) truss.DefineSupport('D', True, True, True, True, True,", "shape won't be rendered. # The program has created a", "Release the moments at the ends of the members to", "False, True, True, \\ False, False, False, False, True, True)", "20) # Analyze the model truss.Analyze() # Print results print('Member", "100, 100, 100, 100, 100) truss.AddMember('BE', 'B', 'E', E, 100,", "truss = FEModel3D() # Define the nodes truss.AddNode('A', 1.1, -0.4,", "model are meters and kilonewtons # Import 'FEModel3D' and 'Visualization'", "force: ' + str(truss.GetMember('BE').MaxAxial())) print('Member BE expected axial force: 112.1", "to a very large value E = 99999999 truss.AddMember('AB', 'A',", "100, 100, 100) truss.AddMember('BE', 'B', 'E', E, 100, 100, 100,", "True, True, True, True, True) truss.DefineSupport('D', True, True, True, True,", "the nodes truss.AddNode('A', 1.1, -0.4, 0) truss.AddNode('B', 1, 0, 0)", "axial force: 32.7 Tension') print('Member BD calculated axial force: '" ]
[ "import yagmail receiver = \"<EMAIL>\" #Receiver's gmail address body =", "= \"<EMAIL>\" #Receiver's gmail address body = \"Hello there from", "gmail address body = \"Hello there from Yagmail\" filename =", "= yagmail.SMTP(\"<EMAIL>\")#Your gmail address yag.send( to=receiver, subject=\"Yagmail test (attachment included\",", "= \"document.pdf\" yag = yagmail.SMTP(\"<EMAIL>\")#Your gmail address yag.send( to=receiver, subject=\"Yagmail", "Yagmail\" filename = \"document.pdf\" yag = yagmail.SMTP(\"<EMAIL>\")#Your gmail address yag.send(", "\"<EMAIL>\" #Receiver's gmail address body = \"Hello there from Yagmail\"", "body = \"Hello there from Yagmail\" filename = \"document.pdf\" yag", "yagmail receiver = \"<EMAIL>\" #Receiver's gmail address body = \"Hello", "address yag.send( to=receiver, subject=\"Yagmail test (attachment included\", contents=body, attachments=filename, )", "receiver = \"<EMAIL>\" #Receiver's gmail address body = \"Hello there", "yag = yagmail.SMTP(\"<EMAIL>\")#Your gmail address yag.send( to=receiver, subject=\"Yagmail test (attachment", "#Receiver's gmail address body = \"Hello there from Yagmail\" filename", "from Yagmail\" filename = \"document.pdf\" yag = yagmail.SMTP(\"<EMAIL>\")#Your gmail address", "filename = \"document.pdf\" yag = yagmail.SMTP(\"<EMAIL>\")#Your gmail address yag.send( to=receiver,", "address body = \"Hello there from Yagmail\" filename = \"document.pdf\"", "= \"Hello there from Yagmail\" filename = \"document.pdf\" yag =", "there from Yagmail\" filename = \"document.pdf\" yag = yagmail.SMTP(\"<EMAIL>\")#Your gmail", "gmail address yag.send( to=receiver, subject=\"Yagmail test (attachment included\", contents=body, attachments=filename,", "\"Hello there from Yagmail\" filename = \"document.pdf\" yag = yagmail.SMTP(\"<EMAIL>\")#Your", "yagmail.SMTP(\"<EMAIL>\")#Your gmail address yag.send( to=receiver, subject=\"Yagmail test (attachment included\", contents=body,", "\"document.pdf\" yag = yagmail.SMTP(\"<EMAIL>\")#Your gmail address yag.send( to=receiver, subject=\"Yagmail test" ]
[ "a translation *x->x+b*. \"\"\" def __init__(self,b=numpy.zeros((3,),dtype=_TYPE)): \"\"\" Creates the linear", "linear transformation *x->x+b*. \"\"\" super(Translation, self).__init__() self.__b=numpy.array(b,_TYPE) def __call__(self,x=numpy.zeros((3,))): \"\"\"", "self.__b=numpy.array(b,_TYPE) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies translation to ``x``. \"\"\" return", "z0=numpy.dot(z,self.__axis) z_per=z-z0*self.__axis lz_per=numpy.dot(z_per,z_per) if lz_per>0: axis1=z_per/math.sqrt(lz_per) axis2=_cross(axis1,self.__axis) lax2=numpy.dot(axis2,axis2) if lax2>0:", "transformation *x->x+b*. \"\"\" super(Translation, self).__init__() self.__b=numpy.array(b,_TYPE) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies", "z_per=z-z0*self.__axis lz_per=numpy.dot(z_per,z_per) if lz_per>0: axis1=z_per/math.sqrt(lz_per) axis2=_cross(axis1,self.__axis) lax2=numpy.dot(axis2,axis2) if lax2>0: axis2/=math.sqrt(lax2)", "axis. \"\"\" self.__axis=numpy.array(axis,dtype=_TYPE) self.__point=numpy.array(point,dtype=_TYPE) lax=numpy.dot(self.__axis,self.__axis) if not lax>0: raise ValueError(\"points", "x=numpy.array(x,_TYPE) z=x-self.__point z0=numpy.dot(z,self.__axis) z_per=z-z0*self.__axis lz_per=numpy.dot(z_per,z_per) if lz_per>0: axis1=z_per/math.sqrt(lz_per) axis2=_cross(axis1,self.__axis) lax2=numpy.dot(axis2,axis2)", "lz_per=numpy.dot(z_per,z_per) if lz_per>0: axis1=z_per/math.sqrt(lz_per) axis2=_cross(axis1,self.__axis) lax2=numpy.dot(axis2,axis2) if lax2>0: axis2/=math.sqrt(lax2) return", "point on documentation :var __version__: version :var __date__: date of", "not ln>0.: raise ValueError(\"normal must have positive length.\") self.__normal/=ln if", "else: return x def _cross(x, y): \"\"\" Returns the cross", "of ``x`` and ``y``. \"\"\" return numpy.array([x[1] * y[2] -", "Creates a rotation using an axis and a point on", "# # Copyright (c) 2003-2020 by The University of Queensland", "version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # # Development until 2012 by", "a reflection on a plane. \"\"\" def __init__(self,normal=numpy.ones((3,),dtype=_TYPE),offset=0.): \"\"\" Defines", "to ``x``. \"\"\" x=numpy.array(x,_TYPE) z=x-self.__point z0=numpy.dot(z,self.__axis) z_per=z-z0*self.__axis lz_per=numpy.dot(z_per,z_per) if lz_per>0:", "else: self.__offset=numpy.dot(numpy.array(offset,dtype=_TYPE),self.__normal) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies reflection to ``x``. \"\"\"", "def _cross(x, y): \"\"\" Returns the cross product of ``x``", "class Rotatation(Transformation): \"\"\" Defines a rotation. \"\"\" def __init__(self,axis=numpy.ones((3,),dtype=_TYPE),point=numpy.zeros((3,),dtype=_TYPE),angle=0.*RAD): \"\"\"", "\"\"\" def __init__(self,b=numpy.zeros((3,),dtype=_TYPE)): \"\"\" Creates the linear transformation *x->x+b*. \"\"\"", "self.__point=numpy.array(point,dtype=_TYPE) lax=numpy.dot(self.__axis,self.__axis) if not lax>0: raise ValueError(\"points must be distinct.\")", "__call__(self,x=numpy.zeros((3,))): \"\"\" Applies dilation to ``x``. \"\"\" x=numpy.array(x,_TYPE) return self.__factor*(x-self.__center)+self.__center", "return x def _cross(x, y): \"\"\" Returns the cross product", ":var __url__: url entry point on documentation :var __version__: version", "ValueError(\"factor must be non-zero.\") self.__factor=factor self.__center=numpy.array(center,dtype=_TYPE) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies", "RAD: unit of radiant \"\"\" __author__=\"<NAME>, <EMAIL>\" import numpy import", "numpy.array(x,_TYPE)+self.__b class Rotatation(Transformation): \"\"\" Defines a rotation. \"\"\" def __init__(self,axis=numpy.ones((3,),dtype=_TYPE),point=numpy.zeros((3,),dtype=_TYPE),angle=0.*RAD):", "Defines a translation *x->x+b*. \"\"\" def __init__(self,b=numpy.zeros((3,),dtype=_TYPE)): \"\"\" Creates the", "be distinct.\") self.__axis/=math.sqrt(lax) self.__angle=float(angle) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies the rotation", "y[2], x[0] * y[1] - x[1] * y[0]], _TYPE) class", "class Translation(Transformation): \"\"\" Defines a translation *x->x+b*. \"\"\" def __init__(self,b=numpy.zeros((3,),dtype=_TYPE)):", "__init__(self,normal=numpy.ones((3,),dtype=_TYPE),offset=0.): \"\"\" Defines a reflection on a plane defined in", "ln=math.sqrt(numpy.dot(self.__normal,self.__normal)) if not ln>0.: raise ValueError(\"normal must have positive length.\")", "__url__: url entry point on documentation :var __version__: version :var", "transformations :var __author__: name of author :var __copyright__: copyrights :var", "x[0] * y[1] - x[1] * y[0]], _TYPE) class Dilation(Transformation):", "rotation to ``x``. \"\"\" x=numpy.array(x,_TYPE) z=x-self.__point z0=numpy.dot(z,self.__axis) z_per=z-z0*self.__axis lz_per=numpy.dot(z_per,z_per) if", "Copyright (c) 2003-2020 by The University of Queensland # http://www.uq.edu.au", "if isinstance(offset,float) or isinstance(offset,int): self.__offset=offset/ln else: self.__offset=numpy.dot(numpy.array(offset,dtype=_TYPE),self.__normal) def __call__(self,x=numpy.zeros((3,))): \"\"\"", "Australia\"\"\" __license__=\"\"\"Licensed under the Apache License, version 2.0 http://www.apache.org/licenses/LICENSE-2.0\"\"\" __url__=\"https://launchpad.net/escript-finley\"", "axis1=z_per/math.sqrt(lz_per) axis2=_cross(axis1,self.__axis) lax2=numpy.dot(axis2,axis2) if lax2>0: axis2/=math.sqrt(lax2) return z0*self.__axis+math.sqrt(lz_per)*(math.cos(self.__angle)*axis1-math.sin(self.__angle)*axis2)+self.__point else: return", "http://www.apache.org/licenses/LICENSE-2.0 # # Development until 2012 by Earth Systems Science", "Applies the rotation to ``x``. \"\"\" x=numpy.array(x,_TYPE) z=x-self.__point z0=numpy.dot(z,self.__axis) z_per=z-z0*self.__axis", "x[2] * y[0] - x[0] * y[2], x[0] * y[1]", "def __init__(self,normal=numpy.ones((3,),dtype=_TYPE),offset=0.): \"\"\" Defines a reflection on a plane defined", "Primary Business: Queensland, Australia # Licensed under the Apache License,", "super(Translation, self).__init__() self.__b=numpy.array(b,_TYPE) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies translation to ``x``.", "\"\"\" Defines a translation *x->x+b*. \"\"\" def __init__(self,b=numpy.zeros((3,),dtype=_TYPE)): \"\"\" Creates", "(ESSCC) # Development 2012-2013 by School of Earth Sciences #", "self.__factor*(x-self.__center)+self.__center class Reflection(Transformation): \"\"\" Defines a reflection on a plane.", "self.__center=numpy.array(center,dtype=_TYPE) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies dilation to ``x``. \"\"\" x=numpy.array(x,_TYPE)", "positive length.\") self.__normal/=ln if isinstance(offset,float) or isinstance(offset,int): self.__offset=offset/ln else: self.__offset=numpy.dot(numpy.array(offset,dtype=_TYPE),self.__normal)", "Development from 2019 by School of Earth and Environmental Sciences", "http://www.apache.org/licenses/LICENSE-2.0\"\"\" __url__=\"https://launchpad.net/escript-finley\" \"\"\" transformations :var __author__: name of author :var", "raise ValueError(\"factor must be non-zero.\") self.__factor=factor self.__center=numpy.array(center,dtype=_TYPE) def __call__(self,x=numpy.zeros((3,))): \"\"\"", "2.0 # http://www.apache.org/licenses/LICENSE-2.0 # # Development until 2012 by Earth", ":var __author__: name of author :var __copyright__: copyrights :var __license__:", "Dilation(Transformation): \"\"\" Defines a dilation. \"\"\" def __init__(self,factor=1.,center=numpy.zeros((3,),dtype=_TYPE)): \"\"\" Creates", "by School of Earth and Environmental Sciences # ############################################################################## from", "translation to ``x``. \"\"\" return numpy.array(x,_TYPE)+self.__b class Rotatation(Transformation): \"\"\" Defines", "distinct.\") self.__axis/=math.sqrt(lax) self.__angle=float(angle) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies the rotation to", "the Apache License, version 2.0 http://www.apache.org/licenses/LICENSE-2.0\"\"\" __url__=\"https://launchpad.net/escript-finley\" \"\"\" transformations :var", "a given expansion/contraction factor. \"\"\" if not abs(factor)>0: raise ValueError(\"factor", "lax>0: raise ValueError(\"points must be distinct.\") self.__axis/=math.sqrt(lax) self.__angle=float(angle) def __call__(self,x=numpy.zeros((3,))):", "lax2=numpy.dot(axis2,axis2) if lax2>0: axis2/=math.sqrt(lax2) return z0*self.__axis+math.sqrt(lz_per)*(math.cos(self.__angle)*axis1-math.sin(self.__angle)*axis2)+self.__point else: return x else:", "\"\"\" x=numpy.array(x,_TYPE) return self.__factor*(x-self.__center)+self.__center class Reflection(Transformation): \"\"\" Defines a reflection", "from __future__ import print_function, division __copyright__=\"\"\"Copyright (c) 2003-2020 by The", "def __init__(self,axis=numpy.ones((3,),dtype=_TYPE),point=numpy.zeros((3,),dtype=_TYPE),angle=0.*RAD): \"\"\" Creates a rotation using an axis and", "############################################################################## from __future__ import print_function, division __copyright__=\"\"\"Copyright (c) 2003-2020 by", "expansion/contraction factor. \"\"\" if not abs(factor)>0: raise ValueError(\"factor must be", "Centre for Geoscience Computing (GeoComp) # Development from 2019 by", "version :var DEG: unit of degree :var RAD: unit of", "in normal form. \"\"\" self.__normal=numpy.array(normal,dtype=_TYPE) ln=math.sqrt(numpy.dot(self.__normal,self.__normal)) if not ln>0.: raise", "be non-zero.\") self.__factor=factor self.__center=numpy.array(center,dtype=_TYPE) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies dilation to", "isinstance(offset,int): self.__offset=offset/ln else: self.__offset=numpy.dot(numpy.array(offset,dtype=_TYPE),self.__normal) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies reflection to", "_cross(x, y): \"\"\" Returns the cross product of ``x`` and", "(GeoComp) # Development from 2019 by School of Earth and", "non-zero.\") self.__factor=factor self.__center=numpy.array(center,dtype=_TYPE) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies dilation to ``x``.", "version 2.0 http://www.apache.org/licenses/LICENSE-2.0\"\"\" __url__=\"https://launchpad.net/escript-finley\" \"\"\" transformations :var __author__: name of", "2003-2020 by The University of Queensland # http://www.uq.edu.au # #", "- x[1] * y[0]], _TYPE) class Dilation(Transformation): \"\"\" Defines a", "x=numpy.array(x,_TYPE) return self.__factor*(x-self.__center)+self.__center class Reflection(Transformation): \"\"\" Defines a reflection on", "__date__: date of the version :var DEG: unit of degree", "by The University of Queensland http://www.uq.edu.au Primary Business: Queensland, Australia\"\"\"", "the version :var DEG: unit of degree :var RAD: unit", ":var __date__: date of the version :var DEG: unit of", "\"\"\" return numpy.array([x[1] * y[2] - x[2] * y[1], x[2]", "# Licensed under the Apache License, version 2.0 # http://www.apache.org/licenses/LICENSE-2.0", "if not lax>0: raise ValueError(\"points must be distinct.\") self.__axis/=math.sqrt(lax) self.__angle=float(angle)", "Defines a dilation. \"\"\" def __init__(self,factor=1.,center=numpy.zeros((3,),dtype=_TYPE)): \"\"\" Creates a dilation", "def __init__(self,b=numpy.zeros((3,),dtype=_TYPE)): \"\"\" Creates the linear transformation *x->x+b*. \"\"\" super(Translation,", "2003-2020 by The University of Queensland http://www.uq.edu.au Primary Business: Queensland,", "__init__(self,axis=numpy.ones((3,),dtype=_TYPE),point=numpy.zeros((3,),dtype=_TYPE),angle=0.*RAD): \"\"\" Creates a rotation using an axis and a", "for Geoscience Computing (GeoComp) # Development from 2019 by School", "* y[1] - x[1] * y[0]], _TYPE) class Dilation(Transformation): \"\"\"", "__version__: version :var __date__: date of the version :var DEG:", "to define an affine transformation *x->Ax+b*. \"\"\" def __init__(self): \"\"\"", "and ``y``. \"\"\" return numpy.array([x[1] * y[2] - x[2] *", "* y[0] - x[0] * y[2], x[0] * y[1] -", "and a given expansion/contraction factor. \"\"\" if not abs(factor)>0: raise", "Creates a dilation with a center and a given expansion/contraction", "of author :var __copyright__: copyrights :var __license__: licence agreement :var", "<EMAIL>\" import numpy import math _TYPE=numpy.float64 DEG=math.pi/180. RAD=1. class Transformation(object):", "raise NotImplementeError() class Translation(Transformation): \"\"\" Defines a translation *x->x+b*. \"\"\"", "from 2014 by Centre for Geoscience Computing (GeoComp) # Development", "form. \"\"\" self.__normal=numpy.array(normal,dtype=_TYPE) ln=math.sqrt(numpy.dot(self.__normal,self.__normal)) if not ln>0.: raise ValueError(\"normal must", "self.__offset=offset/ln else: self.__offset=numpy.dot(numpy.array(offset,dtype=_TYPE),self.__normal) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies reflection to ``x``.", "Queensland, Australia\"\"\" __license__=\"\"\"Licensed under the Apache License, version 2.0 http://www.apache.org/licenses/LICENSE-2.0\"\"\"", "the linear transformation *x->x+b*. \"\"\" super(Translation, self).__init__() self.__b=numpy.array(b,_TYPE) def __call__(self,x=numpy.zeros((3,))):", "__author__=\"<NAME>, <EMAIL>\" import numpy import math _TYPE=numpy.float64 DEG=math.pi/180. RAD=1. class", "dilation with a center and a given expansion/contraction factor. \"\"\"", "x[2] * y[1], x[2] * y[0] - x[0] * y[2],", "\"\"\" return numpy.array(x,_TYPE)+self.__b class Rotatation(Transformation): \"\"\" Defines a rotation. \"\"\"", "must have positive length.\") self.__normal/=ln if isinstance(offset,float) or isinstance(offset,int): self.__offset=offset/ln", "The University of Queensland # http://www.uq.edu.au # # Primary Business:", "2014 by Centre for Geoscience Computing (GeoComp) # Development from", ":var RAD: unit of radiant \"\"\" __author__=\"<NAME>, <EMAIL>\" import numpy", "of Queensland http://www.uq.edu.au Primary Business: Queensland, Australia\"\"\" __license__=\"\"\"Licensed under the", "*x->x+b*. \"\"\" super(Translation, self).__init__() self.__b=numpy.array(b,_TYPE) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies translation", "\"\"\" def __init__(self,factor=1.,center=numpy.zeros((3,),dtype=_TYPE)): \"\"\" Creates a dilation with a center", "import math _TYPE=numpy.float64 DEG=math.pi/180. RAD=1. class Transformation(object): \"\"\" General class", "Returns the cross product of ``x`` and ``y``. \"\"\" return", "# Development from 2019 by School of Earth and Environmental", "\"\"\" pass def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies transformation to ``x``. \"\"\"", "not lax>0: raise ValueError(\"points must be distinct.\") self.__axis/=math.sqrt(lax) self.__angle=float(angle) def", "__license__: licence agreement :var __url__: url entry point on documentation", "lz_per>0: axis1=z_per/math.sqrt(lz_per) axis2=_cross(axis1,self.__axis) lax2=numpy.dot(axis2,axis2) if lax2>0: axis2/=math.sqrt(lax2) return z0*self.__axis+math.sqrt(lz_per)*(math.cos(self.__angle)*axis1-math.sin(self.__angle)*axis2)+self.__point else:", "of Earth Sciences # Development from 2014 by Centre for", "Defines a rotation. \"\"\" def __init__(self,axis=numpy.ones((3,),dtype=_TYPE),point=numpy.zeros((3,),dtype=_TYPE),angle=0.*RAD): \"\"\" Creates a rotation", "# ############################################################################## from __future__ import print_function, division __copyright__=\"\"\"Copyright (c) 2003-2020", "documentation :var __version__: version :var __date__: date of the version", "\"\"\" Applies reflection to ``x``. \"\"\" x=numpy.array(x,_TYPE) return x -", "\"\"\" transformations :var __author__: name of author :var __copyright__: copyrights", "self.__angle=float(angle) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies the rotation to ``x``. \"\"\"", "Apache License, version 2.0 http://www.apache.org/licenses/LICENSE-2.0\"\"\" __url__=\"https://launchpad.net/escript-finley\" \"\"\" transformations :var __author__:", "a center and a given expansion/contraction factor. \"\"\" if not", "Business: Queensland, Australia\"\"\" __license__=\"\"\"Licensed under the Apache License, version 2.0", "the rotation to ``x``. \"\"\" x=numpy.array(x,_TYPE) z=x-self.__point z0=numpy.dot(z,self.__axis) z_per=z-z0*self.__axis lz_per=numpy.dot(z_per,z_per)", "if lax2>0: axis2/=math.sqrt(lax2) return z0*self.__axis+math.sqrt(lz_per)*(math.cos(self.__angle)*axis1-math.sin(self.__angle)*axis2)+self.__point else: return x else: return", "raise ValueError(\"points must be distinct.\") self.__axis/=math.sqrt(lax) self.__angle=float(angle) def __call__(self,x=numpy.zeros((3,))): \"\"\"", "on documentation :var __version__: version :var __date__: date of the", "the axis. \"\"\" self.__axis=numpy.array(axis,dtype=_TYPE) self.__point=numpy.array(point,dtype=_TYPE) lax=numpy.dot(self.__axis,self.__axis) if not lax>0: raise", "Sciences # Development from 2014 by Centre for Geoscience Computing", ":var __license__: licence agreement :var __url__: url entry point on", "\"\"\" Creates a rotation using an axis and a point", "__init__(self,b=numpy.zeros((3,),dtype=_TYPE)): \"\"\" Creates the linear transformation *x->x+b*. \"\"\" super(Translation, self).__init__()", "# Primary Business: Queensland, Australia # Licensed under the Apache", "division __copyright__=\"\"\"Copyright (c) 2003-2020 by The University of Queensland http://www.uq.edu.au", "self.__normal=numpy.array(normal,dtype=_TYPE) ln=math.sqrt(numpy.dot(self.__normal,self.__normal)) if not ln>0.: raise ValueError(\"normal must have positive", "self).__init__() self.__b=numpy.array(b,_TYPE) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies translation to ``x``. \"\"\"", "(c) 2003-2020 by The University of Queensland http://www.uq.edu.au Primary Business:", "y[1] - x[1] * y[0]], _TYPE) class Dilation(Transformation): \"\"\" Defines", "z0*self.__axis+math.sqrt(lz_per)*(math.cos(self.__angle)*axis1-math.sin(self.__angle)*axis2)+self.__point else: return x else: return x def _cross(x, y):", "__url__=\"https://launchpad.net/escript-finley\" \"\"\" transformations :var __author__: name of author :var __copyright__:", "DEG=math.pi/180. RAD=1. class Transformation(object): \"\"\" General class to define an", "\"\"\" Creates the linear transformation *x->x+b*. \"\"\" super(Translation, self).__init__() self.__b=numpy.array(b,_TYPE)", "Development 2012-2013 by School of Earth Sciences # Development from", "a plane defined in normal form. \"\"\" self.__normal=numpy.array(normal,dtype=_TYPE) ln=math.sqrt(numpy.dot(self.__normal,self.__normal)) if", "raise ValueError(\"normal must have positive length.\") self.__normal/=ln if isinstance(offset,float) or", ":var __copyright__: copyrights :var __license__: licence agreement :var __url__: url", "until 2012 by Earth Systems Science Computational Center (ESSCC) #", "class Transformation(object): \"\"\" General class to define an affine transformation", "self.__normal/=ln if isinstance(offset,float) or isinstance(offset,int): self.__offset=offset/ln else: self.__offset=numpy.dot(numpy.array(offset,dtype=_TYPE),self.__normal) def __call__(self,x=numpy.zeros((3,))):", "\"\"\" x=numpy.array(x,_TYPE) z=x-self.__point z0=numpy.dot(z,self.__axis) z_per=z-z0*self.__axis lz_per=numpy.dot(z_per,z_per) if lz_per>0: axis1=z_per/math.sqrt(lz_per) axis2=_cross(axis1,self.__axis)", "ln>0.: raise ValueError(\"normal must have positive length.\") self.__normal/=ln if isinstance(offset,float)", "a rotation. \"\"\" def __init__(self,axis=numpy.ones((3,),dtype=_TYPE),point=numpy.zeros((3,),dtype=_TYPE),angle=0.*RAD): \"\"\" Creates a rotation using", "\"\"\" self.__normal=numpy.array(normal,dtype=_TYPE) ln=math.sqrt(numpy.dot(self.__normal,self.__normal)) if not ln>0.: raise ValueError(\"normal must have", "by Earth Systems Science Computational Center (ESSCC) # Development 2012-2013", "\"\"\" Defines a rotation. \"\"\" def __init__(self,axis=numpy.ones((3,),dtype=_TYPE),point=numpy.zeros((3,),dtype=_TYPE),angle=0.*RAD): \"\"\" Creates a", "# Copyright (c) 2003-2020 by The University of Queensland #", "self.__axis/=math.sqrt(lax) self.__angle=float(angle) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies the rotation to ``x``.", "\"\"\" def __init__(self): \"\"\" Creates a linear transformation. \"\"\" pass", "numpy.array([x[1] * y[2] - x[2] * y[1], x[2] * y[0]", "DEG: unit of degree :var RAD: unit of radiant \"\"\"", "define an affine transformation *x->Ax+b*. \"\"\" def __init__(self): \"\"\" Creates", "__author__: name of author :var __copyright__: copyrights :var __license__: licence", "\"\"\" raise NotImplementeError() class Translation(Transformation): \"\"\" Defines a translation *x->x+b*.", "__call__(self,x=numpy.zeros((3,))): \"\"\" Applies the rotation to ``x``. \"\"\" x=numpy.array(x,_TYPE) z=x-self.__point", "degree :var RAD: unit of radiant \"\"\" __author__=\"<NAME>, <EMAIL>\" import", "y[0] - x[0] * y[2], x[0] * y[1] - x[1]", "- x[0] * y[2], x[0] * y[1] - x[1] *", "\"\"\" Applies transformation to ``x``. \"\"\" raise NotImplementeError() class Translation(Transformation):", "of degree :var RAD: unit of radiant \"\"\" __author__=\"<NAME>, <EMAIL>\"", "import print_function, division __copyright__=\"\"\"Copyright (c) 2003-2020 by The University of", "General class to define an affine transformation *x->Ax+b*. \"\"\" def", "\"\"\" def __init__(self,axis=numpy.ones((3,),dtype=_TYPE),point=numpy.zeros((3,),dtype=_TYPE),angle=0.*RAD): \"\"\" Creates a rotation using an axis", "have positive length.\") self.__normal/=ln if isinstance(offset,float) or isinstance(offset,int): self.__offset=offset/ln else:", "abs(factor)>0: raise ValueError(\"factor must be non-zero.\") self.__factor=factor self.__center=numpy.array(center,dtype=_TYPE) def __call__(self,x=numpy.zeros((3,))):", "length.\") self.__normal/=ln if isinstance(offset,float) or isinstance(offset,int): self.__offset=offset/ln else: self.__offset=numpy.dot(numpy.array(offset,dtype=_TYPE),self.__normal) def", "rotation using an axis and a point on the axis.", "rotation. \"\"\" def __init__(self,axis=numpy.ones((3,),dtype=_TYPE),point=numpy.zeros((3,),dtype=_TYPE),angle=0.*RAD): \"\"\" Creates a rotation using an", "The University of Queensland http://www.uq.edu.au Primary Business: Queensland, Australia\"\"\" __license__=\"\"\"Licensed", "transformation to ``x``. \"\"\" raise NotImplementeError() class Translation(Transformation): \"\"\" Defines", "__init__(self,factor=1.,center=numpy.zeros((3,),dtype=_TYPE)): \"\"\" Creates a dilation with a center and a", "School of Earth and Environmental Sciences # ############################################################################## from __future__", "licence agreement :var __url__: url entry point on documentation :var", "the cross product of ``x`` and ``y``. \"\"\" return numpy.array([x[1]", ":var DEG: unit of degree :var RAD: unit of radiant", "__copyright__=\"\"\"Copyright (c) 2003-2020 by The University of Queensland http://www.uq.edu.au Primary", "*x->x+b*. \"\"\" def __init__(self,b=numpy.zeros((3,),dtype=_TYPE)): \"\"\" Creates the linear transformation *x->x+b*.", "Systems Science Computational Center (ESSCC) # Development 2012-2013 by School", "using an axis and a point on the axis. \"\"\"", "Transformation(object): \"\"\" General class to define an affine transformation *x->Ax+b*.", "############################################################################## # # Copyright (c) 2003-2020 by The University of", "url entry point on documentation :var __version__: version :var __date__:", "License, version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # # Development until 2012", "of Earth and Environmental Sciences # ############################################################################## from __future__ import", "\"\"\" __author__=\"<NAME>, <EMAIL>\" import numpy import math _TYPE=numpy.float64 DEG=math.pi/180. RAD=1.", "Queensland http://www.uq.edu.au Primary Business: Queensland, Australia\"\"\" __license__=\"\"\"Licensed under the Apache", "ValueError(\"normal must have positive length.\") self.__normal/=ln if isinstance(offset,float) or isinstance(offset,int):", "x else: return x def _cross(x, y): \"\"\" Returns the", "isinstance(offset,float) or isinstance(offset,int): self.__offset=offset/ln else: self.__offset=numpy.dot(numpy.array(offset,dtype=_TYPE),self.__normal) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies", "with a center and a given expansion/contraction factor. \"\"\" if", "point on the axis. \"\"\" self.__axis=numpy.array(axis,dtype=_TYPE) self.__point=numpy.array(point,dtype=_TYPE) lax=numpy.dot(self.__axis,self.__axis) if not", "import numpy import math _TYPE=numpy.float64 DEG=math.pi/180. RAD=1. class Transformation(object): \"\"\"", "y[0]], _TYPE) class Dilation(Transformation): \"\"\" Defines a dilation. \"\"\" def", "factor. \"\"\" if not abs(factor)>0: raise ValueError(\"factor must be non-zero.\")", "\"\"\" Creates a linear transformation. \"\"\" pass def __call__(self,x=numpy.zeros((3,))): \"\"\"", "axis2/=math.sqrt(lax2) return z0*self.__axis+math.sqrt(lz_per)*(math.cos(self.__angle)*axis1-math.sin(self.__angle)*axis2)+self.__point else: return x else: return x def", "Development until 2012 by Earth Systems Science Computational Center (ESSCC)", "to ``x``. \"\"\" x=numpy.array(x,_TYPE) return self.__factor*(x-self.__center)+self.__center class Reflection(Transformation): \"\"\" Defines", "__copyright__: copyrights :var __license__: licence agreement :var __url__: url entry", "agreement :var __url__: url entry point on documentation :var __version__:", "x[0] * y[2], x[0] * y[1] - x[1] * y[0]],", "an affine transformation *x->Ax+b*. \"\"\" def __init__(self): \"\"\" Creates a", "def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies transformation to ``x``. \"\"\" raise NotImplementeError()", "``x``. \"\"\" return numpy.array(x,_TYPE)+self.__b class Rotatation(Transformation): \"\"\" Defines a rotation.", "``x``. \"\"\" x=numpy.array(x,_TYPE) return self.__factor*(x-self.__center)+self.__center class Reflection(Transformation): \"\"\" Defines a", "Applies translation to ``x``. \"\"\" return numpy.array(x,_TYPE)+self.__b class Rotatation(Transformation): \"\"\"", "on the axis. \"\"\" self.__axis=numpy.array(axis,dtype=_TYPE) self.__point=numpy.array(point,dtype=_TYPE) lax=numpy.dot(self.__axis,self.__axis) if not lax>0:", "self.__factor=factor self.__center=numpy.array(center,dtype=_TYPE) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies dilation to ``x``. \"\"\"", "and a point on the axis. \"\"\" self.__axis=numpy.array(axis,dtype=_TYPE) self.__point=numpy.array(point,dtype=_TYPE) lax=numpy.dot(self.__axis,self.__axis)", "class Reflection(Transformation): \"\"\" Defines a reflection on a plane. \"\"\"", "product of ``x`` and ``y``. \"\"\" return numpy.array([x[1] * y[2]", "y[1], x[2] * y[0] - x[0] * y[2], x[0] *", "__call__(self,x=numpy.zeros((3,))): \"\"\" Applies reflection to ``x``. \"\"\" x=numpy.array(x,_TYPE) return x", "Licensed under the Apache License, version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 #", "Science Computational Center (ESSCC) # Development 2012-2013 by School of", "2019 by School of Earth and Environmental Sciences # ##############################################################################", "class to define an affine transformation *x->Ax+b*. \"\"\" def __init__(self):", "\"\"\" super(Translation, self).__init__() self.__b=numpy.array(b,_TYPE) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies translation to", "# Development 2012-2013 by School of Earth Sciences # Development", "author :var __copyright__: copyrights :var __license__: licence agreement :var __url__:", "must be non-zero.\") self.__factor=factor self.__center=numpy.array(center,dtype=_TYPE) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies dilation", "class Dilation(Transformation): \"\"\" Defines a dilation. \"\"\" def __init__(self,factor=1.,center=numpy.zeros((3,),dtype=_TYPE)): \"\"\"", "\"\"\" Defines a reflection on a plane. \"\"\" def __init__(self,normal=numpy.ones((3,),dtype=_TYPE),offset=0.):", "\"\"\" self.__axis=numpy.array(axis,dtype=_TYPE) self.__point=numpy.array(point,dtype=_TYPE) lax=numpy.dot(self.__axis,self.__axis) if not lax>0: raise ValueError(\"points must", "on a plane. \"\"\" def __init__(self,normal=numpy.ones((3,),dtype=_TYPE),offset=0.): \"\"\" Defines a reflection", "unit of radiant \"\"\" __author__=\"<NAME>, <EMAIL>\" import numpy import math", "* y[2] - x[2] * y[1], x[2] * y[0] -", "by The University of Queensland # http://www.uq.edu.au # # Primary", "date of the version :var DEG: unit of degree :var", "def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies translation to ``x``. \"\"\" return numpy.array(x,_TYPE)+self.__b", "*x->Ax+b*. \"\"\" def __init__(self): \"\"\" Creates a linear transformation. \"\"\"", "of Queensland # http://www.uq.edu.au # # Primary Business: Queensland, Australia", "to ``x``. \"\"\" raise NotImplementeError() class Translation(Transformation): \"\"\" Defines a", "to ``x``. \"\"\" return numpy.array(x,_TYPE)+self.__b class Rotatation(Transformation): \"\"\" Defines a", "y[2] - x[2] * y[1], x[2] * y[0] - x[0]", "\"\"\" Applies translation to ``x``. \"\"\" return numpy.array(x,_TYPE)+self.__b class Rotatation(Transformation):", "* y[0]], _TYPE) class Dilation(Transformation): \"\"\" Defines a dilation. \"\"\"", "2012 by Earth Systems Science Computational Center (ESSCC) # Development", "given expansion/contraction factor. \"\"\" if not abs(factor)>0: raise ValueError(\"factor must", "a reflection on a plane defined in normal form. \"\"\"", "if not ln>0.: raise ValueError(\"normal must have positive length.\") self.__normal/=ln", "Queensland, Australia # Licensed under the Apache License, version 2.0", "University of Queensland # http://www.uq.edu.au # # Primary Business: Queensland,", "self.__axis=numpy.array(axis,dtype=_TYPE) self.__point=numpy.array(point,dtype=_TYPE) lax=numpy.dot(self.__axis,self.__axis) if not lax>0: raise ValueError(\"points must be", "Applies dilation to ``x``. \"\"\" x=numpy.array(x,_TYPE) return self.__factor*(x-self.__center)+self.__center class Reflection(Transformation):", "\"\"\" Defines a dilation. \"\"\" def __init__(self,factor=1.,center=numpy.zeros((3,),dtype=_TYPE)): \"\"\" Creates a", "linear transformation. \"\"\" pass def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies transformation to", "``x``. \"\"\" x=numpy.array(x,_TYPE) z=x-self.__point z0=numpy.dot(z,self.__axis) z_per=z-z0*self.__axis lz_per=numpy.dot(z_per,z_per) if lz_per>0: axis1=z_per/math.sqrt(lz_per)", "dilation. \"\"\" def __init__(self,factor=1.,center=numpy.zeros((3,),dtype=_TYPE)): \"\"\" Creates a dilation with a", "\"\"\" Defines a reflection on a plane defined in normal", "lax=numpy.dot(self.__axis,self.__axis) if not lax>0: raise ValueError(\"points must be distinct.\") self.__axis/=math.sqrt(lax)", "\"\"\" General class to define an affine transformation *x->Ax+b*. \"\"\"", "Center (ESSCC) # Development 2012-2013 by School of Earth Sciences", "of the version :var DEG: unit of degree :var RAD:", "Apache License, version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # # Development until", "a point on the axis. \"\"\" self.__axis=numpy.array(axis,dtype=_TYPE) self.__point=numpy.array(point,dtype=_TYPE) lax=numpy.dot(self.__axis,self.__axis) if", "\"\"\" if not abs(factor)>0: raise ValueError(\"factor must be non-zero.\") self.__factor=factor", "if not abs(factor)>0: raise ValueError(\"factor must be non-zero.\") self.__factor=factor self.__center=numpy.array(center,dtype=_TYPE)", "Defines a reflection on a plane. \"\"\" def __init__(self,normal=numpy.ones((3,),dtype=_TYPE),offset=0.): \"\"\"", "Computing (GeoComp) # Development from 2019 by School of Earth", "the Apache License, version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # # Development", "Business: Queensland, Australia # Licensed under the Apache License, version", "under the Apache License, version 2.0 http://www.apache.org/licenses/LICENSE-2.0\"\"\" __url__=\"https://launchpad.net/escript-finley\" \"\"\" transformations", "y): \"\"\" Returns the cross product of ``x`` and ``y``.", "NotImplementeError() class Translation(Transformation): \"\"\" Defines a translation *x->x+b*. \"\"\" def", "Earth Systems Science Computational Center (ESSCC) # Development 2012-2013 by", "axis and a point on the axis. \"\"\" self.__axis=numpy.array(axis,dtype=_TYPE) self.__point=numpy.array(point,dtype=_TYPE)", "Creates a linear transformation. \"\"\" pass def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies", "a dilation with a center and a given expansion/contraction factor.", "center and a given expansion/contraction factor. \"\"\" if not abs(factor)>0:", "def __init__(self,factor=1.,center=numpy.zeros((3,),dtype=_TYPE)): \"\"\" Creates a dilation with a center and", "License, version 2.0 http://www.apache.org/licenses/LICENSE-2.0\"\"\" __url__=\"https://launchpad.net/escript-finley\" \"\"\" transformations :var __author__: name", "# # Development until 2012 by Earth Systems Science Computational", "must be distinct.\") self.__axis/=math.sqrt(lax) self.__angle=float(angle) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies the", "Development from 2014 by Centre for Geoscience Computing (GeoComp) #", "- x[2] * y[1], x[2] * y[0] - x[0] *", "Applies transformation to ``x``. \"\"\" raise NotImplementeError() class Translation(Transformation): \"\"\"", "2012-2013 by School of Earth Sciences # Development from 2014", "Earth and Environmental Sciences # ############################################################################## from __future__ import print_function,", "2.0 http://www.apache.org/licenses/LICENSE-2.0\"\"\" __url__=\"https://launchpad.net/escript-finley\" \"\"\" transformations :var __author__: name of author", "University of Queensland http://www.uq.edu.au Primary Business: Queensland, Australia\"\"\" __license__=\"\"\"Licensed under", "numpy import math _TYPE=numpy.float64 DEG=math.pi/180. RAD=1. class Transformation(object): \"\"\" General", "http://www.uq.edu.au # # Primary Business: Queensland, Australia # Licensed under", "copyrights :var __license__: licence agreement :var __url__: url entry point", "unit of degree :var RAD: unit of radiant \"\"\" __author__=\"<NAME>,", "\"\"\" Applies the rotation to ``x``. \"\"\" x=numpy.array(x,_TYPE) z=x-self.__point z0=numpy.dot(z,self.__axis)", "self.__offset=numpy.dot(numpy.array(offset,dtype=_TYPE),self.__normal) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies reflection to ``x``. \"\"\" x=numpy.array(x,_TYPE)", "Reflection(Transformation): \"\"\" Defines a reflection on a plane. \"\"\" def", "``x``. \"\"\" raise NotImplementeError() class Translation(Transformation): \"\"\" Defines a translation", "Earth Sciences # Development from 2014 by Centre for Geoscience", "return x else: return x def _cross(x, y): \"\"\" Returns", "return numpy.array(x,_TYPE)+self.__b class Rotatation(Transformation): \"\"\" Defines a rotation. \"\"\" def", "a plane. \"\"\" def __init__(self,normal=numpy.ones((3,),dtype=_TYPE),offset=0.): \"\"\" Defines a reflection on", "Creates the linear transformation *x->x+b*. \"\"\" super(Translation, self).__init__() self.__b=numpy.array(b,_TYPE) def", "under the Apache License, version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # #", "Primary Business: Queensland, Australia\"\"\" __license__=\"\"\"Licensed under the Apache License, version", "def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies dilation to ``x``. \"\"\" x=numpy.array(x,_TYPE) return", "lax2>0: axis2/=math.sqrt(lax2) return z0*self.__axis+math.sqrt(lz_per)*(math.cos(self.__angle)*axis1-math.sin(self.__angle)*axis2)+self.__point else: return x else: return x", "Sciences # ############################################################################## from __future__ import print_function, division __copyright__=\"\"\"Copyright (c)", "* y[1], x[2] * y[0] - x[0] * y[2], x[0]", "return self.__factor*(x-self.__center)+self.__center class Reflection(Transformation): \"\"\" Defines a reflection on a", "a rotation using an axis and a point on the", "http://www.uq.edu.au Primary Business: Queensland, Australia\"\"\" __license__=\"\"\"Licensed under the Apache License,", "\"\"\" Returns the cross product of ``x`` and ``y``. \"\"\"", "``x`` and ``y``. \"\"\" return numpy.array([x[1] * y[2] - x[2]", "a linear transformation. \"\"\" pass def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies transformation", "reflection on a plane. \"\"\" def __init__(self,normal=numpy.ones((3,),dtype=_TYPE),offset=0.): \"\"\" Defines a", "version :var __date__: date of the version :var DEG: unit", "# http://www.apache.org/licenses/LICENSE-2.0 # # Development until 2012 by Earth Systems", "__init__(self): \"\"\" Creates a linear transformation. \"\"\" pass def __call__(self,x=numpy.zeros((3,))):", "* y[2], x[0] * y[1] - x[1] * y[0]], _TYPE)", "return z0*self.__axis+math.sqrt(lz_per)*(math.cos(self.__angle)*axis1-math.sin(self.__angle)*axis2)+self.__point else: return x else: return x def _cross(x,", "print_function, division __copyright__=\"\"\"Copyright (c) 2003-2020 by The University of Queensland", "\"\"\" Creates a dilation with a center and a given", "__license__=\"\"\"Licensed under the Apache License, version 2.0 http://www.apache.org/licenses/LICENSE-2.0\"\"\" __url__=\"https://launchpad.net/escript-finley\" \"\"\"", "plane defined in normal form. \"\"\" self.__normal=numpy.array(normal,dtype=_TYPE) ln=math.sqrt(numpy.dot(self.__normal,self.__normal)) if not", "normal form. \"\"\" self.__normal=numpy.array(normal,dtype=_TYPE) ln=math.sqrt(numpy.dot(self.__normal,self.__normal)) if not ln>0.: raise ValueError(\"normal", "Geoscience Computing (GeoComp) # Development from 2019 by School of", "def __init__(self): \"\"\" Creates a linear transformation. \"\"\" pass def", "math _TYPE=numpy.float64 DEG=math.pi/180. RAD=1. class Transformation(object): \"\"\" General class to", "else: return x else: return x def _cross(x, y): \"\"\"", "if lz_per>0: axis1=z_per/math.sqrt(lz_per) axis2=_cross(axis1,self.__axis) lax2=numpy.dot(axis2,axis2) if lax2>0: axis2/=math.sqrt(lax2) return z0*self.__axis+math.sqrt(lz_per)*(math.cos(self.__angle)*axis1-math.sin(self.__angle)*axis2)+self.__point", "or isinstance(offset,int): self.__offset=offset/ln else: self.__offset=numpy.dot(numpy.array(offset,dtype=_TYPE),self.__normal) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies reflection", "by School of Earth Sciences # Development from 2014 by", "__future__ import print_function, division __copyright__=\"\"\"Copyright (c) 2003-2020 by The University", "Defines a reflection on a plane defined in normal form.", "# Development from 2014 by Centre for Geoscience Computing (GeoComp)", "\"\"\" Applies dilation to ``x``. \"\"\" x=numpy.array(x,_TYPE) return self.__factor*(x-self.__center)+self.__center class", "axis2=_cross(axis1,self.__axis) lax2=numpy.dot(axis2,axis2) if lax2>0: axis2/=math.sqrt(lax2) return z0*self.__axis+math.sqrt(lz_per)*(math.cos(self.__angle)*axis1-math.sin(self.__angle)*axis2)+self.__point else: return x", "return numpy.array([x[1] * y[2] - x[2] * y[1], x[2] *", "by Centre for Geoscience Computing (GeoComp) # Development from 2019", "from 2019 by School of Earth and Environmental Sciences #", "Applies reflection to ``x``. \"\"\" x=numpy.array(x,_TYPE) return x - 2*(numpy.dot(x,self.__normal)-self.__offset)*self.__normal", "RAD=1. class Transformation(object): \"\"\" General class to define an affine", "transformation. \"\"\" pass def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies transformation to ``x``.", "(c) 2003-2020 by The University of Queensland # http://www.uq.edu.au #", "Rotatation(Transformation): \"\"\" Defines a rotation. \"\"\" def __init__(self,axis=numpy.ones((3,),dtype=_TYPE),point=numpy.zeros((3,),dtype=_TYPE),angle=0.*RAD): \"\"\" Creates", "radiant \"\"\" __author__=\"<NAME>, <EMAIL>\" import numpy import math _TYPE=numpy.float64 DEG=math.pi/180.", "of radiant \"\"\" __author__=\"<NAME>, <EMAIL>\" import numpy import math _TYPE=numpy.float64", "_TYPE=numpy.float64 DEG=math.pi/180. RAD=1. class Transformation(object): \"\"\" General class to define", "``y``. \"\"\" return numpy.array([x[1] * y[2] - x[2] * y[1],", "# Development until 2012 by Earth Systems Science Computational Center", "and Environmental Sciences # ############################################################################## from __future__ import print_function, division", "def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies reflection to ``x``. \"\"\" x=numpy.array(x,_TYPE) return", "School of Earth Sciences # Development from 2014 by Centre", "Translation(Transformation): \"\"\" Defines a translation *x->x+b*. \"\"\" def __init__(self,b=numpy.zeros((3,),dtype=_TYPE)): \"\"\"", "__call__(self,x=numpy.zeros((3,))): \"\"\" Applies translation to ``x``. \"\"\" return numpy.array(x,_TYPE)+self.__b class", "cross product of ``x`` and ``y``. \"\"\" return numpy.array([x[1] *", "reflection on a plane defined in normal form. \"\"\" self.__normal=numpy.array(normal,dtype=_TYPE)", "x def _cross(x, y): \"\"\" Returns the cross product of", "plane. \"\"\" def __init__(self,normal=numpy.ones((3,),dtype=_TYPE),offset=0.): \"\"\" Defines a reflection on a", "Australia # Licensed under the Apache License, version 2.0 #", "pass def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies transformation to ``x``. \"\"\" raise", "transformation *x->Ax+b*. \"\"\" def __init__(self): \"\"\" Creates a linear transformation.", "# # Primary Business: Queensland, Australia # Licensed under the", ":var __version__: version :var __date__: date of the version :var", "an axis and a point on the axis. \"\"\" self.__axis=numpy.array(axis,dtype=_TYPE)", "z=x-self.__point z0=numpy.dot(z,self.__axis) z_per=z-z0*self.__axis lz_per=numpy.dot(z_per,z_per) if lz_per>0: axis1=z_per/math.sqrt(lz_per) axis2=_cross(axis1,self.__axis) lax2=numpy.dot(axis2,axis2) if", "name of author :var __copyright__: copyrights :var __license__: licence agreement", "Queensland # http://www.uq.edu.au # # Primary Business: Queensland, Australia #", "a dilation. \"\"\" def __init__(self,factor=1.,center=numpy.zeros((3,),dtype=_TYPE)): \"\"\" Creates a dilation with", "# http://www.uq.edu.au # # Primary Business: Queensland, Australia # Licensed", "not abs(factor)>0: raise ValueError(\"factor must be non-zero.\") self.__factor=factor self.__center=numpy.array(center,dtype=_TYPE) def", "on a plane defined in normal form. \"\"\" self.__normal=numpy.array(normal,dtype=_TYPE) ln=math.sqrt(numpy.dot(self.__normal,self.__normal))", "Computational Center (ESSCC) # Development 2012-2013 by School of Earth", "entry point on documentation :var __version__: version :var __date__: date", "x[1] * y[0]], _TYPE) class Dilation(Transformation): \"\"\" Defines a dilation.", "dilation to ``x``. \"\"\" x=numpy.array(x,_TYPE) return self.__factor*(x-self.__center)+self.__center class Reflection(Transformation): \"\"\"", "\"\"\" def __init__(self,normal=numpy.ones((3,),dtype=_TYPE),offset=0.): \"\"\" Defines a reflection on a plane", "affine transformation *x->Ax+b*. \"\"\" def __init__(self): \"\"\" Creates a linear", "ValueError(\"points must be distinct.\") self.__axis/=math.sqrt(lax) self.__angle=float(angle) def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies", "def __call__(self,x=numpy.zeros((3,))): \"\"\" Applies the rotation to ``x``. \"\"\" x=numpy.array(x,_TYPE)", "__call__(self,x=numpy.zeros((3,))): \"\"\" Applies transformation to ``x``. \"\"\" raise NotImplementeError() class", "_TYPE) class Dilation(Transformation): \"\"\" Defines a dilation. \"\"\" def __init__(self,factor=1.,center=numpy.zeros((3,),dtype=_TYPE)):", "defined in normal form. \"\"\" self.__normal=numpy.array(normal,dtype=_TYPE) ln=math.sqrt(numpy.dot(self.__normal,self.__normal)) if not ln>0.:", "translation *x->x+b*. \"\"\" def __init__(self,b=numpy.zeros((3,),dtype=_TYPE)): \"\"\" Creates the linear transformation", "Environmental Sciences # ############################################################################## from __future__ import print_function, division __copyright__=\"\"\"Copyright" ]
[ "Cosmological constant # Solver definitions Rstart = 3 Rend =", "<gh_stars>1-10 from bosonstar.ComplexBosonStar import Complex_Boson_Star # ===================== # All imporntnat", "50.00 deltaR = 1 N = 100000 e_pow_minus_delta_guess = 0.4999", "5.0 # Dimension (total not only spacial) Lambda = -0.2", "pewpew.print_parameters() alpha0 = pewpew.radial_walker(Rstart, Rend, deltaR, N, eps) # =====================================", "pewpew.radial_walker(Rstart, Rend, deltaR, N, eps) # ===================================== # Output and", "= 0.4999 verbose = 2 eps = 1e-10 # Small", "= 1e-10 # Small epsilon to avoid r \\neq 0", "# ===================== # All imporntnat definitions # ===================== # Physics", "= -0.2 # Cosmological constant # Solver definitions Rstart =", "centeral phi D = 5.0 # Dimension (total not only", "Physics defintions phi0 = 0.40 # centeral phi D =", "essential step, but recommended) pewpew.normalise_edelta() pewpew.check_Einstein_equation() # =============================== path =", "plotting # ===================================== soldict = pewpew.get_solution() # Makes sure that", "Complex_Boson_Star # ===================== # All imporntnat definitions # ===================== #", "deltaR = 1 N = 100000 e_pow_minus_delta_guess = 0.4999 verbose", "alpha0 = pewpew.radial_walker(Rstart, Rend, deltaR, N, eps) # ===================================== #", "# All imporntnat definitions # ===================== # Physics defintions phi0", "0.4999 verbose = 2 eps = 1e-10 # Small epsilon", "===================================== # Output and plotting # ===================================== soldict = pewpew.get_solution()", "definitions # ===================== # Physics defintions phi0 = 0.40 #", "bosonstar.ComplexBosonStar import Complex_Boson_Star # ===================== # All imporntnat definitions #", "Solver definitions Rstart = 3 Rend = 50.00 deltaR =", "Lambda = -0.2 # Cosmological constant # Solver definitions Rstart", "= 5.0 # Dimension (total not only spacial) Lambda =", "eps) # ===================================== # Output and plotting # ===================================== soldict", "# Physics defintions phi0 = 0.40 # centeral phi D", "= 1 N = 100000 e_pow_minus_delta_guess = 0.4999 verbose =", "but recommended) pewpew.normalise_edelta() pewpew.check_Einstein_equation() # =============================== path = pewpew.get_path() pewpew.plot_solution()", "(total not only spacial) Lambda = -0.2 # Cosmological constant", "Output and plotting # ===================================== soldict = pewpew.get_solution() # Makes", "imporntnat definitions # ===================== # Physics defintions phi0 = 0.40", "goes asymptotically to 1 # (Not an essential step, but", "constant # Solver definitions Rstart = 3 Rend = 50.00", "phi0, D, Lambda, verbose) pewpew.print_parameters() alpha0 = pewpew.radial_walker(Rstart, Rend, deltaR,", "100000 e_pow_minus_delta_guess = 0.4999 verbose = 2 eps = 1e-10", "only spacial) Lambda = -0.2 # Cosmological constant # Solver", "# Dimension (total not only spacial) Lambda = -0.2 #", "D, Lambda, verbose) pewpew.print_parameters() alpha0 = pewpew.radial_walker(Rstart, Rend, deltaR, N,", "soldict = pewpew.get_solution() # Makes sure that lapse goes asymptotically", "# Main routine # ==================================== pewpew = Complex_Boson_Star(e_pow_minus_delta_guess, phi0, D,", "import Complex_Boson_Star # ===================== # All imporntnat definitions # =====================", "N = 100000 e_pow_minus_delta_guess = 0.4999 verbose = 2 eps", "0 # ==================================== # Main routine # ==================================== pewpew =", "# Makes sure that lapse goes asymptotically to 1 #", "= 2 eps = 1e-10 # Small epsilon to avoid", "defintions phi0 = 0.40 # centeral phi D = 5.0", "# Small epsilon to avoid r \\neq 0 # ====================================", "==================================== pewpew = Complex_Boson_Star(e_pow_minus_delta_guess, phi0, D, Lambda, verbose) pewpew.print_parameters() alpha0", "to avoid r \\neq 0 # ==================================== # Main routine", "avoid r \\neq 0 # ==================================== # Main routine #", "deltaR, N, eps) # ===================================== # Output and plotting #", "asymptotically to 1 # (Not an essential step, but recommended)", "recommended) pewpew.normalise_edelta() pewpew.check_Einstein_equation() # =============================== path = pewpew.get_path() pewpew.plot_solution() pewpew.print_solution()", "lapse goes asymptotically to 1 # (Not an essential step,", "Makes sure that lapse goes asymptotically to 1 # (Not", "pewpew.get_solution() # Makes sure that lapse goes asymptotically to 1", "Small epsilon to avoid r \\neq 0 # ==================================== #", "===================================== soldict = pewpew.get_solution() # Makes sure that lapse goes", "Lambda, verbose) pewpew.print_parameters() alpha0 = pewpew.radial_walker(Rstart, Rend, deltaR, N, eps)", "===================== # Physics defintions phi0 = 0.40 # centeral phi", "\\neq 0 # ==================================== # Main routine # ==================================== pewpew", "= Complex_Boson_Star(e_pow_minus_delta_guess, phi0, D, Lambda, verbose) pewpew.print_parameters() alpha0 = pewpew.radial_walker(Rstart,", "step, but recommended) pewpew.normalise_edelta() pewpew.check_Einstein_equation() # =============================== path = pewpew.get_path()", "# Solver definitions Rstart = 3 Rend = 50.00 deltaR", "1 # (Not an essential step, but recommended) pewpew.normalise_edelta() pewpew.check_Einstein_equation()", "2 eps = 1e-10 # Small epsilon to avoid r", "that lapse goes asymptotically to 1 # (Not an essential", "phi0 = 0.40 # centeral phi D = 5.0 #", "and plotting # ===================================== soldict = pewpew.get_solution() # Makes sure", "N, eps) # ===================================== # Output and plotting # =====================================", "D = 5.0 # Dimension (total not only spacial) Lambda", "= 100000 e_pow_minus_delta_guess = 0.4999 verbose = 2 eps =", "to 1 # (Not an essential step, but recommended) pewpew.normalise_edelta()", "verbose) pewpew.print_parameters() alpha0 = pewpew.radial_walker(Rstart, Rend, deltaR, N, eps) #", "# centeral phi D = 5.0 # Dimension (total not", "definitions Rstart = 3 Rend = 50.00 deltaR = 1", "an essential step, but recommended) pewpew.normalise_edelta() pewpew.check_Einstein_equation() # =============================== path", "1 N = 100000 e_pow_minus_delta_guess = 0.4999 verbose = 2", "==================================== # Main routine # ==================================== pewpew = Complex_Boson_Star(e_pow_minus_delta_guess, phi0,", "# (Not an essential step, but recommended) pewpew.normalise_edelta() pewpew.check_Einstein_equation() #", "# ===================== # Physics defintions phi0 = 0.40 # centeral", "verbose = 2 eps = 1e-10 # Small epsilon to", "Rend, deltaR, N, eps) # ===================================== # Output and plotting", "r \\neq 0 # ==================================== # Main routine # ====================================", "(Not an essential step, but recommended) pewpew.normalise_edelta() pewpew.check_Einstein_equation() # ===============================", "Dimension (total not only spacial) Lambda = -0.2 # Cosmological", "pewpew = Complex_Boson_Star(e_pow_minus_delta_guess, phi0, D, Lambda, verbose) pewpew.print_parameters() alpha0 =", "# ===================================== soldict = pewpew.get_solution() # Makes sure that lapse", "eps = 1e-10 # Small epsilon to avoid r \\neq", "# ==================================== # Main routine # ==================================== pewpew = Complex_Boson_Star(e_pow_minus_delta_guess,", "-0.2 # Cosmological constant # Solver definitions Rstart = 3", "Main routine # ==================================== pewpew = Complex_Boson_Star(e_pow_minus_delta_guess, phi0, D, Lambda,", "# Output and plotting # ===================================== soldict = pewpew.get_solution() #", "# ===================================== # Output and plotting # ===================================== soldict =", "= pewpew.get_solution() # Makes sure that lapse goes asymptotically to", "Complex_Boson_Star(e_pow_minus_delta_guess, phi0, D, Lambda, verbose) pewpew.print_parameters() alpha0 = pewpew.radial_walker(Rstart, Rend,", "# Cosmological constant # Solver definitions Rstart = 3 Rend", "= 0.40 # centeral phi D = 5.0 # Dimension", "from bosonstar.ComplexBosonStar import Complex_Boson_Star # ===================== # All imporntnat definitions", "Rend = 50.00 deltaR = 1 N = 100000 e_pow_minus_delta_guess", "1e-10 # Small epsilon to avoid r \\neq 0 #", "0.40 # centeral phi D = 5.0 # Dimension (total", "3 Rend = 50.00 deltaR = 1 N = 100000", "epsilon to avoid r \\neq 0 # ==================================== # Main", "All imporntnat definitions # ===================== # Physics defintions phi0 =", "routine # ==================================== pewpew = Complex_Boson_Star(e_pow_minus_delta_guess, phi0, D, Lambda, verbose)", "e_pow_minus_delta_guess = 0.4999 verbose = 2 eps = 1e-10 #", "= 50.00 deltaR = 1 N = 100000 e_pow_minus_delta_guess =", "= 3 Rend = 50.00 deltaR = 1 N =", "phi D = 5.0 # Dimension (total not only spacial)", "= pewpew.radial_walker(Rstart, Rend, deltaR, N, eps) # ===================================== # Output", "Rstart = 3 Rend = 50.00 deltaR = 1 N", "not only spacial) Lambda = -0.2 # Cosmological constant #", "sure that lapse goes asymptotically to 1 # (Not an", "===================== # All imporntnat definitions # ===================== # Physics defintions", "# ==================================== pewpew = Complex_Boson_Star(e_pow_minus_delta_guess, phi0, D, Lambda, verbose) pewpew.print_parameters()", "spacial) Lambda = -0.2 # Cosmological constant # Solver definitions" ]
[ "as f: license = f.read() with open('requirements.txt', encoding='utf-8') as f:", "with open('requirements.txt', encoding='utf-8') as f: reqs = f.read() pkgs =", "for p in find_packages() if p.startswith('fastNLP')] print(pkgs) setup( name='FastNLP', version='0.7.0',", "p.startswith('fastNLP')] print(pkgs) setup( name='FastNLP', version='0.7.0', url='https://gitee.com/fastnlp/fastNLP', description='fastNLP: Deep Learning Toolkit", "FastNLP Team', long_description=readme, long_description_content_type='text/markdown', license='Apache License', author='<NAME>', python_requires='>=3.6', packages=pkgs, install_requires=reqs.strip().split('\\n'),", "open('requirements.txt', encoding='utf-8') as f: reqs = f.read() pkgs = [p", "Team', long_description=readme, long_description_content_type='text/markdown', license='Apache License', author='<NAME>', python_requires='>=3.6', packages=pkgs, install_requires=reqs.strip().split('\\n'), )", "= [p for p in find_packages() if p.startswith('fastNLP')] print(pkgs) setup(", "description='fastNLP: Deep Learning Toolkit for NLP, developed by Fudan FastNLP", "Toolkit for NLP, developed by Fudan FastNLP Team', long_description=readme, long_description_content_type='text/markdown',", "[p for p in find_packages() if p.startswith('fastNLP')] print(pkgs) setup( name='FastNLP',", "setup, find_packages with open('README.md', encoding='utf-8') as f: readme = f.read()", "f.read() pkgs = [p for p in find_packages() if p.startswith('fastNLP')]", "if p.startswith('fastNLP')] print(pkgs) setup( name='FastNLP', version='0.7.0', url='https://gitee.com/fastnlp/fastNLP', description='fastNLP: Deep Learning", "print(pkgs) setup( name='FastNLP', version='0.7.0', url='https://gitee.com/fastnlp/fastNLP', description='fastNLP: Deep Learning Toolkit for", "with open('README.md', encoding='utf-8') as f: readme = f.read() with open('LICENSE',", "readme = f.read() with open('LICENSE', encoding='utf-8') as f: license =", "#!/usr/bin/env python # coding=utf-8 from setuptools import setup, find_packages with", "encoding='utf-8') as f: license = f.read() with open('requirements.txt', encoding='utf-8') as", "import setup, find_packages with open('README.md', encoding='utf-8') as f: readme =", "setup( name='FastNLP', version='0.7.0', url='https://gitee.com/fastnlp/fastNLP', description='fastNLP: Deep Learning Toolkit for NLP,", "in find_packages() if p.startswith('fastNLP')] print(pkgs) setup( name='FastNLP', version='0.7.0', url='https://gitee.com/fastnlp/fastNLP', description='fastNLP:", "by Fudan FastNLP Team', long_description=readme, long_description_content_type='text/markdown', license='Apache License', author='<NAME>', python_requires='>=3.6',", "NLP, developed by Fudan FastNLP Team', long_description=readme, long_description_content_type='text/markdown', license='Apache License',", "find_packages() if p.startswith('fastNLP')] print(pkgs) setup( name='FastNLP', version='0.7.0', url='https://gitee.com/fastnlp/fastNLP', description='fastNLP: Deep", "f: readme = f.read() with open('LICENSE', encoding='utf-8') as f: license", "name='FastNLP', version='0.7.0', url='https://gitee.com/fastnlp/fastNLP', description='fastNLP: Deep Learning Toolkit for NLP, developed", "encoding='utf-8') as f: reqs = f.read() pkgs = [p for", "for NLP, developed by Fudan FastNLP Team', long_description=readme, long_description_content_type='text/markdown', license='Apache", "as f: readme = f.read() with open('LICENSE', encoding='utf-8') as f:", "coding=utf-8 from setuptools import setup, find_packages with open('README.md', encoding='utf-8') as", "as f: reqs = f.read() pkgs = [p for p", "= f.read() with open('LICENSE', encoding='utf-8') as f: license = f.read()", "url='https://gitee.com/fastnlp/fastNLP', description='fastNLP: Deep Learning Toolkit for NLP, developed by Fudan", "open('LICENSE', encoding='utf-8') as f: license = f.read() with open('requirements.txt', encoding='utf-8')", "with open('LICENSE', encoding='utf-8') as f: license = f.read() with open('requirements.txt',", "f: license = f.read() with open('requirements.txt', encoding='utf-8') as f: reqs", "f: reqs = f.read() pkgs = [p for p in", "f.read() with open('requirements.txt', encoding='utf-8') as f: reqs = f.read() pkgs", "Fudan FastNLP Team', long_description=readme, long_description_content_type='text/markdown', license='Apache License', author='<NAME>', python_requires='>=3.6', packages=pkgs,", "developed by Fudan FastNLP Team', long_description=readme, long_description_content_type='text/markdown', license='Apache License', author='<NAME>',", "open('README.md', encoding='utf-8') as f: readme = f.read() with open('LICENSE', encoding='utf-8')", "f.read() with open('LICENSE', encoding='utf-8') as f: license = f.read() with", "# coding=utf-8 from setuptools import setup, find_packages with open('README.md', encoding='utf-8')", "= f.read() with open('requirements.txt', encoding='utf-8') as f: reqs = f.read()", "encoding='utf-8') as f: readme = f.read() with open('LICENSE', encoding='utf-8') as", "python # coding=utf-8 from setuptools import setup, find_packages with open('README.md',", "Learning Toolkit for NLP, developed by Fudan FastNLP Team', long_description=readme,", "Deep Learning Toolkit for NLP, developed by Fudan FastNLP Team',", "license = f.read() with open('requirements.txt', encoding='utf-8') as f: reqs =", "pkgs = [p for p in find_packages() if p.startswith('fastNLP')] print(pkgs)", "p in find_packages() if p.startswith('fastNLP')] print(pkgs) setup( name='FastNLP', version='0.7.0', url='https://gitee.com/fastnlp/fastNLP',", "version='0.7.0', url='https://gitee.com/fastnlp/fastNLP', description='fastNLP: Deep Learning Toolkit for NLP, developed by", "setuptools import setup, find_packages with open('README.md', encoding='utf-8') as f: readme", "from setuptools import setup, find_packages with open('README.md', encoding='utf-8') as f:", "reqs = f.read() pkgs = [p for p in find_packages()", "find_packages with open('README.md', encoding='utf-8') as f: readme = f.read() with", "= f.read() pkgs = [p for p in find_packages() if" ]
[ "Access Token. Public APIs are mostly used in browsers. #", "ApiAttributeError from ory_client.exceptions import ApiTypeError from ory_client.exceptions import ApiValueError from", "ory_client.exceptions import ApiValueError from ory_client.exceptions import ApiKeyError from ory_client.exceptions import", "# flake8: noqa \"\"\" Ory APIs Documentation for all public", "can only be accessed with a valid Personal Access Token.", "are mostly used in browsers. # noqa: E501 The version", "Administrative APIs can only be accessed with a valid Personal", "a valid Personal Access Token. Public APIs are mostly used", "in browsers. # noqa: E501 The version of the OpenAPI", "\"v0.0.1-alpha.187\" # import ApiClient from ory_client.api_client import ApiClient # import", "document: v0.0.1-alpha.187 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" __version__ =", "Ory APIs Documentation for all public and administrative Ory APIs.", "OpenApiException from ory_client.exceptions import ApiAttributeError from ory_client.exceptions import ApiTypeError from", "<EMAIL> Generated by: https://openapi-generator.tech \"\"\" __version__ = \"v0.0.1-alpha.187\" # import", "all public and administrative Ory APIs. Administrative APIs can only", "APIs. Administrative APIs can only be accessed with a valid", "import OpenApiException from ory_client.exceptions import ApiAttributeError from ory_client.exceptions import ApiTypeError", "https://openapi-generator.tech \"\"\" __version__ = \"v0.0.1-alpha.187\" # import ApiClient from ory_client.api_client", "import Configuration # import exceptions from ory_client.exceptions import OpenApiException from", "accessed with a valid Personal Access Token. Public APIs are", "The version of the OpenAPI document: v0.0.1-alpha.187 Contact: <EMAIL> Generated", "and administrative Ory APIs. Administrative APIs can only be accessed", "import ApiClient from ory_client.api_client import ApiClient # import Configuration from", "ory_client.configuration import Configuration # import exceptions from ory_client.exceptions import OpenApiException", "ory_client.exceptions import ApiTypeError from ory_client.exceptions import ApiValueError from ory_client.exceptions import", "exceptions from ory_client.exceptions import OpenApiException from ory_client.exceptions import ApiAttributeError from", "__version__ = \"v0.0.1-alpha.187\" # import ApiClient from ory_client.api_client import ApiClient", "ApiClient # import Configuration from ory_client.configuration import Configuration # import", "only be accessed with a valid Personal Access Token. Public", "Configuration from ory_client.configuration import Configuration # import exceptions from ory_client.exceptions", "noqa: E501 The version of the OpenAPI document: v0.0.1-alpha.187 Contact:", "the OpenAPI document: v0.0.1-alpha.187 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\"", "by: https://openapi-generator.tech \"\"\" __version__ = \"v0.0.1-alpha.187\" # import ApiClient from", "import Configuration from ory_client.configuration import Configuration # import exceptions from", "import ApiClient # import Configuration from ory_client.configuration import Configuration #", "be accessed with a valid Personal Access Token. Public APIs", "Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" __version__ = \"v0.0.1-alpha.187\" #", "Generated by: https://openapi-generator.tech \"\"\" __version__ = \"v0.0.1-alpha.187\" # import ApiClient", "import exceptions from ory_client.exceptions import OpenApiException from ory_client.exceptions import ApiAttributeError", "from ory_client.exceptions import OpenApiException from ory_client.exceptions import ApiAttributeError from ory_client.exceptions", "import ApiValueError from ory_client.exceptions import ApiKeyError from ory_client.exceptions import ApiException", "used in browsers. # noqa: E501 The version of the", "from ory_client.api_client import ApiClient # import Configuration from ory_client.configuration import", "Token. Public APIs are mostly used in browsers. # noqa:", "for all public and administrative Ory APIs. Administrative APIs can", "ApiClient from ory_client.api_client import ApiClient # import Configuration from ory_client.configuration", "# import exceptions from ory_client.exceptions import OpenApiException from ory_client.exceptions import", "import ApiAttributeError from ory_client.exceptions import ApiTypeError from ory_client.exceptions import ApiValueError", "Configuration # import exceptions from ory_client.exceptions import OpenApiException from ory_client.exceptions", "E501 The version of the OpenAPI document: v0.0.1-alpha.187 Contact: <EMAIL>", "OpenAPI document: v0.0.1-alpha.187 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" __version__", "= \"v0.0.1-alpha.187\" # import ApiClient from ory_client.api_client import ApiClient #", "from ory_client.configuration import Configuration # import exceptions from ory_client.exceptions import", "Personal Access Token. Public APIs are mostly used in browsers.", "from ory_client.exceptions import ApiTypeError from ory_client.exceptions import ApiValueError from ory_client.exceptions", "APIs Documentation for all public and administrative Ory APIs. Administrative", "\"\"\" __version__ = \"v0.0.1-alpha.187\" # import ApiClient from ory_client.api_client import", "<filename>clients/client/python/ory_client/__init__.py # flake8: noqa \"\"\" Ory APIs Documentation for all", "ory_client.api_client import ApiClient # import Configuration from ory_client.configuration import Configuration", "ory_client.exceptions import OpenApiException from ory_client.exceptions import ApiAttributeError from ory_client.exceptions import", "\"\"\" Ory APIs Documentation for all public and administrative Ory", "administrative Ory APIs. Administrative APIs can only be accessed with", "v0.0.1-alpha.187 Contact: <EMAIL> Generated by: https://openapi-generator.tech \"\"\" __version__ = \"v0.0.1-alpha.187\"", "Ory APIs. Administrative APIs can only be accessed with a", "noqa \"\"\" Ory APIs Documentation for all public and administrative", "ApiTypeError from ory_client.exceptions import ApiValueError from ory_client.exceptions import ApiKeyError from", "Public APIs are mostly used in browsers. # noqa: E501", "public and administrative Ory APIs. Administrative APIs can only be", "ory_client.exceptions import ApiAttributeError from ory_client.exceptions import ApiTypeError from ory_client.exceptions import", "version of the OpenAPI document: v0.0.1-alpha.187 Contact: <EMAIL> Generated by:", "flake8: noqa \"\"\" Ory APIs Documentation for all public and", "browsers. # noqa: E501 The version of the OpenAPI document:", "# import Configuration from ory_client.configuration import Configuration # import exceptions", "with a valid Personal Access Token. Public APIs are mostly", "Documentation for all public and administrative Ory APIs. Administrative APIs", "import ApiTypeError from ory_client.exceptions import ApiValueError from ory_client.exceptions import ApiKeyError", "from ory_client.exceptions import ApiValueError from ory_client.exceptions import ApiKeyError from ory_client.exceptions", "# noqa: E501 The version of the OpenAPI document: v0.0.1-alpha.187", "valid Personal Access Token. Public APIs are mostly used in", "APIs are mostly used in browsers. # noqa: E501 The", "from ory_client.exceptions import ApiAttributeError from ory_client.exceptions import ApiTypeError from ory_client.exceptions", "of the OpenAPI document: v0.0.1-alpha.187 Contact: <EMAIL> Generated by: https://openapi-generator.tech", "APIs can only be accessed with a valid Personal Access", "# import ApiClient from ory_client.api_client import ApiClient # import Configuration", "mostly used in browsers. # noqa: E501 The version of" ]
[ "the corresponding response. Provide the prediction response and extra information", "the bias attribute configs, these decide which attributes may be", "compute the reward\"\"\" @abstractmethod def get_module_version(self) -> str: \"\"\"Return the", "def compute_reward(self, outcome_request: dict) -> ComputeRewardResponse: \"\"\"From an outcome, compute", "request to the provided url and returns the corresponding response", "the prediction. The response and dictionary will be provided to", "BiasAttributeConfigListResponse, ComputeRewardResponse, DefaultPredictionResponse, ExclusionRuleConditionListResponse, PredictionResponsePayloadFormatListResponse) class BaseActivityCustomCode(ABC): \"\"\" The main", "Define the exclusion rules for the activity \"\"\" return ExclusionRuleConditionListResponse(exclusion_rule_conditions=[])", "\"\"\" The main class of this repository: the one to", "-> Response: \"\"\" Send a mock request to the provided", "the one to be implemented \"\"\" is_for_mocker: bool def __init__(self,", "created while creating the prediction request from `send_mock_prediction_request`. \"\"\" def", "class BaseActivityCustomCode(ABC): \"\"\" The main class of this repository: the", "of the module.\"\"\" @abstractmethod def send_mock_prediction_request( self, url_prediction_endpoint: str )", "\"\"\" Define the bias attribute configs, these decide which attributes", "attributes may be used by atmospherex as bias attributes \"\"\"", "str, prediction_response: Response, info_from_prediction: dict, ) -> Response: \"\"\" Send", "while creating the prediction request from `send_mock_prediction_request`. \"\"\" def get_prediction_response_payload_formats(", "information if required for computing the prediction. The response and", ") -> PredictionResponsePayloadFormatListResponse: \"\"\" Return the list of available format", "dict) -> None: \"\"\"Raise a ValidationError if the received prediction", "\"\"\" def get_prediction_response_payload_formats( self, ) -> PredictionResponsePayloadFormatListResponse: \"\"\" Return the", "default \"\"\" return default_prediction_response def get_exclusion_rule_conditions(self) -> ExclusionRuleConditionListResponse: \"\"\" Define", "the activity \"\"\" return ExclusionRuleConditionListResponse(exclusion_rule_conditions=[]) def get_applied_exclusion_conditions( self, prediction_request: dict", "one to be implemented \"\"\" is_for_mocker: bool def __init__(self, is_for_mocker:", "the version of the module.\"\"\" @abstractmethod def send_mock_prediction_request( self, url_prediction_endpoint:", "url_prediction_endpoint: str ) -> Tuple[Response, dict]: \"\"\" Send a mock", "request to the provided url and returns the corresponding response.", "= is_for_mocker @abstractmethod def validate_prediction_request(self, prediction_request: dict) -> None: \"\"\"Raise", "can format the prediction the way you want based on", "return AppliedExclusionConditionsResponse(applied_exclusion_conditions=[]) def get_bias_attribute_configs(self) -> BiasAttributeConfigListResponse: \"\"\" Define the bias", "ExclusionRuleConditionListResponse(exclusion_rule_conditions=[]) def get_applied_exclusion_conditions( self, prediction_request: dict # noqa pylint: disable=unused-argument", "# noqa pylint: disable=unused-argument ) -> AppliedExclusionConditionsResponse: \"\"\" Define the", "of this repository: the one to be implemented \"\"\" is_for_mocker:", "None: \"\"\"Raise a ValidationError if the received prediction request is", "url and returns the corresponding response with extra information if", "from `send_mock_prediction_request`. \"\"\" def get_prediction_response_payload_formats( self, ) -> PredictionResponsePayloadFormatListResponse: \"\"\"", "is_for_mocker @abstractmethod def validate_prediction_request(self, prediction_request: dict) -> None: \"\"\"Raise a", "@abstractmethod def send_mock_prediction_request( self, url_prediction_endpoint: str ) -> Tuple[Response, dict]:", "PredictionResponsePayloadFormatListResponse: \"\"\" Return the list of available format of the", "repository: the one to be implemented \"\"\" is_for_mocker: bool def", "from .pydantic_models import (AppliedExclusionConditionsResponse, BiasAttributeConfigListResponse, ComputeRewardResponse, DefaultPredictionResponse, ExclusionRuleConditionListResponse, PredictionResponsePayloadFormatListResponse) class", "way you want based on the information returned by default", "pylint: disable=unused-argument ) -> dict: \"\"\" You can format the", "attribute configs, these decide which attributes may be used by", "outcome_request: dict) -> ComputeRewardResponse: \"\"\"From an outcome, compute the reward\"\"\"", "Send a mock request to the provided url and returns", "None: \"\"\"Raise a ValidationError if the received outcome request is", "-> Tuple[Response, dict]: \"\"\" Send a mock request to the", "url_outcome_endpoint: str, prediction_response: Response, info_from_prediction: dict, ) -> Response: \"\"\"", "for computing the prediction. The response and dictionary will be", "prediction request from `send_mock_prediction_request`. \"\"\" def get_prediction_response_payload_formats( self, ) ->", "format_prediction_payload_response( self, default_prediction_response: DefaultPredictionResponse, payload_format: str, # noqa pylint: disable=unused-argument", "\"\"\"Return the version of the module.\"\"\" @abstractmethod def send_mock_prediction_request( self,", "PredictionResponsePayloadFormatListResponse) class BaseActivityCustomCode(ABC): \"\"\" The main class of this repository:", "be provided to the `send_mock_outcome_request`. \"\"\" @abstractmethod def send_mock_outcome_request( self,", "not valid\"\"\" @abstractmethod def compute_reward(self, outcome_request: dict) -> ComputeRewardResponse: \"\"\"From", "get_prediction_response_payload_formats( self, ) -> PredictionResponsePayloadFormatListResponse: \"\"\" Return the list of", "BiasAttributeConfigListResponse: \"\"\" Define the bias attribute configs, these decide which", "The name of the format should be unique. \"\"\" return", "received prediction request is not valid\"\"\" @abstractmethod def validate_outcome_request(self, outcome_request:", ") -> AppliedExclusionConditionsResponse: \"\"\" Define the exclusion rules for the", "these decide which attributes may be used by atmospherex as", "exclusion rules for the activity \"\"\" return ExclusionRuleConditionListResponse(exclusion_rule_conditions=[]) def get_applied_exclusion_conditions(", "import Tuple from requests import Response from .pydantic_models import (AppliedExclusionConditionsResponse,", "default_prediction_response: DefaultPredictionResponse, payload_format: str, # noqa pylint: disable=unused-argument ) ->", "by default \"\"\" return default_prediction_response def get_exclusion_rule_conditions(self) -> ExclusionRuleConditionListResponse: \"\"\"", "module.\"\"\" @abstractmethod def send_mock_prediction_request( self, url_prediction_endpoint: str ) -> Tuple[Response,", "outcome request is not valid\"\"\" @abstractmethod def compute_reward(self, outcome_request: dict)", "return ExclusionRuleConditionListResponse(exclusion_rule_conditions=[]) def get_applied_exclusion_conditions( self, prediction_request: dict # noqa pylint:", "the prediction request from `send_mock_prediction_request`. \"\"\" def get_prediction_response_payload_formats( self, )", "is not valid\"\"\" @abstractmethod def compute_reward(self, outcome_request: dict) -> ComputeRewardResponse:", "Define the exclusion rules for the activity \"\"\" return AppliedExclusionConditionsResponse(applied_exclusion_conditions=[])", "from typing import Tuple from requests import Response from .pydantic_models", "prediction_request: dict # noqa pylint: disable=unused-argument ) -> AppliedExclusionConditionsResponse: \"\"\"", "= False): self.is_for_mocker = is_for_mocker @abstractmethod def validate_prediction_request(self, prediction_request: dict)", "on the information returned by default \"\"\" return default_prediction_response def", "dict) -> ComputeRewardResponse: \"\"\"From an outcome, compute the reward\"\"\" @abstractmethod", "extra information created while creating the prediction request from `send_mock_prediction_request`.", "a ValidationError if the received prediction request is not valid\"\"\"", "the corresponding response with extra information if required for computing", "def validate_prediction_request(self, prediction_request: dict) -> None: \"\"\"Raise a ValidationError if", "to be implemented \"\"\" is_for_mocker: bool def __init__(self, is_for_mocker: bool", "@abstractmethod def validate_prediction_request(self, prediction_request: dict) -> None: \"\"\"Raise a ValidationError", "from abc import ABC, abstractmethod from typing import Tuple from", "return {\"prediction_response_payload_formats\": []} def format_prediction_payload_response( self, default_prediction_response: DefaultPredictionResponse, payload_format: str,", "is_for_mocker: bool def __init__(self, is_for_mocker: bool = False): self.is_for_mocker =", "the information returned by default \"\"\" return default_prediction_response def get_exclusion_rule_conditions(self)", "extra information if required for computing the prediction. The response", "str, # noqa pylint: disable=unused-argument ) -> dict: \"\"\" You", "-> ExclusionRuleConditionListResponse: \"\"\" Define the exclusion rules for the activity", "import Response from .pydantic_models import (AppliedExclusionConditionsResponse, BiasAttributeConfigListResponse, ComputeRewardResponse, DefaultPredictionResponse, ExclusionRuleConditionListResponse,", "prediction the way you want based on the information returned", "the exclusion rules for the activity \"\"\" return AppliedExclusionConditionsResponse(applied_exclusion_conditions=[]) def", "Define the bias attribute configs, these decide which attributes may", "abstractmethod from typing import Tuple from requests import Response from", "a ValidationError if the received outcome request is not valid\"\"\"", "activity \"\"\" return AppliedExclusionConditionsResponse(applied_exclusion_conditions=[]) def get_bias_attribute_configs(self) -> BiasAttributeConfigListResponse: \"\"\" Define", "will be provided to the `send_mock_outcome_request`. \"\"\" @abstractmethod def send_mock_outcome_request(", "may be used by atmospherex as bias attributes \"\"\" return", "the `send_mock_outcome_request`. \"\"\" @abstractmethod def send_mock_outcome_request( self, url_outcome_endpoint: str, prediction_response:", "from requests import Response from .pydantic_models import (AppliedExclusionConditionsResponse, BiasAttributeConfigListResponse, ComputeRewardResponse,", "The main class of this repository: the one to be", "returned by default \"\"\" return default_prediction_response def get_exclusion_rule_conditions(self) -> ExclusionRuleConditionListResponse:", "if required for computing the prediction. The response and dictionary", "def send_mock_outcome_request( self, url_outcome_endpoint: str, prediction_response: Response, info_from_prediction: dict, )", "the received outcome request is not valid\"\"\" @abstractmethod def compute_reward(self,", "a name and a description The name of the format", "typing import Tuple from requests import Response from .pydantic_models import", "corresponding response with extra information if required for computing the", "and dictionary will be provided to the `send_mock_outcome_request`. \"\"\" @abstractmethod", "self, prediction_request: dict # noqa pylint: disable=unused-argument ) -> AppliedExclusionConditionsResponse:", "response and extra information created while creating the prediction request", "-> None: \"\"\"Raise a ValidationError if the received prediction request", "and extra information created while creating the prediction request from", "\"\"\" is_for_mocker: bool def __init__(self, is_for_mocker: bool = False): self.is_for_mocker", "not valid\"\"\" @abstractmethod def validate_outcome_request(self, outcome_request: dict) -> None: \"\"\"Raise", "AppliedExclusionConditionsResponse: \"\"\" Define the exclusion rules for the activity \"\"\"", "returns the corresponding response with extra information if required for", "\"\"\" Return the list of available format of the prediction", "received outcome request is not valid\"\"\" @abstractmethod def compute_reward(self, outcome_request:", "to the provided url and returns the corresponding response. Provide", "of available format of the prediction payload. Every format should", "request is not valid\"\"\" @abstractmethod def validate_outcome_request(self, outcome_request: dict) ->", "-> AppliedExclusionConditionsResponse: \"\"\" Define the exclusion rules for the activity", "-> str: \"\"\"Return the version of the module.\"\"\" @abstractmethod def", "main class of this repository: the one to be implemented", "noqa pylint: disable=unused-argument ) -> AppliedExclusionConditionsResponse: \"\"\" Define the exclusion", "with extra information if required for computing the prediction. The", "def get_exclusion_rule_conditions(self) -> ExclusionRuleConditionListResponse: \"\"\" Define the exclusion rules for", "def format_prediction_payload_response( self, default_prediction_response: DefaultPredictionResponse, payload_format: str, # noqa pylint:", "`send_mock_outcome_request`. \"\"\" @abstractmethod def send_mock_outcome_request( self, url_outcome_endpoint: str, prediction_response: Response,", "get_applied_exclusion_conditions( self, prediction_request: dict # noqa pylint: disable=unused-argument ) ->", "a description The name of the format should be unique.", "def get_bias_attribute_configs(self) -> BiasAttributeConfigListResponse: \"\"\" Define the bias attribute configs,", "noqa pylint: disable=unused-argument ) -> dict: \"\"\" You can format", "format of the prediction payload. Every format should have a", "def get_module_version(self) -> str: \"\"\"Return the version of the module.\"\"\"", "returns the corresponding response. Provide the prediction response and extra", "the exclusion rules for the activity \"\"\" return ExclusionRuleConditionListResponse(exclusion_rule_conditions=[]) def", "validate_outcome_request(self, outcome_request: dict) -> None: \"\"\"Raise a ValidationError if the", "prediction response and extra information created while creating the prediction", "should be unique. \"\"\" return {\"prediction_response_payload_formats\": []} def format_prediction_payload_response( self,", "DefaultPredictionResponse, ExclusionRuleConditionListResponse, PredictionResponsePayloadFormatListResponse) class BaseActivityCustomCode(ABC): \"\"\" The main class of", "response and dictionary will be provided to the `send_mock_outcome_request`. \"\"\"", "self.is_for_mocker = is_for_mocker @abstractmethod def validate_prediction_request(self, prediction_request: dict) -> None:", "def get_applied_exclusion_conditions( self, prediction_request: dict # noqa pylint: disable=unused-argument )", "outcome_request: dict) -> None: \"\"\"Raise a ValidationError if the received", "send_mock_prediction_request( self, url_prediction_endpoint: str ) -> Tuple[Response, dict]: \"\"\" Send", "bool def __init__(self, is_for_mocker: bool = False): self.is_for_mocker = is_for_mocker", "corresponding response. Provide the prediction response and extra information created", "payload. Every format should have a name and a description", "[]} def format_prediction_payload_response( self, default_prediction_response: DefaultPredictionResponse, payload_format: str, # noqa", "the activity \"\"\" return AppliedExclusionConditionsResponse(applied_exclusion_conditions=[]) def get_bias_attribute_configs(self) -> BiasAttributeConfigListResponse: \"\"\"", "activity \"\"\" return ExclusionRuleConditionListResponse(exclusion_rule_conditions=[]) def get_applied_exclusion_conditions( self, prediction_request: dict #", "ValidationError if the received outcome request is not valid\"\"\" @abstractmethod", "to the provided url and returns the corresponding response with", "-> BiasAttributeConfigListResponse: \"\"\" Define the bias attribute configs, these decide", "<filename>atmosphere/custom_activity/base_class.py<gh_stars>0 from abc import ABC, abstractmethod from typing import Tuple", "the provided url and returns the corresponding response with extra", "validate_prediction_request(self, prediction_request: dict) -> None: \"\"\"Raise a ValidationError if the", "str: \"\"\"Return the version of the module.\"\"\" @abstractmethod def send_mock_prediction_request(", "Response, info_from_prediction: dict, ) -> Response: \"\"\" Send a mock", "ValidationError if the received prediction request is not valid\"\"\" @abstractmethod", "__init__(self, is_for_mocker: bool = False): self.is_for_mocker = is_for_mocker @abstractmethod def", "{\"prediction_response_payload_formats\": []} def format_prediction_payload_response( self, default_prediction_response: DefaultPredictionResponse, payload_format: str, #", "-> ComputeRewardResponse: \"\"\"From an outcome, compute the reward\"\"\" @abstractmethod def", "@abstractmethod def get_module_version(self) -> str: \"\"\"Return the version of the", "-> PredictionResponsePayloadFormatListResponse: \"\"\" Return the list of available format of", "`send_mock_prediction_request`. \"\"\" def get_prediction_response_payload_formats( self, ) -> PredictionResponsePayloadFormatListResponse: \"\"\" Return", "list of available format of the prediction payload. Every format", "should have a name and a description The name of", "\"\"\" return default_prediction_response def get_exclusion_rule_conditions(self) -> ExclusionRuleConditionListResponse: \"\"\" Define the", "dict: \"\"\" You can format the prediction the way you", "prediction. The response and dictionary will be provided to the", "information returned by default \"\"\" return default_prediction_response def get_exclusion_rule_conditions(self) ->", "mock request to the provided url and returns the corresponding", "unique. \"\"\" return {\"prediction_response_payload_formats\": []} def format_prediction_payload_response( self, default_prediction_response: DefaultPredictionResponse,", "class of this repository: the one to be implemented \"\"\"", "rules for the activity \"\"\" return ExclusionRuleConditionListResponse(exclusion_rule_conditions=[]) def get_applied_exclusion_conditions( self,", "configs, these decide which attributes may be used by atmospherex", "disable=unused-argument ) -> AppliedExclusionConditionsResponse: \"\"\" Define the exclusion rules for", "format should be unique. \"\"\" return {\"prediction_response_payload_formats\": []} def format_prediction_payload_response(", "Return the list of available format of the prediction payload.", "import (AppliedExclusionConditionsResponse, BiasAttributeConfigListResponse, ComputeRewardResponse, DefaultPredictionResponse, ExclusionRuleConditionListResponse, PredictionResponsePayloadFormatListResponse) class BaseActivityCustomCode(ABC): \"\"\"", "and returns the corresponding response with extra information if required", "dict) -> None: \"\"\"Raise a ValidationError if the received outcome", "format should have a name and a description The name", "format the prediction the way you want based on the", "the module.\"\"\" @abstractmethod def send_mock_prediction_request( self, url_prediction_endpoint: str ) ->", "the provided url and returns the corresponding response. Provide the", "the prediction the way you want based on the information", "\"\"\" Send a mock request to the provided url and", "ExclusionRuleConditionListResponse: \"\"\" Define the exclusion rules for the activity \"\"\"", "\"\"\"From an outcome, compute the reward\"\"\" @abstractmethod def get_module_version(self) ->", "be implemented \"\"\" is_for_mocker: bool def __init__(self, is_for_mocker: bool =", "provided to the `send_mock_outcome_request`. \"\"\" @abstractmethod def send_mock_outcome_request( self, url_outcome_endpoint:", "request from `send_mock_prediction_request`. \"\"\" def get_prediction_response_payload_formats( self, ) -> PredictionResponsePayloadFormatListResponse:", "available format of the prediction payload. Every format should have", "valid\"\"\" @abstractmethod def validate_outcome_request(self, outcome_request: dict) -> None: \"\"\"Raise a", "(AppliedExclusionConditionsResponse, BiasAttributeConfigListResponse, ComputeRewardResponse, DefaultPredictionResponse, ExclusionRuleConditionListResponse, PredictionResponsePayloadFormatListResponse) class BaseActivityCustomCode(ABC): \"\"\" The", "name of the format should be unique. \"\"\" return {\"prediction_response_payload_formats\":", "AppliedExclusionConditionsResponse(applied_exclusion_conditions=[]) def get_bias_attribute_configs(self) -> BiasAttributeConfigListResponse: \"\"\" Define the bias attribute", "for the activity \"\"\" return ExclusionRuleConditionListResponse(exclusion_rule_conditions=[]) def get_applied_exclusion_conditions( self, prediction_request:", "import ABC, abstractmethod from typing import Tuple from requests import", "computing the prediction. The response and dictionary will be provided", "this repository: the one to be implemented \"\"\" is_for_mocker: bool", "a mock request to the provided url and returns the", "-> None: \"\"\"Raise a ValidationError if the received outcome request", "default_prediction_response def get_exclusion_rule_conditions(self) -> ExclusionRuleConditionListResponse: \"\"\" Define the exclusion rules", "decide which attributes may be used by atmospherex as bias", "provided url and returns the corresponding response. Provide the prediction", "of the format should be unique. \"\"\" return {\"prediction_response_payload_formats\": []}", "get_exclusion_rule_conditions(self) -> ExclusionRuleConditionListResponse: \"\"\" Define the exclusion rules for the", "the reward\"\"\" @abstractmethod def get_module_version(self) -> str: \"\"\"Return the version", "DefaultPredictionResponse, payload_format: str, # noqa pylint: disable=unused-argument ) -> dict:", "prediction request is not valid\"\"\" @abstractmethod def validate_outcome_request(self, outcome_request: dict)", "\"\"\" return ExclusionRuleConditionListResponse(exclusion_rule_conditions=[]) def get_applied_exclusion_conditions( self, prediction_request: dict # noqa", "ComputeRewardResponse, DefaultPredictionResponse, ExclusionRuleConditionListResponse, PredictionResponsePayloadFormatListResponse) class BaseActivityCustomCode(ABC): \"\"\" The main class", "compute_reward(self, outcome_request: dict) -> ComputeRewardResponse: \"\"\"From an outcome, compute the", "def __init__(self, is_for_mocker: bool = False): self.is_for_mocker = is_for_mocker @abstractmethod", "The response and dictionary will be provided to the `send_mock_outcome_request`.", "dict, ) -> Response: \"\"\" Send a mock request to", "dict]: \"\"\" Send a mock request to the provided url", "the received prediction request is not valid\"\"\" @abstractmethod def validate_outcome_request(self,", "\"\"\" return {\"prediction_response_payload_formats\": []} def format_prediction_payload_response( self, default_prediction_response: DefaultPredictionResponse, payload_format:", "exclusion rules for the activity \"\"\" return AppliedExclusionConditionsResponse(applied_exclusion_conditions=[]) def get_bias_attribute_configs(self)", "\"\"\" Define the exclusion rules for the activity \"\"\" return", "disable=unused-argument ) -> dict: \"\"\" You can format the prediction", "requests import Response from .pydantic_models import (AppliedExclusionConditionsResponse, BiasAttributeConfigListResponse, ComputeRewardResponse, DefaultPredictionResponse,", "required for computing the prediction. The response and dictionary will", "rules for the activity \"\"\" return AppliedExclusionConditionsResponse(applied_exclusion_conditions=[]) def get_bias_attribute_configs(self) ->", "self, default_prediction_response: DefaultPredictionResponse, payload_format: str, # noqa pylint: disable=unused-argument )", "for the activity \"\"\" return AppliedExclusionConditionsResponse(applied_exclusion_conditions=[]) def get_bias_attribute_configs(self) -> BiasAttributeConfigListResponse:", "which attributes may be used by atmospherex as bias attributes", ".pydantic_models import (AppliedExclusionConditionsResponse, BiasAttributeConfigListResponse, ComputeRewardResponse, DefaultPredictionResponse, ExclusionRuleConditionListResponse, PredictionResponsePayloadFormatListResponse) class BaseActivityCustomCode(ABC):", "dict # noqa pylint: disable=unused-argument ) -> AppliedExclusionConditionsResponse: \"\"\" Define", "Response from .pydantic_models import (AppliedExclusionConditionsResponse, BiasAttributeConfigListResponse, ComputeRewardResponse, DefaultPredictionResponse, ExclusionRuleConditionListResponse, PredictionResponsePayloadFormatListResponse)", "bias attribute configs, these decide which attributes may be used", "info_from_prediction: dict, ) -> Response: \"\"\" Send a mock request", "reward\"\"\" @abstractmethod def get_module_version(self) -> str: \"\"\"Return the version of", ") -> Tuple[Response, dict]: \"\"\" Send a mock request to", "of the prediction payload. Every format should have a name", "description The name of the format should be unique. \"\"\"", "version of the module.\"\"\" @abstractmethod def send_mock_prediction_request( self, url_prediction_endpoint: str", "Tuple from requests import Response from .pydantic_models import (AppliedExclusionConditionsResponse, BiasAttributeConfigListResponse,", "and a description The name of the format should be", "Provide the prediction response and extra information created while creating", "implemented \"\"\" is_for_mocker: bool def __init__(self, is_for_mocker: bool = False):", "be used by atmospherex as bias attributes \"\"\" return BiasAttributeConfigListResponse(bias_attribute_configs=[])", "be unique. \"\"\" return {\"prediction_response_payload_formats\": []} def format_prediction_payload_response( self, default_prediction_response:", "dictionary will be provided to the `send_mock_outcome_request`. \"\"\" @abstractmethod def", "get_module_version(self) -> str: \"\"\"Return the version of the module.\"\"\" @abstractmethod", "prediction_response: Response, info_from_prediction: dict, ) -> Response: \"\"\" Send a", "return default_prediction_response def get_exclusion_rule_conditions(self) -> ExclusionRuleConditionListResponse: \"\"\" Define the exclusion", "the prediction payload. Every format should have a name and", "def validate_outcome_request(self, outcome_request: dict) -> None: \"\"\"Raise a ValidationError if", "is_for_mocker: bool = False): self.is_for_mocker = is_for_mocker @abstractmethod def validate_prediction_request(self,", "response with extra information if required for computing the prediction.", "Every format should have a name and a description The", "str ) -> Tuple[Response, dict]: \"\"\" Send a mock request", "the list of available format of the prediction payload. Every", "-> dict: \"\"\" You can format the prediction the way", "# noqa pylint: disable=unused-argument ) -> dict: \"\"\" You can", "Tuple[Response, dict]: \"\"\" Send a mock request to the provided", ") -> dict: \"\"\" You can format the prediction the", "information created while creating the prediction request from `send_mock_prediction_request`. \"\"\"", "BaseActivityCustomCode(ABC): \"\"\" The main class of this repository: the one", "get_bias_attribute_configs(self) -> BiasAttributeConfigListResponse: \"\"\" Define the bias attribute configs, these", "an outcome, compute the reward\"\"\" @abstractmethod def get_module_version(self) -> str:", "\"\"\" @abstractmethod def send_mock_outcome_request( self, url_outcome_endpoint: str, prediction_response: Response, info_from_prediction:", "ExclusionRuleConditionListResponse, PredictionResponsePayloadFormatListResponse) class BaseActivityCustomCode(ABC): \"\"\" The main class of this", "\"\"\"Raise a ValidationError if the received prediction request is not", "self, ) -> PredictionResponsePayloadFormatListResponse: \"\"\" Return the list of available", "if the received prediction request is not valid\"\"\" @abstractmethod def", "abc import ABC, abstractmethod from typing import Tuple from requests", "outcome, compute the reward\"\"\" @abstractmethod def get_module_version(self) -> str: \"\"\"Return", "prediction_request: dict) -> None: \"\"\"Raise a ValidationError if the received", "@abstractmethod def validate_outcome_request(self, outcome_request: dict) -> None: \"\"\"Raise a ValidationError", "ComputeRewardResponse: \"\"\"From an outcome, compute the reward\"\"\" @abstractmethod def get_module_version(self)", "have a name and a description The name of the", "to the `send_mock_outcome_request`. \"\"\" @abstractmethod def send_mock_outcome_request( self, url_outcome_endpoint: str,", "You can format the prediction the way you want based", "want based on the information returned by default \"\"\" return", "False): self.is_for_mocker = is_for_mocker @abstractmethod def validate_prediction_request(self, prediction_request: dict) ->", "\"\"\" You can format the prediction the way you want", ") -> Response: \"\"\" Send a mock request to the", "@abstractmethod def compute_reward(self, outcome_request: dict) -> ComputeRewardResponse: \"\"\"From an outcome,", "self, url_prediction_endpoint: str ) -> Tuple[Response, dict]: \"\"\" Send a", "the way you want based on the information returned by", "\"\"\"Raise a ValidationError if the received outcome request is not", "based on the information returned by default \"\"\" return default_prediction_response", "\"\"\" return AppliedExclusionConditionsResponse(applied_exclusion_conditions=[]) def get_bias_attribute_configs(self) -> BiasAttributeConfigListResponse: \"\"\" Define the", "request is not valid\"\"\" @abstractmethod def compute_reward(self, outcome_request: dict) ->", "def send_mock_prediction_request( self, url_prediction_endpoint: str ) -> Tuple[Response, dict]: \"\"\"", "if the received outcome request is not valid\"\"\" @abstractmethod def", "provided url and returns the corresponding response with extra information", "url and returns the corresponding response. Provide the prediction response", "@abstractmethod def send_mock_outcome_request( self, url_outcome_endpoint: str, prediction_response: Response, info_from_prediction: dict,", "and returns the corresponding response. Provide the prediction response and", "def get_prediction_response_payload_formats( self, ) -> PredictionResponsePayloadFormatListResponse: \"\"\" Return the list", "ABC, abstractmethod from typing import Tuple from requests import Response", "the format should be unique. \"\"\" return {\"prediction_response_payload_formats\": []} def", "name and a description The name of the format should", "the prediction response and extra information created while creating the", "prediction payload. Every format should have a name and a", "Response: \"\"\" Send a mock request to the provided url", "creating the prediction request from `send_mock_prediction_request`. \"\"\" def get_prediction_response_payload_formats( self,", "valid\"\"\" @abstractmethod def compute_reward(self, outcome_request: dict) -> ComputeRewardResponse: \"\"\"From an", "payload_format: str, # noqa pylint: disable=unused-argument ) -> dict: \"\"\"", "you want based on the information returned by default \"\"\"", "pylint: disable=unused-argument ) -> AppliedExclusionConditionsResponse: \"\"\" Define the exclusion rules", "is not valid\"\"\" @abstractmethod def validate_outcome_request(self, outcome_request: dict) -> None:", "send_mock_outcome_request( self, url_outcome_endpoint: str, prediction_response: Response, info_from_prediction: dict, ) ->", "self, url_outcome_endpoint: str, prediction_response: Response, info_from_prediction: dict, ) -> Response:", "bool = False): self.is_for_mocker = is_for_mocker @abstractmethod def validate_prediction_request(self, prediction_request:", "response. Provide the prediction response and extra information created while" ]
[ "String type, which should be unicode type(my_str) #declare string: ip_addr", "#check it with boolean:(True) ip_addr == '192.168.1.1' #(false) ip_addr ==", "ip_addr '1.1' in ip_addr '15.1' not in ip_addr #Strings also", "the first character ip_addr[0] #we can also get the last", "for all strings. my_str = 'whatever' #Shows the String type,", "'1' which is the first character ip_addr[0] #we can also", "unicode_literals #Ensures Unicode is used for all strings. my_str =", "Unicode is used for all strings. my_str = 'whatever' #Shows", "of string: len(ip_addr) #Example string concatenation my_str = 'Hello' my_str", "#Shows the String type, which should be unicode type(my_str) #declare", "= '192.168.1.1' #check it with boolean:(True) ip_addr == '192.168.1.1' #(false)", "#show length of string: len(ip_addr) #Example string concatenation my_str =", "ip_addr[0] #we can also get the last using negative notation.", "= 'whatever' #Shows the String type, which should be unicode", "the case below we get '1' which is the first", "#in the case below we get '1' which is the", "len(ip_addr) #Example string concatenation my_str = 'Hello' my_str + '", "in ip_addr #Strings also have indices starting at '0' #in", "all strings. my_str = 'whatever' #Shows the String type, which", "follow gets the last: ip_addr[-1] #second to last: ip_addr[-2] #show", "'10.1.1.1' #is this substring in this variable? '192.168' in ip_addr", "from __future__ import print_function, unicode_literals #Ensures Unicode is used for", "also have indices starting at '0' #in the case below", "== '192.168.1.1' #(false) ip_addr == '10.1.1.1' #is this substring in", "starting at '0' #in the case below we get '1'", "'192.168.1.1' #(false) ip_addr == '10.1.1.1' #is this substring in this", "#second to last: ip_addr[-2] #show length of string: len(ip_addr) #Example", "below we get '1' which is the first character ip_addr[0]", "it with boolean:(True) ip_addr == '192.168.1.1' #(false) ip_addr == '10.1.1.1'", "'0' #in the case below we get '1' which is", "at '0' #in the case below we get '1' which", "indices starting at '0' #in the case below we get", "'15.1' not in ip_addr #Strings also have indices starting at", "'192.168.1.1' #check it with boolean:(True) ip_addr == '192.168.1.1' #(false) ip_addr", "in ip_addr '15.1' not in ip_addr #Strings also have indices", "negative notation. The follow gets the last: ip_addr[-1] #second to", "ip_addr[-1] #second to last: ip_addr[-2] #show length of string: len(ip_addr)", "print_function, unicode_literals #Ensures Unicode is used for all strings. my_str", "type, which should be unicode type(my_str) #declare string: ip_addr =", "ip_addr #Strings also have indices starting at '0' #in the", "with boolean:(True) ip_addr == '192.168.1.1' #(false) ip_addr == '10.1.1.1' #is", "length of string: len(ip_addr) #Example string concatenation my_str = 'Hello'", "the last using negative notation. The follow gets the last:", "ip_addr = '192.168.1.1' #check it with boolean:(True) ip_addr == '192.168.1.1'", "last: ip_addr[-2] #show length of string: len(ip_addr) #Example string concatenation", "string: ip_addr = '192.168.1.1' #check it with boolean:(True) ip_addr ==", "character ip_addr[0] #we can also get the last using negative", "boolean:(True) ip_addr == '192.168.1.1' #(false) ip_addr == '10.1.1.1' #is this", "The follow gets the last: ip_addr[-1] #second to last: ip_addr[-2]", "#Example string concatenation my_str = 'Hello' my_str + ' something'", "strings. my_str = 'whatever' #Shows the String type, which should", "is the first character ip_addr[0] #we can also get the", "gets the last: ip_addr[-1] #second to last: ip_addr[-2] #show length", "not in ip_addr #Strings also have indices starting at '0'", "my_str = 'whatever' #Shows the String type, which should be", "should be unicode type(my_str) #declare string: ip_addr = '192.168.1.1' #check", "__future__ import print_function, unicode_literals #Ensures Unicode is used for all", "used for all strings. my_str = 'whatever' #Shows the String", "this substring in this variable? '192.168' in ip_addr '1.1' in", "substring in this variable? '192.168' in ip_addr '1.1' in ip_addr", "unicode type(my_str) #declare string: ip_addr = '192.168.1.1' #check it with", "#(false) ip_addr == '10.1.1.1' #is this substring in this variable?", "the last: ip_addr[-1] #second to last: ip_addr[-2] #show length of", "ip_addr '15.1' not in ip_addr #Strings also have indices starting", "we get '1' which is the first character ip_addr[0] #we", "type(my_str) #declare string: ip_addr = '192.168.1.1' #check it with boolean:(True)", "is used for all strings. my_str = 'whatever' #Shows the", "using negative notation. The follow gets the last: ip_addr[-1] #second", "get the last using negative notation. The follow gets the", "the String type, which should be unicode type(my_str) #declare string:", "last: ip_addr[-1] #second to last: ip_addr[-2] #show length of string:", "string: len(ip_addr) #Example string concatenation my_str = 'Hello' my_str +", "ip_addr[-2] #show length of string: len(ip_addr) #Example string concatenation my_str", "be unicode type(my_str) #declare string: ip_addr = '192.168.1.1' #check it", "#is this substring in this variable? '192.168' in ip_addr '1.1'", "#Ensures Unicode is used for all strings. my_str = 'whatever'", "== '10.1.1.1' #is this substring in this variable? '192.168' in", "which is the first character ip_addr[0] #we can also get", "which should be unicode type(my_str) #declare string: ip_addr = '192.168.1.1'", "last using negative notation. The follow gets the last: ip_addr[-1]", "variable? '192.168' in ip_addr '1.1' in ip_addr '15.1' not in", "can also get the last using negative notation. The follow", "this variable? '192.168' in ip_addr '1.1' in ip_addr '15.1' not", "'1.1' in ip_addr '15.1' not in ip_addr #Strings also have", "'whatever' #Shows the String type, which should be unicode type(my_str)", "ip_addr == '192.168.1.1' #(false) ip_addr == '10.1.1.1' #is this substring", "get '1' which is the first character ip_addr[0] #we can", "also get the last using negative notation. The follow gets", "'192.168' in ip_addr '1.1' in ip_addr '15.1' not in ip_addr", "have indices starting at '0' #in the case below we", "ip_addr == '10.1.1.1' #is this substring in this variable? '192.168'", "first character ip_addr[0] #we can also get the last using", "<reponame>modulo16/PfNE from __future__ import print_function, unicode_literals #Ensures Unicode is used", "notation. The follow gets the last: ip_addr[-1] #second to last:", "case below we get '1' which is the first character", "in this variable? '192.168' in ip_addr '1.1' in ip_addr '15.1'", "in ip_addr '1.1' in ip_addr '15.1' not in ip_addr #Strings", "#declare string: ip_addr = '192.168.1.1' #check it with boolean:(True) ip_addr", "#we can also get the last using negative notation. The", "to last: ip_addr[-2] #show length of string: len(ip_addr) #Example string", "import print_function, unicode_literals #Ensures Unicode is used for all strings.", "#Strings also have indices starting at '0' #in the case" ]
[ "buffer pp_kbddriver_plus.inputs['previous-line'] = pp_kbddriver_plus.inputs['current-line'] pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['current-character']='' if name !='': #", "self.event_callback('pp-key-'+ char,pp_kbddriver_plus.title) else: if name != '': # print 'bound", "a new line if match =='<Return>': # do match of", "is False: return 'error','No DRIVER section in '+self.filepath # all", "self.event_callback(name,pp_kbddriver_plus.title) # look through entries for any-character for entry in", "Return to make eol work' # go through entries and", "== 'DRIVER': continue entry=copy.deepcopy(pp_kbddriver_plus.TEMPLATE) entry[pp_kbddriver_plus.NAME]=self.config.get(section,'name') entry[pp_kbddriver_plus.DIRECTION]=self.config.get(section,'direction') if entry[pp_kbddriver_plus.DIRECTION] == 'none':", "DIRECTION = 1 # in/out MATCH = 2 # for", "(but fileterd in _key_received) canvas.bind(\"<Key>\", lambda event,match='<Key>',name='': self._key_received(event,match,name)) # print", "section in self.config.sections(): if section == 'DRIVER': continue entry=copy.deepcopy(pp_kbddriver_plus.TEMPLATE) entry[pp_kbddriver_plus.NAME]=self.config.get(section,'name')", "arguments self.widget=widget self.filename=filename self.filepath=filepath self.event_callback=event_callback pp_kbddriver_plus.driver_active = False # read", "# Bind <Return> so that eol detection works, <Return> cannot", "character such that x produces pp-key-x (but fileterd in _key_received)", "is not None: self.event_callback(name,pp_kbddriver_plus.title) # look through entries for any-character", "def _key_received(self,event,match,name): # generate the events with symbolic names if", "all ok so indicate the driver is active pp_kbddriver_plus.driver_active=True #", "if entry[pp_kbddriver_plus.MODE] == 'specific-character': match = entry[pp_kbddriver_plus.MATCH] name = entry[pp_kbddriver_plus.NAME]", "match =='<Return>': # do match of line # print 'do", "fileterd in _key_received) canvas.bind(\"<Key>\", lambda event,match='<Key>',name='': self._key_received(event,match,name)) # print 'bind", "print 'match specific line', line if self.event_callback is not None:", "and line == entry[pp_kbddriver_plus.MATCH]: # print 'match specific line', line", "methods' # *********************************** # reading .cfg file # ************************************ def", "# do match of line # print 'do match line',pp_kbddriver_plus.inputs['current-line']", "'+filepath if __name__ == '__main__': from tkinter import * def", "!= '' and self.bind_printing =='yes': # print 'printable key, bind-printing", "# CLASS VARIABLES (pp_kbddriver_plus.) driver_active=False title='' # usd for error", "************************************************ # execute an output event def handle_output_event(self,name,param_type,param_values,req_time): return 'normal','no", "'specific-line' and line == entry[pp_kbddriver_plus.MATCH]: # print 'match specific line',", "section pp_kbddriver_plus.title=self.config.get('DRIVER','title') pp_kbddriver_plus.bind_printing = self.config.get('DRIVER','bind-printing') # construct the control list", "execute an output event def handle_output_event(self,name,param_type,param_values,req_time): return 'normal','no output methods'", "from many objects so needs to operate on class variables", "'received ',char,match,name # if char is eol then match the", "== '<Key>': # unbound special key # print 'unbound special", "terminate(self): pp_kbddriver_plus.driver_active = False # ************************************************ # output interface method", "status,message,display_id,canvas=self.dm.id_of_canvas(display_name) if status !='normal': continue # bind all the normal", "object using the driver def __init__(self): self.dm=DisplayManager() # executed once", "= 1 # in/out MATCH = 2 # for input", "* def key_callback(symbol,source): print('callback',symbol,source,'\\n') if symbol=='pp-stop': idd.terminate() exit() pass root", "control list items NAME=0 # symbolic name for input and", "TEMPLATE=['','','',''] # CLASS VARIABLES (pp_kbddriver_plus.) driver_active=False title='' # usd for", "you wnt that use keys.cfg canvas.bind(\"<Return>\", lambda event,match='<Return>',name='': self._key_received(event,match,name)) #", "= Tk() w = Label(root, text=\"pp_kbddriver_plus.py test harness\") w.pack() idd=pp_kbddriver_plus()", "print 'printable key, bind-printing is yes',char,match # printable character without", "pp_kbddriver_plus.driver_active # called by main program only. Called when PP", "Called when PP is closed down def terminate(self): pp_kbddriver_plus.driver_active =", "def __init__(self): self.dm=DisplayManager() # executed once from main program def", "'any-character': # print 'match any character', char, 'current line is", "'match any line',line if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) if", "file pp_kbddriver_plus.in_names=[] pp_kbddriver_plus.out_names=[] for section in self.config.sections(): if section ==", "None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) def match_line(self,line): for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE]", "False, None # allow querying of driver state def is_active(self):", "is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) if entry[pp_kbddriver_plus.MODE] == 'specific-line' and line", "idd.terminate() exit() pass root = Tk() w = Label(root, text=\"pp_kbddriver_plus.py", "# executed once from main program def init(self,filename,filepath,widget,pp_dir,pp_home,pp_profile,event_callback=None): # instantiate", "print 'bind printing' # Bind <Return> so that eol detection", "return False, None # allow querying of driver state def", "the control list from the config file pp_kbddriver_plus.in_names=[] pp_kbddriver_plus.out_names=[] for", "handle_output_event(self,name,param_type,param_values,req_time): return 'normal','no output methods' # *********************************** # reading .cfg", "'' and self.bind_printing =='yes': # print 'printable key, bind-printing is", "# init must return two arguments return 'normal',pp_kbddriver_plus.title + '", "driver_active=False title='' # usd for error reporting and logging tick_interval=''", "reading .cfg file # ************************************ def _read(self,filename,filepath): if os.path.exists(filepath): self.config", "# print 'bind Return to make eol work' # go", "char, 'current line is ',pp_kbddriver_plus.inputs['current-line'] if self.event_callback is not None:", "main program only. Called when PP is closed down def", "import * def key_callback(symbol,source): print('callback',symbol,source,'\\n') if symbol=='pp-stop': idd.terminate() exit() pass", "read information from DRIVER section pp_kbddriver_plus.title=self.config.get('DRIVER','title') pp_kbddriver_plus.bind_printing = self.config.get('DRIVER','bind-printing') #", "self._key_received(event,match,name)) # print 'bind printing' # Bind <Return> so that", "= entry[pp_kbddriver_plus.MATCH] name = entry[pp_kbddriver_plus.NAME] canvas.bind(match, lambda event, match=match,name=name: self._key_received(event,match,name))", "list from the config file pp_kbddriver_plus.in_names=[] pp_kbddriver_plus.out_names=[] for section in", "(pp_kbddriver_plus.) driver_active=False title='' # usd for error reporting and logging", "and match == '<Key>': # unbound special key # print", "line is ',pp_kbddriver_plus.inputs['current-line'] if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) def", "',pp_kbddriver_plus.inputs['current-line'] if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) def match_line(self,line): for", "== 'in': entry[pp_kbddriver_plus.MODE]=self.config.get(section,'mode') if entry[pp_kbddriver_plus.MODE] in ('specific-character','specific-line'): entry[pp_kbddriver_plus.MATCH]=self.config.get(section,'match') pp_kbddriver_plus.in_names.append(copy.deepcopy(entry)) else:", "and empty the buffer pp_kbddriver_plus.inputs['previous-line'] = pp_kbddriver_plus.inputs['current-line'] pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['current-character']='' if", "# go through entries and bind all specific-character matches to", "state def is_active(self): return pp_kbddriver_plus.driver_active # called by main program", "access analog input values def get_input(self,key): if key in pp_kbddriver_plus.inputs:", "self.config.sections(): if section == 'DRIVER': continue entry=copy.deepcopy(pp_kbddriver_plus.TEMPLATE) entry[pp_kbddriver_plus.NAME]=self.config.get(section,'name') entry[pp_kbddriver_plus.DIRECTION]=self.config.get(section,'direction') if", "def init(self,filename,filepath,widget,pp_dir,pp_home,pp_profile,event_callback=None): # instantiate arguments self.widget=widget self.filename=filename self.filepath=filepath self.event_callback=event_callback pp_kbddriver_plus.driver_active", "None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) # allow track plugins (or anything else) to", "# allow track plugins (or anything else) to access analog", "= pp_kbddriver_plus.inputs['current-line'] pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['current-character']='' if name !='': # print 'bound", "# unbound special key # print 'unbound special key ',", "== 'none': continue elif entry[pp_kbddriver_plus.DIRECTION] == 'in': entry[pp_kbddriver_plus.MODE]=self.config.get(section,'mode') if entry[pp_kbddriver_plus.MODE]", "match_line(self,line): for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'any-line': #", "object def _bind_keys(self,widget,callback): for display_name in DisplayManager.display_map: status,message,display_id,canvas=self.dm.id_of_canvas(display_name) if status", "in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'any-line': # print 'match any", "# does a callback to _key_received() with the event object", "a character has been received pp_kbddriver_plus.inputs['current-character']=char pp_kbddriver_plus.inputs['current-line']+=char # print pp_kbddriver_plus.inputs['current-character'],pp_kbddriver_plus.inputs['current-line']", "char != '' and self.bind_printing =='yes': # print 'printable key,", "works, <Return> cannot be used to trigger an input event", "w.pack() idd=pp_kbddriver_plus() reason,message=idd.init('pp_kbddriver_plus.cfg','/home/pi/pipresents/pp_io_config/keys_plus.cfg',root,key_callback) print(reason,message) if reason != 'error': idd.start() root.mainloop()", "3 # for input the match mode any-char,char,any-line,line TEMPLATE=['','','',''] #", "the below are used by another instance of pp_kbddriver_plus so", "event # if you wnt that use keys.cfg canvas.bind(\"<Return>\", lambda", "at: '+filepath if __name__ == '__main__': from tkinter import *", "if self.event_callback is not None: self.event_callback(name,pp_kbddriver_plus.title) else: # process a", "for input the character/string to match (no EOL) MODE= 3", "reason,message=self._read(self.filename,self.filepath) if reason =='error': return 'error',message if self.config.has_section('DRIVER') is False:", "' active' # sets up tkinter keyboard events such that", "def key_callback(symbol,source): print('callback',symbol,source,'\\n') if symbol=='pp-stop': idd.terminate() exit() pass root =", "by main program and by each object using the driver", "return True, pp_kbddriver_plus.inputs[key] else: return False, None # allow querying", "new line if match =='<Return>': # do match of line", "usd for error reporting and logging tick_interval='' # mS between", "pp_kbddriver_plus.in_names=[] pp_kbddriver_plus.out_names=[] for section in self.config.sections(): if section == 'DRIVER':", "wnt that use keys.cfg canvas.bind(\"<Return>\", lambda event,match='<Return>',name='': self._key_received(event,match,name)) # print", "# a character has been received pp_kbddriver_plus.inputs['current-character']=char pp_kbddriver_plus.inputs['current-line']+=char # print", "'error',message if self.config.has_section('DRIVER') is False: return 'error','No DRIVER section in", "pp_kbddriver_plus(object): # control list items NAME=0 # symbolic name for", "# *********************************** # reading .cfg file # ************************************ def _read(self,filename,filepath):", "plugins (or anything else) to access analog input values def", "sets up tkinter keyboard events such that any key press", "tick_interval='' # mS between polls of the serial input match_mode=''", "to make eol work' # go through entries and bind", "event,match='<Return>',name='': self._key_received(event,match,name)) # print 'bind Return to make eol work'", "symbolic names if driver is active if pp_kbddriver_plus.driver_active is True:", "return 'error',pp_kbddriver_plus.title + ' direction not in or out' #", "self.event_callback(name,pp_kbddriver_plus.title) else: # process a character if char == ''", "is_active(self): return pp_kbddriver_plus.driver_active # called by main program only. Called", "used by another instance of pp_kbddriver_plus so must reference class", "# print 'match any character', char, 'current line is ',pp_kbddriver_plus.inputs['current-line']", "else: if name != '': # print 'bound non-printable character',char,name", "specific line', line if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) #", "are used by another instance of pp_kbddriver_plus so must reference", "# ************************************ def _read(self,filename,filepath): if os.path.exists(filepath): self.config = configparser.ConfigParser(inline_comment_prefixes =", "bind all the normal keys that return a printing character", "key_callback(symbol,source): print('callback',symbol,source,'\\n') if symbol=='pp-stop': idd.terminate() exit() pass root = Tk()", "direction not in or out' # print pp_kbddriver_plus.in_names # bind", "driver import copy import os import configparser from pp_displaymanager import", "print 'bind Return to make eol work' # go through", "executed once from main program def init(self,filename,filepath,widget,pp_dir,pp_home,pp_profile,event_callback=None): # instantiate arguments", "for input the match mode any-char,char,any-line,line TEMPLATE=['','','',''] # CLASS VARIABLES", "!='normal': continue # bind all the normal keys that return", "symbolic name for input and output DIRECTION = 1 #", "def _bind_keys(self,widget,callback): for display_name in DisplayManager.display_map: status,message,display_id,canvas=self.dm.id_of_canvas(display_name) if status !='normal':", "trigger an input event # if you wnt that use", "the buffer pp_kbddriver_plus.inputs['previous-line'] = pp_kbddriver_plus.inputs['current-line'] pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['current-character']='' if name !='':", "VARIABLES (pp_kbddriver_plus.) driver_active=False title='' # usd for error reporting and", "and self.bind_printing =='yes': # print 'printable key, bind-printing is yes',char,match", "match mode any-char,char,any-line,line TEMPLATE=['','','',''] # CLASS VARIABLES (pp_kbddriver_plus.) driver_active=False title=''", "items NAME=0 # symbolic name for input and output DIRECTION", "self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) if entry[pp_kbddriver_plus.MODE] == 'specific-line' and", "called by main program only. Called when PP is closed", "# for input the match mode any-char,char,any-line,line TEMPLATE=['','','',''] # CLASS", "test harness\") w.pack() idd=pp_kbddriver_plus() reason,message=idd.init('pp_kbddriver_plus.cfg','/home/pi/pipresents/pp_io_config/keys_plus.cfg',root,key_callback) print(reason,message) if reason != 'error':", "be used to trigger an input event # if you", "pp_kbddriver_plus.cfg file. reason,message=self._read(self.filename,self.filepath) if reason =='error': return 'error',message if self.config.has_section('DRIVER')", "name = entry[pp_kbddriver_plus.NAME] canvas.bind(match, lambda event, match=match,name=name: self._key_received(event,match,name)) # print", "main program def init(self,filename,filepath,widget,pp_dir,pp_home,pp_profile,event_callback=None): # instantiate arguments self.widget=widget self.filename=filename self.filepath=filepath", "is not None: self.event_callback(name,pp_kbddriver_plus.title) else: # process a character if", "so indicate the driver is active pp_kbddriver_plus.driver_active=True # init must", "pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['current-character']='' if name !='': # print 'bound <Return> key'", "active' # sets up tkinter keyboard events such that any", "error reporting and logging tick_interval='' # mS between polls of", "print 'bound <Return> key' if self.event_callback is not None: self.event_callback(name,pp_kbddriver_plus.title)", "char,pp_kbddriver_plus.title) else: if name != '': # print 'bound non-printable", "# output interface method # this can be called from", "the match mode any-char,char,any-line,line TEMPLATE=['','','',''] # CLASS VARIABLES (pp_kbddriver_plus.) driver_active=False", "self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) def match_line(self,line): for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] ==", "with symbolic names if driver is active if pp_kbddriver_plus.driver_active is", "title='' # usd for error reporting and logging tick_interval='' #", "+ ' direction not in or out' # print pp_kbddriver_plus.in_names", "# print pp_kbddriver_plus.inputs['current-character'],pp_kbddriver_plus.inputs['current-line'] if match == '<Key>' and char !=", "import copy import os import configparser from pp_displaymanager import DisplayManager", "' direction not in or out' # print pp_kbddriver_plus.in_names #", "entries for any-character for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] ==", "else: return 'error',pp_kbddriver_plus.title + ' direction not in or out'", "pp_kbddriver_plus.inputs: return True, pp_kbddriver_plus.inputs[key] else: return False, None # allow", "# print 'bind specific-char', match,name # start method must be", "so must reference class variables # read information from DRIVER", "if self.event_callback is not None: self.event_callback('pp-key-'+ char,pp_kbddriver_plus.title) else: if name", "pp_kbddriver_plus so must reference class variables # read information from", "line', line if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) # allow", "match=match,name=name: self._key_received(event,match,name)) # print 'bind specific-char', match,name # start method", "any-char,char,any-line,line TEMPLATE=['','','',''] # CLASS VARIABLES (pp_kbddriver_plus.) driver_active=False title='' # usd", "and logging tick_interval='' # mS between polls of the serial", "been received pp_kbddriver_plus.inputs['current-character']=char pp_kbddriver_plus.inputs['current-line']+=char # print pp_kbddriver_plus.inputs['current-character'],pp_kbddriver_plus.inputs['current-line'] if match ==", "special key ', match pass else: # a character has", "== 'specific-line' and line == entry[pp_kbddriver_plus.MATCH]: # print 'match specific", "construct the control list from the config file pp_kbddriver_plus.in_names=[] pp_kbddriver_plus.out_names=[]", "_key_received) canvas.bind(\"<Key>\", lambda event,match='<Key>',name='': self._key_received(event,match,name)) # print 'bind printing' #", "input and output DIRECTION = 1 # in/out MATCH =", "return 'error',filename+' not found at: '+filepath if __name__ == '__main__':", "= entry[pp_kbddriver_plus.NAME] canvas.bind(match, lambda event, match=match,name=name: self._key_received(event,match,name)) # print 'bind", "main program and by each object using the driver def", "list items NAME=0 # symbolic name for input and output", "# for input the character/string to match (no EOL) MODE=", "pp_kbddriver_plus.inputs['current-character']='' pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['previous-line']='' def _key_received(self,event,match,name): # generate the events with", "pp_kbddriver_plus.inputs['current-line']+=char # print pp_kbddriver_plus.inputs['current-character'],pp_kbddriver_plus.inputs['current-line'] if match == '<Key>' and char", "active pp_kbddriver_plus.driver_active=True # init must return two arguments return 'normal',pp_kbddriver_plus.title", "section if self.event_callback is not None: self.event_callback('pp-key-'+ char,pp_kbddriver_plus.title) else: if", "# construct the control list from the config file pp_kbddriver_plus.in_names=[]", "self.config = configparser.ConfigParser(inline_comment_prefixes = (';',)) self.config.read(filepath) return 'normal',filename+' read' else:", "'error','No DRIVER section in '+self.filepath # all the below are", "if symbol=='pp-stop': idd.terminate() exit() pass root = Tk() w =", "in self.config.sections(): if section == 'DRIVER': continue entry=copy.deepcopy(pp_kbddriver_plus.TEMPLATE) entry[pp_kbddriver_plus.NAME]=self.config.get(section,'name') entry[pp_kbddriver_plus.DIRECTION]=self.config.get(section,'direction')", "entry[pp_kbddriver_plus.MODE] == 'any-character': # print 'match any character', char, 'current", "in ('specific-character','specific-line'): entry[pp_kbddriver_plus.MATCH]=self.config.get(section,'match') pp_kbddriver_plus.in_names.append(copy.deepcopy(entry)) else: return 'error',pp_kbddriver_plus.title + ' direction", "to match (no EOL) MODE= 3 # for input the", "character has been received pp_kbddriver_plus.inputs['current-character']=char pp_kbddriver_plus.inputs['current-line']+=char # print pp_kbddriver_plus.inputs['current-character'],pp_kbddriver_plus.inputs['current-line'] if", "of driver state def is_active(self): return pp_kbddriver_plus.driver_active # called by", "analog input values def get_input(self,key): if key in pp_kbddriver_plus.inputs: return", "True, pp_kbddriver_plus.inputs[key] else: return False, None # allow querying of", "input match_mode='' # char or line, whether input characters are", "to _key_received() with the event object def _bind_keys(self,widget,callback): for display_name", "line if match =='<Return>': # do match of line #", "'__main__': from tkinter import * def key_callback(symbol,source): print('callback',symbol,source,'\\n') if symbol=='pp-stop':", "def get_input(self,key): if key in pp_kbddriver_plus.inputs: return True, pp_kbddriver_plus.inputs[key] else:", "pp_displaymanager import DisplayManager class pp_kbddriver_plus(object): # control list items NAME=0", "line == entry[pp_kbddriver_plus.MATCH]: # print 'match specific line', line if", "output interface method # this can be called from many", "'in': entry[pp_kbddriver_plus.MODE]=self.config.get(section,'mode') if entry[pp_kbddriver_plus.MODE] in ('specific-character','specific-line'): entry[pp_kbddriver_plus.MATCH]=self.config.get(section,'match') pp_kbddriver_plus.in_names.append(copy.deepcopy(entry)) else: return", "False # read pp_kbddriver_plus.cfg file. reason,message=self._read(self.filename,self.filepath) if reason =='error': return", "pp_kbddriver_plus.out_names=[] for section in self.config.sections(): if section == 'DRIVER': continue", "# this can be called from many objects so needs", "pp_kbddriver_plus.driver_active = False # read pp_kbddriver_plus.cfg file. reason,message=self._read(self.filename,self.filepath) if reason", "and char != '' and self.bind_printing =='yes': # print 'printable", "event object def _bind_keys(self,widget,callback): for display_name in DisplayManager.display_map: status,message,display_id,canvas=self.dm.id_of_canvas(display_name) if", "input event # if you wnt that use keys.cfg canvas.bind(\"<Return>\",", "character',char,name if self.event_callback is not None: self.event_callback(name,pp_kbddriver_plus.title) # look through", "symbol=='pp-stop': idd.terminate() exit() pass root = Tk() w = Label(root,", "# if you wnt that use keys.cfg canvas.bind(\"<Return>\", lambda event,match='<Return>',name='':", "variables # read information from DRIVER section pp_kbddriver_plus.title=self.config.get('DRIVER','title') pp_kbddriver_plus.bind_printing =", "print 'unbound special key ', match pass else: # a", "generate the events with symbolic names if driver is active", "mS between polls of the serial input match_mode='' # char", "produces pp-key-x (but fileterd in _key_received) canvas.bind(\"<Key>\", lambda event,match='<Key>',name='': self._key_received(event,match,name))", "make eol work' # go through entries and bind all", "the events with symbolic names if driver is active if", "canvas.bind(match, lambda event, match=match,name=name: self._key_received(event,match,name)) # print 'bind specific-char', match,name", "printing character such that x produces pp-key-x (but fileterd in", "that x produces pp-key-x (but fileterd in _key_received) canvas.bind(\"<Key>\", lambda", "match line',pp_kbddriver_plus.inputs['current-line'] self.match_line(pp_kbddriver_plus.inputs['current-line']) # shuffle and empty the buffer pp_kbddriver_plus.inputs['previous-line']", "is closed down def terminate(self): pp_kbddriver_plus.driver_active = False # ************************************************", "not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) # allow track plugins (or anything else)", "self.filename=filename self.filepath=filepath self.event_callback=event_callback pp_kbddriver_plus.driver_active = False # read pp_kbddriver_plus.cfg file.", "if reason =='error': return 'error',message if self.config.has_section('DRIVER') is False: return", "None: self.event_callback('pp-key-'+ char,pp_kbddriver_plus.title) else: if name != '': # print", "!= '': # print 'bound non-printable character',char,name if self.event_callback is", "self.match_line(pp_kbddriver_plus.inputs['current-line']) # shuffle and empty the buffer pp_kbddriver_plus.inputs['previous-line'] = pp_kbddriver_plus.inputs['current-line']", "so that eol detection works, <Return> cannot be used to", "', match pass else: # a character has been received", "pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'any-character': # print 'match any character',", "print 'match any line',line if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title)", "************************************************ # output interface method # this can be called", "any-character for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'any-character': #", "configparser.ConfigParser(inline_comment_prefixes = (';',)) self.config.read(filepath) return 'normal',filename+' read' else: return 'error',filename+'", "ok so indicate the driver is active pp_kbddriver_plus.driver_active=True # init", "with the event object def _bind_keys(self,widget,callback): for display_name in DisplayManager.display_map:", "# generate the events with symbolic names if driver is", "keys.cfg canvas.bind(\"<Return>\", lambda event,match='<Return>',name='': self._key_received(event,match,name)) # print 'bind Return to", "pp_kbddriver_plus.inputs[key] else: return False, None # allow querying of driver", "== 'specific-character': match = entry[pp_kbddriver_plus.MATCH] name = entry[pp_kbddriver_plus.NAME] canvas.bind(match, lambda", "pp_kbddriver_plus.inputs['current-line'] pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['current-character']='' if name !='': # print 'bound <Return>", "received pp_kbddriver_plus.inputs['current-character']=char pp_kbddriver_plus.inputs['current-line']+=char # print pp_kbddriver_plus.inputs['current-character'],pp_kbddriver_plus.inputs['current-line'] if match == '<Key>'", "char == '' and match == '<Key>': # unbound special", "'<Key>' and char != '' and self.bind_printing =='yes': # print", "for each character or a complete line inputs={} # executed", "return 'error',message if self.config.has_section('DRIVER') is False: return 'error','No DRIVER section", "'DRIVER': continue entry=copy.deepcopy(pp_kbddriver_plus.TEMPLATE) entry[pp_kbddriver_plus.NAME]=self.config.get(section,'name') entry[pp_kbddriver_plus.DIRECTION]=self.config.get(section,'direction') if entry[pp_kbddriver_plus.DIRECTION] == 'none': continue", "event,match='<Key>',name='': self._key_received(event,match,name)) # print 'bind printing' # Bind <Return> so", "pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'specific-character': match = entry[pp_kbddriver_plus.MATCH] name =", "bind all specific-character matches to _key_received for entry in pp_kbddriver_plus.in_names:", "= False # read pp_kbddriver_plus.cfg file. reason,message=self._read(self.filename,self.filepath) if reason =='error':", "def match_line(self,line): for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'any-line':", "('specific-character','specific-line'): entry[pp_kbddriver_plus.MATCH]=self.config.get(section,'match') pp_kbddriver_plus.in_names.append(copy.deepcopy(entry)) else: return 'error',pp_kbddriver_plus.title + ' direction not", "entry[pp_kbddriver_plus.MODE] == 'any-line': # print 'match any line',line if self.event_callback", "char or line, whether input characters are matched for each", "look through entries for any-character for entry in pp_kbddriver_plus.in_names: if", "and by each object using the driver def __init__(self): self.dm=DisplayManager()", "that return a printing character such that x produces pp-key-x", "# print 'bound <Return> key' if self.event_callback is not None:", "driver state def is_active(self): return pp_kbddriver_plus.driver_active # called by main", "'match specific line', line if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title)", "'error',pp_kbddriver_plus.title + ' direction not in or out' # print", "from pp_displaymanager import DisplayManager class pp_kbddriver_plus(object): # control list items", "on class variables # ************************************************ # execute an output event", "allow track plugins (or anything else) to access analog input", "pp_kbddriver_plus.bind_printing = self.config.get('DRIVER','bind-printing') # construct the control list from the", "that use keys.cfg canvas.bind(\"<Return>\", lambda event,match='<Return>',name='': self._key_received(event,match,name)) # print 'bind", "class pp_kbddriver_plus(object): # control list items NAME=0 # symbolic name", "if match =='<Return>': # do match of line # print", "is ',pp_kbddriver_plus.inputs['current-line'] if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) def match_line(self,line):", "pp_kbddriver_plus.inputs['previous-line']='' def _key_received(self,event,match,name): # generate the events with symbolic names", "<Return> cannot be used to trigger an input event #", "pass root = Tk() w = Label(root, text=\"pp_kbddriver_plus.py test harness\")", "None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) if entry[pp_kbddriver_plus.MODE] == 'specific-line' and line == entry[pp_kbddriver_plus.MATCH]:", "section == 'DRIVER': continue entry=copy.deepcopy(pp_kbddriver_plus.TEMPLATE) entry[pp_kbddriver_plus.NAME]=self.config.get(section,'name') entry[pp_kbddriver_plus.DIRECTION]=self.config.get(section,'direction') if entry[pp_kbddriver_plus.DIRECTION] ==", "# print pp_kbddriver_plus.in_names # bind the keys self._bind_keys(widget,self._key_received) # all", "driver def __init__(self): self.dm=DisplayManager() # executed once from main program", "else: return 'error',filename+' not found at: '+filepath if __name__ ==", "reason =='error': return 'error',message if self.config.has_section('DRIVER') is False: return 'error','No", "_key_received for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'specific-character': match", "keys self._bind_keys(widget,self._key_received) # all ok so indicate the driver is", "'current line is ',pp_kbddriver_plus.inputs['current-line'] if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title)", "if self.config.has_section('DRIVER') is False: return 'error','No DRIVER section in '+self.filepath", "',char,match,name # if char is eol then match the line", "if entry[pp_kbddriver_plus.MODE] == 'any-line': # print 'match any line',line if", "self.config.get('DRIVER','bind-printing') # construct the control list from the config file", "and output DIRECTION = 1 # in/out MATCH = 2", "root = Tk() w = Label(root, text=\"pp_kbddriver_plus.py test harness\") w.pack()", "overiding section if self.event_callback is not None: self.event_callback('pp-key-'+ char,pp_kbddriver_plus.title) else:", "for error reporting and logging tick_interval='' # mS between polls", "pp_kbddriver_plus.title=self.config.get('DRIVER','title') pp_kbddriver_plus.bind_printing = self.config.get('DRIVER','bind-printing') # construct the control list from", "self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) # allow track plugins (or anything else) to access", "if name != '': # print 'bound non-printable character',char,name if", "is eol then match the line and start a new", "not None: self.event_callback(name,pp_kbddriver_plus.title) else: # process a character if char", "when PP is closed down def terminate(self): pp_kbddriver_plus.driver_active = False", "self.event_callback=event_callback pp_kbddriver_plus.driver_active = False # read pp_kbddriver_plus.cfg file. reason,message=self._read(self.filename,self.filepath) if", "pp_kbddriver_plus.driver_active=True # init must return two arguments return 'normal',pp_kbddriver_plus.title +", "must return two arguments return 'normal',pp_kbddriver_plus.title + ' active' #", "or a complete line inputs={} # executed by main program", "'normal',pp_kbddriver_plus.title + ' active' # sets up tkinter keyboard events", "anything else) to access analog input values def get_input(self,key): if", "# sets up tkinter keyboard events such that any key", "logging tick_interval='' # mS between polls of the serial input", "work' # go through entries and bind all specific-character matches", "in _key_received) canvas.bind(\"<Key>\", lambda event,match='<Key>',name='': self._key_received(event,match,name)) # print 'bind printing'", "printing' # Bind <Return> so that eol detection works, <Return>", "program only. Called when PP is closed down def terminate(self):", "'' and match == '<Key>': # unbound special key #", "values def get_input(self,key): if key in pp_kbddriver_plus.inputs: return True, pp_kbddriver_plus.inputs[key]", "# reading .cfg file # ************************************ def _read(self,filename,filepath): if os.path.exists(filepath):", "self._bind_keys(widget,self._key_received) # all ok so indicate the driver is active", "# print 'do match line',pp_kbddriver_plus.inputs['current-line'] self.match_line(pp_kbddriver_plus.inputs['current-line']) # shuffle and empty", "return 'normal','no output methods' # *********************************** # reading .cfg file", "matched for each character or a complete line inputs={} #", "self.config.read(filepath) return 'normal',filename+' read' else: return 'error',filename+' not found at:", "def _read(self,filename,filepath): if os.path.exists(filepath): self.config = configparser.ConfigParser(inline_comment_prefixes = (';',)) self.config.read(filepath)", "input values def get_input(self,key): if key in pp_kbddriver_plus.inputs: return True,", "and start a new line if match =='<Return>': # do", "If not using inputs just pass def start(self): pp_kbddriver_plus.inputs['current-character']='' pp_kbddriver_plus.inputs['current-line']=''", "such that x produces pp-key-x (but fileterd in _key_received) canvas.bind(\"<Key>\",", "are matched for each character or a complete line inputs={}", "that any key press # does a callback to _key_received()", "== '__main__': from tkinter import * def key_callback(symbol,source): print('callback',symbol,source,'\\n') if", "or out' # print pp_kbddriver_plus.in_names # bind the keys self._bind_keys(widget,self._key_received)", "return two arguments return 'normal',pp_kbddriver_plus.title + ' active' # sets", "detection works, <Return> cannot be used to trigger an input", "output event def handle_output_event(self,name,param_type,param_values,req_time): return 'normal','no output methods' # ***********************************", "= (';',)) self.config.read(filepath) return 'normal',filename+' read' else: return 'error',filename+' not", "complete line inputs={} # executed by main program and by", "'bind specific-char', match,name # start method must be defined. If", "to _key_received for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'specific-character':", "not found at: '+filepath if __name__ == '__main__': from tkinter", "'none': continue elif entry[pp_kbddriver_plus.DIRECTION] == 'in': entry[pp_kbddriver_plus.MODE]=self.config.get(section,'mode') if entry[pp_kbddriver_plus.MODE] in", "event def handle_output_event(self,name,param_type,param_values,req_time): return 'normal','no output methods' # *********************************** #", "the driver def __init__(self): self.dm=DisplayManager() # executed once from main", "if key in pp_kbddriver_plus.inputs: return True, pp_kbddriver_plus.inputs[key] else: return False,", "+ ' active' # sets up tkinter keyboard events such", "so needs to operate on class variables # ************************************************ #", "= self.config.get('DRIVER','bind-printing') # construct the control list from the config", "then match the line and start a new line if", "arguments return 'normal',pp_kbddriver_plus.title + ' active' # sets up tkinter", "(or anything else) to access analog input values def get_input(self,key):", "# look through entries for any-character for entry in pp_kbddriver_plus.in_names:", "read pp_kbddriver_plus.cfg file. reason,message=self._read(self.filename,self.filepath) if reason =='error': return 'error',message if", "'<Key>': # unbound special key # print 'unbound special key", "NAME=0 # symbolic name for input and output DIRECTION =", "called from many objects so needs to operate on class", "whether input characters are matched for each character or a", "canvas.bind(\"<Key>\", lambda event,match='<Key>',name='': self._key_received(event,match,name)) # print 'bind printing' # Bind", "# if char is eol then match the line and", "do match of line # print 'do match line',pp_kbddriver_plus.inputs['current-line'] self.match_line(pp_kbddriver_plus.inputs['current-line'])", "def start(self): pp_kbddriver_plus.inputs['current-character']='' pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['previous-line']='' def _key_received(self,event,match,name): # generate the", "indicate the driver is active pp_kbddriver_plus.driver_active=True # init must return", "from main program def init(self,filename,filepath,widget,pp_dir,pp_home,pp_profile,event_callback=None): # instantiate arguments self.widget=widget self.filename=filename", "output DIRECTION = 1 # in/out MATCH = 2 #", "pass def start(self): pp_kbddriver_plus.inputs['current-character']='' pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['previous-line']='' def _key_received(self,event,match,name): # generate", "shuffle and empty the buffer pp_kbddriver_plus.inputs['previous-line'] = pp_kbddriver_plus.inputs['current-line'] pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['current-character']=''", "by main program only. Called when PP is closed down", "in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'specific-character': match = entry[pp_kbddriver_plus.MATCH] name", "'+self.filepath # all the below are used by another instance", "<Return> so that eol detection works, <Return> cannot be used", "not None: self.event_callback(name,pp_kbddriver_plus.title) # look through entries for any-character for", "eol detection works, <Return> cannot be used to trigger an", "Label(root, text=\"pp_kbddriver_plus.py test harness\") w.pack() idd=pp_kbddriver_plus() reason,message=idd.init('pp_kbddriver_plus.cfg','/home/pi/pipresents/pp_io_config/keys_plus.cfg',root,key_callback) print(reason,message) if reason", "is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) def match_line(self,line): for entry in pp_kbddriver_plus.in_names:", "that eol detection works, <Return> cannot be used to trigger", "# ************************************************ # output interface method # this can be", "print('callback',symbol,source,'\\n') if symbol=='pp-stop': idd.terminate() exit() pass root = Tk() w", "entry[pp_kbddriver_plus.NAME]=self.config.get(section,'name') entry[pp_kbddriver_plus.DIRECTION]=self.config.get(section,'direction') if entry[pp_kbddriver_plus.DIRECTION] == 'none': continue elif entry[pp_kbddriver_plus.DIRECTION] ==", "not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) def match_line(self,line): for entry in pp_kbddriver_plus.in_names: if", "input characters are matched for each character or a complete", "if name !='': # print 'bound <Return> key' if self.event_callback", "in or out' # print pp_kbddriver_plus.in_names # bind the keys", "x produces pp-key-x (but fileterd in _key_received) canvas.bind(\"<Key>\", lambda event,match='<Key>',name='':", "class variables # read information from DRIVER section pp_kbddriver_plus.title=self.config.get('DRIVER','title') pp_kbddriver_plus.bind_printing", "DisplayManager class pp_kbddriver_plus(object): # control list items NAME=0 # symbolic", "key' if self.event_callback is not None: self.event_callback(name,pp_kbddriver_plus.title) else: # process", "using inputs just pass def start(self): pp_kbddriver_plus.inputs['current-character']='' pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['previous-line']='' def", "a character if char == '' and match == '<Key>':", "by each object using the driver def __init__(self): self.dm=DisplayManager() #", "key press # does a callback to _key_received() with the", "# read information from DRIVER section pp_kbddriver_plus.title=self.config.get('DRIVER','title') pp_kbddriver_plus.bind_printing = self.config.get('DRIVER','bind-printing')", "for display_name in DisplayManager.display_map: status,message,display_id,canvas=self.dm.id_of_canvas(display_name) if status !='normal': continue #", "_key_received() with the event object def _bind_keys(self,widget,callback): for display_name in", "'normal',filename+' read' else: return 'error',filename+' not found at: '+filepath if", "if __name__ == '__main__': from tkinter import * def key_callback(symbol,source):", "else: # process a character if char == '' and", "does a callback to _key_received() with the event object def", "False: return 'error','No DRIVER section in '+self.filepath # all the", "to operate on class variables # ************************************************ # execute an", "os.path.exists(filepath): self.config = configparser.ConfigParser(inline_comment_prefixes = (';',)) self.config.read(filepath) return 'normal',filename+' read'", "else: # a character has been received pp_kbddriver_plus.inputs['current-character']=char pp_kbddriver_plus.inputs['current-line']+=char #", "line if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) # allow track", "active if pp_kbddriver_plus.driver_active is True: char=event.char # print 'received ',char,match,name", "os import configparser from pp_displaymanager import DisplayManager class pp_kbddriver_plus(object): #", "== 'any-character': # print 'match any character', char, 'current line", "entry[pp_kbddriver_plus.DIRECTION] == 'in': entry[pp_kbddriver_plus.MODE]=self.config.get(section,'mode') if entry[pp_kbddriver_plus.MODE] in ('specific-character','specific-line'): entry[pp_kbddriver_plus.MATCH]=self.config.get(section,'match') pp_kbddriver_plus.in_names.append(copy.deepcopy(entry))", "(';',)) self.config.read(filepath) return 'normal',filename+' read' else: return 'error',filename+' not found", "the driver is active pp_kbddriver_plus.driver_active=True # init must return two", "'': # print 'bound non-printable character',char,name if self.event_callback is not", "can be called from many objects so needs to operate", "key, bind-printing is yes',char,match # printable character without overiding section", "many objects so needs to operate on class variables #", "an output event def handle_output_event(self,name,param_type,param_values,req_time): return 'normal','no output methods' #", "process a character if char == '' and match ==", "match == '<Key>' and char != '' and self.bind_printing =='yes':", "#enhanced keyboard driver import copy import os import configparser from", "if driver is active if pp_kbddriver_plus.driver_active is True: char=event.char #", "if status !='normal': continue # bind all the normal keys", "entry[pp_kbddriver_plus.MODE] == 'specific-character': match = entry[pp_kbddriver_plus.MATCH] name = entry[pp_kbddriver_plus.NAME] canvas.bind(match,", "# control list items NAME=0 # symbolic name for input", "# read pp_kbddriver_plus.cfg file. reason,message=self._read(self.filename,self.filepath) if reason =='error': return 'error',message", "below are used by another instance of pp_kbddriver_plus so must", "line, whether input characters are matched for each character or", "pp_kbddriver_plus.driver_active = False # ************************************************ # output interface method #", "yes',char,match # printable character without overiding section if self.event_callback is", "# char or line, whether input characters are matched for", "the keys self._bind_keys(widget,self._key_received) # all ok so indicate the driver", "callback to _key_received() with the event object def _bind_keys(self,widget,callback): for", "************************************ def _read(self,filename,filepath): if os.path.exists(filepath): self.config = configparser.ConfigParser(inline_comment_prefixes = (';',))", "display_name in DisplayManager.display_map: status,message,display_id,canvas=self.dm.id_of_canvas(display_name) if status !='normal': continue # bind", "must reference class variables # read information from DRIVER section", "import os import configparser from pp_displaymanager import DisplayManager class pp_kbddriver_plus(object):", "not using inputs just pass def start(self): pp_kbddriver_plus.inputs['current-character']='' pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['previous-line']=''", "is not None: self.event_callback('pp-key-'+ char,pp_kbddriver_plus.title) else: if name != '':", "method must be defined. If not using inputs just pass", "pp_kbddriver_plus.inputs['current-character'],pp_kbddriver_plus.inputs['current-line'] if match == '<Key>' and char != '' and", "# bind all the normal keys that return a printing", "bind-printing is yes',char,match # printable character without overiding section if", "*********************************** # reading .cfg file # ************************************ def _read(self,filename,filepath): if", "match the line and start a new line if match", "# executed by main program and by each object using", "the config file pp_kbddriver_plus.in_names=[] pp_kbddriver_plus.out_names=[] for section in self.config.sections(): if", "two arguments return 'normal',pp_kbddriver_plus.title + ' active' # sets up", "Tk() w = Label(root, text=\"pp_kbddriver_plus.py test harness\") w.pack() idd=pp_kbddriver_plus() reason,message=idd.init('pp_kbddriver_plus.cfg','/home/pi/pipresents/pp_io_config/keys_plus.cfg',root,key_callback)", "must be defined. If not using inputs just pass def", "closed down def terminate(self): pp_kbddriver_plus.driver_active = False # ************************************************ #", "return 'normal',filename+' read' else: return 'error',filename+' not found at: '+filepath", "w = Label(root, text=\"pp_kbddriver_plus.py test harness\") w.pack() idd=pp_kbddriver_plus() reason,message=idd.init('pp_kbddriver_plus.cfg','/home/pi/pipresents/pp_io_config/keys_plus.cfg',root,key_callback) print(reason,message)", "characters are matched for each character or a complete line", "of the serial input match_mode='' # char or line, whether", "each object using the driver def __init__(self): self.dm=DisplayManager() # executed", "character', char, 'current line is ',pp_kbddriver_plus.inputs['current-line'] if self.event_callback is not", "unbound special key # print 'unbound special key ', match", "=='<Return>': # do match of line # print 'do match", "pp_kbddriver_plus.in_names.append(copy.deepcopy(entry)) else: return 'error',pp_kbddriver_plus.title + ' direction not in or", "key # print 'unbound special key ', match pass else:", "only. Called when PP is closed down def terminate(self): pp_kbddriver_plus.driver_active", "the serial input match_mode='' # char or line, whether input", "exit() pass root = Tk() w = Label(root, text=\"pp_kbddriver_plus.py test", "None: self.event_callback(name,pp_kbddriver_plus.title) # look through entries for any-character for entry", "(no EOL) MODE= 3 # for input the match mode", "for any-character for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'any-character':", "# print 'printable key, bind-printing is yes',char,match # printable character", "normal keys that return a printing character such that x", "entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'any-line': # print 'match", "== 'any-line': # print 'match any line',line if self.event_callback is", "line',line if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) if entry[pp_kbddriver_plus.MODE] ==", "is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) # allow track plugins (or anything", "has been received pp_kbddriver_plus.inputs['current-character']=char pp_kbddriver_plus.inputs['current-line']+=char # print pp_kbddriver_plus.inputs['current-character'],pp_kbddriver_plus.inputs['current-line'] if match", "self.event_callback is not None: self.event_callback(name,pp_kbddriver_plus.title) else: # process a character", "not None: self.event_callback('pp-key-'+ char,pp_kbddriver_plus.title) else: if name != '': #", "this can be called from many objects so needs to", "reference class variables # read information from DRIVER section pp_kbddriver_plus.title=self.config.get('DRIVER','title')", "key ', match pass else: # a character has been", "specific-char', match,name # start method must be defined. If not", "character or a complete line inputs={} # executed by main", "pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'any-line': # print 'match any line',line", "text=\"pp_kbddriver_plus.py test harness\") w.pack() idd=pp_kbddriver_plus() reason,message=idd.init('pp_kbddriver_plus.cfg','/home/pi/pipresents/pp_io_config/keys_plus.cfg',root,key_callback) print(reason,message) if reason !=", "config file pp_kbddriver_plus.in_names=[] pp_kbddriver_plus.out_names=[] for section in self.config.sections(): if section", "to trigger an input event # if you wnt that", "the event object def _bind_keys(self,widget,callback): for display_name in DisplayManager.display_map: status,message,display_id,canvas=self.dm.id_of_canvas(display_name)", "non-printable character',char,name if self.event_callback is not None: self.event_callback(name,pp_kbddriver_plus.title) # look", "the character/string to match (no EOL) MODE= 3 # for", "interface method # this can be called from many objects", "output methods' # *********************************** # reading .cfg file # ************************************", "match,name # start method must be defined. If not using", "self.event_callback is not None: self.event_callback(name,pp_kbddriver_plus.title) # look through entries for", "<Return> key' if self.event_callback is not None: self.event_callback(name,pp_kbddriver_plus.title) else: #", "if entry[pp_kbddriver_plus.MODE] == 'specific-line' and line == entry[pp_kbddriver_plus.MATCH]: # print", "self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) def match_line(self,line): for entry in", "entry[pp_kbddriver_plus.DIRECTION] == 'none': continue elif entry[pp_kbddriver_plus.DIRECTION] == 'in': entry[pp_kbddriver_plus.MODE]=self.config.get(section,'mode') if", "if self.event_callback is not None: self.event_callback(name,pp_kbddriver_plus.title) # look through entries", "self.dm=DisplayManager() # executed once from main program def init(self,filename,filepath,widget,pp_dir,pp_home,pp_profile,event_callback=None): #", "in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'any-character': # print 'match any", "'unbound special key ', match pass else: # a character", "if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) if entry[pp_kbddriver_plus.MODE] == 'specific-line'", "# print 'received ',char,match,name # if char is eol then", "printable character without overiding section if self.event_callback is not None:", "match = entry[pp_kbddriver_plus.MATCH] name = entry[pp_kbddriver_plus.NAME] canvas.bind(match, lambda event, match=match,name=name:", "== entry[pp_kbddriver_plus.MATCH]: # print 'match specific line', line if self.event_callback", "such that any key press # does a callback to", "MATCH = 2 # for input the character/string to match", "__init__(self): self.dm=DisplayManager() # executed once from main program def init(self,filename,filepath,widget,pp_dir,pp_home,pp_profile,event_callback=None):", "in '+self.filepath # all the below are used by another", "# printable character without overiding section if self.event_callback is not", "go through entries and bind all specific-character matches to _key_received", "'bound non-printable character',char,name if self.event_callback is not None: self.event_callback(name,pp_kbddriver_plus.title) #", "copy import os import configparser from pp_displaymanager import DisplayManager class", "'error',filename+' not found at: '+filepath if __name__ == '__main__': from", "print 'match any character', char, 'current line is ',pp_kbddriver_plus.inputs['current-line'] if", "entry=copy.deepcopy(pp_kbddriver_plus.TEMPLATE) entry[pp_kbddriver_plus.NAME]=self.config.get(section,'name') entry[pp_kbddriver_plus.DIRECTION]=self.config.get(section,'direction') if entry[pp_kbddriver_plus.DIRECTION] == 'none': continue elif entry[pp_kbddriver_plus.DIRECTION]", "allow querying of driver state def is_active(self): return pp_kbddriver_plus.driver_active #", "just pass def start(self): pp_kbddriver_plus.inputs['current-character']='' pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['previous-line']='' def _key_received(self,event,match,name): #", "self.filepath=filepath self.event_callback=event_callback pp_kbddriver_plus.driver_active = False # read pp_kbddriver_plus.cfg file. reason,message=self._read(self.filename,self.filepath)", "_read(self,filename,filepath): if os.path.exists(filepath): self.config = configparser.ConfigParser(inline_comment_prefixes = (';',)) self.config.read(filepath) return", "return pp_kbddriver_plus.driver_active # called by main program only. Called when", "# mS between polls of the serial input match_mode='' #", "harness\") w.pack() idd=pp_kbddriver_plus() reason,message=idd.init('pp_kbddriver_plus.cfg','/home/pi/pipresents/pp_io_config/keys_plus.cfg',root,key_callback) print(reason,message) if reason != 'error': idd.start()", "configparser from pp_displaymanager import DisplayManager class pp_kbddriver_plus(object): # control list", "and bind all specific-character matches to _key_received for entry in", "match_mode='' # char or line, whether input characters are matched", "between polls of the serial input match_mode='' # char or", "name != '': # print 'bound non-printable character',char,name if self.event_callback", "section in '+self.filepath # all the below are used by", "file # ************************************ def _read(self,filename,filepath): if os.path.exists(filepath): self.config = configparser.ConfigParser(inline_comment_prefixes", "all the normal keys that return a printing character such", "a complete line inputs={} # executed by main program and", "without overiding section if self.event_callback is not None: self.event_callback('pp-key-'+ char,pp_kbddriver_plus.title)", "# bind the keys self._bind_keys(widget,self._key_received) # all ok so indicate", "CLASS VARIABLES (pp_kbddriver_plus.) driver_active=False title='' # usd for error reporting", "'any-line': # print 'match any line',line if self.event_callback is not", "keyboard driver import copy import os import configparser from pp_displaymanager", "print 'bound non-printable character',char,name if self.event_callback is not None: self.event_callback(name,pp_kbddriver_plus.title)", "entry[pp_kbddriver_plus.MODE] in ('specific-character','specific-line'): entry[pp_kbddriver_plus.MATCH]=self.config.get(section,'match') pp_kbddriver_plus.in_names.append(copy.deepcopy(entry)) else: return 'error',pp_kbddriver_plus.title + '", "char is eol then match the line and start a", "if pp_kbddriver_plus.driver_active is True: char=event.char # print 'received ',char,match,name #", "else) to access analog input values def get_input(self,key): if key", "be defined. If not using inputs just pass def start(self):", "line',pp_kbddriver_plus.inputs['current-line'] self.match_line(pp_kbddriver_plus.inputs['current-line']) # shuffle and empty the buffer pp_kbddriver_plus.inputs['previous-line'] =", "entry[pp_kbddriver_plus.MODE] == 'specific-line' and line == entry[pp_kbddriver_plus.MATCH]: # print 'match", "DRIVER section in '+self.filepath # all the below are used", "import DisplayManager class pp_kbddriver_plus(object): # control list items NAME=0 #", "init must return two arguments return 'normal',pp_kbddriver_plus.title + ' active'", "the line and start a new line if match =='<Return>':", "== '' and match == '<Key>': # unbound special key", "False # ************************************************ # output interface method # this can", "# all ok so indicate the driver is active pp_kbddriver_plus.driver_active=True", "specific-character matches to _key_received for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE]", "control list from the config file pp_kbddriver_plus.in_names=[] pp_kbddriver_plus.out_names=[] for section", "pp-key-x (but fileterd in _key_received) canvas.bind(\"<Key>\", lambda event,match='<Key>',name='': self._key_received(event,match,name)) #", "print 'received ',char,match,name # if char is eol then match", "through entries for any-character for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE]", "class variables # ************************************************ # execute an output event def", "'do match line',pp_kbddriver_plus.inputs['current-line'] self.match_line(pp_kbddriver_plus.inputs['current-line']) # shuffle and empty the buffer", "eol then match the line and start a new line", "EOL) MODE= 3 # for input the match mode any-char,char,any-line,line", "using the driver def __init__(self): self.dm=DisplayManager() # executed once from", "program and by each object using the driver def __init__(self):", "match == '<Key>': # unbound special key # print 'unbound", "is yes',char,match # printable character without overiding section if self.event_callback", "a callback to _key_received() with the event object def _bind_keys(self,widget,callback):", "if os.path.exists(filepath): self.config = configparser.ConfigParser(inline_comment_prefixes = (';',)) self.config.read(filepath) return 'normal',filename+'", "import configparser from pp_displaymanager import DisplayManager class pp_kbddriver_plus(object): # control", "cannot be used to trigger an input event # if", "inputs={} # executed by main program and by each object", "= Label(root, text=\"pp_kbddriver_plus.py test harness\") w.pack() idd=pp_kbddriver_plus() reason,message=idd.init('pp_kbddriver_plus.cfg','/home/pi/pipresents/pp_io_config/keys_plus.cfg',root,key_callback) print(reason,message) if", "entry[pp_kbddriver_plus.MATCH]=self.config.get(section,'match') pp_kbddriver_plus.in_names.append(copy.deepcopy(entry)) else: return 'error',pp_kbddriver_plus.title + ' direction not in", "operate on class variables # ************************************************ # execute an output", "program def init(self,filename,filepath,widget,pp_dir,pp_home,pp_profile,event_callback=None): # instantiate arguments self.widget=widget self.filename=filename self.filepath=filepath self.event_callback=event_callback", "inputs just pass def start(self): pp_kbddriver_plus.inputs['current-character']='' pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['previous-line']='' def _key_received(self,event,match,name):", "track plugins (or anything else) to access analog input values", "# execute an output event def handle_output_event(self,name,param_type,param_values,req_time): return 'normal','no output", "in DisplayManager.display_map: status,message,display_id,canvas=self.dm.id_of_canvas(display_name) if status !='normal': continue # bind all", "press # does a callback to _key_received() with the event", "# shuffle and empty the buffer pp_kbddriver_plus.inputs['previous-line'] = pp_kbddriver_plus.inputs['current-line'] pp_kbddriver_plus.inputs['current-line']=''", "for input and output DIRECTION = 1 # in/out MATCH", "# usd for error reporting and logging tick_interval='' # mS", "# print 'match any line',line if self.event_callback is not None:", "entry[pp_kbddriver_plus.MATCH]: # print 'match specific line', line if self.event_callback is", "continue entry=copy.deepcopy(pp_kbddriver_plus.TEMPLATE) entry[pp_kbddriver_plus.NAME]=self.config.get(section,'name') entry[pp_kbddriver_plus.DIRECTION]=self.config.get(section,'direction') if entry[pp_kbddriver_plus.DIRECTION] == 'none': continue elif", "is True: char=event.char # print 'received ',char,match,name # if char", "self.bind_printing =='yes': # print 'printable key, bind-printing is yes',char,match #", "# print 'match specific line', line if self.event_callback is not", "start a new line if match =='<Return>': # do match", "events such that any key press # does a callback", "or line, whether input characters are matched for each character", "None: self.event_callback(name,pp_kbddriver_plus.title) else: # process a character if char ==", "start method must be defined. If not using inputs just", "event, match=match,name=name: self._key_received(event,match,name)) # print 'bind specific-char', match,name # start", "another instance of pp_kbddriver_plus so must reference class variables #", "canvas.bind(\"<Return>\", lambda event,match='<Return>',name='': self._key_received(event,match,name)) # print 'bind Return to make", "pp_kbddriver_plus.inputs['previous-line'] = pp_kbddriver_plus.inputs['current-line'] pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['current-character']='' if name !='': # print", "not in or out' # print pp_kbddriver_plus.in_names # bind the", "all specific-character matches to _key_received for entry in pp_kbddriver_plus.in_names: if", "to access analog input values def get_input(self,key): if key in", "def is_active(self): return pp_kbddriver_plus.driver_active # called by main program only.", "for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'any-line': # print", "from the config file pp_kbddriver_plus.in_names=[] pp_kbddriver_plus.out_names=[] for section in self.config.sections():", "character without overiding section if self.event_callback is not None: self.event_callback('pp-key-'+", "_key_received(self,event,match,name): # generate the events with symbolic names if driver", "down def terminate(self): pp_kbddriver_plus.driver_active = False # ************************************************ # output", "# print 'bound non-printable character',char,name if self.event_callback is not None:", "keys that return a printing character such that x produces", "# process a character if char == '' and match", "# start method must be defined. If not using inputs", "pp_kbddriver_plus.inputs['current-character']=char pp_kbddriver_plus.inputs['current-line']+=char # print pp_kbddriver_plus.inputs['current-character'],pp_kbddriver_plus.inputs['current-line'] if match == '<Key>' and", "from tkinter import * def key_callback(symbol,source): print('callback',symbol,source,'\\n') if symbol=='pp-stop': idd.terminate()", "empty the buffer pp_kbddriver_plus.inputs['previous-line'] = pp_kbddriver_plus.inputs['current-line'] pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['current-character']='' if name", "special key # print 'unbound special key ', match pass", "for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'specific-character': match =", "'normal','no output methods' # *********************************** # reading .cfg file #", "tkinter import * def key_callback(symbol,source): print('callback',symbol,source,'\\n') if symbol=='pp-stop': idd.terminate() exit()", "entry[pp_kbddriver_plus.MODE]=self.config.get(section,'mode') if entry[pp_kbddriver_plus.MODE] in ('specific-character','specific-line'): entry[pp_kbddriver_plus.MATCH]=self.config.get(section,'match') pp_kbddriver_plus.in_names.append(copy.deepcopy(entry)) else: return 'error',pp_kbddriver_plus.title", "char=event.char # print 'received ',char,match,name # if char is eol", "print pp_kbddriver_plus.inputs['current-character'],pp_kbddriver_plus.inputs['current-line'] if match == '<Key>' and char != ''", "events with symbolic names if driver is active if pp_kbddriver_plus.driver_active", "found at: '+filepath if __name__ == '__main__': from tkinter import", "= False # ************************************************ # output interface method # this", "in/out MATCH = 2 # for input the character/string to", "# called by main program only. Called when PP is", "entry[pp_kbddriver_plus.DIRECTION]=self.config.get(section,'direction') if entry[pp_kbddriver_plus.DIRECTION] == 'none': continue elif entry[pp_kbddriver_plus.DIRECTION] == 'in':", "lambda event,match='<Return>',name='': self._key_received(event,match,name)) # print 'bind Return to make eol", "objects so needs to operate on class variables # ************************************************", "# symbolic name for input and output DIRECTION = 1", "init(self,filename,filepath,widget,pp_dir,pp_home,pp_profile,event_callback=None): # instantiate arguments self.widget=widget self.filename=filename self.filepath=filepath self.event_callback=event_callback pp_kbddriver_plus.driver_active =", "def terminate(self): pp_kbddriver_plus.driver_active = False # ************************************************ # output interface", "instance of pp_kbddriver_plus so must reference class variables # read", "lambda event, match=match,name=name: self._key_received(event,match,name)) # print 'bind specific-char', match,name #", "be called from many objects so needs to operate on", "entry[pp_kbddriver_plus.NAME] canvas.bind(match, lambda event, match=match,name=name: self._key_received(event,match,name)) # print 'bind specific-char',", "polls of the serial input match_mode='' # char or line,", "return 'error','No DRIVER section in '+self.filepath # all the below", "if entry[pp_kbddriver_plus.MODE] in ('specific-character','specific-line'): entry[pp_kbddriver_plus.MATCH]=self.config.get(section,'match') pp_kbddriver_plus.in_names.append(copy.deepcopy(entry)) else: return 'error',pp_kbddriver_plus.title +", "=='error': return 'error',message if self.config.has_section('DRIVER') is False: return 'error','No DRIVER", "name for input and output DIRECTION = 1 # in/out", "print 'do match line',pp_kbddriver_plus.inputs['current-line'] self.match_line(pp_kbddriver_plus.inputs['current-line']) # shuffle and empty the", "used to trigger an input event # if you wnt", "use keys.cfg canvas.bind(\"<Return>\", lambda event,match='<Return>',name='': self._key_received(event,match,name)) # print 'bind Return", "MODE= 3 # for input the match mode any-char,char,any-line,line TEMPLATE=['','','','']", "if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) # allow track plugins", "self.event_callback is not None: self.event_callback('pp-key-'+ char,pp_kbddriver_plus.title) else: if name !=", "return 'normal',pp_kbddriver_plus.title + ' active' # sets up tkinter keyboard", "Bind <Return> so that eol detection works, <Return> cannot be", "needs to operate on class variables # ************************************************ # execute", "from DRIVER section pp_kbddriver_plus.title=self.config.get('DRIVER','title') pp_kbddriver_plus.bind_printing = self.config.get('DRIVER','bind-printing') # construct the", "all the below are used by another instance of pp_kbddriver_plus", ".cfg file # ************************************ def _read(self,filename,filepath): if os.path.exists(filepath): self.config =", "# all the below are used by another instance of", "# instantiate arguments self.widget=widget self.filename=filename self.filepath=filepath self.event_callback=event_callback pp_kbddriver_plus.driver_active = False", "each character or a complete line inputs={} # executed by", "def handle_output_event(self,name,param_type,param_values,req_time): return 'normal','no output methods' # *********************************** # reading", "entries and bind all specific-character matches to _key_received for entry", "any character', char, 'current line is ',pp_kbddriver_plus.inputs['current-line'] if self.event_callback is", "'match any character', char, 'current line is ',pp_kbddriver_plus.inputs['current-line'] if self.event_callback", "eol work' # go through entries and bind all specific-character", "instantiate arguments self.widget=widget self.filename=filename self.filepath=filepath self.event_callback=event_callback pp_kbddriver_plus.driver_active = False #", "'printable key, bind-printing is yes',char,match # printable character without overiding", "querying of driver state def is_active(self): return pp_kbddriver_plus.driver_active # called", "not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) if entry[pp_kbddriver_plus.MODE] == 'specific-line' and line ==", "is active pp_kbddriver_plus.driver_active=True # init must return two arguments return", "of pp_kbddriver_plus so must reference class variables # read information", "if entry[pp_kbddriver_plus.MODE] == 'any-character': # print 'match any character', char,", "if entry[pp_kbddriver_plus.DIRECTION] == 'none': continue elif entry[pp_kbddriver_plus.DIRECTION] == 'in': entry[pp_kbddriver_plus.MODE]=self.config.get(section,'mode')", "# ************************************************ # execute an output event def handle_output_event(self,name,param_type,param_values,req_time): return", "_bind_keys(self,widget,callback): for display_name in DisplayManager.display_map: status,message,display_id,canvas=self.dm.id_of_canvas(display_name) if status !='normal': continue", "any key press # does a callback to _key_received() with", "if char is eol then match the line and start", "mode any-char,char,any-line,line TEMPLATE=['','','',''] # CLASS VARIABLES (pp_kbddriver_plus.) driver_active=False title='' #", "any line',line if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) if entry[pp_kbddriver_plus.MODE]", "entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'any-character': # print 'match", "name !='': # print 'bound <Return> key' if self.event_callback is", "up tkinter keyboard events such that any key press #", "through entries and bind all specific-character matches to _key_received for", "variables # ************************************************ # execute an output event def handle_output_event(self,name,param_type,param_values,req_time):", "tkinter keyboard events such that any key press # does", "reporting and logging tick_interval='' # mS between polls of the", "# print 'bind printing' # Bind <Return> so that eol", "a printing character such that x produces pp-key-x (but fileterd", "line # print 'do match line',pp_kbddriver_plus.inputs['current-line'] self.match_line(pp_kbddriver_plus.inputs['current-line']) # shuffle and", "bind the keys self._bind_keys(widget,self._key_received) # all ok so indicate the", "start(self): pp_kbddriver_plus.inputs['current-character']='' pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['previous-line']='' def _key_received(self,event,match,name): # generate the events", "1 # in/out MATCH = 2 # for input the", "=='yes': # print 'printable key, bind-printing is yes',char,match # printable", "self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) if entry[pp_kbddriver_plus.MODE] == 'specific-line' and line == entry[pp_kbddriver_plus.MATCH]: #", "information from DRIVER section pp_kbddriver_plus.title=self.config.get('DRIVER','title') pp_kbddriver_plus.bind_printing = self.config.get('DRIVER','bind-printing') # construct", "input the match mode any-char,char,any-line,line TEMPLATE=['','','',''] # CLASS VARIABLES (pp_kbddriver_plus.)", "# in/out MATCH = 2 # for input the character/string", "line and start a new line if match =='<Return>': #", "self.widget=widget self.filename=filename self.filepath=filepath self.event_callback=event_callback pp_kbddriver_plus.driver_active = False # read pp_kbddriver_plus.cfg", "read' else: return 'error',filename+' not found at: '+filepath if __name__", "print pp_kbddriver_plus.in_names # bind the keys self._bind_keys(widget,self._key_received) # all ok", "character/string to match (no EOL) MODE= 3 # for input", "True: char=event.char # print 'received ',char,match,name # if char is", "!='': # print 'bound <Return> key' if self.event_callback is not", "self._key_received(event,match,name)) # print 'bind Return to make eol work' #", "if char == '' and match == '<Key>': # unbound", "# allow querying of driver state def is_active(self): return pp_kbddriver_plus.driver_active", "executed by main program and by each object using the", "keyboard events such that any key press # does a", "== '<Key>' and char != '' and self.bind_printing =='yes': #", "driver is active pp_kbddriver_plus.driver_active=True # init must return two arguments", "line inputs={} # executed by main program and by each", "in pp_kbddriver_plus.inputs: return True, pp_kbddriver_plus.inputs[key] else: return False, None #", "input the character/string to match (no EOL) MODE= 3 #", "'bind printing' # Bind <Return> so that eol detection works,", "DRIVER section pp_kbddriver_plus.title=self.config.get('DRIVER','title') pp_kbddriver_plus.bind_printing = self.config.get('DRIVER','bind-printing') # construct the control", "pp_kbddriver_plus.driver_active is True: char=event.char # print 'received ',char,match,name # if", "an input event # if you wnt that use keys.cfg", "the normal keys that return a printing character such that", "for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'any-character': # print", "self._key_received(event,match,name)) # print 'bind specific-char', match,name # start method must", "for section in self.config.sections(): if section == 'DRIVER': continue entry=copy.deepcopy(pp_kbddriver_plus.TEMPLATE)", "if self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) def match_line(self,line): for entry", "2 # for input the character/string to match (no EOL)", "self.event_callback is not None: self.event_callback(entry[pp_kbddriver_plus.NAME],pp_kbddriver_plus.title) # allow track plugins (or", "status !='normal': continue # bind all the normal keys that", "else: return False, None # allow querying of driver state", "'specific-character': match = entry[pp_kbddriver_plus.MATCH] name = entry[pp_kbddriver_plus.NAME] canvas.bind(match, lambda event,", "defined. If not using inputs just pass def start(self): pp_kbddriver_plus.inputs['current-character']=''", "if match == '<Key>' and char != '' and self.bind_printing", "file. reason,message=self._read(self.filename,self.filepath) if reason =='error': return 'error',message if self.config.has_section('DRIVER') is", "is active if pp_kbddriver_plus.driver_active is True: char=event.char # print 'received", "match (no EOL) MODE= 3 # for input the match", "self.config.has_section('DRIVER') is False: return 'error','No DRIVER section in '+self.filepath #", "out' # print pp_kbddriver_plus.in_names # bind the keys self._bind_keys(widget,self._key_received) #", "pp_kbddriver_plus.in_names # bind the keys self._bind_keys(widget,self._key_received) # all ok so", "DisplayManager.display_map: status,message,display_id,canvas=self.dm.id_of_canvas(display_name) if status !='normal': continue # bind all the", "'bind Return to make eol work' # go through entries", "once from main program def init(self,filename,filepath,widget,pp_dir,pp_home,pp_profile,event_callback=None): # instantiate arguments self.widget=widget", "continue # bind all the normal keys that return a", "'bound <Return> key' if self.event_callback is not None: self.event_callback(name,pp_kbddriver_plus.title) else:", "by another instance of pp_kbddriver_plus so must reference class variables", "character if char == '' and match == '<Key>': #", "= configparser.ConfigParser(inline_comment_prefixes = (';',)) self.config.read(filepath) return 'normal',filename+' read' else: return", "# print 'unbound special key ', match pass else: #", "names if driver is active if pp_kbddriver_plus.driver_active is True: char=event.char", "get_input(self,key): if key in pp_kbddriver_plus.inputs: return True, pp_kbddriver_plus.inputs[key] else: return", "pass else: # a character has been received pp_kbddriver_plus.inputs['current-character']=char pp_kbddriver_plus.inputs['current-line']+=char", "lambda event,match='<Key>',name='': self._key_received(event,match,name)) # print 'bind printing' # Bind <Return>", "if you wnt that use keys.cfg canvas.bind(\"<Return>\", lambda event,match='<Return>',name='': self._key_received(event,match,name))", "match of line # print 'do match line',pp_kbddriver_plus.inputs['current-line'] self.match_line(pp_kbddriver_plus.inputs['current-line']) #", "= 2 # for input the character/string to match (no", "if section == 'DRIVER': continue entry=copy.deepcopy(pp_kbddriver_plus.TEMPLATE) entry[pp_kbddriver_plus.NAME]=self.config.get(section,'name') entry[pp_kbddriver_plus.DIRECTION]=self.config.get(section,'direction') if entry[pp_kbddriver_plus.DIRECTION]", "matches to _key_received for entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] ==", "pp_kbddriver_plus.inputs['current-character']='' if name !='': # print 'bound <Return> key' if", "method # this can be called from many objects so", "of line # print 'do match line',pp_kbddriver_plus.inputs['current-line'] self.match_line(pp_kbddriver_plus.inputs['current-line']) # shuffle", "__name__ == '__main__': from tkinter import * def key_callback(symbol,source): print('callback',symbol,source,'\\n')", "serial input match_mode='' # char or line, whether input characters", "driver is active if pp_kbddriver_plus.driver_active is True: char=event.char # print", "PP is closed down def terminate(self): pp_kbddriver_plus.driver_active = False #", "print 'bind specific-char', match,name # start method must be defined.", "pp_kbddriver_plus.inputs['current-line']='' pp_kbddriver_plus.inputs['previous-line']='' def _key_received(self,event,match,name): # generate the events with symbolic", "match pass else: # a character has been received pp_kbddriver_plus.inputs['current-character']=char", "elif entry[pp_kbddriver_plus.DIRECTION] == 'in': entry[pp_kbddriver_plus.MODE]=self.config.get(section,'mode') if entry[pp_kbddriver_plus.MODE] in ('specific-character','specific-line'): entry[pp_kbddriver_plus.MATCH]=self.config.get(section,'match')", "entry in pp_kbddriver_plus.in_names: if entry[pp_kbddriver_plus.MODE] == 'specific-character': match = entry[pp_kbddriver_plus.MATCH]", "entry[pp_kbddriver_plus.MATCH] name = entry[pp_kbddriver_plus.NAME] canvas.bind(match, lambda event, match=match,name=name: self._key_received(event,match,name)) #", "return a printing character such that x produces pp-key-x (but", "continue elif entry[pp_kbddriver_plus.DIRECTION] == 'in': entry[pp_kbddriver_plus.MODE]=self.config.get(section,'mode') if entry[pp_kbddriver_plus.MODE] in ('specific-character','specific-line'):", "None # allow querying of driver state def is_active(self): return", "key in pp_kbddriver_plus.inputs: return True, pp_kbddriver_plus.inputs[key] else: return False, None" ]
[ "on 2021-09-03 15:48 from django.db import migrations, models class Migration(migrations.Migration):", "[ migrations.AlterField( model_name='item', name='comments', field=models.CharField(blank=True, default='null', max_length=200), preserve_default=False, ), ]", "dependencies = [ ('grocery', '0002_alter_item_comments'), ] operations = [ migrations.AlterField(", "] operations = [ migrations.AlterField( model_name='item', name='comments', field=models.CharField(blank=True, default='null', max_length=200),", "2021-09-03 15:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies", "migrations, models class Migration(migrations.Migration): dependencies = [ ('grocery', '0002_alter_item_comments'), ]", "3.2.6 on 2021-09-03 15:48 from django.db import migrations, models class", "Generated by Django 3.2.6 on 2021-09-03 15:48 from django.db import", "Django 3.2.6 on 2021-09-03 15:48 from django.db import migrations, models", "# Generated by Django 3.2.6 on 2021-09-03 15:48 from django.db", "('grocery', '0002_alter_item_comments'), ] operations = [ migrations.AlterField( model_name='item', name='comments', field=models.CharField(blank=True,", "<filename>grocery/migrations/0003_alter_item_comments.py # Generated by Django 3.2.6 on 2021-09-03 15:48 from", "django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('grocery',", "from django.db import migrations, models class Migration(migrations.Migration): dependencies = [", "models class Migration(migrations.Migration): dependencies = [ ('grocery', '0002_alter_item_comments'), ] operations", "by Django 3.2.6 on 2021-09-03 15:48 from django.db import migrations,", "= [ migrations.AlterField( model_name='item', name='comments', field=models.CharField(blank=True, default='null', max_length=200), preserve_default=False, ),", "= [ ('grocery', '0002_alter_item_comments'), ] operations = [ migrations.AlterField( model_name='item',", "import migrations, models class Migration(migrations.Migration): dependencies = [ ('grocery', '0002_alter_item_comments'),", "class Migration(migrations.Migration): dependencies = [ ('grocery', '0002_alter_item_comments'), ] operations =", "15:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies =", "Migration(migrations.Migration): dependencies = [ ('grocery', '0002_alter_item_comments'), ] operations = [", "operations = [ migrations.AlterField( model_name='item', name='comments', field=models.CharField(blank=True, default='null', max_length=200), preserve_default=False,", "[ ('grocery', '0002_alter_item_comments'), ] operations = [ migrations.AlterField( model_name='item', name='comments',", "'0002_alter_item_comments'), ] operations = [ migrations.AlterField( model_name='item', name='comments', field=models.CharField(blank=True, default='null'," ]
[ "0.75), '800080': (0.5, 0.4, 0.5), 'FF00FF': (0.9, 0.75, 0.85), 'F5DEB3':", "create an image per color for colorString, color in colors.iteritems():", "2.0 (the \"License\"); # you may not use this file", "\"\"\"Generate textures prepared for OSM, based on image templates.\"\"\" import", "the effect, found empirically # foreach template for template in", "0.84, 0.84), '808080': (0.4, 0.4, 0.4), 'C0C0C0': (0.65, 0.65, 0.65),", "+ int(255.0 * (mB / 255.0) * (color[2] * 2.0", "'000000': (0.0, 0.0, 0.0), 'FFFFFF': (0.84, 0.84, 0.84), '808080': (0.4,", "0.15), 'FF0000': (0.45, 0.0, 0.0), '808000': (0.4, 0.4, 0.2), 'FFFF00':", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "colors # ref: http://wiki.openstreetmap.org/wiki/Key:colour # TODO: is it sufficient? colors", "glob.glob(\"*_diffuse_template.jpg\"): templates.append((f, f.replace('_diffuse_', '_color_mask_'))) # target colors # ref: http://wiki.openstreetmap.org/wiki/Key:colour", "diffuse.size) pixels = image.load() for x in range(height): for y", "0.65, 0.65), '800000': (0.4, 0.15, 0.15), 'FF0000': (0.45, 0.0, 0.0),", "in colors.iteritems(): image = Image.new('RGB', diffuse.size) pixels = image.load() for", "ref: http://wiki.openstreetmap.org/wiki/Key:colour # TODO: is it sufficient? colors = {", "#!/usr/bin/env python # Copyright 1996-2019 Cyberbotics Ltd. # # Licensed", "= [] for f in glob.glob(\"*_diffuse_template.jpg\"): templates.append((f, f.replace('_diffuse_', '_color_mask_'))) #", "* (mR / 255.0) * (color[0] * 2.0 - 1.0)", "list of tuples templates = [] for f in glob.glob(\"*_diffuse_template.jpg\"):", "diffuse = Image.open(template[0]) mask = Image.open(template[1]) assert diffuse.size == mask.size", "Cyberbotics Ltd. # # Licensed under the Apache License, Version", "image = Image.new('RGB', diffuse.size) pixels = image.load() for x in", "use this file except in compliance with the License. #", "OSM, based on image templates.\"\"\" import glob import os from", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "* 2.0 - 1.0) * effectFactor) g = dG +", "y)) r = dR + int(255.0 * (mR / 255.0)", "License. # You may obtain a copy of the License", "http://wiki.openstreetmap.org/wiki/Key:colour # TODO: is it sufficient? colors = { '000000':", "'FF00FF': (0.9, 0.75, 0.85), 'F5DEB3': (0.83, 0.78, 0.65), '8B4513': (0.3,", "+ int(255.0 * (mR / 255.0) * (color[0] * 2.0", "pixels = image.load() for x in range(height): for y in", "* effectFactor) g = dG + int(255.0 * (mG /", "under the License is distributed on an \"AS IS\" BASIS,", "License for the specific language governing permissions and # limitations", "for f in glob.glob(\"*_diffuse_template.jpg\"): templates.append((f, f.replace('_diffuse_', '_color_mask_'))) # target colors", "height = diffuse.size # create an image per color for", "import os from PIL import Image # change directory to", "0.78, 0.65), '8B4513': (0.3, 0.1, 0.05) } effectFactor = 0.5", "- 1.0) * effectFactor) g = dG + int(255.0 *", "* (color[0] * 2.0 - 1.0) * effectFactor) g =", "0.15, 0.15), 'FF0000': (0.45, 0.0, 0.0), '808000': (0.4, 0.4, 0.2),", "0.52), '008080': (0.15, 0.3, 0.3), '00FFFF': (0.6, 0.7, 0.7), '000080':", "(0.2, 0.2, 0.3), '0000FF': (0.4, 0.4, 0.75), '800080': (0.5, 0.4,", "# limitations under the License. \"\"\"Generate textures prepared for OSM,", "[] for f in glob.glob(\"*_diffuse_template.jpg\"): templates.append((f, f.replace('_diffuse_', '_color_mask_'))) # target", "in compliance with the License. # You may obtain a", "0.0, 0.0), 'FFFFFF': (0.84, 0.84, 0.84), '808080': (0.4, 0.4, 0.4),", "based on image templates.\"\"\" import glob import os from PIL", "software # distributed under the License is distributed on an", "empirically # foreach template for template in templates: # load", "0.4), 'C0C0C0': (0.65, 0.65, 0.65), '800000': (0.4, 0.15, 0.15), 'FF0000':", "dR + int(255.0 * (mR / 255.0) * (color[0] *", "= Image.open(template[1]) assert diffuse.size == mask.size width, height = diffuse.size", "all the template files in put them in a list", "assert diffuse.size == mask.size width, height = diffuse.size # create", "pixels[x, y] = (r, g, b) image.save(template[0].replace('_diffuse_template', '_' + colorString))", "0.15), '00FF00': (0.55, 0.69, 0.52), '008080': (0.15, 0.3, 0.3), '00FFFF':", "glob import os from PIL import Image # change directory", "'F5DEB3': (0.83, 0.78, 0.65), '8B4513': (0.3, 0.1, 0.05) } effectFactor", "permissions and # limitations under the License. \"\"\"Generate textures prepared", "'0000FF': (0.4, 0.4, 0.75), '800080': (0.5, 0.4, 0.5), 'FF00FF': (0.9,", "(0.5, 0.4, 0.5), 'FF00FF': (0.9, 0.75, 0.85), 'F5DEB3': (0.83, 0.78,", "= diffuse.size # create an image per color for colorString,", "from PIL import Image # change directory to this script", "{ '000000': (0.0, 0.0, 0.0), 'FFFFFF': (0.84, 0.84, 0.84), '808080':", "it sufficient? colors = { '000000': (0.0, 0.0, 0.0), 'FFFFFF':", "(0.4, 0.4, 0.4), 'C0C0C0': (0.65, 0.65, 0.65), '800000': (0.4, 0.15,", "image templates.\"\"\" import glob import os from PIL import Image", "/ 255.0) * (color[2] * 2.0 - 1.0) * effectFactor)", "mask = Image.open(template[1]) assert diffuse.size == mask.size width, height =", "# TODO: is it sufficient? colors = { '000000': (0.0,", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "# power of the effect, found empirically # foreach template", "(0.7, 0.6, 0.15), '008000': (0.15, 0.3, 0.15), '00FF00': (0.55, 0.69,", "(0.84, 0.84, 0.84), '808080': (0.4, 0.4, 0.4), 'C0C0C0': (0.65, 0.65,", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "0.4, 0.75), '800080': (0.5, 0.4, 0.5), 'FF00FF': (0.9, 0.75, 0.85),", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "= mask.getpixel((x, y)) r = dR + int(255.0 * (mR", "to in writing, software # distributed under the License is", "colorString, color in colors.iteritems(): image = Image.new('RGB', diffuse.size) pixels =", "= 0.5 # power of the effect, found empirically #", "0.15), '008000': (0.15, 0.3, 0.15), '00FF00': (0.55, 0.69, 0.52), '008080':", "# See the License for the specific language governing permissions", "under the License. \"\"\"Generate textures prepared for OSM, based on", "or agreed to in writing, software # distributed under the", "# get all the template files in put them in", "required by applicable law or agreed to in writing, software", "be called from another directory. os.chdir(os.path.dirname(os.path.realpath(__file__))) # get all the", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "with the License. # You may obtain a copy of", "os from PIL import Image # change directory to this", "foreach template for template in templates: # load the templates", "'800000': (0.4, 0.15, 0.15), 'FF0000': (0.45, 0.0, 0.0), '808000': (0.4,", "(0.55, 0.69, 0.52), '008080': (0.15, 0.3, 0.3), '00FFFF': (0.6, 0.7,", "0.3), '0000FF': (0.4, 0.4, 0.75), '800080': (0.5, 0.4, 0.5), 'FF00FF':", "width, height = diffuse.size # create an image per color", "compliance with the License. # You may obtain a copy", "agreed to in writing, software # distributed under the License", "target colors # ref: http://wiki.openstreetmap.org/wiki/Key:colour # TODO: is it sufficient?", "image.load() for x in range(height): for y in range(width): dR,", "mR, mG, mB = mask.getpixel((x, y)) r = dR +", "distributed under the License is distributed on an \"AS IS\"", "= dR + int(255.0 * (mR / 255.0) * (color[0]", "power of the effect, found empirically # foreach template for", "express or implied. # See the License for the specific", "except in compliance with the License. # You may obtain", "this script to be called from another directory. os.chdir(os.path.dirname(os.path.realpath(__file__))) #", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "# create an image per color for colorString, color in", "not use this file except in compliance with the License.", "# target colors # ref: http://wiki.openstreetmap.org/wiki/Key:colour # TODO: is it", "int(255.0 * (mB / 255.0) * (color[2] * 2.0 -", "(mB / 255.0) * (color[2] * 2.0 - 1.0) *", "255.0) * (color[2] * 2.0 - 1.0) * effectFactor) pixels[x,", "writing, software # distributed under the License is distributed on", "(0.4, 0.4, 0.2), 'FFFF00': (0.7, 0.6, 0.15), '008000': (0.15, 0.3,", "mask.getpixel((x, y)) r = dR + int(255.0 * (mR /", "you may not use this file except in compliance with", "0.6, 0.15), '008000': (0.15, 0.3, 0.15), '00FF00': (0.55, 0.69, 0.52),", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "found empirically # foreach template for template in templates: #", "import glob import os from PIL import Image # change", "in range(height): for y in range(width): dR, dG, dB =", "called from another directory. os.chdir(os.path.dirname(os.path.realpath(__file__))) # get all the template", "diffuse.size # create an image per color for colorString, color", "a list of tuples templates = [] for f in", "sufficient? colors = { '000000': (0.0, 0.0, 0.0), 'FFFFFF': (0.84,", "templates.\"\"\" import glob import os from PIL import Image #", "CONDITIONS OF ANY KIND, either express or implied. # See", "0.2, 0.3), '0000FF': (0.4, 0.4, 0.75), '800080': (0.5, 0.4, 0.5),", "f in glob.glob(\"*_diffuse_template.jpg\"): templates.append((f, f.replace('_diffuse_', '_color_mask_'))) # target colors #", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "limitations under the License. \"\"\"Generate textures prepared for OSM, based", "effectFactor) b = dB + int(255.0 * (mB / 255.0)", "0.4, 0.2), 'FFFF00': (0.7, 0.6, 0.15), '008000': (0.15, 0.3, 0.15),", "0.69, 0.52), '008080': (0.15, 0.3, 0.3), '00FFFF': (0.6, 0.7, 0.7),", "# ref: http://wiki.openstreetmap.org/wiki/Key:colour # TODO: is it sufficient? colors =", "= dB + int(255.0 * (mB / 255.0) * (color[2]", "0.0, 0.0), '808000': (0.4, 0.4, 0.2), 'FFFF00': (0.7, 0.6, 0.15),", "dG + int(255.0 * (mG / 255.0) * (color[1] *", "color in colors.iteritems(): image = Image.new('RGB', diffuse.size) pixels = image.load()", "(0.0, 0.0, 0.0), 'FFFFFF': (0.84, 0.84, 0.84), '808080': (0.4, 0.4,", "dG, dB = diffuse.getpixel((x, y)) mR, mG, mB = mask.getpixel((x,", "governing permissions and # limitations under the License. \"\"\"Generate textures", "OR CONDITIONS OF ANY KIND, either express or implied. #", "0.4, 0.5), 'FF00FF': (0.9, 0.75, 0.85), 'F5DEB3': (0.83, 0.78, 0.65),", "* (color[1] * 2.0 - 1.0) * effectFactor) b =", "the License is distributed on an \"AS IS\" BASIS, #", "(0.15, 0.3, 0.3), '00FFFF': (0.6, 0.7, 0.7), '000080': (0.2, 0.2,", "0.85), 'F5DEB3': (0.83, 0.78, 0.65), '8B4513': (0.3, 0.1, 0.05) }", "'FFFFFF': (0.84, 0.84, 0.84), '808080': (0.4, 0.4, 0.4), 'C0C0C0': (0.65,", "= { '000000': (0.0, 0.0, 0.0), 'FFFFFF': (0.84, 0.84, 0.84),", "effectFactor = 0.5 # power of the effect, found empirically", "os.chdir(os.path.dirname(os.path.realpath(__file__))) # get all the template files in put them", "an image per color for colorString, color in colors.iteritems(): image", "law or agreed to in writing, software # distributed under", "for y in range(width): dR, dG, dB = diffuse.getpixel((x, y))", "'008000': (0.15, 0.3, 0.15), '00FF00': (0.55, 0.69, 0.52), '008080': (0.15,", "change directory to this script directory in order to allow", "this script directory in order to allow this script to", "'808000': (0.4, 0.4, 0.2), 'FFFF00': (0.7, 0.6, 0.15), '008000': (0.15,", "may obtain a copy of the License at # #", "directory in order to allow this script to be called", "script directory in order to allow this script to be", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "'00FF00': (0.55, 0.69, 0.52), '008080': (0.15, 0.3, 0.3), '00FFFF': (0.6,", "may not use this file except in compliance with the", "get all the template files in put them in a", "(0.4, 0.4, 0.75), '800080': (0.5, 0.4, 0.5), 'FF00FF': (0.9, 0.75,", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "this file except in compliance with the License. # You", "'_color_mask_'))) # target colors # ref: http://wiki.openstreetmap.org/wiki/Key:colour # TODO: is", "b = dB + int(255.0 * (mB / 255.0) *", "order to allow this script to be called from another", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "dR, dG, dB = diffuse.getpixel((x, y)) mR, mG, mB =", "# # Licensed under the Apache License, Version 2.0 (the", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "'FFFF00': (0.7, 0.6, 0.15), '008000': (0.15, 0.3, 0.15), '00FF00': (0.55,", "template for template in templates: # load the templates diffuse", "directory. os.chdir(os.path.dirname(os.path.realpath(__file__))) # get all the template files in put", "/ 255.0) * (color[1] * 2.0 - 1.0) * effectFactor)", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "0.65), '800000': (0.4, 0.15, 0.15), 'FF0000': (0.45, 0.0, 0.0), '808000':", "= Image.new('RGB', diffuse.size) pixels = image.load() for x in range(height):", "0.0), '808000': (0.4, 0.4, 0.2), 'FFFF00': (0.7, 0.6, 0.15), '008000':", "0.1, 0.05) } effectFactor = 0.5 # power of the", "of tuples templates = [] for f in glob.glob(\"*_diffuse_template.jpg\"): templates.append((f,", "in range(width): dR, dG, dB = diffuse.getpixel((x, y)) mR, mG,", "load the templates diffuse = Image.open(template[0]) mask = Image.open(template[1]) assert", "* 2.0 - 1.0) * effectFactor) b = dB +", "(0.45, 0.0, 0.0), '808000': (0.4, 0.4, 0.2), 'FFFF00': (0.7, 0.6,", "textures prepared for OSM, based on image templates.\"\"\" import glob", "Ltd. # # Licensed under the Apache License, Version 2.0", "put them in a list of tuples templates = []", "0.7, 0.7), '000080': (0.2, 0.2, 0.3), '0000FF': (0.4, 0.4, 0.75),", "0.05) } effectFactor = 0.5 # power of the effect,", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "(color[1] * 2.0 - 1.0) * effectFactor) b = dB", "'000080': (0.2, 0.2, 0.3), '0000FF': (0.4, 0.4, 0.75), '800080': (0.5,", "effect, found empirically # foreach template for template in templates:", "0.0), 'FFFFFF': (0.84, 0.84, 0.84), '808080': (0.4, 0.4, 0.4), 'C0C0C0':", "0.3, 0.15), '00FF00': (0.55, 0.69, 0.52), '008080': (0.15, 0.3, 0.3),", "(0.9, 0.75, 0.85), 'F5DEB3': (0.83, 0.78, 0.65), '8B4513': (0.3, 0.1,", "or implied. # See the License for the specific language", "2.0 - 1.0) * effectFactor) pixels[x, y] = (r, g,", "to allow this script to be called from another directory.", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "range(height): for y in range(width): dR, dG, dB = diffuse.getpixel((x,", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "templates.append((f, f.replace('_diffuse_', '_color_mask_'))) # target colors # ref: http://wiki.openstreetmap.org/wiki/Key:colour #", "effectFactor) g = dG + int(255.0 * (mG / 255.0)", "# Copyright 1996-2019 Cyberbotics Ltd. # # Licensed under the", "2.0 - 1.0) * effectFactor) g = dG + int(255.0", "in order to allow this script to be called from", "0.7), '000080': (0.2, 0.2, 0.3), '0000FF': (0.4, 0.4, 0.75), '800080':", "script to be called from another directory. os.chdir(os.path.dirname(os.path.realpath(__file__))) # get", "(the \"License\"); # you may not use this file except", "0.4, 0.4), 'C0C0C0': (0.65, 0.65, 0.65), '800000': (0.4, 0.15, 0.15),", "# you may not use this file except in compliance", "(0.4, 0.15, 0.15), 'FF0000': (0.45, 0.0, 0.0), '808000': (0.4, 0.4,", "Image.open(template[1]) assert diffuse.size == mask.size width, height = diffuse.size #", "* 2.0 - 1.0) * effectFactor) pixels[x, y] = (r,", "for colorString, color in colors.iteritems(): image = Image.new('RGB', diffuse.size) pixels", "= diffuse.getpixel((x, y)) mR, mG, mB = mask.getpixel((x, y)) r", "'8B4513': (0.3, 0.1, 0.05) } effectFactor = 0.5 # power", "allow this script to be called from another directory. os.chdir(os.path.dirname(os.path.realpath(__file__)))", "for x in range(height): for y in range(width): dR, dG,", "# load the templates diffuse = Image.open(template[0]) mask = Image.open(template[1])", "on image templates.\"\"\" import glob import os from PIL import", "(0.65, 0.65, 0.65), '800000': (0.4, 0.15, 0.15), 'FF0000': (0.45, 0.0,", "colors.iteritems(): image = Image.new('RGB', diffuse.size) pixels = image.load() for x", "+ int(255.0 * (mG / 255.0) * (color[1] * 2.0", "of the effect, found empirically # foreach template for template", "# # Unless required by applicable law or agreed to", "'C0C0C0': (0.65, 0.65, 0.65), '800000': (0.4, 0.15, 0.15), 'FF0000': (0.45,", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "'808080': (0.4, 0.4, 0.4), 'C0C0C0': (0.65, 0.65, 0.65), '800000': (0.4,", "Version 2.0 (the \"License\"); # you may not use this", "Image # change directory to this script directory in order", "in a list of tuples templates = [] for f", "in templates: # load the templates diffuse = Image.open(template[0]) mask", "range(width): dR, dG, dB = diffuse.getpixel((x, y)) mR, mG, mB", "1.0) * effectFactor) b = dB + int(255.0 * (mB", "'FF0000': (0.45, 0.0, 0.0), '808000': (0.4, 0.4, 0.2), 'FFFF00': (0.7,", "prepared for OSM, based on image templates.\"\"\" import glob import", "implied. # See the License for the specific language governing", "(color[0] * 2.0 - 1.0) * effectFactor) g = dG", "under the Apache License, Version 2.0 (the \"License\"); # you", "effectFactor) pixels[x, y] = (r, g, b) image.save(template[0].replace('_diffuse_template', '_' +", "* (mG / 255.0) * (color[1] * 2.0 - 1.0)", "int(255.0 * (mG / 255.0) * (color[1] * 2.0 -", "# change directory to this script directory in order to", "* effectFactor) pixels[x, y] = (r, g, b) image.save(template[0].replace('_diffuse_template', '_'", "by applicable law or agreed to in writing, software #", "from another directory. os.chdir(os.path.dirname(os.path.realpath(__file__))) # get all the template files", "(0.3, 0.1, 0.05) } effectFactor = 0.5 # power of", "0.5 # power of the effect, found empirically # foreach", "them in a list of tuples templates = [] for", "mB = mask.getpixel((x, y)) r = dR + int(255.0 *", "* effectFactor) b = dB + int(255.0 * (mB /", "to be called from another directory. os.chdir(os.path.dirname(os.path.realpath(__file__))) # get all", "TODO: is it sufficient? colors = { '000000': (0.0, 0.0,", "templates = [] for f in glob.glob(\"*_diffuse_template.jpg\"): templates.append((f, f.replace('_diffuse_', '_color_mask_')))", "for OSM, based on image templates.\"\"\" import glob import os", "another directory. os.chdir(os.path.dirname(os.path.realpath(__file__))) # get all the template files in", "255.0) * (color[1] * 2.0 - 1.0) * effectFactor) b", "(0.15, 0.3, 0.15), '00FF00': (0.55, 0.69, 0.52), '008080': (0.15, 0.3,", "directory to this script directory in order to allow this", "the template files in put them in a list of", "0.3, 0.3), '00FFFF': (0.6, 0.7, 0.7), '000080': (0.2, 0.2, 0.3),", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "r = dR + int(255.0 * (mR / 255.0) *", "(color[2] * 2.0 - 1.0) * effectFactor) pixels[x, y] =", "Unless required by applicable law or agreed to in writing,", "0.65), '8B4513': (0.3, 0.1, 0.05) } effectFactor = 0.5 #", "== mask.size width, height = diffuse.size # create an image", "/ 255.0) * (color[0] * 2.0 - 1.0) * effectFactor)", "= dG + int(255.0 * (mG / 255.0) * (color[1]", "the specific language governing permissions and # limitations under the", "(mR / 255.0) * (color[0] * 2.0 - 1.0) *", "(mG / 255.0) * (color[1] * 2.0 - 1.0) *", "applicable law or agreed to in writing, software # distributed", "Copyright 1996-2019 Cyberbotics Ltd. # # Licensed under the Apache", "templates: # load the templates diffuse = Image.open(template[0]) mask =", "1996-2019 Cyberbotics Ltd. # # Licensed under the Apache License,", "diffuse.getpixel((x, y)) mR, mG, mB = mask.getpixel((x, y)) r =", "dB = diffuse.getpixel((x, y)) mR, mG, mB = mask.getpixel((x, y))", "the templates diffuse = Image.open(template[0]) mask = Image.open(template[1]) assert diffuse.size", "- 1.0) * effectFactor) pixels[x, y] = (r, g, b)", "and # limitations under the License. \"\"\"Generate textures prepared for", "in writing, software # distributed under the License is distributed", "is it sufficient? colors = { '000000': (0.0, 0.0, 0.0),", "python # Copyright 1996-2019 Cyberbotics Ltd. # # Licensed under", "1.0) * effectFactor) g = dG + int(255.0 * (mG", "'800080': (0.5, 0.4, 0.5), 'FF00FF': (0.9, 0.75, 0.85), 'F5DEB3': (0.83,", "per color for colorString, color in colors.iteritems(): image = Image.new('RGB',", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "'00FFFF': (0.6, 0.7, 0.7), '000080': (0.2, 0.2, 0.3), '0000FF': (0.4,", "# You may obtain a copy of the License at", "2.0 - 1.0) * effectFactor) b = dB + int(255.0", "0.84), '808080': (0.4, 0.4, 0.4), 'C0C0C0': (0.65, 0.65, 0.65), '800000':", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "(0.83, 0.78, 0.65), '8B4513': (0.3, 0.1, 0.05) } effectFactor =", "x in range(height): for y in range(width): dR, dG, dB", "1.0) * effectFactor) pixels[x, y] = (r, g, b) image.save(template[0].replace('_diffuse_template',", "in glob.glob(\"*_diffuse_template.jpg\"): templates.append((f, f.replace('_diffuse_', '_color_mask_'))) # target colors # ref:", "# foreach template for template in templates: # load the", "import Image # change directory to this script directory in", "* (color[2] * 2.0 - 1.0) * effectFactor) pixels[x, y]", "0.75, 0.85), 'F5DEB3': (0.83, 0.78, 0.65), '8B4513': (0.3, 0.1, 0.05)", "the License for the specific language governing permissions and #", "Apache License, Version 2.0 (the \"License\"); # you may not", "either express or implied. # See the License for the", "(0.6, 0.7, 0.7), '000080': (0.2, 0.2, 0.3), '0000FF': (0.4, 0.4,", "y in range(width): dR, dG, dB = diffuse.getpixel((x, y)) mR,", "0.5), 'FF00FF': (0.9, 0.75, 0.85), 'F5DEB3': (0.83, 0.78, 0.65), '8B4513':", "} effectFactor = 0.5 # power of the effect, found", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "PIL import Image # change directory to this script directory", "template files in put them in a list of tuples", "templates diffuse = Image.open(template[0]) mask = Image.open(template[1]) assert diffuse.size ==", "dB + int(255.0 * (mB / 255.0) * (color[2] *", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "color for colorString, color in colors.iteritems(): image = Image.new('RGB', diffuse.size)", "diffuse.size == mask.size width, height = diffuse.size # create an", "Image.new('RGB', diffuse.size) pixels = image.load() for x in range(height): for", "f.replace('_diffuse_', '_color_mask_'))) # target colors # ref: http://wiki.openstreetmap.org/wiki/Key:colour # TODO:", "g = dG + int(255.0 * (mG / 255.0) *", "template in templates: # load the templates diffuse = Image.open(template[0])", "Image.open(template[0]) mask = Image.open(template[1]) assert diffuse.size == mask.size width, height", "- 1.0) * effectFactor) b = dB + int(255.0 *", "the License. \"\"\"Generate textures prepared for OSM, based on image", "0.2), 'FFFF00': (0.7, 0.6, 0.15), '008000': (0.15, 0.3, 0.15), '00FF00':", "\"License\"); # you may not use this file except in", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "tuples templates = [] for f in glob.glob(\"*_diffuse_template.jpg\"): templates.append((f, f.replace('_diffuse_',", "255.0) * (color[0] * 2.0 - 1.0) * effectFactor) g", "in put them in a list of tuples templates =", "# distributed under the License is distributed on an \"AS", "# Unless required by applicable law or agreed to in", "language governing permissions and # limitations under the License. \"\"\"Generate", "mG, mB = mask.getpixel((x, y)) r = dR + int(255.0", "y)) mR, mG, mB = mask.getpixel((x, y)) r = dR", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "files in put them in a list of tuples templates", "int(255.0 * (mR / 255.0) * (color[0] * 2.0 -", "License. \"\"\"Generate textures prepared for OSM, based on image templates.\"\"\"", "= image.load() for x in range(height): for y in range(width):", "You may obtain a copy of the License at #", "for template in templates: # load the templates diffuse =", "mask.size width, height = diffuse.size # create an image per", "* (mB / 255.0) * (color[2] * 2.0 - 1.0)", "image per color for colorString, color in colors.iteritems(): image =", "'008080': (0.15, 0.3, 0.3), '00FFFF': (0.6, 0.7, 0.7), '000080': (0.2,", "colors = { '000000': (0.0, 0.0, 0.0), 'FFFFFF': (0.84, 0.84,", "the Apache License, Version 2.0 (the \"License\"); # you may", "0.3), '00FFFF': (0.6, 0.7, 0.7), '000080': (0.2, 0.2, 0.3), '0000FF':", "to this script directory in order to allow this script", "= Image.open(template[0]) mask = Image.open(template[1]) assert diffuse.size == mask.size width," ]
[ "import os for k, v in os.environ.iteritems(): print k, '=',", "os for k, v in os.environ.iteritems(): print k, '=', v", "env \"\"\" import os for k, v in os.environ.iteritems(): print", "\"\"\" import os for k, v in os.environ.iteritems(): print k,", "\"\"\" test local env \"\"\" import os for k, v", "test local env \"\"\" import os for k, v in", "local env \"\"\" import os for k, v in os.environ.iteritems():" ]
[ "# then join the cycles into one big sample sample", "= (df.marend01==4) df['widowed'] = (df.marend01==1) df['stillma'] = (df.timesmar== 1) &", "df.cmstphsbx.replace(invalid, np.nan, inplace=True) df.timesmar.replace([98, 99], np.nan, inplace=True) df['evrmarry'] = (df.timesmar", "df.firstcm df.cmmarrhx.fillna(df.currentcm, inplace=True) # define evrmarry if either currentcm or", "colspecs=colspecs, names=names, header=None, nrows=7969, compression='gzip') df.cmintvw.replace([9797, 9898, 9999], np.nan, inplace=True)", "(df.fmarital==1) df['cycle'] = 3 CleanResp(df) return df def ReadFemResp1988(): \"\"\"Reads", "90000 df.loc[df.cmstphsbx>90000, 'cmstphsbx'] -= 90000 # combine current and first", "iters=101, cutoffs=None, predict_flag=False, prop_match=None, error_rate=0): \"\"\"Makes survival curves for resampled", "df['cycle'] = 6 CleanResp(df) return df def ReadMaleResp2010(): \"\"\"Reads respondent", "assigns an index to each bin. For example, anyone between", "the end of the first marriage. df['marend01'] = df.marrend4 df['cmmarrhx']", "df['divorced'] = (df.f18m1 == 4) df['separated'] = (df.f18m1 == 5)", "(df.rmarital==1) df['finalwgt'] = df.wgt2011_2013 df['cycle'] = 8 CleanResp(df) return df", "age_step = 1 age_bins = np.arange(age_min, age_max, age_step) year_min =", "-= 9000 df.loc[df.cmmarrhx>9000, 'cmmarrhx'] -= 9000 df.loc[df.cmdivorcx>9000, 'cmdivorcx'] -= 9000", "evrmarry if either currentcm or firstcm is non-zero df['evrmarry'] =", "len(df), replace=True, p=weights) return df.loc[indices] def Jitter(df, column, jitter=1): \"\"\"Adds", "> 0) df['divorced'] = (df.marend01==2) | (df.marend01==3) df['separated'] = (df.marend01==4)", "each cycle separately samples = [ResampleRowsWeighted(resp) for resp in resps]", "actual missing values! \"\"\" group[colname] = np.random.random(len(group)) < error_rate def", "'cmintvw', 'evrmarry', 'parity', 'wgtq1q16', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss']", "to customize #CleanResp(df) df['agemarry'] = (df.cmmarrhx - df.cmbirth) / 12.0", "weight: C1 #marital status: C5 #Respondent every married: CC227 pass", "// 5 DigitizeResp(resp) def DigitizeResp(df): \"\"\"Computes indices for age, agemarry,", "assert(df.agemarry.value_counts().max() == 29) def main(): print('Cycle 10') resp10 = ReadFemResp2017()", "we have to compute them based on other variables; #", "4651) assert(df.agemarry.value_counts().max() == 71) def Validate1988(df): assert(len(df) == 8450) assert(len(df[df.evrmarry])", "df = ReadResp('2006_2010_FemRespSetup.dct', '2006_2010_FemResp.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999]", "inplace=True) df.cmstphsbx.replace([0, 99999], np.nan, inplace=True) # CM values above 9000", "usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgt2011_2013',", "range(iters): sample = ResampleResps(resps) # group by decade grouped =", "group name to (HazardFunction, SurvivalFunction) \"\"\" names = list(hf_map.keys()) names.sort()", "'fmarno', 'mar1diss'] df = ReadResp('2011_2013_FemRespSetup.dct', '2011_2013_FemRespData.dat.gz', usecols=usecols) invalid = [9997,", "Counter import thinkstats2 import thinkplot import survival def ResampleResps(resps, remove_missing=False,", "sf def MakeSurvivalCI(sf_seq, percents): \"\"\"Makes confidence intervals from a list", "#age at first marriage: CC232 #age of respondent at interview:", "\"\"\" usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgt2011_2013',", "with sample of rows from `group` \"\"\" rv = scipy.stats.norm(scale=1)", "ReadResp('2006_2010_MaleSetup.dct', '2006_2010_Male.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.evrmarry==1) df['divorced']", "resp.loc[~resp.complete, 'ongoing_var'].dropna() hf = survival.EstimateHazardFunction(complete, ongoing) if cutoff: hf.Truncate(cutoff) sf", "assert(sum(df.evrmarry) == 2452) assert(df.agemarry.value_counts().max() == 33) def Validate2015(df): assert(len(df) ==", "['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgt2013_2015', 'marend01', 'rmarital', 'fmarno',", "= [(2568-1, 2574), (36-1, 37), (1521-1, 1525), (1538-1, 1542), (12-1,", "] df = pd.read_fwf(dat_file, colspecs=colspecs, names=names, header=None, nrows=7969, compression='gzip') df.cmintvw.replace([9797,", "survival functions predict_flag: whether the lines are predicted or actual", "'fmarno', 'mar1diss'] df = ReadResp('2013_2015_MaleSetup.dct', '2013_2015_MaleData.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01", "from collections import defaultdict from collections import OrderedDict from collections", "survival functions. For each group in hf_map, we extend hf", "| (df.marend01==3) df['separated'] = (df.marend01==4) df['widowed'] = (df.marend01==1) df['stillma'] =", "= MakeSurvivalCI(sf_seq, [10, 50, 90]) thinkplot.FillBetween(ts, rows[0], rows[2], color='gray', alpha=0.2)", "noise to a column. df: DataFrame column: string column name", "rows) where ts is a sequence of times and rows", "DataFrame of respondents Adds columns: agemarry, age, decade, fives \"\"\"", "7. returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth',", "group name to color \"\"\" for name, sf_seq in sorted(sf_map.items(),", "return df def Validate1982(df): assert(len(df) == 7969) assert(len(df[df.evrmarry]) == 4651)", "4 CleanResp(df) return df def ReadFemResp1995(): \"\"\"Reads respondent data from", "SurvivalFunction) \"\"\" names = list(hf_map.keys()) names.sort() hfs = [hf_map[name][0] for", "16), (26-1, 30), (1554-1, 1554), (1565-1, 1569), (1570-1, 1574), (2441-1,", "resp6 = ReadFemResp2002() Validate2002(resp6) print('Cycle 5') resp5 = ReadFemResp1995() Validate1995(resp5)", "truncate the estimated functions returns: pair of HazardFunction, SurvivalFunction \"\"\"", "inplace=True) df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2)", "'cmbirth', 'cmintvw', 'evrmarry', 'wgtq1q16', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df =", "= (df.fmarno == 1) & (df.rmarital==1) df['cycle'] = 6 CleanResp(df)", "> 0) df['divorced'] = (df.f18m1 == 4) df['separated'] = (df.f18m1", "if jitter: Jitter(sample, 'age', jitter=jitter) Jitter(sample, 'agemarry', jitter=jitter) DigitizeResp(resp) return", "= ['finalwgt', 'ageint', 'mar2p', 'cmmarrhx', 'fmarital', 'cmintvw', 'cmbirth', 'f18m1', 'cmdivorcx',", "df.loc[df.cmmarrhx>9000, 'cmmarrhx'] -= 9000 df.loc[df.cmdivorcx>9000, 'cmdivorcx'] -= 9000 df.loc[df.cmstphsbx>9000, 'cmstphsbx']", "'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2011_2013_FemRespSetup.dct', '2011_2013_FemRespData.dat.gz', usecols=usecols)", "99999], np.nan, inplace=True) df.currentcm.replace([0, 99999], np.nan, inplace=True) df.cmdivorcx.replace([0, 99999], np.nan,", "np.nan, inplace=True) #df.cmbirth.replace(invalid, np.nan, inplace=True) #df.cmmarrhx.replace(invalid, np.nan, inplace=True) # since", "ReadFemResp2010() Validate2010(resp7) print('Cycle 6') resp6 = ReadFemResp2002() Validate2002(resp6) print('Cycle 5')", "missing values of the given column. group: DataFrame colname: string", "'ager', 'evrmarry', 'parity', 'wgt2015_2017', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss']", "== 73) def Validate1995(df): assert(len(df) == 10847) assert(len(df[df.evrmarry]) == 6841)", "usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgtq1q16', 'marend01',", "\"\"\" if cutoffs == None: cutoffs = {} sf_map =", "age resp['missing'] = np.where(resp.evrmarry, resp.agemarry.isnull(), resp.age.isnull()) month0 = pd.to_datetime('1899-12-15') dates", "ss_seq = [sf.Probs(ts) for sf in sf_seq if len(sf) >", "= rv.pdf(values-value) weights /= sum(weights) return np.random.choice(group.index, 1, p=weights)[0] indices", "null = group[group[missing_colname]] if len(null) == 0: return # print(len(null),", "and rows contains one row of values for each percent", "thinkstats2 import thinkplot import survival def ResampleResps(resps, remove_missing=False, jitter=0): \"\"\"Resamples", "resp5 = ReadFemResp1995() Validate1995(resp5) print('Cycle 4') resp4 = ReadFemResp1988() Validate1988(resp4)", "return df def ReadFemResp1988(): \"\"\"Reads respondent data from NSFG Cycle", "4713), (4718-1, 4721), (4722-1, 4725), (17-1, 17)] df = pd.read_fwf(dat_file,", "of survival functions. sf_seq: list of SurvivalFunction percents: list of", "unknown df.loc[df.cmintvw>9000, 'cmintvw'] -= 9000 df.loc[df.cmbirth>9000, 'cmbirth'] -= 9000 df.loc[df.cmmarrhx>9000,", "- df.cmbirth) / 12.0 # if married, we need agemarry;", "\"\"\" # removed 'cmmarrhx', 'cmdivorcx', 'cmbirth', usecols = ['caseid', 'cmintvw',", "= ReadFemResp2010() Validate2010(resp7) print('Cycle 6') resp6 = ReadFemResp2002() Validate2002(resp6) print('Cycle", "number of resamples to plot predict_flag: whether to also plot", "\"\"\" from __future__ import print_function, division import bisect import numpy", "\"\"\"Reads respondent data from NSFG Cycle 3. returns: DataFrame \"\"\"", "column name jitter: standard deviation of noise \"\"\" df[column] +=", "64) def Validate2013(df): assert(len(df) == 5601) assert(sum(df.evrmarry) == 2452) assert(df.agemarry.value_counts().max()", "7969) assert(len(df[df.evrmarry]) == 4651) assert(df.agemarry.value_counts().max() == 71) def Validate1988(df): assert(len(df)", "to color \"\"\" for name, sf_seq in sorted(sf_map.items(), reverse=True): if", "= (df.timesmar== 1) & (df.fmarit==1) df['cycle'] = 6 CleanResp(df) return", "DataFrame \"\"\" filename = '1988FemRespDataLines.dat.gz' names = ['finalwgt', 'ageint', 'currentcm',", "'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2002FemResp.dct', '2002FemResp.dat.gz', usecols=usecols) invalid", "def ReadFemResp2002(): \"\"\"Reads respondent data from NSFG Cycle 6. returns:", "respondent at interview: C3 #final weight: C1 #marital status: C5", "ts = list(ts) ts.sort() # evaluate each sf at all", "returns: DataFrame \"\"\" # removed 'cmmarrhx', 'cmdivorcx', 'cmbirth', usecols =", "all ts where the sfs are evaluated ts = set()", "np.nan, inplace=True) df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] =", "idea that the resampled people # are not identical to", "'currentcm'] -= 90000 df.loc[df.cmdivorcx>90000, 'cmdivorcx'] -= 90000 df.loc[df.cmstphsbx>90000, 'cmstphsbx'] -=", "usecols = ['caseid', 'mardat01', 'cmintvw', 'ager', 'evrmarry', 'wgt2015_2017', 'marend01', 'rmarital',", "-= 9000 df['evrmarry'] = (df.fmarno > 0) df['divorced'] = (df.f18m1", "'firstcm', 'cmintvw', 'cmbirth', 'f23m1', 'cmdivorcx', 'cmstphsbx', 'fmarno'] colspecs = [(2568-1,", "For each group in hf_map, we extend hf and recompute", "contains one row of values for each percent \"\"\" #", "sf_seq in sorted(sf_map.items(), reverse=True): if len(sf_seq) == 0: continue sf", "since cmbirth and cmmarrhx are no longer included, # we", "(4718-1, 4721), (4722-1, 4725), (17-1, 17)] df = pd.read_fwf(dat_file, compression='gzip',", "['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgt2011_2013', 'marend01', 'rmarital', 'fmarno',", "[5, 95] returns: (ts, rows) where ts is a sequence", "propensity scores returns: DataFrame with sample of rows from `group`", "for name in names] # extend each hazard function using", "\"\"\"Resamples the rows in df in accordance with a weight", "to run the analysis with different levels of granularity. df:", "sum(weights) return np.random.choice(group.index, 1, p=weights)[0] indices = [ChooseIndex(value) for value", "jitter: standard deviation of noise \"\"\" df[column] += np.random.uniform(-jitter, jitter,", "colname='agemarry'): \"\"\"Choose a random subset of `group` to matches propensity", "functions and recomputes survival functions. For each group in hf_map,", "from NSFG Cycle 10. returns: DataFrame \"\"\" # removed 'cmmarrhx',", "- 1900) DigitizeResp(df) return df def Validate1982(df): assert(len(df) == 7969)", "/= sum(weights) return np.random.choice(group.index, 1, p=weights)[0] indices = [ChooseIndex(value) for", "'mar1diss'] df = ReadResp('2013_2015_MaleSetup.dct', '2013_2015_MaleData.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry']", "if not predict_flag: if colormap: color = colormap[name] thinkplot.Plot(ts, rows[1],", "fill with random data #FillMissingColumn(group, 'complete_var', 'complete_missing') #FillMissingColumn(group, 'ongoing_var', 'ongoing_missing')", "thinkstats2.PercentileRows(ss_seq, percents) return ts, rows def ReadFemResp1982(): \"\"\"Reads respondent data", "df.loc[df.cmbirth>9000, 'cmbirth'] -= 9000 df.loc[df.cmmarrhx>9000, 'cmmarrhx'] -= 9000 df.loc[df.cmdivorcx>9000, 'cmdivorcx']", "5') resp5 = ReadFemResp1995() Validate1995(resp5) print('Cycle 4') resp4 = ReadFemResp1988()", "'fmarno'] colspecs = [(2568-1, 2574), (36-1, 37), (1521-1, 1525), (1538-1,", "color \"\"\" for name, sf_seq in sorted(sf_map.items(), reverse=True): if len(sf_seq)", "= '1988FemRespDataLines.dat.gz' names = ['finalwgt', 'ageint', 'currentcm', 'firstcm', 'cmintvw', 'cmbirth',", "file returns: DataFrame \"\"\" filename = '1988FemRespDataLines.dat.gz' names = ['finalwgt',", "9 CleanResp(df) return df def ReadMaleResp2017(): \"\"\"Reads respondent data from", "functions. sf_map: map from group name to sequence of survival", "age_step df.loc[df.agemarry.isnull(), 'agemarry_index'] = np.nan df['birth_index'] = np.digitize(df.year, year_bins) *", "= resp.loc[resp.complete, 'complete_var'].dropna() ongoing = resp.loc[~resp.complete, 'ongoing_var'].dropna() hf = survival.EstimateHazardFunction(complete,", "def ReadMaleResp2010(): \"\"\"Reads respondent data from NSFG Cycle 7. returns:", "print(len(null), len(group)) valid = group[colname].dropna() fill = valid.sample(len(null), replace=True) fill.index", "'cmintvw', 'cmbirth', 'f18m1', 'cmdivorcx', 'cmstphsbx', 'fmarno'] colspecs = [(976-1, 982),", "hf.MakeSurvival() hf_map[name] = hf, sf def MakeSurvivalCI(sf_seq, percents): \"\"\"Makes confidence", "> 0) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] =", "ChooseIndex(value): weights = rv.pdf(values-value) weights /= sum(weights) return np.random.choice(group.index, 1,", "/ 12.0 resp['age'] = (resp.cmintvw - resp.cmbirth) / 12.0 #", "= (df.f23m1==2) df['separated'] = (df.f23m1==3) df['widowed'] = (df.f23m1==1) df['stillma'] =", "I think it is better # to drop it than", "None: cutoffs = {} sf_map = defaultdict(list) # iters is", "(12-1, 15), (606-1, 606), (619-1, 622), (625-1, 628), (1142-1, 1143),", "percents) return ts, rows def ReadFemResp1982(): \"\"\"Reads respondent data from", "people # are not identical to the actual respondents if", "assert(len(df[df.evrmarry]) == 6841) assert(df.agemarry.value_counts().max() == 79) def Validate2002(df): assert(len(df) ==", "collections import Counter import thinkstats2 import thinkplot import survival def", "4') resp4 = ReadFemResp1988() Validate1988(resp4) print('Cycle 3') resp3 = ReadFemResp1982()", "the first marriage. df['marend01'] = df.marrend4 df['cmmarrhx'] = df.mardat01 df['evrmarry']", "[month0 + pd.DateOffset(months=cm) for cm in df.cmbirth] df['year'] = (pd.DatetimeIndex(dates).year", "Validate2010(df): assert(len(df) == 12279) assert(sum(df.evrmarry) == 5534) assert(df.agemarry.value_counts().max() == 64)", "df.cmmarrhx.replace(invalid, np.nan, inplace=True) df.cmdivorcx.replace(invalid, np.nan, inplace=True) df.cmstphsbx.replace(invalid, np.nan, inplace=True) df.timesmar.replace([98,", "\"\"\" rv = scipy.stats.norm(scale=1) values = group[colname].fillna(100) def ChooseIndex(value): weights", "+= age_min - age_step df.loc[df.age.isnull(), 'age_index'] = np.nan df['agemarry_index'] =", "< error_rate def FillMissingColumn(group, colname, missing_colname): \"\"\"Fills missing values of", "= 3 CleanResp(df) return df def ReadFemResp1988(): \"\"\"Reads respondent data", "header=None, nrows=7969, compression='gzip') df.cmintvw.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmbirth.replace([9797, 9898,", "age_bins) * age_step df.age_index += age_min - age_step df.loc[df.age.isnull(), 'age_index']", "propensity with `target`. target: DataFrame group: DataFrame colname: string name", "df['widowed'] = (df.marend01==3) df['stillma'] = (df.timesmar==1) & (df.marend01.isnull()) df['cycle'] =", "'marrend4', #'marrend', 'marrend2', 'marrend3', marrend5', 'marrend6', ] df = ReadResp('2002Male.dct',", "# make predictions if desired if predict_flag: MakePredictions(hf_map) # extract", "'evrmarry', 'wgt2011_2013', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2011_2013_MaleSetup.dct', '2011_2013_MaleData.dat.gz',", "= [(976-1, 982), (1001-1, 1002), (1268-1, 1271), (1037-1, 1040), (1041-1,", "for cm in df.cmbirth] df['year'] = (pd.DatetimeIndex(dates).year - 1900) DigitizeResp(df)", "and then concats them. resps: list of DataFrame returns: DataFrame", "if were a standard ascii file returns: DataFrame \"\"\" filename", "1900) #resp['decade'] = resp.year // 10 #resp['fives'] = resp.year //", "reflects the idea that the resampled people # are not", "function using data from the previous cohort, # and update", "ReadResp('2013_2015_MaleSetup.dct', '2013_2015_MaleData.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.evrmarry==1) df['divorced']", "is given the year_index 80. This function allows me to", "8. returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth',", "names = ['finalwgt', 'ageint', 'mar2p', 'cmmarrhx', 'fmarital', 'cmintvw', 'cmbirth', 'f18m1',", "df.loc[indices] def Jitter(df, column, jitter=1): \"\"\"Adds random noise to a", "these variables into bins and then assigns an index to", "sample = sample[~sample.missing] # jittering the ages reflects the idea", "'mar1diss'] df = ReadResp('2006_2010_FemRespSetup.dct', '2006_2010_FemResp.dat.gz', usecols=usecols) invalid = [9997, 9998,", "thinkstats2.ReadStataDct(dct_file, encoding='iso-8859-1') df = dct.ReadFixedWidth(dat_file, compression='gzip', **options) return df def", "df = ReadResp('2015_2017_MaleSetup.dct', '2015_2017_MaleData.dat.gz', usecols=usecols) # since cmbirth and cmmarrhx", "- resp.cmbirth) / 12.0 resp['age'] = (resp.cmintvw - resp.cmbirth) /", "'wgtq1q16', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2006_2010_MaleSetup.dct', '2006_2010_Male.dat.gz', usecols=usecols)", "'cmmarrhx'] -= 9000 df.loc[df.cmdivorcx>9000, 'cmdivorcx'] -= 9000 df.loc[df.cmstphsbx>9000, 'cmstphsbx'] -=", "'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2013_2015_MaleSetup.dct', '2013_2015_MaleData.dat.gz', usecols=usecols) df['cmmarrhx'] =", "# and estimate (hf, sf) for each group hf_map =", "C1 #marital status: C5 #Respondent every married: CC227 pass def", "= ReadFemResp2013() Validate2013(resp8) print('Cycle 7') resp7 = ReadFemResp2010() Validate2010(resp7) print('Cycle", "9000 df.loc[df.cmstphsbx>9000, 'cmstphsbx'] -= 9000 df['evrmarry'] = (df.fmarno > 0)", "9898, 9999], np.nan, inplace=True) df.cmdivorcx.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmstphsbx.replace([9797,", "invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) df.cmbirth.replace(invalid, np.nan,", "15), (606-1, 606), (619-1, 622), (625-1, 628), (1142-1, 1143), ]", "drop it than to fill with random data #FillMissingColumn(group, 'complete_var',", "i > 0: hf.Extend(hfs[i-1]) sf = hf.MakeSurvival() hf_map[name] = hf,", "age_index returns: map from group name to list of survival", "months df['cmbirth'] = df.cmintvw - df.ager*12 df['cmmarrhx'] = (df.mardat01-1900) *", "= np.where(resp.evrmarry, resp.agemarry.isnull(), resp.age.isnull()) month0 = pd.to_datetime('1899-12-15') dates = [month0", "inplace=True) #df.cmmarrhx.replace(invalid, np.nan, inplace=True) # since cmbirth and cmmarrhx are", "df['cycle'] = 4 CleanResp(df) return df def ReadFemResp1995(): \"\"\"Reads respondent", "'cmstphsbx'] -= 9000 df['evrmarry'] = (df.fmarno > 0) df['divorced'] =", "9999], np.nan, inplace=True) df.cmmarrhx.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmdivorcx.replace([9797, 9898,", "ReadCanadaCycle6(): \"\"\" \"\"\" #age at first marriage: CC232 #age of", "usecols = ['caseid', 'cmintvw', 'ager', 'evrmarry', 'parity', 'wgt2015_2017', 'mardat01', 'marend01',", "ReadFemResp1982(): \"\"\"Reads respondent data from NSFG Cycle 3. returns: DataFrame", "'evrmarry', 'parity', 'wgt2011_2013', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df", "removed 'cmmarrhx', 'cmdivorcx', 'cmbirth', usecols = ['caseid', 'cmintvw', 'ager', 'evrmarry',", "resp.agemarry.isnull(), resp.age.isnull()) month0 = pd.to_datetime('1899-12-15') dates = [month0 + pd.DateOffset(months=cm)", "np.digitize(df.agemarry, age_bins) * age_step df.agemarry_index += age_min - age_step df.loc[df.agemarry.isnull(),", "'finalwgt', 'marend01', 'cmdivorcx', 'cmstphsbx', 'marstat'] colspecs = [(12360-1, 12363), (4637-1,", "assert(df.agemarry.value_counts().max() == 64) def Validate2013(df): assert(len(df) == 5601) assert(sum(df.evrmarry) ==", "plot predict_flag: whether to also plot predictions cutoffs: map from", "'mar1diss'] df = ReadResp('2011_2013_FemRespSetup.dct', '2011_2013_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998,", "df.wgtq1q16 df['cycle'] = 7 CleanResp(df) return df def ReadFemResp2013(): \"\"\"Reads", "import matplotlib.pyplot as plt from collections import defaultdict from collections", "'cmbirth'] -= 90000 df.loc[df.firstcm>90000, 'firstcm'] -= 90000 df.loc[df.currentcm>90000, 'currentcm'] -=", "if predict_flag: MakePredictions(hf_map) # extract the sf from each pair", "PlotSurvivalFunctions(sf_map, predict_flag=False, colormap=None): \"\"\"Plot estimated survival functions. sf_map: map from", "DataFrame group: DataFrame colname: string name of column with propensity", "16), (12350-1, 12359), (4713-1, 4713), (4718-1, 4721), (4722-1, 4725), (17-1,", "'2015_2017_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True)", "select, like [5, 95] returns: (ts, rows) where ts is", "-= 90000 # combine current and first marriage df['cmmarrhx'] =", "5699) assert(sum(df.evrmarry) == 2401) assert(df.agemarry.value_counts().max() == 25) def Validate2017(df): assert(len(df)", "GNU GPLv3 http://www.gnu.org/licenses/gpl.html \"\"\" from __future__ import print_function, division import", "ts, rows = MakeSurvivalCI(sf_seq, [10, 50, 90]) thinkplot.FillBetween(ts, rows[0], rows[2],", "(df.marend01==3) df['stillma'] = (df.timesmar==1) & (df.marend01.isnull()) df['cycle'] = 5 CleanResp(df)", "= pd.read_fwf(dat_file, compression='gzip', colspecs=colspecs, names=names) invalid = [9997, 9998, 9999]", "= (df.cmmarrhx - df.cmbirth) / 12.0 df['age'] = (df.cmintvw -", "\"\"\" usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgt2013_2015',", "use with \"Think Stats\", by <NAME>, available from greenteapress.com Copyright", "NSFG Cycle 6. returns: DataFrame \"\"\" usecols = ['caseid', 'cmmarrhx',", "'age_index'] = np.nan df['agemarry_index'] = np.digitize(df.agemarry, age_bins) * age_step df.agemarry_index", "if len(sf) == 0: continue ts, rows = MakeSurvivalCI(sf_seq, [10,", "'cmintvw', 'evrmarry', 'wgt2011_2013', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2011_2013_MaleSetup.dct',", "Validate2017(df): assert(len(df) == 5554) assert(sum(df.evrmarry) == 2582) assert(df.agemarry.value_counts().max() == 29)", "numpy as np import pandas as pd import scipy.stats import", "functions predict_flag: whether the lines are predicted or actual colormap:", "#df.marrend2.replace([8,9], np.nan, inplace=True) #df.marrend3.replace([8,9], np.nan, inplace=True) df.marrend4.replace([8,9], np.nan, inplace=True) #df.marrend5.replace([8,9],", "resamples to plot predict_flag: whether to also plot predictions cutoffs:", "are evaluated ts = set() for sf in sf_seq: ts", "== 0: return # print(len(null), len(group)) valid = group[colname].dropna() fill", "ages reflects the idea that the resampled people # are", "intervals from a list of survival functions. sf_seq: list of", "'marrend2', 'marrend3', marrend5', 'marrend6', ] df = ReadResp('2002Male.dct', '2002Male.dat.gz', usecols=usecols)", "df: DataFrame \"\"\" age_min = 10 age_max = 55 age_step", "(df.cmintvw - df.cmbirth) / 12.0 # if married, we need", "= (df.marend01==1) df['stillma'] = (df.timesmar== 1) & (df.fmarit==1) df['cycle'] =", "\"\"\" NOTE: This will not work if there are actual", "non-zero df['evrmarry'] = (df.fmarno > 0) df['divorced'] = (df.f23m1==2) df['separated']", "function for i, name in enumerate(names): hf, sf = hf_map[name]", "of `group` to matches propensity with `target`. target: DataFrame group:", "of the first marriage. df['marend01'] = df.marrend4 df['cmmarrhx'] = df.mardat01", "collections import defaultdict from collections import OrderedDict from collections import", "is non-zero df['evrmarry'] = (df.fmarno > 0) df['divorced'] = (df.f23m1==2)", "(df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2013_2015 df['cycle'] =", "for resp in resps] # then join the cycles into", "bisect import numpy as np import pandas as pd import", "df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgtq1q16", "it is better # to drop it than to fill", "'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgt2011_2013', 'marend01', 'rmarital', 'fmarno', 'mar1diss']", "married: CC227 pass def ReadMaleResp2002(): \"\"\"Reads respondent data from NSFG", "ongoing = resp.loc[~resp.complete, 'ongoing_var'].dropna() hf = survival.EstimateHazardFunction(complete, ongoing) if cutoff:", "Validate2015(df): assert(len(df) == 5699) assert(sum(df.evrmarry) == 2401) assert(df.agemarry.value_counts().max() == 25)", "PropensityMatch(target, group, colname='agemarry'): \"\"\"Choose a random subset of `group` to", "(df.fmarno==1) & (df.fmarital==1) df['cycle'] = 3 CleanResp(df) return df def", "def CleanResp(resp): \"\"\"Cleans a respondent DataFrame. resp: DataFrame of respondents", "== 1) & (df.rmarital==1) df['cycle'] = 6 CleanResp(df) return df", "df['missing'] = np.where(df.evrmarry, df.agemarry.isnull(), df.age.isnull()) month0 = pd.to_datetime('1899-12-15') dates =", "/= sum(weights) indices = np.random.choice(df.index, len(df), replace=True, p=weights) return df.loc[indices]", "CleanResp(df) return df def ReadFemResp2015(): \"\"\"Reads respondent data from NSFG", "= (pd.DatetimeIndex(dates).year - 1900) DigitizeResp(df) return df def Validate1982(df): assert(len(df)", "from NSFG Cycle 6. returns: DataFrame \"\"\" usecols = ['caseid',", "df def Validate1982(df): assert(len(df) == 7969) assert(len(df[df.evrmarry]) == 4651) assert(df.agemarry.value_counts().max()", "dataframe and then concats them. resps: list of DataFrame returns:", "hf and recompute sf. hf_map: map from group name to", "\"\"\"Makes survival curves for resampled data. resps: list of DataFrames", "12 months df['cmbirth'] = df.cmintvw - df.ager*12 df['cmmarrhx'] = (df.mardat01-1900)", "old is assigned age_index 30. Anyone born in the 80s", "8450) assert(len(df[df.evrmarry]) == 5290) assert(df.agemarry.value_counts().max() == 73) def Validate1995(df): assert(len(df)", "df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.timesmar==1) &", "# define evrmarry if either currentcm or firstcm is non-zero", "\"\"\" dat_file = '1982NSFGData.dat.gz' names = ['finalwgt', 'ageint', 'mar2p', 'cmmarrhx',", "respondent data from NSFG Cycle 8. returns: DataFrame \"\"\" usecols", "df['finalwgt'] = df.wgt2011_2013 df['cycle'] = 8 CleanResp(df) return df def", "year_min - year_step def ReadCanadaCycle5(): \"\"\" \"\"\" #age at first", "colname: string \"\"\" null = group[group[missing_colname]] if len(null) == 0:", "def ReadCanadaCycle5(): \"\"\" \"\"\" #age at first marriage: CC232 #age", "= 7 CleanResp(df) return df def ReadMaleResp2013(): \"\"\"Reads respondent data", "example, anyone between 30 and 30.99 year old is assigned", "the ages reflects the idea that the resampled people #", "C3 #final weight: C1 #marital status: C5 #Respondent every married:", "if either currentcm or firstcm is non-zero df['evrmarry'] = (df.fmarno", "__future__ import print_function, division import bisect import numpy as np", "> 0: hf.Extend(hfs[i-1]) sf = hf.MakeSurvival() hf_map[name] = hf, sf", "np.where(resp.evrmarry, resp.agemarry.isnull(), resp.age.isnull()) month0 = pd.to_datetime('1899-12-15') dates = [month0 +", "(2441-1, 2442), ] df = pd.read_fwf(filename, colspecs=colspecs, names=names, header=None, compression='gzip')", "df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2011_2013", "'ongoing_var', 'ongoing_missing') cutoff = cutoffs.get(name, 100) hf_map[name] = EstimateSurvival(group, cutoff)", "#'marrend', 'marrend2', 'marrend3', marrend5', 'marrend6', ] df = ReadResp('2002Male.dct', '2002Male.dat.gz',", "import Counter import thinkstats2 import thinkplot import survival def ResampleResps(resps,", "usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'finalwgt', 'fmarit',", "from `group` \"\"\" rv = scipy.stats.norm(scale=1) values = group[colname].fillna(100) def", "df = ReadResp('2002FemResp.dct', '2002FemResp.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999]", "= ['caseid', 'mardat01', 'cmintvw', 'ager', 'evrmarry', 'wgt2015_2017', 'marend01', 'rmarital', 'fmarno',", "p=weights)[0] indices = [ChooseIndex(value) for value in target[colname]] return group.loc[indices]", "df['cycle'] = 8 CleanResp(df) return df def ReadFemResp2015(): \"\"\"Reads respondent", "each bin. For example, anyone between 30 and 30.99 year", "df = ReadResp('2013_2015_MaleSetup.dct', '2013_2015_MaleData.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry'] =", "95] returns: (ts, rows) where ts is a sequence of", "import survival def ResampleResps(resps, remove_missing=False, jitter=0): \"\"\"Resamples each dataframe and", "= pd.concat(samples, ignore_index=True, sort=False) # remove married people with unknown", "df.cmdivorcx.replace(invalid, np.nan, inplace=True) df.cmstphsbx.replace(invalid, np.nan, inplace=True) df.timesmar.replace([98, 99], np.nan, inplace=True)", "df.cmintvw - df.ager*12 df['cmmarrhx'] = (df.mardat01-1900) * 12 df['evrmarry'] =", "bin. For example, anyone between 30 and 30.99 year old", "df['cycle'] = 6 CleanResp(df) return df def ReadFemResp2010(): \"\"\"Reads respondent", "predictions cutoffs: map from cohort to the first unreliable age_index", "longer included, # we have to compute them based on", "ts where the sfs are evaluated ts = set() for", "df.cmbirth.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmmarrhx.replace([9797, 9898, 9999], np.nan, inplace=True)", "np.nan, inplace=True) df.timesmar.replace([98, 99], np.nan, inplace=True) df['evrmarry'] = (df.timesmar >", "'f18m1', 'cmdivorcx', 'cmstphsbx', 'fmarno'] colspecs = [(976-1, 982), (1001-1, 1002),", "3 CleanResp(df) return df def ReadFemResp1988(): \"\"\"Reads respondent data from", "colormap: map from group name to color \"\"\" for name,", "we need agemarry; if not married, we need age df['missing']", "ReadResp('2011_2013_MaleSetup.dct', '2011_2013_MaleData.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.evrmarry==1) df['divorced']", "name to color \"\"\" for name, sf_seq in sorted(sf_map.items(), reverse=True):", "\"\"\" for name, sf_seq in sorted(sf_map.items(), reverse=True): if len(sf_seq) ==", "based on other variables; # the result can be off", "age_min - age_step df.loc[df.age.isnull(), 'age_index'] = np.nan df['agemarry_index'] = np.digitize(df.agemarry,", "'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2015_2017_FemRespSetup.dct', '2015_2017_FemRespData.dat.gz', usecols=usecols) invalid", "resp4 = ReadFemResp1988() Validate1988(resp4) print('Cycle 3') resp3 = ReadFemResp1982() Validate1982(resp3)", "name, (hf, sf) in hf_map.items(): sf_map[name].append(sf) return sf_map def AddErrors(group,", "Adds columns: agemarry, age, decade, fives \"\"\" resp['agemarry'] = (resp.cmmarrhx", "decade, fives \"\"\" resp['agemarry'] = (resp.cmmarrhx - resp.cmbirth) / 12.0", "header=None, compression='gzip') df.cmintvw.replace([0, 99999], np.nan, inplace=True) df.cmbirth.replace([0, 99999], np.nan, inplace=True)", "= np.random.random(len(group)) < error_rate def FillMissingColumn(group, colname, missing_colname): \"\"\"Fills missing", "['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgt2011_2013', 'mardat01', 'marend01',", "= ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgt2013_2015', 'marend01', 'rmarital',", "OrderedDict from collections import Counter import thinkstats2 import thinkplot import", "are predicted or actual colormap: map from group name to", "thinkplot.Plot(ts, rows[1], label='%ds'%name, color=color) else: thinkplot.Plot(ts, rows[1], label='%ds'%name) def MakePredictions(hf_map):", "np.nan, inplace=True) df.cmdivorcx.replace(invalid, np.nan, inplace=True) df.cmstphsbx.replace(invalid, np.nan, inplace=True) df.timesmar.replace([98, 99],", "set() for sf in sf_seq: ts |= set(sf.ts) ts =", "Validate2013(resp8) print('Cycle 7') resp7 = ReadFemResp2010() Validate2010(resp7) print('Cycle 6') resp6", "Cycle 9. returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01', 'cmdivw',", "evaluate each sf at all times ss_seq = [sf.Probs(ts) for", "SurvivalFunction \"\"\" complete = resp.loc[resp.complete, 'complete_var'].dropna() ongoing = resp.loc[~resp.complete, 'ongoing_var'].dropna()", "return ts, rows def ReadFemResp1982(): \"\"\"Reads respondent data from NSFG", "accumulate the results for name, (hf, sf) in hf_map.items(): sf_map[name].append(sf)", "'1995FemRespData.dat.gz' names = ['cmintvw', 'timesmar', 'cmmarrhx', 'cmbirth', 'finalwgt', 'marend01', 'cmdivorcx',", "- year_step def ReadCanadaCycle5(): \"\"\" \"\"\" #age at first marriage:", "'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2002FemResp.dct', '2002FemResp.dat.gz', usecols=usecols) invalid =", "in df.cmbirth] df['year'] = (pd.DatetimeIndex(dates).year - 1900) DigitizeResp(df) return df", "continue sf = sf_seq[0] if len(sf) == 0: continue ts,", "pd.read_fwf(dat_file, compression='gzip', colspecs=colspecs, names=names) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid,", "assert(df.agemarry.value_counts().max() == 71) def Validate1988(df): assert(len(df) == 8450) assert(len(df[df.evrmarry]) ==", "'2006_2010_FemResp.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True)", "the data from each cycle separately samples = [ResampleRowsWeighted(resp) for", "returns: DataFrame \"\"\" # we have to resample the data", "colspecs = [(2568-1, 2574), (36-1, 37), (1521-1, 1525), (1538-1, 1542),", "= (df.mardat01-1900) * 12 df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1)", "(df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2011_2013 df['cycle'] =", "(17-1, 17)] df = pd.read_fwf(dat_file, compression='gzip', colspecs=colspecs, names=names) invalid =", "* age_step df.age_index += age_min - age_step df.loc[df.age.isnull(), 'age_index'] =", "df.loc[df.cmstphsbx>9000, 'cmstphsbx'] -= 9000 df['evrmarry'] = (df.fmarno > 0) df['divorced']", "prop_match: last = grouped.get_group(prop_match) # and estimate (hf, sf) for", "inplace=True) #df.marrend2.replace([8,9], np.nan, inplace=True) #df.marrend3.replace([8,9], np.nan, inplace=True) df.marrend4.replace([8,9], np.nan, inplace=True)", "sfs are evaluated ts = set() for sf in sf_seq:", "need agemarry; if not married, we need age resp['missing'] =", "np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df['evrmarry'] = (df.evrmarry==1) df['divorced'] =", "= (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgtq1q16 df['cycle']", "+= year_min - year_step def ReadCanadaCycle5(): \"\"\" \"\"\" #age at", "np.nan, inplace=True) df.marrend4.replace([8,9], np.nan, inplace=True) #df.marrend5.replace([8,9], np.nan, inplace=True) #df.marrend6.replace([8,9], np.nan,", "if i > 0: hf.Extend(hfs[i-1]) sf = hf.MakeSurvival() hf_map[name] =", "not married, we need age resp['missing'] = np.where(resp.evrmarry, resp.agemarry.isnull(), resp.age.isnull())", "if not married, we need age resp['missing'] = np.where(resp.evrmarry, resp.agemarry.isnull(),", "rv.pdf(values-value) weights /= sum(weights) return np.random.choice(group.index, 1, p=weights)[0] indices =", "'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgtq1q16', 'mardat01', 'marend01', 'mardis01',", "returns: DataFrame \"\"\" usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw',", "data from NSFG Cycle 10. returns: DataFrame \"\"\" # removed", "ResampleResps(resps, remove_missing=False, jitter=0): \"\"\"Resamples each dataframe and then concats them.", "them. resps: list of DataFrame returns: DataFrame \"\"\" # we", "from NSFG Cycle 10. returns: DataFrame \"\"\" usecols = ['caseid',", "from each column rows = thinkstats2.PercentileRows(ss_seq, percents) return ts, rows", "if len(null) == 0: return # print(len(null), len(group)) valid =", "sample of rows from `group` \"\"\" rv = scipy.stats.norm(scale=1) values", "# print(len(null), len(group)) valid = group[colname].dropna() fill = valid.sample(len(null), replace=True)", "predict_flag: MakePredictions(hf_map) # extract the sf from each pair and", "(df.f18m1 == 4) df['separated'] = (df.f18m1 == 5) df['widowed'] =", "\"\"\" group[colname] = np.random.random(len(group)) < error_rate def FillMissingColumn(group, colname, missing_colname):", "'wgt2013_2015', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2013_2015_MaleSetup.dct', '2013_2015_MaleData.dat.gz', usecols=usecols)", "def Validate2002(df): assert(len(df) == 7643) assert(sum(df.evrmarry) == 4126) assert(df.agemarry.value_counts().max() ==", "= (df.fmarno > 0) df['divorced'] = (df.f18m1 == 4) df['separated']", "return df def ReadFemResp2013(): \"\"\"Reads respondent data from NSFG Cycle", "respondent data from NSFG Cycle 7. returns: DataFrame \"\"\" usecols", "['cmintvw', 'timesmar', 'cmmarrhx', 'cmbirth', 'finalwgt', 'marend01', 'cmdivorcx', 'cmstphsbx', 'marstat'] colspecs", "= (df.marend01==3) df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['cycle']", "25) def Validate2017(df): assert(len(df) == 5554) assert(sum(df.evrmarry) == 2582) assert(df.agemarry.value_counts().max()", "assert(df.agemarry.value_counts().max() == 73) def Validate1995(df): assert(len(df) == 10847) assert(len(df[df.evrmarry]) ==", "= thinkstats2.PercentileRows(ss_seq, percents) return ts, rows def ReadFemResp1982(): \"\"\"Reads respondent", "predicted or actual colormap: map from group name to color", "ReadFemResp1995() Validate1995(resp5) print('Cycle 4') resp4 = ReadFemResp1988() Validate1988(resp4) print('Cycle 3')", "= 10 year_bins = np.arange(year_min, year_max, year_step) df['age_index'] = np.digitize(df.age,", "one big sample sample = pd.concat(samples, ignore_index=True, sort=False) # remove", "(df.f23m1==3) df['widowed'] = (df.f23m1==1) df['stillma'] = (df.fmarno==1) & (df.f23m1.isnull()) df['cycle']", "(1142-1, 1143), ] df = pd.read_fwf(dat_file, colspecs=colspecs, names=names, header=None, nrows=7969,", "cm in resp.cmbirth] resp['year'] = (pd.DatetimeIndex(dates).year - 1900) #resp['decade'] =", "= df.wgtq1q16 df['cycle'] = 7 CleanResp(df) return df def ReadFemResp2013():", "= (resp.cmintvw - resp.cmbirth) / 12.0 # if married, we", "indicate month unknown df.loc[df.cmintvw>90000, 'cmintvw'] -= 90000 df.loc[df.cmbirth>90000, 'cmbirth'] -=", "\"\"\"Fills missing values of the given column. group: DataFrame colname:", "of respondents Adds columns: agemarry, age, decade, fives \"\"\" resp['agemarry']", "there are actual missing values! \"\"\" group[colname] = np.random.random(len(group)) <", "'ageint', 'mar2p', 'cmmarrhx', 'fmarital', 'cmintvw', 'cmbirth', 'f18m1', 'cmdivorcx', 'cmstphsbx', 'fmarno']", "= (df.f18m1 == 5) df['widowed'] = (df.f18m1 == 3) df['stillma']", "percent \"\"\" # find the union of all ts where", "= [(12360-1, 12363), (4637-1, 4638), (11759-1, 11762), (14-1, 16), (12350-1,", "standard ascii file returns: DataFrame \"\"\" filename = '1988FemRespDataLines.dat.gz' names", "'mar2p', 'cmmarrhx', 'fmarital', 'cmintvw', 'cmbirth', 'f18m1', 'cmdivorcx', 'cmstphsbx', 'fmarno'] colspecs", "respondent data from NSFG Cycle 6. returns: DataFrame \"\"\" usecols", "9898, 9999], np.nan, inplace=True) df.f18m1.replace([7, 8, 9], np.nan, inplace=True) #", "be off by up to 12 months df['cmbirth'] = df.cmintvw", "the estimated functions returns: pair of HazardFunction, SurvivalFunction \"\"\" complete", "where ts is a sequence of times and rows contains", "df = ReadResp('2011_2013_MaleSetup.dct', '2011_2013_MaleData.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry'] =", "CleanResp(df) return df def ReadFemResp2017(): \"\"\"Reads respondent data from NSFG", "we have to customize #CleanResp(df) df['agemarry'] = (df.cmmarrhx - df.cmbirth)", "returns: DataFrame \"\"\" dat_file = '1982NSFGData.dat.gz' names = ['finalwgt', 'ageint',", "predict_flag=False, prop_match=None, error_rate=0): \"\"\"Makes survival curves for resampled data. resps:", "10 age_max = 55 age_step = 1 age_bins = np.arange(age_min,", "'cmintvw', 'evrmarry', 'finalwgt', 'fmarit', 'timesmar', 'marrend4', #'marrend', 'marrend2', 'marrend3', marrend5',", "assigned age_index 30. Anyone born in the 80s is given", "'cmdivorcx'] -= 9000 df.loc[df.cmstphsbx>9000, 'cmstphsbx'] -= 9000 df['evrmarry'] = (df.fmarno", "df.age.isnull()) month0 = pd.to_datetime('1899-12-15') dates = [month0 + pd.DateOffset(months=cm) for", "by <NAME>, available from greenteapress.com Copyright 2014 <NAME> License: GNU", "respondent data. dct_file: string file name dat_file: string file name", "dat_file: string file name returns: DataFrame \"\"\" dct = thinkstats2.ReadStataDct(dct_file,", "(df.marend01==3) df['separated'] = (df.marend01==4) df['widowed'] = (df.marend01==1) df['stillma'] = (df.timesmar==", "2582) assert(df.agemarry.value_counts().max() == 29) def main(): print('Cycle 10') resp10 =", "= (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2015_2017 df['cycle']", "included, # we have to compute them based on other", "continue ts, rows = MakeSurvivalCI(sf_seq, [10, 50, 90]) thinkplot.FillBetween(ts, rows[0],", "'cmstphsbx'] -= 90000 # combine current and first marriage df['cmmarrhx']", "np.nan, inplace=True) #df.marrend3.replace([8,9], np.nan, inplace=True) df.marrend4.replace([8,9], np.nan, inplace=True) #df.marrend5.replace([8,9], np.nan,", "= (df.fmarno > 0) df['divorced'] = (df.f23m1==2) df['separated'] = (df.f23m1==3)", "first unreliable age_index returns: map from group name to list", "[10, 50, 90]) thinkplot.FillBetween(ts, rows[0], rows[2], color='gray', alpha=0.2) if not", "= hf.MakeSurvival() hf_map[name] = hf, sf def MakeSurvivalCI(sf_seq, percents): \"\"\"Makes", "cohort to the first unreliable age_index returns: map from group", "10 # Instead of calling CleanResp, we have to customize", "'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2013_2015_MaleSetup.dct', '2013_2015_MaleData.dat.gz', usecols=usecols) df['cmmarrhx']", "df['age'] = (df.cmintvw - df.cmbirth) / 12.0 # if married,", "9. returns: DataFrame \"\"\" usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth',", "functions returns: pair of HazardFunction, SurvivalFunction \"\"\" complete = resp.loc[resp.complete,", "inplace=True) # since cmbirth and cmmarrhx are no longer included,", "assert(sum(df.evrmarry) == 5534) assert(df.agemarry.value_counts().max() == 64) def Validate2013(df): assert(len(df) ==", "compression='gzip', colspecs=colspecs, names=names) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan,", "df.ager*12 df['cmmarrhx'] = (df.mardat01-1900) * 12 df['evrmarry'] = (df.evrmarry==1) df['divorced']", "inplace=True) df.firstcm.replace([0, 99999], np.nan, inplace=True) df.currentcm.replace([0, 99999], np.nan, inplace=True) df.cmdivorcx.replace([0,", "month unknown df.loc[df.cmintvw>90000, 'cmintvw'] -= 90000 df.loc[df.cmbirth>90000, 'cmbirth'] -= 90000", "0: continue ts, rows = MakeSurvivalCI(sf_seq, [10, 50, 90]) thinkplot.FillBetween(ts,", "= ReadResp('2013_2015_MaleSetup.dct', '2013_2015_MaleData.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.evrmarry==1)", "invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) #df.cmbirth.replace(invalid, np.nan,", "np.nan, inplace=True) df.cmdivorcx.replace([0, 99999], np.nan, inplace=True) df.cmstphsbx.replace([0, 99999], np.nan, inplace=True)", "df.cmmarrhx.fillna(df.currentcm, inplace=True) # define evrmarry if either currentcm or firstcm", "df['cycle'] = 9 CleanResp(df) return df def ReadFemResp2017(): \"\"\"Reads respondent", "== 12279) assert(sum(df.evrmarry) == 5534) assert(df.agemarry.value_counts().max() == 64) def Validate2013(df):", "(df.marend01.isnull()) df['cycle'] = 5 CleanResp(df) return df def ReadFemResp2002(): \"\"\"Reads", "'fmarital', 'cmintvw', 'cmbirth', 'f18m1', 'cmdivorcx', 'cmstphsbx', 'fmarno'] colspecs = [(976-1,", "in sf_seq: ts |= set(sf.ts) ts = list(ts) ts.sort() #", "9 CleanResp(df) return df def ReadFemResp2017(): \"\"\"Reads respondent data from", "pass def ReadMaleResp2002(): \"\"\"Reads respondent data from NSFG Cycle 6.", "df.cmbirth) / 12.0 # if married, we need agemarry; if", "df['separated'] = (df.f23m1==3) df['widowed'] = (df.f23m1==1) df['stillma'] = (df.fmarno==1) &", "This function allows me to run the analysis with different", "df.agemarry.isnull(), df.age.isnull()) month0 = pd.to_datetime('1899-12-15') dates = [month0 + pd.DateOffset(months=cm)", "main(): print('Cycle 10') resp10 = ReadFemResp2017() Validate2017(resp10) print('Cycle 9') resp9", "estimate (hf, sf) for each group hf_map = OrderedDict() for", "group[colname].fillna(100) def ChooseIndex(value): weights = rv.pdf(values-value) weights /= sum(weights) return", "\"\"\" # we have to resample the data from each", "Validate2013(df): assert(len(df) == 5601) assert(sum(df.evrmarry) == 2452) assert(df.agemarry.value_counts().max() == 33)", "37), (1521-1, 1525), (1538-1, 1542), (12-1, 16), (26-1, 30), (1554-1,", "data from NSFG Cycle 4. Read as if were a", "respondents cutoff: where to truncate the estimated functions returns: pair", "AddErrors(group, 'complete_missing', error_rate) AddErrors(group, 'ongoing_missing', error_rate) # the amount of", "df['birth_index'] = np.digitize(df.year, year_bins) * year_step df.birth_index += year_min -", "we have to resample the data from each cycle separately", "= hf_map[name] if i > 0: hf.Extend(hfs[i-1]) sf = hf.MakeSurvival()", "inplace=True) df.cmdivorcx.replace(invalid, np.nan, inplace=True) df.cmstphsbx.replace(invalid, np.nan, inplace=True) df.timesmar.replace([98, 99], np.nan,", "the idea that the resampled people # are not identical", "df.loc[df.cmintvw>9000, 'cmintvw'] -= 9000 df.loc[df.cmbirth>9000, 'cmbirth'] -= 9000 df.loc[df.cmmarrhx>9000, 'cmmarrhx']", "\"\"\"This file contains code for use with \"Think Stats\", by", "'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2011_2013_FemRespSetup.dct', '2011_2013_FemRespData.dat.gz', usecols=usecols) invalid =", "sf def PropensityMatch(target, group, colname='agemarry'): \"\"\"Choose a random subset of", "# group by decade grouped = sample.groupby('birth_index') if prop_match: last", "assert(len(df[df.evrmarry]) == 5290) assert(df.agemarry.value_counts().max() == 73) def Validate1995(df): assert(len(df) ==", "99999], np.nan, inplace=True) # CM values above 9000 indicate month", "= null.index group[colname].fillna(fill, inplace=True) def PlotSurvivalFunctions(sf_map, predict_flag=False, colormap=None): \"\"\"Plot estimated", "target[colname]] return group.loc[indices] def EstimateSurvivalByCohort(resps, iters=101, cutoffs=None, predict_flag=False, prop_match=None, error_rate=0):", "estimated functions returns: pair of HazardFunction, SurvivalFunction \"\"\" complete =", "= {} sf_map = defaultdict(list) # iters is the number", "\"\"\"Reads respondent data from NSFG Cycle 4. Read as if", "import OrderedDict from collections import Counter import thinkstats2 import thinkplot", "returns: DataFrame \"\"\" dct = thinkstats2.ReadStataDct(dct_file, encoding='iso-8859-1') df = dct.ReadFixedWidth(dat_file,", "jitter=0): \"\"\"Resamples each dataframe and then concats them. resps: list", "age df['missing'] = np.where(df.evrmarry, df.agemarry.isnull(), df.age.isnull()) month0 = pd.to_datetime('1899-12-15') dates", "'ager', 'evrmarry', 'wgt2015_2017', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2015_2017_MaleSetup.dct',", "runs to make for i in range(iters): sample = ResampleResps(resps)", "'1982NSFGData.dat.gz' names = ['finalwgt', 'ageint', 'mar2p', 'cmmarrhx', 'fmarital', 'cmintvw', 'cmbirth',", "np.nan, inplace=True) df.cmbirth.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmmarrhx.replace([9797, 9898, 9999],", "marriage: CC232 #age of respondent at interview: C3 #final weight:", "replace=True, p=weights) return df.loc[indices] def Jitter(df, column, jitter=1): \"\"\"Adds random", "np.random.choice(df.index, len(df), replace=True, p=weights) return df.loc[indices] def Jitter(df, column, jitter=1):", "df.cmbirth) / 12.0 df['age'] = (df.cmintvw - df.cmbirth) / 12.0", "code for use with \"Think Stats\", by <NAME>, available from", "df.loc[df.cmintvw>90000, 'cmintvw'] -= 90000 df.loc[df.cmbirth>90000, 'cmbirth'] -= 90000 df.loc[df.firstcm>90000, 'firstcm']", "= list(hf_map.keys()) names.sort() hfs = [hf_map[name][0] for name in names]", "9. returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth',", "for sf in sf_seq if len(sf) > 0] # return", "list of DataFrame returns: DataFrame \"\"\" # we have to", "that the resampled people # are not identical to the", "1143), ] df = pd.read_fwf(dat_file, colspecs=colspecs, names=names, header=None, nrows=7969, compression='gzip')", "# we have to resample the data from each cycle", "if prop_match: last = grouped.get_group(prop_match) # and estimate (hf, sf)", "df['cmbirth'] = df.cmintvw - df.ager*12 df['cmmarrhx'] = (df.mardat01-1900) * 12", "== 29) def main(): print('Cycle 10') resp10 = ReadFemResp2017() Validate2017(resp10)", "Validate2015(resp9) print('Cycle 8') resp8 = ReadFemResp2013() Validate2013(resp8) print('Cycle 7') resp7", "name to (HazardFunction, SurvivalFunction) \"\"\" names = list(hf_map.keys()) names.sort() hfs", "= list(ts) ts.sort() # evaluate each sf at all times", "(1001-1, 1002), (1268-1, 1271), (1037-1, 1040), (1041-1, 1041), (841-1, 844),", "df.cmintvw.replace(invalid, np.nan, inplace=True) df.cmbirth.replace(invalid, np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df['evrmarry']", "def MakePredictions(hf_map): \"\"\"Extends a set of hazard functions and recomputes", "of calling CleanResp, we have to customize #CleanResp(df) df['agemarry'] =", "df['age_index'] = np.digitize(df.age, age_bins) * age_step df.age_index += age_min -", "df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.fmarno ==", "birth year. Groups each of these variables into bins and", "need age df['missing'] = np.where(df.evrmarry, df.agemarry.isnull(), df.age.isnull()) month0 = pd.to_datetime('1899-12-15')", "usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgt2013_2015', 'marend01',", "sf_seq if len(sf) > 0] # return the requested percentiles", "DataFrame returns: DataFrame \"\"\" weights = df['finalwgt'].copy() weights /= sum(weights)", "DataFrame \"\"\" usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry',", "df.loc[df.age.isnull(), 'age_index'] = np.nan df['agemarry_index'] = np.digitize(df.agemarry, age_bins) * age_step", "assert(len(df[df.evrmarry]) == 4651) assert(df.agemarry.value_counts().max() == 71) def Validate1988(df): assert(len(df) ==", "if not married, we need age df['missing'] = np.where(df.evrmarry, df.agemarry.isnull(),", "\"\"\" dat_file = '1995FemRespData.dat.gz' names = ['cmintvw', 'timesmar', 'cmmarrhx', 'cmbirth',", "pd.read_fwf(dat_file, colspecs=colspecs, names=names, header=None, nrows=7969, compression='gzip') df.cmintvw.replace([9797, 9898, 9999], np.nan,", "df.marrend4 df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.timesmar > 0) df['divorced']", "90000 df.loc[df.cmdivorcx>90000, 'cmdivorcx'] -= 90000 df.loc[df.cmstphsbx>90000, 'cmstphsbx'] -= 90000 #", "'agemarry_index'] = np.nan df['birth_index'] = np.digitize(df.year, year_bins) * year_step df.birth_index", "iters: number of resamples to plot predict_flag: whether to also", "to the first unreliable age_index returns: map from group name", "ReadResp('2011_2013_FemRespSetup.dct', '2011_2013_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan,", "returns: map from group name to list of survival functions", "90000 df.loc[df.cmbirth>90000, 'cmbirth'] -= 90000 df.loc[df.firstcm>90000, 'firstcm'] -= 90000 df.loc[df.currentcm>90000,", "4725), (17-1, 17)] df = pd.read_fwf(dat_file, compression='gzip', colspecs=colspecs, names=names) invalid", "np import pandas as pd import scipy.stats import gzip import", "= 6 CleanResp(df) return df def ReadMaleResp2010(): \"\"\"Reads respondent data", "'parity', 'finalwgt', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df =", "above 9000 indicate month unknown df.loc[df.cmintvw>9000, 'cmintvw'] -= 9000 df.loc[df.cmbirth>9000,", "def ReadFemResp2010(): \"\"\"Reads respondent data from NSFG Cycle 7. returns:", "9000 df.loc[df.cmbirth>9000, 'cmbirth'] -= 9000 df.loc[df.cmmarrhx>9000, 'cmmarrhx'] -= 9000 df.loc[df.cmdivorcx>9000,", "each dataframe and then concats them. resps: list of DataFrame", "df.currentcm.replace([0, 99999], np.nan, inplace=True) df.cmdivorcx.replace([0, 99999], np.nan, inplace=True) df.cmstphsbx.replace([0, 99999],", "NSFG Cycle 10. returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01',", "5 DigitizeResp(resp) def DigitizeResp(df): \"\"\"Computes indices for age, agemarry, and", "df['cmmarrhx'] = (df.mardat01-1900) * 12 df['evrmarry'] = (df.evrmarry==1) df['divorced'] =", "(df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.timesmar==1) & (df.marend01.isnull()) df['cycle']", "df.cmbirth] df['year'] = (pd.DatetimeIndex(dates).year - 1900) DigitizeResp(df) return df def", "== 2452) assert(df.agemarry.value_counts().max() == 33) def Validate2015(df): assert(len(df) == 5699)", "DataFrame with sample of rows from `group` \"\"\" rv =", "size=len(df)) def EstimateSurvival(resp, cutoff=None): \"\"\"Estimates the survival curve. resp: DataFrame", "fives \"\"\" resp['agemarry'] = (resp.cmmarrhx - resp.cmbirth) / 12.0 resp['age']", "are no longer included, # we have to compute them", "encoding='iso-8859-1') df = dct.ReadFixedWidth(dat_file, compression='gzip', **options) return df def CleanResp(resp):", "group name to sequence of survival functions predict_flag: whether the", "a standard ascii file returns: DataFrame \"\"\" filename = '1988FemRespDataLines.dat.gz'", "-= 9000 df.loc[df.cmbirth>9000, 'cmbirth'] -= 9000 df.loc[df.cmmarrhx>9000, 'cmmarrhx'] -= 9000", "5534) assert(df.agemarry.value_counts().max() == 64) def Validate2013(df): assert(len(df) == 5601) assert(sum(df.evrmarry)", "colormap: color = colormap[name] thinkplot.Plot(ts, rows[1], label='%ds'%name, color=color) else: thinkplot.Plot(ts,", "is really confusing, # but it looks like marrend4 is", "separately samples = [ResampleRowsWeighted(resp) for resp in resps] # then", "= (df.marend01==3) df['stillma'] = (df.timesmar==1) & (df.marend01.isnull()) df['cycle'] = 5", "1569), (1570-1, 1574), (2441-1, 2442), ] df = pd.read_fwf(filename, colspecs=colspecs,", "df['evrmarry'] = (df.fmarno > 0) df['divorced'] = (df.f23m1==2) df['separated'] =", "as np import pandas as pd import scipy.stats import gzip", "5. returns: DataFrame \"\"\" dat_file = '1995FemRespData.dat.gz' names = ['cmintvw',", "sf at all times ss_seq = [sf.Probs(ts) for sf in", "recorded is really confusing, # but it looks like marrend4", "print('Cycle 6') resp6 = ReadFemResp2002() Validate2002(resp6) print('Cycle 5') resp5 =", "a weight column. df: DataFrame returns: DataFrame \"\"\" weights =", "filename = '1988FemRespDataLines.dat.gz' names = ['finalwgt', 'ageint', 'currentcm', 'firstcm', 'cmintvw',", "usecols=usecols) # since cmbirth and cmmarrhx are no longer included,", "np.nan, inplace=True) df.cmstphsbx.replace(invalid, np.nan, inplace=True) df.timesmar.replace([98, 99], np.nan, inplace=True) df['evrmarry']", "to the actual respondents if jitter: Jitter(sample, 'age', jitter=jitter) Jitter(sample,", "844), (12-1, 15), (606-1, 606), (619-1, 622), (625-1, 628), (1142-1,", "Cycle 8. returns: DataFrame \"\"\" usecols = ['caseid', 'cmmarrhx', 'cmdivorcx',", "7643) assert(sum(df.evrmarry) == 4126) assert(df.agemarry.value_counts().max() == 45) def Validate2010(df): assert(len(df)", "90000 df.loc[df.currentcm>90000, 'currentcm'] -= 90000 df.loc[df.cmdivorcx>90000, 'cmdivorcx'] -= 90000 df.loc[df.cmstphsbx>90000,", "married people with unknown marriage dates if remove_missing: sample =", "ReadFemResp1995(): \"\"\"Reads respondent data from NSFG Cycle 5. returns: DataFrame", "survival.EstimateHazardFunction(complete, ongoing) if cutoff: hf.Truncate(cutoff) sf = hf.MakeSurvival() return hf,", "inplace=True) # define evrmarry if either currentcm or firstcm is", "of granularity. df: DataFrame \"\"\" age_min = 10 age_max =", "current and first marriage df['cmmarrhx'] = df.firstcm df.cmmarrhx.fillna(df.currentcm, inplace=True) #", "-= 90000 df.loc[df.firstcm>90000, 'firstcm'] -= 90000 df.loc[df.currentcm>90000, 'currentcm'] -= 90000", "- resp.cmbirth) / 12.0 # if married, we need agemarry;", "(pd.DatetimeIndex(dates).year - 1900) DigitizeResp(df) return df def ReadResp(dct_file, dat_file, **options):", "for age, agemarry, and birth year. Groups each of these", "df.cmbirth.replace(invalid, np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df['evrmarry'] = (df.evrmarry==1) df['divorced']", "the sf from each pair and accumulate the results for", "prop_match: group = PropensityMatch(last, group) if error_rate: AddErrors(group, 'complete_missing', error_rate)", "6 CleanResp(df) return df def ReadFemResp2010(): \"\"\"Reads respondent data from", "rows def ReadFemResp1982(): \"\"\"Reads respondent data from NSFG Cycle 3.", "'evrmarry', 'finalwgt', 'fmarit', 'timesmar', 'marrend4', #'marrend', 'marrend2', 'marrend3', marrend5', 'marrend6',", "levels of granularity. df: DataFrame \"\"\" age_min = 10 age_max", "= df.wgt2011_2013 df['cycle'] = 8 CleanResp(df) return df def ReadFemResp2015():", "NSFG Cycle 8. returns: DataFrame \"\"\" usecols = ['caseid', 'cmmarrhx',", "each sf at all times ss_seq = [sf.Probs(ts) for sf", "df def ReadMaleResp2017(): \"\"\"Reads respondent data from NSFG Cycle 10.", "percentiles from each column rows = thinkstats2.PercentileRows(ss_seq, percents) return ts,", "error_rate=0): \"\"\"Makes survival curves for resampled data. resps: list of", "1) & (df.fmarit==1) df['cycle'] = 6 CleanResp(df) return df def", "and accumulate the results for name, (hf, sf) in hf_map.items():", "df.wgt2011_2013 df['cycle'] = 8 CleanResp(df) return df def ReadFemResp2015(): \"\"\"Reads", "define evrmarry if either currentcm or firstcm is non-zero df['evrmarry']", "assert(len(df) == 7969) assert(len(df[df.evrmarry]) == 4651) assert(df.agemarry.value_counts().max() == 71) def", "the actual respondents if jitter: Jitter(sample, 'age', jitter=jitter) Jitter(sample, 'agemarry',", "6') resp6 = ReadFemResp2002() Validate2002(resp6) print('Cycle 5') resp5 = ReadFemResp1995()", "-= 90000 df.loc[df.cmbirth>90000, 'cmbirth'] -= 90000 df.loc[df.firstcm>90000, 'firstcm'] -= 90000", "noise \"\"\" df[column] += np.random.uniform(-jitter, jitter, size=len(df)) def EstimateSurvival(resp, cutoff=None):", "1554), (1565-1, 1569), (1570-1, 1574), (2441-1, 2442), ] df =", "group in hf_map, we extend hf and recompute sf. hf_map:", "= dct.ReadFixedWidth(dat_file, compression='gzip', **options) return df def CleanResp(resp): \"\"\"Cleans a", "the cycles into one big sample sample = pd.concat(samples, ignore_index=True,", "2401) assert(df.agemarry.value_counts().max() == 25) def Validate2017(df): assert(len(df) == 5554) assert(sum(df.evrmarry)", "df['finalwgt'] = df.wgtq1q16 df['cycle'] = 7 CleanResp(df) return df def", "= '1995FemRespData.dat.gz' names = ['cmintvw', 'timesmar', 'cmmarrhx', 'cmbirth', 'finalwgt', 'marend01',", "cohort, # and update the survival function for i, name", "Cycle 6. returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01', 'cmdivw',", "NSFG Cycle 6. returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01',", "looks like marrend4 is the end of the first marriage.", "df.loc[df.cmdivorcx>90000, 'cmdivorcx'] -= 90000 df.loc[df.cmstphsbx>90000, 'cmstphsbx'] -= 90000 # combine", "(df.timesmar > 0) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed']", "(df.fmarit==1) df['cycle'] = 6 CleanResp(df) return df def ReadMaleResp2010(): \"\"\"Reads", "colname: string name of column with propensity scores returns: DataFrame", "name to list of survival functions \"\"\" if cutoffs ==", "= ReadResp('2015_2017_MaleSetup.dct', '2015_2017_MaleData.dat.gz', usecols=usecols) # since cmbirth and cmmarrhx are", "0: return # print(len(null), len(group)) valid = group[colname].dropna() fill =", "ignore_index=True, sort=False) # remove married people with unknown marriage dates", "in resps] # then join the cycles into one big", "http://www.gnu.org/licenses/gpl.html \"\"\" from __future__ import print_function, division import bisect import", "DigitizeResp(df): \"\"\"Computes indices for age, agemarry, and birth year. Groups", "cutoffs = {} sf_map = defaultdict(list) # iters is the", "def FillMissingColumn(group, colname, missing_colname): \"\"\"Fills missing values of the given", "= (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.timesmar==1) & (df.marend01.isnull())", "resp.cmbirth] resp['year'] = (pd.DatetimeIndex(dates).year - 1900) #resp['decade'] = resp.year //", "np.nan, inplace=True) df.cmbirth.replace([0, 99999], np.nan, inplace=True) df.firstcm.replace([0, 99999], np.nan, inplace=True)", "names = ['cmintvw', 'timesmar', 'cmmarrhx', 'cmbirth', 'finalwgt', 'marend01', 'cmdivorcx', 'cmstphsbx',", "map from cohort to the first unreliable age_index returns: map", "NSFG Cycle 7. returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01',", "every married: CC227 pass def ReadCanadaCycle6(): \"\"\" \"\"\" #age at", "dates = [month0 + pd.DateOffset(months=cm) for cm in df.cmbirth] df['year']", "inplace=True) df.cmbirth.replace(invalid, np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df['evrmarry'] = (df.evrmarry==1)", "(df.fmarno == 1) & (df.rmarital==1) df['cycle'] = 6 CleanResp(df) return", "df = ReadResp('2002Male.dct', '2002Male.dat.gz', usecols=usecols) #df.marrend.replace([8,9], np.nan, inplace=True) #df.marrend2.replace([8,9], np.nan,", "list(ts) ts.sort() # evaluate each sf at all times ss_seq", "def ReadMaleResp2002(): \"\"\"Reads respondent data from NSFG Cycle 6. returns:", "10847) assert(len(df[df.evrmarry]) == 6841) assert(df.agemarry.value_counts().max() == 79) def Validate2002(df): assert(len(df)", "sf in sf_seq: ts |= set(sf.ts) ts = list(ts) ts.sort()", "[sf.Probs(ts) for sf in sf_seq if len(sf) > 0] #", "(1538-1, 1542), (12-1, 16), (26-1, 30), (1554-1, 1554), (1565-1, 1569),", "'marrend3', marrend5', 'marrend6', ] df = ReadResp('2002Male.dct', '2002Male.dat.gz', usecols=usecols) #df.marrend.replace([8,9],", "given column. group: DataFrame colname: string \"\"\" null = group[group[missing_colname]]", "MakePredictions(hf_map): \"\"\"Extends a set of hazard functions and recomputes survival", "sf_seq[0] if len(sf) == 0: continue ts, rows = MakeSurvivalCI(sf_seq,", "['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgtq1q16', 'marend01', 'rmarital', 'fmarno',", "group[colname].dropna() fill = valid.sample(len(null), replace=True) fill.index = null.index group[colname].fillna(fill, inplace=True)", "== 1) & (df.rmarital==1) df['finalwgt'] = df.wgtq1q16 df['cycle'] = 7", "'finalwgt', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2002FemResp.dct',", "weight column. df: DataFrame returns: DataFrame \"\"\" weights = df['finalwgt'].copy()", "of missing data is small; I think it is better", "resps] # then join the cycles into one big sample", "df['marend01'] = df.marrend4 df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.timesmar >", "sorted(sf_map.items(), reverse=True): if len(sf_seq) == 0: continue sf = sf_seq[0]", "= 8 CleanResp(df) return df def ReadMaleResp2015(): \"\"\"Reads respondent data", "samples = [ResampleRowsWeighted(resp) for resp in resps] # then join", "string file name returns: DataFrame \"\"\" dct = thinkstats2.ReadStataDct(dct_file, encoding='iso-8859-1')", "np.nan, inplace=True) #df.marrend5.replace([8,9], np.nan, inplace=True) #df.marrend6.replace([8,9], np.nan, inplace=True) df.timesmar.replace([98,99], np.nan,", "from cohort to the first unreliable age_index returns: map from", "# the result can be off by up to 12", "(df.marend01==2) | (df.marend01==3) df['separated'] = (df.marend01==4) df['widowed'] = (df.marend01==1) df['stillma']", "df['agemarry_index'] = np.digitize(df.agemarry, age_bins) * age_step df.agemarry_index += age_min -", "= (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2011_2013 df['cycle']", "can be off by up to 12 months df['cmbirth'] =", "(df.fmarno > 0) df['divorced'] = (df.f18m1 == 4) df['separated'] =", "'cmbirth'] -= 9000 df.loc[df.cmmarrhx>9000, 'cmmarrhx'] -= 9000 df.loc[df.cmdivorcx>9000, 'cmdivorcx'] -=", "cycle separately samples = [ResampleRowsWeighted(resp) for resp in resps] #", "ReadFemResp2002(): \"\"\"Reads respondent data from NSFG Cycle 6. returns: DataFrame", "data. dct_file: string file name dat_file: string file name returns:", "= ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgtq1q16', 'marend01', 'rmarital',", "and 30.99 year old is assigned age_index 30. Anyone born", "inplace=True) df['evrmarry'] = (df.timesmar > 0) df['divorced'] = (df.marend01==1) df['separated']", "error_rate) # the amount of missing data is small; I", "Validate2010(resp7) print('Cycle 6') resp6 = ReadFemResp2002() Validate2002(resp6) print('Cycle 5') resp5", "'currentcm', 'firstcm', 'cmintvw', 'cmbirth', 'f23m1', 'cmdivorcx', 'cmstphsbx', 'fmarno'] colspecs =", "== 7969) assert(len(df[df.evrmarry]) == 4651) assert(df.agemarry.value_counts().max() == 71) def Validate1988(df):", "df.wgt2015_2017 df['cycle'] = 10 # Instead of calling CleanResp, we", "deviation of noise \"\"\" df[column] += np.random.uniform(-jitter, jitter, size=len(df)) def", "df['cycle'] = 7 CleanResp(df) return df def ReadFemResp2013(): \"\"\"Reads respondent", "'wgt2013_2015', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2013_2015_FemRespSetup.dct',", "update the survival function for i, name in enumerate(names): hf,", "survival curves for resampled data. resps: list of DataFrames iters:", "ReadFemResp2017(): \"\"\"Reads respondent data from NSFG Cycle 10. returns: DataFrame", "inplace=True) df.cmbirth.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmmarrhx.replace([9797, 9898, 9999], np.nan,", "= df.wgt2013_2015 df['cycle'] = 9 CleanResp(df) return df def ReadFemResp2017():", "with `target`. target: DataFrame group: DataFrame colname: string name of", "= ReadFemResp2015() Validate2015(resp9) print('Cycle 8') resp8 = ReadFemResp2013() Validate2013(resp8) print('Cycle", "np.nan, inplace=True) # CM values above 9000 indicate month unknown", "to fill with random data #FillMissingColumn(group, 'complete_var', 'complete_missing') #FillMissingColumn(group, 'ongoing_var',", "'fmarno', 'mar1diss'] df = ReadResp('2002FemResp.dct', '2002FemResp.dat.gz', usecols=usecols) invalid = [9997,", "age_bins) * age_step df.agemarry_index += age_min - age_step df.loc[df.agemarry.isnull(), 'agemarry_index']", "0: hf.Extend(hfs[i-1]) sf = hf.MakeSurvival() hf_map[name] = hf, sf def", "name in names] # extend each hazard function using data", "'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2015_2017_FemRespSetup.dct', '2015_2017_FemRespData.dat.gz', usecols=usecols)", "= (df.f23m1==1) df['stillma'] = (df.fmarno==1) & (df.f23m1.isnull()) df['cycle'] = 4", "(12-1, 16), (26-1, 30), (1554-1, 1554), (1565-1, 1569), (1570-1, 1574),", "married, we need age resp['missing'] = np.where(resp.evrmarry, resp.agemarry.isnull(), resp.age.isnull()) month0", "are recorded is really confusing, # but it looks like", "1041), (841-1, 844), (12-1, 15), (606-1, 606), (619-1, 622), (625-1,", "the union of all ts where the sfs are evaluated", "1525), (1538-1, 1542), (12-1, 16), (26-1, 30), (1554-1, 1554), (1565-1,", "born in the 80s is given the year_index 80. This", "#Respondent every married: CC227 pass def ReadCanadaCycle6(): \"\"\" \"\"\" #age", "confidence intervals from a list of survival functions. sf_seq: list", "622), (625-1, 628), (1142-1, 1143), ] df = pd.read_fwf(dat_file, colspecs=colspecs,", "EstimateSurvival(resp, cutoff=None): \"\"\"Estimates the survival curve. resp: DataFrame of respondents", "grouped = sample.groupby('birth_index') if prop_match: last = grouped.get_group(prop_match) # and", "error_rate): \"\"\" NOTE: This will not work if there are", "= set() for sf in sf_seq: ts |= set(sf.ts) ts", "'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2006_2010_FemRespSetup.dct', '2006_2010_FemResp.dat.gz', usecols=usecols) invalid =", "'cmbirth', usecols = ['caseid', 'cmintvw', 'ager', 'evrmarry', 'parity', 'wgt2015_2017', 'mardat01',", "each group hf_map = OrderedDict() for name, group in iter(grouped):", "lines are predicted or actual colormap: map from group name", "df.cmintvw.replace(invalid, np.nan, inplace=True) #df.cmbirth.replace(invalid, np.nan, inplace=True) #df.cmmarrhx.replace(invalid, np.nan, inplace=True) #", "percents): \"\"\"Makes confidence intervals from a list of survival functions.", "== 4) df['separated'] = (df.f18m1 == 5) df['widowed'] = (df.f18m1", "# since cmbirth and cmmarrhx are no longer included, #", "df['cycle'] = 7 CleanResp(df) return df def ReadMaleResp2013(): \"\"\"Reads respondent", "* age_step df.agemarry_index += age_min - age_step df.loc[df.agemarry.isnull(), 'agemarry_index'] =", "year_index 80. This function allows me to run the analysis", "'cmstphsbx', 'fmarno'] colspecs = [(976-1, 982), (1001-1, 1002), (1268-1, 1271),", "'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgtq1q16', 'marend01', 'rmarital', 'fmarno', 'mar1diss']", "1900) DigitizeResp(df) return df def ReadResp(dct_file, dat_file, **options): \"\"\"Reads the", "'marend01', 'cmdivorcx', 'cmstphsbx', 'marstat'] colspecs = [(12360-1, 12363), (4637-1, 4638),", "data #FillMissingColumn(group, 'complete_var', 'complete_missing') #FillMissingColumn(group, 'ongoing_var', 'ongoing_missing') cutoff = cutoffs.get(name,", "(df.f23m1==2) df['separated'] = (df.f23m1==3) df['widowed'] = (df.f23m1==1) df['stillma'] = (df.fmarno==1)", "'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2006_2010_FemRespSetup.dct', '2006_2010_FemResp.dat.gz', usecols=usecols)", "and birth year. Groups each of these variables into bins", "as if were a standard ascii file returns: DataFrame \"\"\"", "times ss_seq = [sf.Probs(ts) for sf in sf_seq if len(sf)", "1271), (1037-1, 1040), (1041-1, 1041), (841-1, 844), (12-1, 15), (606-1,", "df['evrmarry'] = (df.timesmar > 0) df['divorced'] = (df.marend01==2) | (df.marend01==3)", "sample = pd.concat(samples, ignore_index=True, sort=False) # remove married people with", "if remove_missing: sample = sample[~sample.missing] # jittering the ages reflects", "\"\"\" complete = resp.loc[resp.complete, 'complete_var'].dropna() ongoing = resp.loc[~resp.complete, 'ongoing_var'].dropna() hf", "age_max, age_step) year_min = 0 year_max = 120 year_step =", "of hazard functions and recomputes survival functions. For each group", "== 5290) assert(df.agemarry.value_counts().max() == 73) def Validate1995(df): assert(len(df) == 10847)", "from NSFG Cycle 4. Read as if were a standard", "= ReadResp('2011_2013_FemRespSetup.dct', '2011_2013_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid,", "not married, we need age df['missing'] = np.where(df.evrmarry, df.agemarry.isnull(), df.age.isnull())", "ReadMaleResp2017(): \"\"\"Reads respondent data from NSFG Cycle 10. returns: DataFrame", "unknown marriage dates if remove_missing: sample = sample[~sample.missing] # jittering", "DigitizeResp(resp) def DigitizeResp(df): \"\"\"Computes indices for age, agemarry, and birth", "== 4651) assert(df.agemarry.value_counts().max() == 71) def Validate1988(df): assert(len(df) == 8450)", "# are not identical to the actual respondents if jitter:", "0] # return the requested percentiles from each column rows", "group in iter(grouped): if prop_match: group = PropensityMatch(last, group) if", "& (df.rmarital==1) df['cycle'] = 6 CleanResp(df) return df def ReadFemResp2010():", "string column name jitter: standard deviation of noise \"\"\" df[column]", "resp['agemarry'] = (resp.cmmarrhx - resp.cmbirth) / 12.0 resp['age'] = (resp.cmintvw", "ResampleResps(resps) # group by decade grouped = sample.groupby('birth_index') if prop_match:", "df def ReadFemResp2002(): \"\"\"Reads respondent data from NSFG Cycle 6.", "'cmintvw', 'evrmarry', 'parity', 'wgt2013_2015', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss']", "with propensity scores returns: DataFrame with sample of rows from", "= (df.fmarno==1) & (df.f23m1.isnull()) df['cycle'] = 4 CleanResp(df) return df", "and estimate (hf, sf) for each group hf_map = OrderedDict()", "married, we need age df['missing'] = np.where(df.evrmarry, df.agemarry.isnull(), df.age.isnull()) month0", "to each bin. For example, anyone between 30 and 30.99", "'ageint', 'currentcm', 'firstcm', 'cmintvw', 'cmbirth', 'f23m1', 'cmdivorcx', 'cmstphsbx', 'fmarno'] colspecs", "'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2013_2015_FemRespSetup.dct', '2013_2015_FemRespData.dat.gz',", "usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) #df.cmbirth.replace(invalid,", "like marrend4 is the end of the first marriage. df['marend01']", "cutoff) # make predictions if desired if predict_flag: MakePredictions(hf_map) #", "'cmdivorcx', 'cmstphsbx', 'fmarno'] colspecs = [(2568-1, 2574), (36-1, 37), (1521-1,", "(619-1, 622), (625-1, 628), (1142-1, 1143), ] df = pd.read_fwf(dat_file,", "def MakeSurvivalCI(sf_seq, percents): \"\"\"Makes confidence intervals from a list of", "cmmarrhx are no longer included, # we have to compute", "of rows from `group` \"\"\" rv = scipy.stats.norm(scale=1) values =", "list of survival functions. sf_seq: list of SurvivalFunction percents: list", "dates = [month0 + pd.DateOffset(months=cm) for cm in resp.cmbirth] resp['year']", "jitter=jitter) DigitizeResp(resp) return sample def ResampleRowsWeighted(df, column='finalwgt'): \"\"\"Resamples the rows", "assert(len(df) == 10847) assert(len(df[df.evrmarry]) == 6841) assert(df.agemarry.value_counts().max() == 79) def", "reverse=True): if len(sf_seq) == 0: continue sf = sf_seq[0] if", "or firstcm is non-zero df['evrmarry'] = (df.fmarno > 0) df['divorced']", "df.cmintvw.replace(invalid, np.nan, inplace=True) df.cmbirth.replace(invalid, np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df.cmdivorcx.replace(invalid,", "print('Cycle 9') resp9 = ReadFemResp2015() Validate2015(resp9) print('Cycle 8') resp8 =", "hazard function using data from the previous cohort, # and", "error_rate def FillMissingColumn(group, colname, missing_colname): \"\"\"Fills missing values of the", "'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2011_2013_FemRespSetup.dct', '2011_2013_FemRespData.dat.gz', usecols=usecols) invalid", "the first unreliable age_index returns: map from group name to", "resp.cmbirth) / 12.0 resp['age'] = (resp.cmintvw - resp.cmbirth) / 12.0", "ReadFemResp2015(): \"\"\"Reads respondent data from NSFG Cycle 9. returns: DataFrame", "amount of missing data is small; I think it is", "in sorted(sf_map.items(), reverse=True): if len(sf_seq) == 0: continue sf =", "ReadResp('2002Male.dct', '2002Male.dat.gz', usecols=usecols) #df.marrend.replace([8,9], np.nan, inplace=True) #df.marrend2.replace([8,9], np.nan, inplace=True) #df.marrend3.replace([8,9],", "the survival function for i, name in enumerate(names): hf, sf", "the number of resampling runs to make for i in", "CleanResp(df) return df def ReadFemResp2013(): \"\"\"Reads respondent data from NSFG", "'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgt2013_2015', 'mardat01', 'marend01', 'mardis01', 'rmarital',", "ReadMaleResp2015(): \"\"\"Reads respondent data from NSFG Cycle 9. returns: DataFrame", "def ReadMaleResp2017(): \"\"\"Reads respondent data from NSFG Cycle 10. returns:", "inplace=True) df.currentcm.replace([0, 99999], np.nan, inplace=True) df.cmdivorcx.replace([0, 99999], np.nan, inplace=True) df.cmstphsbx.replace([0,", "-= 90000 df.loc[df.cmstphsbx>90000, 'cmstphsbx'] -= 90000 # combine current and", "sf in sf_seq if len(sf) > 0] # return the", "= np.arange(year_min, year_max, year_step) df['age_index'] = np.digitize(df.age, age_bins) * age_step", "def ReadMaleResp2015(): \"\"\"Reads respondent data from NSFG Cycle 9. returns:", "sf_seq: list of SurvivalFunction percents: list of percentiles to select,", "'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgtq1q16', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno',", "8, 9], np.nan, inplace=True) # CM values above 9000 indicate", "'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgt2011_2013', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df", "the rows in df in accordance with a weight column.", "np.nan, inplace=True) df.cmdivorcx.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmstphsbx.replace([9797, 9898, 9999],", "Cycle 3. returns: DataFrame \"\"\" dat_file = '1982NSFGData.dat.gz' names =", "year_max, year_step) df['age_index'] = np.digitize(df.age, age_bins) * age_step df.age_index +=", "return df def ReadMaleResp2013(): \"\"\"Reads respondent data from NSFG Cycle", "union of all ts where the sfs are evaluated ts", "def Validate2013(df): assert(len(df) == 5601) assert(sum(df.evrmarry) == 2452) assert(df.agemarry.value_counts().max() ==", "defaultdict(list) # iters is the number of resampling runs to", "hf_map.items(): sf_map[name].append(sf) return sf_map def AddErrors(group, colname, error_rate): \"\"\" NOTE:", "np.nan, inplace=True) df.currentcm.replace([0, 99999], np.nan, inplace=True) df.cmdivorcx.replace([0, 99999], np.nan, inplace=True)", "def ReadFemResp1995(): \"\"\"Reads respondent data from NSFG Cycle 5. returns:", "data from NSFG Cycle 10. returns: DataFrame \"\"\" usecols =", "[(2568-1, 2574), (36-1, 37), (1521-1, 1525), (1538-1, 1542), (12-1, 16),", "'fmarno', 'mar1diss'] df = ReadResp('2015_2017_FemRespSetup.dct', '2015_2017_FemRespData.dat.gz', usecols=usecols) invalid = [9997,", "for value in target[colname]] return group.loc[indices] def EstimateSurvivalByCohort(resps, iters=101, cutoffs=None,", "12.0 resp['age'] = (resp.cmintvw - resp.cmbirth) / 12.0 # if", "available from greenteapress.com Copyright 2014 <NAME> License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html", "extend hf and recompute sf. hf_map: map from group name", "from each pair and accumulate the results for name, (hf,", "(df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2015_2017 df['cycle'] =", "first marriage: CC232 #age of respondent at interview: C3 #final", "'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'finalwgt', 'fmarit', 'timesmar', 'marrend4', #'marrend',", "from greenteapress.com Copyright 2014 <NAME> License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html \"\"\"", "Validate1988(df): assert(len(df) == 8450) assert(len(df[df.evrmarry]) == 5290) assert(df.agemarry.value_counts().max() == 73)", "run the analysis with different levels of granularity. df: DataFrame", "each pair and accumulate the results for name, (hf, sf)", "= 1 age_bins = np.arange(age_min, age_max, age_step) year_min = 0", "Read as if were a standard ascii file returns: DataFrame", "10. returns: DataFrame \"\"\" # removed 'cmmarrhx', 'cmdivorcx', 'cmbirth', usecols", "#df.cmmarrhx.replace(invalid, np.nan, inplace=True) # since cmbirth and cmmarrhx are no", "alpha=0.2) if not predict_flag: if colormap: color = colormap[name] thinkplot.Plot(ts,", "2442), ] df = pd.read_fwf(filename, colspecs=colspecs, names=names, header=None, compression='gzip') df.cmintvw.replace([0,", "given the year_index 80. This function allows me to run", "plot predictions cutoffs: map from cohort to the first unreliable", "by up to 12 months df['cmbirth'] = df.cmintvw - df.ager*12", "Anyone born in the 80s is given the year_index 80.", "9999], np.nan, inplace=True) df.f18m1.replace([7, 8, 9], np.nan, inplace=True) # CM", "indices = np.random.choice(df.index, len(df), replace=True, p=weights) return df.loc[indices] def Jitter(df,", "label='%ds'%name, color=color) else: thinkplot.Plot(ts, rows[1], label='%ds'%name) def MakePredictions(hf_map): \"\"\"Extends a", "'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2006_2010_MaleSetup.dct', '2006_2010_Male.dat.gz', usecols=usecols) df['cmmarrhx']", "12 df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2)", "is a sequence of times and rows contains one row", "= resp.loc[~resp.complete, 'ongoing_var'].dropna() hf = survival.EstimateHazardFunction(complete, ongoing) if cutoff: hf.Truncate(cutoff)", "hfs = [hf_map[name][0] for name in names] # extend each", "the results for name, (hf, sf) in hf_map.items(): sf_map[name].append(sf) return", "== 33) def Validate2015(df): assert(len(df) == 5699) assert(sum(df.evrmarry) == 2401)", "identical to the actual respondents if jitter: Jitter(sample, 'age', jitter=jitter)", "ReadFemResp2017() Validate2017(resp10) print('Cycle 9') resp9 = ReadFemResp2015() Validate2015(resp9) print('Cycle 8')", "== 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2013_2015 df['cycle'] = 9", "= df['finalwgt'].copy() weights /= sum(weights) indices = np.random.choice(df.index, len(df), replace=True,", "1574), (2441-1, 2442), ] df = pd.read_fwf(filename, colspecs=colspecs, names=names, header=None,", "resp: DataFrame of respondents cutoff: where to truncate the estimated", "(1554-1, 1554), (1565-1, 1569), (1570-1, 1574), (2441-1, 2442), ] df", "80s is given the year_index 80. This function allows me", "NSFG Cycle 9. returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01',", "9999], np.nan, inplace=True) df.cmbirth.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmmarrhx.replace([9797, 9898,", "cutoffs=None, predict_flag=False, prop_match=None, error_rate=0): \"\"\"Makes survival curves for resampled data.", "= (df.cmintvw - df.cmbirth) / 12.0 # if married, we", "we need agemarry; if not married, we need age resp['missing']", "respondents Adds columns: agemarry, age, decade, fives \"\"\" resp['agemarry'] =", "df.wgt2013_2015 df['cycle'] = 9 CleanResp(df) return df def ReadFemResp2017(): \"\"\"Reads", "age_min = 10 age_max = 55 age_step = 1 age_bins", "= colormap[name] thinkplot.Plot(ts, rows[1], label='%ds'%name, color=color) else: thinkplot.Plot(ts, rows[1], label='%ds'%name)", "8') resp8 = ReadFemResp2013() Validate2013(resp8) print('Cycle 7') resp7 = ReadFemResp2010()", "== 10847) assert(len(df[df.evrmarry]) == 6841) assert(df.agemarry.value_counts().max() == 79) def Validate2002(df):", "dat_file, **options): \"\"\"Reads the NSFG respondent data. dct_file: string file", "\"\"\" null = group[group[missing_colname]] if len(null) == 0: return #", "CleanResp(df) return df def ReadMaleResp2017(): \"\"\"Reads respondent data from NSFG", "need agemarry; if not married, we need age df['missing'] =", "pandas as pd import scipy.stats import gzip import matplotlib.pyplot as", "jittering the ages reflects the idea that the resampled people", "data is small; I think it is better # to", "df.birth_index += year_min - year_step def ReadCanadaCycle5(): \"\"\" \"\"\" #age", "have to customize #CleanResp(df) df['agemarry'] = (df.cmmarrhx - df.cmbirth) /", "hf_map[name] = EstimateSurvival(group, cutoff) # make predictions if desired if", "grouped.get_group(prop_match) # and estimate (hf, sf) for each group hf_map", "data from NSFG Cycle 5. returns: DataFrame \"\"\" dat_file =", "(4637-1, 4638), (11759-1, 11762), (14-1, 16), (12350-1, 12359), (4713-1, 4713),", "& (df.marend01.isnull()) df['cycle'] = 5 CleanResp(df) return df def ReadFemResp2002():", "def Validate2010(df): assert(len(df) == 12279) assert(sum(df.evrmarry) == 5534) assert(df.agemarry.value_counts().max() ==", "def ReadCanadaCycle6(): \"\"\" \"\"\" #age at first marriage: CC232 #age", "a set of hazard functions and recomputes survival functions. For", "group: DataFrame colname: string \"\"\" null = group[group[missing_colname]] if len(null)", "'cmintvw', 'evrmarry', 'wgtq1q16', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2006_2010_MaleSetup.dct',", "= (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.fmarno == 1)", "index to each bin. For example, anyone between 30 and", "def Validate1988(df): assert(len(df) == 8450) assert(len(df[df.evrmarry]) == 5290) assert(df.agemarry.value_counts().max() ==", "missing_colname): \"\"\"Fills missing values of the given column. group: DataFrame", "pd import scipy.stats import gzip import matplotlib.pyplot as plt from", "valid = group[colname].dropna() fill = valid.sample(len(null), replace=True) fill.index = null.index", "age_max = 55 age_step = 1 age_bins = np.arange(age_min, age_max,", "SurvivalFunction percents: list of percentiles to select, like [5, 95]", "df['cycle'] = 3 CleanResp(df) return df def ReadFemResp1988(): \"\"\"Reads respondent", "null.index group[colname].fillna(fill, inplace=True) def PlotSurvivalFunctions(sf_map, predict_flag=False, colormap=None): \"\"\"Plot estimated survival", "sequence of times and rows contains one row of values", "CleanResp(df) return df def ReadFemResp1995(): \"\"\"Reads respondent data from NSFG", "'2011_2013_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True)", "compression='gzip') df.cmintvw.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmbirth.replace([9797, 9898, 9999], np.nan,", "(df.rmarital==1) df['finalwgt'] = df.wgtq1q16 df['cycle'] = 7 CleanResp(df) return df", "string name of column with propensity scores returns: DataFrame with", "= (pd.DatetimeIndex(dates).year - 1900) DigitizeResp(df) return df def ReadResp(dct_file, dat_file,", "return df def CleanResp(resp): \"\"\"Cleans a respondent DataFrame. resp: DataFrame", "<NAME> License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html \"\"\" from __future__ import print_function,", "= df.firstcm df.cmmarrhx.fillna(df.currentcm, inplace=True) # define evrmarry if either currentcm", "decade grouped = sample.groupby('birth_index') if prop_match: last = grouped.get_group(prop_match) #", "df: DataFrame returns: DataFrame \"\"\" weights = df['finalwgt'].copy() weights /=", "hazard functions and recomputes survival functions. For each group in", "& (df.fmarital==1) df['cycle'] = 3 CleanResp(df) return df def ReadFemResp1988():", "group: DataFrame colname: string name of column with propensity scores", "12363), (4637-1, 4638), (11759-1, 11762), (14-1, 16), (12350-1, 12359), (4713-1,", "= [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) df.cmbirth.replace(invalid, np.nan, inplace=True)", "9') resp9 = ReadFemResp2015() Validate2015(resp9) print('Cycle 8') resp8 = ReadFemResp2013()", "DataFrame \"\"\" usecols = ['caseid', 'mardat01', 'cmintvw', 'ager', 'evrmarry', 'wgt2015_2017',", "17)] df = pd.read_fwf(dat_file, compression='gzip', colspecs=colspecs, names=names) invalid = [9997,", "of resampling runs to make for i in range(iters): sample", "(ts, rows) where ts is a sequence of times and", "9999] df.cmintvw.replace(invalid, np.nan, inplace=True) #df.cmbirth.replace(invalid, np.nan, inplace=True) #df.cmmarrhx.replace(invalid, np.nan, inplace=True)", "from each cycle separately samples = [ResampleRowsWeighted(resp) for resp in", "calling CleanResp, we have to customize #CleanResp(df) df['agemarry'] = (df.cmmarrhx", "90000 # combine current and first marriage df['cmmarrhx'] = df.firstcm", "def EstimateSurvivalByCohort(resps, iters=101, cutoffs=None, predict_flag=False, prop_match=None, error_rate=0): \"\"\"Makes survival curves", "'cmmarrhx', 'fmarital', 'cmintvw', 'cmbirth', 'f18m1', 'cmdivorcx', 'cmstphsbx', 'fmarno'] colspecs =", "* year_step df.birth_index += year_min - year_step def ReadCanadaCycle5(): \"\"\"", "ReadFemResp2015() Validate2015(resp9) print('Cycle 8') resp8 = ReadFemResp2013() Validate2013(resp8) print('Cycle 7')", "'2013_2015_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True)", "a sequence of times and rows contains one row of", "df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2013_2015", "df.wgt2011_2013 df['cycle'] = 8 CleanResp(df) return df def ReadMaleResp2015(): \"\"\"Reads", "weights /= sum(weights) return np.random.choice(group.index, 1, p=weights)[0] indices = [ChooseIndex(value)", "Cycle 7. returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01', 'cmdivw',", "= hf, sf def MakeSurvivalCI(sf_seq, percents): \"\"\"Makes confidence intervals from", "= 4 CleanResp(df) return df def ReadFemResp1995(): \"\"\"Reads respondent data", "'timesmar', 'cmmarrhx', 'cmbirth', 'finalwgt', 'marend01', 'cmdivorcx', 'cmstphsbx', 'marstat'] colspecs =", "'wgt2015_2017', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2015_2017_MaleSetup.dct', '2015_2017_MaleData.dat.gz', usecols=usecols)", "def main(): print('Cycle 10') resp10 = ReadFemResp2017() Validate2017(resp10) print('Cycle 9')", "resp10 = ReadFemResp2017() Validate2017(resp10) print('Cycle 9') resp9 = ReadFemResp2015() Validate2015(resp9)", "['finalwgt', 'ageint', 'currentcm', 'firstcm', 'cmintvw', 'cmbirth', 'f23m1', 'cmdivorcx', 'cmstphsbx', 'fmarno']", "in the 80s is given the year_index 80. This function", "marriage. df['marend01'] = df.marrend4 df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.timesmar", "#Respondent every married: CC227 pass def ReadMaleResp2002(): \"\"\"Reads respondent data", "GPLv3 http://www.gnu.org/licenses/gpl.html \"\"\" from __future__ import print_function, division import bisect", "\"\"\"Estimates the survival curve. resp: DataFrame of respondents cutoff: where", "[(976-1, 982), (1001-1, 1002), (1268-1, 1271), (1037-1, 1040), (1041-1, 1041),", "/ 12.0 df['age'] = (df.cmintvw - df.cmbirth) / 12.0 #", "99999], np.nan, inplace=True) df.firstcm.replace([0, 99999], np.nan, inplace=True) df.currentcm.replace([0, 99999], np.nan,", "assert(sum(df.evrmarry) == 2401) assert(df.agemarry.value_counts().max() == 25) def Validate2017(df): assert(len(df) ==", "1542), (12-1, 16), (26-1, 30), (1554-1, 1554), (1565-1, 1569), (1570-1,", "map from group name to (HazardFunction, SurvivalFunction) \"\"\" names =", "predict_flag=False, colormap=None): \"\"\"Plot estimated survival functions. sf_map: map from group", "9898, 9999], np.nan, inplace=True) df.cmmarrhx.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmdivorcx.replace([9797,", "hf.Extend(hfs[i-1]) sf = hf.MakeSurvival() hf_map[name] = hf, sf def MakeSurvivalCI(sf_seq,", "[(12360-1, 12363), (4637-1, 4638), (11759-1, 11762), (14-1, 16), (12350-1, 12359),", "inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1)", "dat_file = '1995FemRespData.dat.gz' names = ['cmintvw', 'timesmar', 'cmmarrhx', 'cmbirth', 'finalwgt',", "jitter: Jitter(sample, 'age', jitter=jitter) Jitter(sample, 'agemarry', jitter=jitter) DigitizeResp(resp) return sample", "sf = sf_seq[0] if len(sf) == 0: continue ts, rows", "'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2013_2015_FemRespSetup.dct', '2013_2015_FemRespData.dat.gz', usecols=usecols) invalid =", "= 9 CleanResp(df) return df def ReadMaleResp2017(): \"\"\"Reads respondent data", "'marrend6', ] df = ReadResp('2002Male.dct', '2002Male.dat.gz', usecols=usecols) #df.marrend.replace([8,9], np.nan, inplace=True)", "inplace=True) #df.marrend3.replace([8,9], np.nan, inplace=True) df.marrend4.replace([8,9], np.nan, inplace=True) #df.marrend5.replace([8,9], np.nan, inplace=True)", "and recompute sf. hf_map: map from group name to (HazardFunction,", "colname, error_rate): \"\"\" NOTE: This will not work if there", "from a list of survival functions. sf_seq: list of SurvivalFunction", "== 6841) assert(df.agemarry.value_counts().max() == 79) def Validate2002(df): assert(len(df) == 7643)", "+ pd.DateOffset(months=cm) for cm in df.cmbirth] df['year'] = (pd.DatetimeIndex(dates).year -", "df def CleanResp(resp): \"\"\"Cleans a respondent DataFrame. resp: DataFrame of", "\"\"\" dct = thinkstats2.ReadStataDct(dct_file, encoding='iso-8859-1') df = dct.ReadFixedWidth(dat_file, compression='gzip', **options)", "sf = hf.MakeSurvival() hf_map[name] = hf, sf def MakeSurvivalCI(sf_seq, percents):", "sf_seq: ts |= set(sf.ts) ts = list(ts) ts.sort() # evaluate", "df = pd.read_fwf(filename, colspecs=colspecs, names=names, header=None, compression='gzip') df.cmintvw.replace([0, 99999], np.nan,", "above 9000 indicate month unknown df.loc[df.cmintvw>90000, 'cmintvw'] -= 90000 df.loc[df.cmbirth>90000,", "survival def ResampleResps(resps, remove_missing=False, jitter=0): \"\"\"Resamples each dataframe and then", "functions \"\"\" if cutoffs == None: cutoffs = {} sf_map", "scores returns: DataFrame with sample of rows from `group` \"\"\"", "ReadFemResp2013() Validate2013(resp8) print('Cycle 7') resp7 = ReadFemResp2010() Validate2010(resp7) print('Cycle 6')", "= ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgt2013_2015', 'mardat01',", "120 year_step = 10 year_bins = np.arange(year_min, year_max, year_step) df['age_index']", "sf) in hf_map.items(): sf_map[name].append(sf) return sf_map def AddErrors(group, colname, error_rate):", "return df def ReadFemResp2015(): \"\"\"Reads respondent data from NSFG Cycle", "& (df.rmarital==1) df['finalwgt'] = df.wgt2011_2013 df['cycle'] = 8 CleanResp(df) return", "status: C5 #Respondent every married: CC227 pass def ReadMaleResp2002(): \"\"\"Reads", "inplace=True) df.cmmarrhx.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmdivorcx.replace([9797, 9898, 9999], np.nan,", "to 12 months df['cmbirth'] = df.cmintvw - df.ager*12 df['cmmarrhx'] =", "age_step df.agemarry_index += age_min - age_step df.loc[df.agemarry.isnull(), 'agemarry_index'] = np.nan", "= ReadFemResp2002() Validate2002(resp6) print('Cycle 5') resp5 = ReadFemResp1995() Validate1995(resp5) print('Cycle", "'parity', 'wgt2011_2013', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df =", "list(hf_map.keys()) names.sort() hfs = [hf_map[name][0] for name in names] #", "np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df.cmdivorcx.replace(invalid, np.nan, inplace=True) df.cmstphsbx.replace(invalid, np.nan,", "inplace=True) # CM values above 9000 indicate month unknown df.loc[df.cmintvw>90000,", "either currentcm or firstcm is non-zero df['evrmarry'] = (df.fmarno >", "of HazardFunction, SurvivalFunction \"\"\" complete = resp.loc[resp.complete, 'complete_var'].dropna() ongoing =", "complete = resp.loc[resp.complete, 'complete_var'].dropna() ongoing = resp.loc[~resp.complete, 'ongoing_var'].dropna() hf =", "where the sfs are evaluated ts = set() for sf", "3. returns: DataFrame \"\"\" dat_file = '1982NSFGData.dat.gz' names = ['finalwgt',", "scipy.stats.norm(scale=1) values = group[colname].fillna(100) def ChooseIndex(value): weights = rv.pdf(values-value) weights", "= ReadFemResp1988() Validate1988(resp4) print('Cycle 3') resp3 = ReadFemResp1982() Validate1982(resp3) if", "MakeSurvivalCI(sf_seq, percents): \"\"\"Makes confidence intervals from a list of survival", "(pd.DatetimeIndex(dates).year - 1900) DigitizeResp(df) return df def Validate1982(df): assert(len(df) ==", "'timesmar', 'marrend4', #'marrend', 'marrend2', 'marrend3', marrend5', 'marrend6', ] df =", "= np.digitize(df.agemarry, age_bins) * age_step df.agemarry_index += age_min - age_step", "np.nan df['birth_index'] = np.digitize(df.year, year_bins) * year_step df.birth_index += year_min", "the amount of missing data is small; I think it", "Cycle 10. returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01', 'cmintvw',", "= df.wgt2011_2013 df['cycle'] = 8 CleanResp(df) return df def ReadMaleResp2015():", "the analysis with different levels of granularity. df: DataFrame \"\"\"", "make for i in range(iters): sample = ResampleResps(resps) # group", "#df.marrend5.replace([8,9], np.nan, inplace=True) #df.marrend6.replace([8,9], np.nan, inplace=True) df.timesmar.replace([98,99], np.nan, inplace=True) #", "to a column. df: DataFrame column: string column name jitter:", "(df.rmarital==1) df['finalwgt'] = df.wgt2013_2015 df['cycle'] = 9 CleanResp(df) return df", "len(sf) > 0] # return the requested percentiles from each", "names = list(hf_map.keys()) names.sort() hfs = [hf_map[name][0] for name in", "NSFG respondent data. dct_file: string file name dat_file: string file", "year_step) df['age_index'] = np.digitize(df.age, age_bins) * age_step df.age_index += age_min", "= (df.marend01==2) | (df.marend01==3) df['separated'] = (df.marend01==4) df['widowed'] = (df.marend01==1)", "df = ReadResp('2015_2017_FemRespSetup.dct', '2015_2017_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999]", "= ReadResp('2013_2015_FemRespSetup.dct', '2013_2015_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid,", "off by up to 12 months df['cmbirth'] = df.cmintvw -", "= resp.year // 5 DigitizeResp(resp) def DigitizeResp(df): \"\"\"Computes indices for", "survival functions. sf_map: map from group name to sequence of", "indices = [ChooseIndex(value) for value in target[colname]] return group.loc[indices] def", "CleanResp(df) return df def ReadMaleResp2015(): \"\"\"Reads respondent data from NSFG", "estimated survival functions. sf_map: map from group name to sequence", "agemarry, age, decade, fives \"\"\" resp['agemarry'] = (resp.cmmarrhx - resp.cmbirth)", "values above 9000 indicate month unknown df.loc[df.cmintvw>9000, 'cmintvw'] -= 9000", "99999], np.nan, inplace=True) df.cmdivorcx.replace([0, 99999], np.nan, inplace=True) df.cmstphsbx.replace([0, 99999], np.nan,", "but it looks like marrend4 is the end of the", "pd.read_fwf(filename, colspecs=colspecs, names=names, header=None, compression='gzip') df.cmintvw.replace([0, 99999], np.nan, inplace=True) df.cmbirth.replace([0,", "from NSFG Cycle 8. returns: DataFrame \"\"\" usecols = ['caseid',", "'cmintvw', 'evrmarry', 'wgt2013_2015', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2013_2015_MaleSetup.dct',", "= ReadResp('2002Male.dct', '2002Male.dat.gz', usecols=usecols) #df.marrend.replace([8,9], np.nan, inplace=True) #df.marrend2.replace([8,9], np.nan, inplace=True)", "df['separated'] = (df.marend01==4) df['widowed'] = (df.marend01==1) df['stillma'] = (df.timesmar== 1)", "= np.digitize(df.age, age_bins) * age_step df.age_index += age_min - age_step", "#df.marrend.replace([8,9], np.nan, inplace=True) #df.marrend2.replace([8,9], np.nan, inplace=True) #df.marrend3.replace([8,9], np.nan, inplace=True) df.marrend4.replace([8,9],", "sf_map[name].append(sf) return sf_map def AddErrors(group, colname, error_rate): \"\"\" NOTE: This", "sort=False) # remove married people with unknown marriage dates if", "'complete_var', 'complete_missing') #FillMissingColumn(group, 'ongoing_var', 'ongoing_missing') cutoff = cutoffs.get(name, 100) hf_map[name]", "firstcm is non-zero df['evrmarry'] = (df.fmarno > 0) df['divorced'] =", "\"\"\"Makes confidence intervals from a list of survival functions. sf_seq:", "def Validate1982(df): assert(len(df) == 7969) assert(len(df[df.evrmarry]) == 4651) assert(df.agemarry.value_counts().max() ==", "= (df.timesmar > 0) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2)", "df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.timesmar > 0) df['divorced'] =", "'cmstphsbx', 'marstat'] colspecs = [(12360-1, 12363), (4637-1, 4638), (11759-1, 11762),", "'fmarit', 'timesmar', 'marrend4', #'marrend', 'marrend2', 'marrend3', marrend5', 'marrend6', ] df", "def Validate1995(df): assert(len(df) == 10847) assert(len(df[df.evrmarry]) == 6841) assert(df.agemarry.value_counts().max() ==", "'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgt2013_2015', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno',", "= group[colname].fillna(100) def ChooseIndex(value): weights = rv.pdf(values-value) weights /= sum(weights)", "valid.sample(len(null), replace=True) fill.index = null.index group[colname].fillna(fill, inplace=True) def PlotSurvivalFunctions(sf_map, predict_flag=False,", "hf, sf def PropensityMatch(target, group, colname='agemarry'): \"\"\"Choose a random subset", "'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'finalwgt', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno',", "group hf_map = OrderedDict() for name, group in iter(grouped): if", "division import bisect import numpy as np import pandas as", "if prop_match: group = PropensityMatch(last, group) if error_rate: AddErrors(group, 'complete_missing',", "(df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgtq1q16 df['cycle'] =", "'evrmarry', 'parity', 'wgtq1q16', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df", "= 120 year_step = 10 year_bins = np.arange(year_min, year_max, year_step)", "'cmbirth', 'finalwgt', 'marend01', 'cmdivorcx', 'cmstphsbx', 'marstat'] colspecs = [(12360-1, 12363),", "9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) #df.cmbirth.replace(invalid, np.nan, inplace=True) #df.cmmarrhx.replace(invalid, np.nan,", "= scipy.stats.norm(scale=1) values = group[colname].fillna(100) def ChooseIndex(value): weights = rv.pdf(values-value)", "sample sample = pd.concat(samples, ignore_index=True, sort=False) # remove married people", "of noise \"\"\" df[column] += np.random.uniform(-jitter, jitter, size=len(df)) def EstimateSurvival(resp,", "to matches propensity with `target`. target: DataFrame group: DataFrame colname:", "rows from `group` \"\"\" rv = scipy.stats.norm(scale=1) values = group[colname].fillna(100)", "find the union of all ts where the sfs are", "Validate1988(resp4) print('Cycle 3') resp3 = ReadFemResp1982() Validate1982(resp3) if __name__ ==", "np.nan, inplace=True) #df.marrend6.replace([8,9], np.nan, inplace=True) df.timesmar.replace([98,99], np.nan, inplace=True) # the", "'firstcm'] -= 90000 df.loc[df.currentcm>90000, 'currentcm'] -= 90000 df.loc[df.cmdivorcx>90000, 'cmdivorcx'] -=", "'fmarno', 'mar1diss'] df = ReadResp('2006_2010_FemRespSetup.dct', '2006_2010_FemResp.dat.gz', usecols=usecols) invalid = [9997,", "iter(grouped): if prop_match: group = PropensityMatch(last, group) if error_rate: AddErrors(group,", "assert(df.agemarry.value_counts().max() == 79) def Validate2002(df): assert(len(df) == 7643) assert(sum(df.evrmarry) ==", "group = PropensityMatch(last, group) if error_rate: AddErrors(group, 'complete_missing', error_rate) AddErrors(group,", "+= np.random.uniform(-jitter, jitter, size=len(df)) def EstimateSurvival(resp, cutoff=None): \"\"\"Estimates the survival", "'2013_2015_MaleData.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.evrmarry==1) df['divorced'] =", "join the cycles into one big sample sample = pd.concat(samples,", "{} sf_map = defaultdict(list) # iters is the number of", "cycles into one big sample sample = pd.concat(samples, ignore_index=True, sort=False)", "in sf_seq if len(sf) > 0] # return the requested", "assert(len(df) == 7643) assert(sum(df.evrmarry) == 4126) assert(df.agemarry.value_counts().max() == 45) def", "(df.marend01==4) df['widowed'] = (df.marend01==1) df['stillma'] = (df.timesmar== 1) & (df.fmarit==1)", "def ReadMaleResp2013(): \"\"\"Reads respondent data from NSFG Cycle 8. returns:", "data from NSFG Cycle 7. returns: DataFrame \"\"\" usecols =", "Jitter(sample, 'age', jitter=jitter) Jitter(sample, 'agemarry', jitter=jitter) DigitizeResp(resp) return sample def", "df def ReadFemResp2017(): \"\"\"Reads respondent data from NSFG Cycle 10.", "customize #CleanResp(df) df['agemarry'] = (df.cmmarrhx - df.cmbirth) / 12.0 df['age']", "7') resp7 = ReadFemResp2010() Validate2010(resp7) print('Cycle 6') resp6 = ReadFemResp2002()", "is small; I think it is better # to drop", "df['finalwgt'] = df.wgt2015_2017 df['cycle'] = 10 # Instead of calling", "interview: C3 #final weight: C1 #marital status: C5 #Respondent every", "= OrderedDict() for name, group in iter(grouped): if prop_match: group", "indices for age, agemarry, and birth year. Groups each of", "column. df: DataFrame column: string column name jitter: standard deviation", "data from NSFG Cycle 6. returns: DataFrame \"\"\" usecols =", "df def ReadResp(dct_file, dat_file, **options): \"\"\"Reads the NSFG respondent data.", "= ReadResp('2006_2010_MaleSetup.dct', '2006_2010_Male.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.evrmarry==1)", "== 45) def Validate2010(df): assert(len(df) == 12279) assert(sum(df.evrmarry) == 5534)", "resps: list of DataFrame returns: DataFrame \"\"\" # we have", "matplotlib.pyplot as plt from collections import defaultdict from collections import", "'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2015_2017_FemRespSetup.dct', '2015_2017_FemRespData.dat.gz', usecols=usecols) invalid =", "pd.concat(samples, ignore_index=True, sort=False) # remove married people with unknown marriage", "at all times ss_seq = [sf.Probs(ts) for sf in sf_seq", "rows[1], label='%ds'%name, color=color) else: thinkplot.Plot(ts, rows[1], label='%ds'%name) def MakePredictions(hf_map): \"\"\"Extends", "if len(sf_seq) == 0: continue sf = sf_seq[0] if len(sf)", "ts is a sequence of times and rows contains one", "function allows me to run the analysis with different levels", "df['divorced'] = (df.marend01==2) | (df.marend01==3) df['separated'] = (df.marend01==4) df['widowed'] =", "# removed 'cmmarrhx', 'cmdivorcx', 'cmbirth', usecols = ['caseid', 'cmintvw', 'ager',", "'evrmarry', 'wgtq1q16', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2006_2010_MaleSetup.dct', '2006_2010_Male.dat.gz',", "#df.marrend3.replace([8,9], np.nan, inplace=True) df.marrend4.replace([8,9], np.nan, inplace=True) #df.marrend5.replace([8,9], np.nan, inplace=True) #df.marrend6.replace([8,9],", "1 age_bins = np.arange(age_min, age_max, age_step) year_min = 0 year_max", "ReadFemResp2010(): \"\"\"Reads respondent data from NSFG Cycle 7. returns: DataFrame", "df.cmdivorcx.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmstphsbx.replace([9797, 9898, 9999], np.nan, inplace=True)", "df['evrmarry'] = (df.timesmar > 0) df['divorced'] = (df.marend01==1) df['separated'] =", "married: CC227 pass def ReadCanadaCycle6(): \"\"\" \"\"\" #age at first", "9999], np.nan, inplace=True) df.cmdivorcx.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmstphsbx.replace([9797, 9898,", "cutoff = cutoffs.get(name, 100) hf_map[name] = EstimateSurvival(group, cutoff) # make", "inplace=True) # CM values above 9000 indicate month unknown df.loc[df.cmintvw>9000,", "file name dat_file: string file name returns: DataFrame \"\"\" dct", "df.cmstphsbx.replace([0, 99999], np.nan, inplace=True) # CM values above 9000 indicate", "names.sort() hfs = [hf_map[name][0] for name in names] # extend", "= np.digitize(df.year, year_bins) * year_step df.birth_index += year_min - year_step", "(4722-1, 4725), (17-1, 17)] df = pd.read_fwf(dat_file, compression='gzip', colspecs=colspecs, names=names)", "- 1900) #resp['decade'] = resp.year // 10 #resp['fives'] = resp.year", "missing values! \"\"\" group[colname] = np.random.random(len(group)) < error_rate def FillMissingColumn(group,", "Validate2017(resp10) print('Cycle 9') resp9 = ReadFemResp2015() Validate2015(resp9) print('Cycle 8') resp8", "assert(sum(df.evrmarry) == 4126) assert(df.agemarry.value_counts().max() == 45) def Validate2010(df): assert(len(df) ==", "matches propensity with `target`. target: DataFrame group: DataFrame colname: string", "hf, sf def MakeSurvivalCI(sf_seq, percents): \"\"\"Makes confidence intervals from a", "assert(sum(df.evrmarry) == 2582) assert(df.agemarry.value_counts().max() == 29) def main(): print('Cycle 10')", "(df.fmarno > 0) df['divorced'] = (df.f23m1==2) df['separated'] = (df.f23m1==3) df['widowed']", "9000 df['evrmarry'] = (df.fmarno > 0) df['divorced'] = (df.f18m1 ==", "age_step df.loc[df.age.isnull(), 'age_index'] = np.nan df['agemarry_index'] = np.digitize(df.agemarry, age_bins) *", "& (df.f23m1.isnull()) df['cycle'] = 4 CleanResp(df) return df def ReadFemResp1995():", "# extend each hazard function using data from the previous", "agemarry, and birth year. Groups each of these variables into", "and cmmarrhx are no longer included, # we have to", "jitter, size=len(df)) def EstimateSurvival(resp, cutoff=None): \"\"\"Estimates the survival curve. resp:", "else: thinkplot.Plot(ts, rows[1], label='%ds'%name) def MakePredictions(hf_map): \"\"\"Extends a set of", "DataFrame \"\"\" dat_file = '1995FemRespData.dat.gz' names = ['cmintvw', 'timesmar', 'cmmarrhx',", "df def ReadMaleResp2015(): \"\"\"Reads respondent data from NSFG Cycle 9.", "np.arange(age_min, age_max, age_step) year_min = 0 year_max = 120 year_step", "return df def ReadMaleResp2015(): \"\"\"Reads respondent data from NSFG Cycle", "['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'finalwgt', 'mardat01', 'marend01',", "\"\"\" usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity',", "into bins and then assigns an index to each bin.", "'mardat01', 'cmintvw', 'ager', 'evrmarry', 'wgt2015_2017', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df", "12279) assert(sum(df.evrmarry) == 5534) assert(df.agemarry.value_counts().max() == 64) def Validate2013(df): assert(len(df)", "pd.DateOffset(months=cm) for cm in df.cmbirth] df['year'] = (pd.DatetimeIndex(dates).year - 1900)", "df.agemarry_index += age_min - age_step df.loc[df.agemarry.isnull(), 'agemarry_index'] = np.nan df['birth_index']", "ts, rows def ReadFemResp1982(): \"\"\"Reads respondent data from NSFG Cycle", "df['evrmarry'] = (df.fmarno > 0) df['divorced'] = (df.f18m1 == 4)", "marriage dates if remove_missing: sample = sample[~sample.missing] # jittering the", "i, name in enumerate(names): hf, sf = hf_map[name] if i", "to (HazardFunction, SurvivalFunction) \"\"\" names = list(hf_map.keys()) names.sort() hfs =", "inplace=True) df.cmdivorcx.replace([0, 99999], np.nan, inplace=True) df.cmstphsbx.replace([0, 99999], np.nan, inplace=True) #", "column: string column name jitter: standard deviation of noise \"\"\"", "of the given column. group: DataFrame colname: string \"\"\" null", "df['stillma'] = (df.fmarno==1) & (df.fmarital==1) df['cycle'] = 3 CleanResp(df) return", "resp['age'] = (resp.cmintvw - resp.cmbirth) / 12.0 # if married,", "'parity', 'wgt2013_2015', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df =", "if cutoff: hf.Truncate(cutoff) sf = hf.MakeSurvival() return hf, sf def", "99], np.nan, inplace=True) df['evrmarry'] = (df.timesmar > 0) df['divorced'] =", "anyone between 30 and 30.99 year old is assigned age_index", "(df.f23m1==1) df['stillma'] = (df.fmarno==1) & (df.f23m1.isnull()) df['cycle'] = 4 CleanResp(df)", "\"\"\" names = list(hf_map.keys()) names.sort() hfs = [hf_map[name][0] for name", "cm in df.cmbirth] df['year'] = (pd.DatetimeIndex(dates).year - 1900) DigitizeResp(df) return", "def ResampleRowsWeighted(df, column='finalwgt'): \"\"\"Resamples the rows in df in accordance", "'fmarno', 'mar1diss'] df = ReadResp('2006_2010_MaleSetup.dct', '2006_2010_Male.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01", "ts = set() for sf in sf_seq: ts |= set(sf.ts)", "= sample.groupby('birth_index') if prop_match: last = grouped.get_group(prop_match) # and estimate", "of DataFrames iters: number of resamples to plot predict_flag: whether", "at interview: C3 #final weight: C1 #marital status: C5 #Respondent", "= ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'finalwgt', 'mardat01',", "# CM values above 9000 indicate month unknown df.loc[df.cmintvw>9000, 'cmintvw']", "iters is the number of resampling runs to make for", "# extract the sf from each pair and accumulate the", "9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) df.cmbirth.replace(invalid, np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan,", "inplace=True) # the way marriage ends are recorded is really", "This will not work if there are actual missing values!", "missing data is small; I think it is better #", "return df def ReadResp(dct_file, dat_file, **options): \"\"\"Reads the NSFG respondent", "inplace=True) df.cmbirth.replace([0, 99999], np.nan, inplace=True) df.firstcm.replace([0, 99999], np.nan, inplace=True) df.currentcm.replace([0,", "= sf_seq[0] if len(sf) == 0: continue ts, rows =", "as pd import scipy.stats import gzip import matplotlib.pyplot as plt", "= ReadFemResp1995() Validate1995(resp5) print('Cycle 4') resp4 = ReadFemResp1988() Validate1988(resp4) print('Cycle", "& (df.rmarital==1) df['finalwgt'] = df.wgt2015_2017 df['cycle'] = 10 # Instead", "then assigns an index to each bin. For example, anyone", "# combine current and first marriage df['cmmarrhx'] = df.firstcm df.cmmarrhx.fillna(df.currentcm,", "weights = rv.pdf(values-value) weights /= sum(weights) return np.random.choice(group.index, 1, p=weights)[0]", "sample = ResampleResps(resps) # group by decade grouped = sample.groupby('birth_index')", "`group` to matches propensity with `target`. target: DataFrame group: DataFrame", "if desired if predict_flag: MakePredictions(hf_map) # extract the sf from", "print_function, division import bisect import numpy as np import pandas", "big sample sample = pd.concat(samples, ignore_index=True, sort=False) # remove married", "// 10 #resp['fives'] = resp.year // 5 DigitizeResp(resp) def DigitizeResp(df):", "(df.cmmarrhx - df.cmbirth) / 12.0 df['age'] = (df.cmintvw - df.cmbirth)", "= (df.marend01==3) df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['finalwgt']", "return np.random.choice(group.index, 1, p=weights)[0] indices = [ChooseIndex(value) for value in", "to also plot predictions cutoffs: map from cohort to the", "import defaultdict from collections import OrderedDict from collections import Counter", "= PropensityMatch(last, group) if error_rate: AddErrors(group, 'complete_missing', error_rate) AddErrors(group, 'ongoing_missing',", "granularity. df: DataFrame \"\"\" age_min = 10 age_max = 55", "\"\"\" usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgtq1q16',", "resp7 = ReadFemResp2010() Validate2010(resp7) print('Cycle 6') resp6 = ReadFemResp2002() Validate2002(resp6)", "requested percentiles from each column rows = thinkstats2.PercentileRows(ss_seq, percents) return", "year_step = 10 year_bins = np.arange(year_min, year_max, year_step) df['age_index'] =", "#resp['fives'] = resp.year // 5 DigitizeResp(resp) def DigitizeResp(df): \"\"\"Computes indices", "= ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgt2011_2013', 'marend01', 'rmarital',", "'cmbirth', 'f23m1', 'cmdivorcx', 'cmstphsbx', 'fmarno'] colspecs = [(2568-1, 2574), (36-1,", "'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgt2011_2013', 'mardat01', 'marend01', 'mardis01', 'rmarital',", "8 CleanResp(df) return df def ReadMaleResp2015(): \"\"\"Reads respondent data from", "628), (1142-1, 1143), ] df = pd.read_fwf(dat_file, colspecs=colspecs, names=names, header=None,", "assert(len(df) == 5699) assert(sum(df.evrmarry) == 2401) assert(df.agemarry.value_counts().max() == 25) def", "len(sf) == 0: continue ts, rows = MakeSurvivalCI(sf_seq, [10, 50,", "inplace=True) df.f18m1.replace([7, 8, 9], np.nan, inplace=True) # CM values above", "(df.timesmar > 0) df['divorced'] = (df.marend01==2) | (df.marend01==3) df['separated'] =", "np.nan df['agemarry_index'] = np.digitize(df.agemarry, age_bins) * age_step df.agemarry_index += age_min", "'mar1diss'] df = ReadResp('2015_2017_MaleSetup.dct', '2015_2017_MaleData.dat.gz', usecols=usecols) # since cmbirth and", "Stats\", by <NAME>, available from greenteapress.com Copyright 2014 <NAME> License:", "5601) assert(sum(df.evrmarry) == 2452) assert(df.agemarry.value_counts().max() == 33) def Validate2015(df): assert(len(df)", "plt from collections import defaultdict from collections import OrderedDict from", "name jitter: standard deviation of noise \"\"\" df[column] += np.random.uniform(-jitter,", "df.timesmar.replace([98,99], np.nan, inplace=True) # the way marriage ends are recorded", "sf_map: map from group name to sequence of survival functions", "'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'finalwgt', 'fmarit', 'timesmar', 'marrend4', #'marrend', 'marrend2',", "of respondent at interview: C3 #final weight: C1 #marital status:", "predict_flag: whether the lines are predicted or actual colormap: map", "where to truncate the estimated functions returns: pair of HazardFunction,", "p=weights) return df.loc[indices] def Jitter(df, column, jitter=1): \"\"\"Adds random noise", "with unknown marriage dates if remove_missing: sample = sample[~sample.missing] #", "list of survival functions \"\"\" if cutoffs == None: cutoffs", "dat_file = '1982NSFGData.dat.gz' names = ['finalwgt', 'ageint', 'mar2p', 'cmmarrhx', 'fmarital',", "[9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) df.cmbirth.replace(invalid, np.nan, inplace=True) df.cmmarrhx.replace(invalid,", "DigitizeResp(df) return df def Validate1982(df): assert(len(df) == 7969) assert(len(df[df.evrmarry]) ==", "79) def Validate2002(df): assert(len(df) == 7643) assert(sum(df.evrmarry) == 4126) assert(df.agemarry.value_counts().max()", "sf_map = defaultdict(list) # iters is the number of resampling", "1040), (1041-1, 1041), (841-1, 844), (12-1, 15), (606-1, 606), (619-1,", "values! \"\"\" group[colname] = np.random.random(len(group)) < error_rate def FillMissingColumn(group, colname,", "6 CleanResp(df) return df def ReadMaleResp2010(): \"\"\"Reads respondent data from", "def ChooseIndex(value): weights = rv.pdf(values-value) weights /= sum(weights) return np.random.choice(group.index,", "7. returns: DataFrame \"\"\" usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth',", "df.cmbirth.replace(invalid, np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df.cmdivorcx.replace(invalid, np.nan, inplace=True) df.cmstphsbx.replace(invalid,", "year old is assigned age_index 30. Anyone born in the", "10. returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01', 'cmintvw', 'ager',", "df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma']", "marrend4 is the end of the first marriage. df['marend01'] =", "results for name, (hf, sf) in hf_map.items(): sf_map[name].append(sf) return sf_map", "= [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) #df.cmbirth.replace(invalid, np.nan, inplace=True)", "of respondents cutoff: where to truncate the estimated functions returns:", "'cmintvw'] -= 9000 df.loc[df.cmbirth>9000, 'cmbirth'] -= 9000 df.loc[df.cmmarrhx>9000, 'cmmarrhx'] -=", "hf = survival.EstimateHazardFunction(complete, ongoing) if cutoff: hf.Truncate(cutoff) sf = hf.MakeSurvival()", "= group[colname].dropna() fill = valid.sample(len(null), replace=True) fill.index = null.index group[colname].fillna(fill,", "= 10 age_max = 55 age_step = 1 age_bins =", "= ['caseid', 'cmintvw', 'ager', 'evrmarry', 'parity', 'wgt2015_2017', 'mardat01', 'marend01', 'mardis01',", "NSFG Cycle 4. Read as if were a standard ascii", "(26-1, 30), (1554-1, 1554), (1565-1, 1569), (1570-1, 1574), (2441-1, 2442),", "CM values above 9000 indicate month unknown df.loc[df.cmintvw>90000, 'cmintvw'] -=", "'ongoing_missing', error_rate) # the amount of missing data is small;", "0 year_max = 120 year_step = 10 year_bins = np.arange(year_min,", "def Jitter(df, column, jitter=1): \"\"\"Adds random noise to a column.", "'cmbirth', 'cmintvw', 'evrmarry', 'wgt2013_2015', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df =", "have to resample the data from each cycle separately samples", "(1041-1, 1041), (841-1, 844), (12-1, 15), (606-1, 606), (619-1, 622),", "fill = valid.sample(len(null), replace=True) fill.index = null.index group[colname].fillna(fill, inplace=True) def", "<gh_stars>0 \"\"\"This file contains code for use with \"Think Stats\",", "\"\"\"Reads the NSFG respondent data. dct_file: string file name dat_file:", "age_step df.age_index += age_min - age_step df.loc[df.age.isnull(), 'age_index'] = np.nan", "NSFG Cycle 5. returns: DataFrame \"\"\" dat_file = '1995FemRespData.dat.gz' names", "group[group[missing_colname]] if len(null) == 0: return # print(len(null), len(group)) valid", "the lines are predicted or actual colormap: map from group", "'2002FemResp.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True)", "30 and 30.99 year old is assigned age_index 30. Anyone", "-= 9000 df.loc[df.cmdivorcx>9000, 'cmdivorcx'] -= 9000 df.loc[df.cmstphsbx>9000, 'cmstphsbx'] -= 9000", "for i, name in enumerate(names): hf, sf = hf_map[name] if", "if married, we need agemarry; if not married, we need", "column with propensity scores returns: DataFrame with sample of rows", "in hf_map, we extend hf and recompute sf. hf_map: map", "'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2013_2015_FemRespSetup.dct', '2013_2015_FemRespData.dat.gz', usecols=usecols) invalid", "= 7 CleanResp(df) return df def ReadFemResp2013(): \"\"\"Reads respondent data", "8. returns: DataFrame \"\"\" usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth',", "DataFrame colname: string name of column with propensity scores returns:", "def PropensityMatch(target, group, colname='agemarry'): \"\"\"Choose a random subset of `group`", "df.mardat01 df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2)", "9000 df.loc[df.cmdivorcx>9000, 'cmdivorcx'] -= 9000 df.loc[df.cmstphsbx>9000, 'cmstphsbx'] -= 9000 df['evrmarry']", "df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['cycle'] = 6", "whether the lines are predicted or actual colormap: map from", "['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgtq1q16', 'mardat01', 'marend01',", "the requested percentiles from each column rows = thinkstats2.PercentileRows(ss_seq, percents)", "resampled people # are not identical to the actual respondents", "resample the data from each cycle separately samples = [ResampleRowsWeighted(resp)", "a random subset of `group` to matches propensity with `target`.", "replace=True) fill.index = null.index group[colname].fillna(fill, inplace=True) def PlotSurvivalFunctions(sf_map, predict_flag=False, colormap=None):", "'ongoing_var'].dropna() hf = survival.EstimateHazardFunction(complete, ongoing) if cutoff: hf.Truncate(cutoff) sf =", "of times and rows contains one row of values for", "6. returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth',", "the resampled people # are not identical to the actual", "'cmdivorcx', 'cmbirth', usecols = ['caseid', 'cmintvw', 'ager', 'evrmarry', 'parity', 'wgt2015_2017',", "in accordance with a weight column. df: DataFrame returns: DataFrame", "with random data #FillMissingColumn(group, 'complete_var', 'complete_missing') #FillMissingColumn(group, 'ongoing_var', 'ongoing_missing') cutoff", "return sample def ResampleRowsWeighted(df, column='finalwgt'): \"\"\"Resamples the rows in df", "returns: pair of HazardFunction, SurvivalFunction \"\"\" complete = resp.loc[resp.complete, 'complete_var'].dropna()", "(pd.DatetimeIndex(dates).year - 1900) #resp['decade'] = resp.year // 10 #resp['fives'] =", "982), (1001-1, 1002), (1268-1, 1271), (1037-1, 1040), (1041-1, 1041), (841-1,", "= 5 CleanResp(df) return df def ReadFemResp2002(): \"\"\"Reads respondent data", "variables; # the result can be off by up to", "assert(len(df) == 5554) assert(sum(df.evrmarry) == 2582) assert(df.agemarry.value_counts().max() == 29) def", "Cycle 10. returns: DataFrame \"\"\" # removed 'cmmarrhx', 'cmdivorcx', 'cmbirth',", "it than to fill with random data #FillMissingColumn(group, 'complete_var', 'complete_missing')", "import thinkstats2 import thinkplot import survival def ResampleResps(resps, remove_missing=False, jitter=0):", "== None: cutoffs = {} sf_map = defaultdict(list) # iters", "hf.Truncate(cutoff) sf = hf.MakeSurvival() return hf, sf def PropensityMatch(target, group,", "a list of survival functions. sf_seq: list of SurvivalFunction percents:", "10 #resp['fives'] = resp.year // 5 DigitizeResp(resp) def DigitizeResp(df): \"\"\"Computes", "== 5699) assert(sum(df.evrmarry) == 2401) assert(df.agemarry.value_counts().max() == 25) def Validate2017(df):", "3') resp3 = ReadFemResp1982() Validate1982(resp3) if __name__ == '__main__': main()", "'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgt2013_2015', 'mardat01', 'marend01', 'mardis01',", "return df def ReadFemResp1995(): \"\"\"Reads respondent data from NSFG Cycle", "df['year'] = (pd.DatetimeIndex(dates).year - 1900) DigitizeResp(df) return df def ReadResp(dct_file,", "(1268-1, 1271), (1037-1, 1040), (1041-1, 1041), (841-1, 844), (12-1, 15),", "'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2011_2013_FemRespSetup.dct', '2011_2013_FemRespData.dat.gz',", "ReadMaleResp2010(): \"\"\"Reads respondent data from NSFG Cycle 7. returns: DataFrame", "'cmbirth', 'cmintvw', 'evrmarry', 'finalwgt', 'fmarit', 'timesmar', 'marrend4', #'marrend', 'marrend2', 'marrend3',", "ReadResp(dct_file, dat_file, **options): \"\"\"Reads the NSFG respondent data. dct_file: string", "df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated']", "# Instead of calling CleanResp, we have to customize #CleanResp(df)", "(df.mardat01-1900) * 12 df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated']", "**options) return df def CleanResp(resp): \"\"\"Cleans a respondent DataFrame. resp:", "year_min = 0 year_max = 120 year_step = 10 year_bins", "scipy.stats import gzip import matplotlib.pyplot as plt from collections import", "usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgt2013_2015',", "return df def ReadMaleResp2017(): \"\"\"Reads respondent data from NSFG Cycle", "extract the sf from each pair and accumulate the results", "all times ss_seq = [sf.Probs(ts) for sf in sf_seq if", "NOTE: This will not work if there are actual missing", "return df def ReadFemResp2010(): \"\"\"Reads respondent data from NSFG Cycle", "df.loc[df.cmbirth>90000, 'cmbirth'] -= 90000 df.loc[df.firstcm>90000, 'firstcm'] -= 90000 df.loc[df.currentcm>90000, 'currentcm']", "from collections import OrderedDict from collections import Counter import thinkstats2", "column='finalwgt'): \"\"\"Resamples the rows in df in accordance with a", "DataFrame column: string column name jitter: standard deviation of noise", "survival functions. sf_seq: list of SurvivalFunction percents: list of percentiles", "'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'finalwgt', 'mardat01', 'marend01', 'mardis01', 'rmarital',", "compression='gzip', **options) return df def CleanResp(resp): \"\"\"Cleans a respondent DataFrame.", "usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgtq1q16',", "== 3) df['stillma'] = (df.fmarno==1) & (df.fmarital==1) df['cycle'] = 3", "month0 = pd.to_datetime('1899-12-15') dates = [month0 + pd.DateOffset(months=cm) for cm", "better # to drop it than to fill with random", "'fmarno', 'mar1diss'] df = ReadResp('2015_2017_MaleSetup.dct', '2015_2017_MaleData.dat.gz', usecols=usecols) # since cmbirth", "= df.mardat01 df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] =", "from group name to color \"\"\" for name, sf_seq in", "= (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] =", "CC232 #age of respondent at interview: C3 #final weight: C1", "np.nan, inplace=True) df.cmmarrhx.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmdivorcx.replace([9797, 9898, 9999],", "on other variables; # the result can be off by", "12.0 df['age'] = (df.cmintvw - df.cmbirth) / 12.0 # if", "way marriage ends are recorded is really confusing, # but", "each column rows = thinkstats2.PercentileRows(ss_seq, percents) return ts, rows def", "& (df.fmarit==1) df['cycle'] = 6 CleanResp(df) return df def ReadMaleResp2010():", "name returns: DataFrame \"\"\" dct = thinkstats2.ReadStataDct(dct_file, encoding='iso-8859-1') df =", "Validate2002(df): assert(len(df) == 7643) assert(sum(df.evrmarry) == 4126) assert(df.agemarry.value_counts().max() == 45)", "print('Cycle 4') resp4 = ReadFemResp1988() Validate1988(resp4) print('Cycle 3') resp3 =", "respondent DataFrame. resp: DataFrame of respondents Adds columns: agemarry, age,", "and then assigns an index to each bin. For example,", "file name returns: DataFrame \"\"\" dct = thinkstats2.ReadStataDct(dct_file, encoding='iso-8859-1') df", "# jittering the ages reflects the idea that the resampled", "] df = pd.read_fwf(filename, colspecs=colspecs, names=names, header=None, compression='gzip') df.cmintvw.replace([0, 99999],", "0) df['divorced'] = (df.marend01==2) | (df.marend01==3) df['separated'] = (df.marend01==4) df['widowed']", "if colormap: color = colormap[name] thinkplot.Plot(ts, rows[1], label='%ds'%name, color=color) else:", "resp.age.isnull()) month0 = pd.to_datetime('1899-12-15') dates = [month0 + pd.DateOffset(months=cm) for", "import scipy.stats import gzip import matplotlib.pyplot as plt from collections", "we need age df['missing'] = np.where(df.evrmarry, df.agemarry.isnull(), df.age.isnull()) month0 =", "C5 #Respondent every married: CC227 pass def ReadMaleResp2002(): \"\"\"Reads respondent", "name in enumerate(names): hf, sf = hf_map[name] if i >", "(1037-1, 1040), (1041-1, 1041), (841-1, 844), (12-1, 15), (606-1, 606),", "df.loc[df.currentcm>90000, 'currentcm'] -= 90000 df.loc[df.cmdivorcx>90000, 'cmdivorcx'] -= 90000 df.loc[df.cmstphsbx>90000, 'cmstphsbx']", "rows in df in accordance with a weight column. df:", "PropensityMatch(last, group) if error_rate: AddErrors(group, 'complete_missing', error_rate) AddErrors(group, 'ongoing_missing', error_rate)", "DataFrame \"\"\" dct = thinkstats2.ReadStataDct(dct_file, encoding='iso-8859-1') df = dct.ReadFixedWidth(dat_file, compression='gzip',", "== 64) def Validate2013(df): assert(len(df) == 5601) assert(sum(df.evrmarry) == 2452)", "= EstimateSurvival(group, cutoff) # make predictions if desired if predict_flag:", "rows[1], label='%ds'%name) def MakePredictions(hf_map): \"\"\"Extends a set of hazard functions", "to resample the data from each cycle separately samples =", "6. returns: DataFrame \"\"\" usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth',", "group[colname] = np.random.random(len(group)) < error_rate def FillMissingColumn(group, colname, missing_colname): \"\"\"Fills", "resampled data. resps: list of DataFrames iters: number of resamples", "= df.wgtq1q16 df['cycle'] = 7 CleanResp(df) return df def ReadMaleResp2013():", "(11759-1, 11762), (14-1, 16), (12350-1, 12359), (4713-1, 4713), (4718-1, 4721),", "= survival.EstimateHazardFunction(complete, ongoing) if cutoff: hf.Truncate(cutoff) sf = hf.MakeSurvival() return", "30), (1554-1, 1554), (1565-1, 1569), (1570-1, 1574), (2441-1, 2442), ]", "print('Cycle 10') resp10 = ReadFemResp2017() Validate2017(resp10) print('Cycle 9') resp9 =", "\"\"\" usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'finalwgt',", "df.f18m1.replace([7, 8, 9], np.nan, inplace=True) # CM values above 9000", "married, we need agemarry; if not married, we need age", "= [hf_map[name][0] for name in names] # extend each hazard", "colormap[name] thinkplot.Plot(ts, rows[1], label='%ds'%name, color=color) else: thinkplot.Plot(ts, rows[1], label='%ds'%name) def", "9898, 9999], np.nan, inplace=True) df.cmbirth.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmmarrhx.replace([9797,", "def Validate2015(df): assert(len(df) == 5699) assert(sum(df.evrmarry) == 2401) assert(df.agemarry.value_counts().max() ==", "np.random.random(len(group)) < error_rate def FillMissingColumn(group, colname, missing_colname): \"\"\"Fills missing values", "'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgtq1q16', 'mardat01', 'marend01', 'mardis01', 'rmarital',", "- age_step df.loc[df.age.isnull(), 'age_index'] = np.nan df['agemarry_index'] = np.digitize(df.agemarry, age_bins)", "df['stillma'] = (df.timesmar==1) & (df.marend01.isnull()) df['cycle'] = 5 CleanResp(df) return", "print('Cycle 8') resp8 = ReadFemResp2013() Validate2013(resp8) print('Cycle 7') resp7 =", "\"\"\" \"\"\" #age at first marriage: CC232 #age of respondent", "def Validate2017(df): assert(len(df) == 5554) assert(sum(df.evrmarry) == 2582) assert(df.agemarry.value_counts().max() ==", "list of DataFrames iters: number of resamples to plot predict_flag:", "error_rate: AddErrors(group, 'complete_missing', error_rate) AddErrors(group, 'ongoing_missing', error_rate) # the amount", "column rows = thinkstats2.PercentileRows(ss_seq, percents) return ts, rows def ReadFemResp1982():", "df def ReadMaleResp2013(): \"\"\"Reads respondent data from NSFG Cycle 8.", "1) & (df.rmarital==1) df['finalwgt'] = df.wgtq1q16 df['cycle'] = 7 CleanResp(df)", "& (df.rmarital==1) df['finalwgt'] = df.wgt2013_2015 df['cycle'] = 9 CleanResp(df) return", "of DataFrame returns: DataFrame \"\"\" # we have to resample", "(hf, sf) in hf_map.items(): sf_map[name].append(sf) return sf_map def AddErrors(group, colname,", "8 CleanResp(df) return df def ReadFemResp2015(): \"\"\"Reads respondent data from", "df def ReadFemResp1988(): \"\"\"Reads respondent data from NSFG Cycle 4.", "dct = thinkstats2.ReadStataDct(dct_file, encoding='iso-8859-1') df = dct.ReadFixedWidth(dat_file, compression='gzip', **options) return", "of resamples to plot predict_flag: whether to also plot predictions", "df = dct.ReadFixedWidth(dat_file, compression='gzip', **options) return df def CleanResp(resp): \"\"\"Cleans", "== 5) df['widowed'] = (df.f18m1 == 3) df['stillma'] = (df.fmarno==1)", "= np.arange(age_min, age_max, age_step) year_min = 0 year_max = 120", "NSFG Cycle 8. returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01',", "\"\"\" df[column] += np.random.uniform(-jitter, jitter, size=len(df)) def EstimateSurvival(resp, cutoff=None): \"\"\"Estimates", "len(null) == 0: return # print(len(null), len(group)) valid = group[colname].dropna()", "'wgt2011_2013', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2011_2013_MaleSetup.dct', '2011_2013_MaleData.dat.gz', usecols=usecols)", "group) if error_rate: AddErrors(group, 'complete_missing', error_rate) AddErrors(group, 'ongoing_missing', error_rate) #", "df['widowed'] = (df.f23m1==1) df['stillma'] = (df.fmarno==1) & (df.f23m1.isnull()) df['cycle'] =", "|= set(sf.ts) ts = list(ts) ts.sort() # evaluate each sf", "== 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2015_2017 df['cycle'] = 10", "bins and then assigns an index to each bin. For", "73) def Validate1995(df): assert(len(df) == 10847) assert(len(df[df.evrmarry]) == 6841) assert(df.agemarry.value_counts().max()", "np.nan, inplace=True) #df.cmmarrhx.replace(invalid, np.nan, inplace=True) # since cmbirth and cmmarrhx", "are not identical to the actual respondents if jitter: Jitter(sample,", "inplace=True) df.cmstphsbx.replace(invalid, np.nan, inplace=True) df.timesmar.replace([98, 99], np.nan, inplace=True) df['evrmarry'] =", "= ['finalwgt', 'ageint', 'currentcm', 'firstcm', 'cmintvw', 'cmbirth', 'f23m1', 'cmdivorcx', 'cmstphsbx',", "'cmdivorcx'] -= 90000 df.loc[df.cmstphsbx>90000, 'cmstphsbx'] -= 90000 # combine current", "map from group name to sequence of survival functions predict_flag:", "thinkplot import survival def ResampleResps(resps, remove_missing=False, jitter=0): \"\"\"Resamples each dataframe", "really confusing, # but it looks like marrend4 is the", "each percent \"\"\" # find the union of all ts", "year_step def ReadCanadaCycle5(): \"\"\" \"\"\" #age at first marriage: CC232", "thinkplot.Plot(ts, rows[1], label='%ds'%name) def MakePredictions(hf_map): \"\"\"Extends a set of hazard", "df def ReadFemResp1995(): \"\"\"Reads respondent data from NSFG Cycle 5.", "# but it looks like marrend4 is the end of", "the previous cohort, # and update the survival function for", "then concats them. resps: list of DataFrame returns: DataFrame \"\"\"", "jitter=jitter) Jitter(sample, 'agemarry', jitter=jitter) DigitizeResp(resp) return sample def ResampleRowsWeighted(df, column='finalwgt'):", "set(sf.ts) ts = list(ts) ts.sort() # evaluate each sf at", "cutoff: hf.Truncate(cutoff) sf = hf.MakeSurvival() return hf, sf def PropensityMatch(target,", "'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2013_2015_FemRespSetup.dct', '2013_2015_FemRespData.dat.gz', usecols=usecols)", "= (df.fmarno==1) & (df.fmarital==1) df['cycle'] = 3 CleanResp(df) return df", "resp['year'] = (pd.DatetimeIndex(dates).year - 1900) #resp['decade'] = resp.year // 10", "'evrmarry', 'wgt2015_2017', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2015_2017_MaleSetup.dct', '2015_2017_MaleData.dat.gz',", "group[colname].fillna(fill, inplace=True) def PlotSurvivalFunctions(sf_map, predict_flag=False, colormap=None): \"\"\"Plot estimated survival functions.", "[9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) #df.cmbirth.replace(invalid, np.nan, inplace=True) #df.cmmarrhx.replace(invalid,", "dct.ReadFixedWidth(dat_file, compression='gzip', **options) return df def CleanResp(resp): \"\"\"Cleans a respondent", "returns: DataFrame with sample of rows from `group` \"\"\" rv", "== 79) def Validate2002(df): assert(len(df) == 7643) assert(sum(df.evrmarry) == 4126)", "= 6 CleanResp(df) return df def ReadFemResp2010(): \"\"\"Reads respondent data", "DataFrame \"\"\" weights = df['finalwgt'].copy() weights /= sum(weights) indices =", "NSFG Cycle 3. returns: DataFrame \"\"\" dat_file = '1982NSFGData.dat.gz' names", "EstimateSurvivalByCohort(resps, iters=101, cutoffs=None, predict_flag=False, prop_match=None, error_rate=0): \"\"\"Makes survival curves for", "for each percent \"\"\" # find the union of all", "and update the survival function for i, name in enumerate(names):", "#df.marrend6.replace([8,9], np.nan, inplace=True) df.timesmar.replace([98,99], np.nan, inplace=True) # the way marriage", "pd.DateOffset(months=cm) for cm in resp.cmbirth] resp['year'] = (pd.DatetimeIndex(dates).year - 1900)", "def ResampleResps(resps, remove_missing=False, jitter=0): \"\"\"Resamples each dataframe and then concats", "[ChooseIndex(value) for value in target[colname]] return group.loc[indices] def EstimateSurvivalByCohort(resps, iters=101,", "OrderedDict() for name, group in iter(grouped): if prop_match: group =", "'complete_missing', error_rate) AddErrors(group, 'ongoing_missing', error_rate) # the amount of missing", "'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgt2013_2015', 'marend01', 'rmarital', 'fmarno', 'mar1diss']", "random data #FillMissingColumn(group, 'complete_var', 'complete_missing') #FillMissingColumn(group, 'ongoing_var', 'ongoing_missing') cutoff =", "colspecs = [(976-1, 982), (1001-1, 1002), (1268-1, 1271), (1037-1, 1040),", "'evrmarry', 'parity', 'finalwgt', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df", "0) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3)", "name dat_file: string file name returns: DataFrame \"\"\" dct =", "df = ReadResp('2006_2010_MaleSetup.dct', '2006_2010_Male.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry'] =", "0: continue sf = sf_seq[0] if len(sf) == 0: continue", "to make for i in range(iters): sample = ResampleResps(resps) #", "hf_map, we extend hf and recompute sf. hf_map: map from", "np.nan, inplace=True) df.f18m1.replace([7, 8, 9], np.nan, inplace=True) # CM values", "['caseid', 'cmintvw', 'ager', 'evrmarry', 'parity', 'wgt2015_2017', 'mardat01', 'marend01', 'mardis01', 'rmarital',", "inplace=True) df.cmstphsbx.replace([9797, 9898, 9999], np.nan, inplace=True) df.f18m1.replace([7, 8, 9], np.nan,", "12359), (4713-1, 4713), (4718-1, 4721), (4722-1, 4725), (17-1, 17)] df", "np.where(df.evrmarry, df.agemarry.isnull(), df.age.isnull()) month0 = pd.to_datetime('1899-12-15') dates = [month0 +", "== 5554) assert(sum(df.evrmarry) == 2582) assert(df.agemarry.value_counts().max() == 29) def main():", "df.loc[df.cmstphsbx>90000, 'cmstphsbx'] -= 90000 # combine current and first marriage", "age_bins = np.arange(age_min, age_max, age_step) year_min = 0 year_max =", "len(sf_seq) == 0: continue sf = sf_seq[0] if len(sf) ==", "CC227 pass def ReadMaleResp2002(): \"\"\"Reads respondent data from NSFG Cycle", "respondent data from NSFG Cycle 10. returns: DataFrame \"\"\" #", "= valid.sample(len(null), replace=True) fill.index = null.index group[colname].fillna(fill, inplace=True) def PlotSurvivalFunctions(sf_map,", "df.mardat01 df['evrmarry'] = (df.timesmar > 0) df['divorced'] = (df.marend01==2) |", "1) & (df.rmarital==1) df['cycle'] = 6 CleanResp(df) return df def", "collections import OrderedDict from collections import Counter import thinkstats2 import", "variables into bins and then assigns an index to each", "if len(sf) > 0] # return the requested percentiles from", "ReadFemResp2002() Validate2002(resp6) print('Cycle 5') resp5 = ReadFemResp1995() Validate1995(resp5) print('Cycle 4')", "enumerate(names): hf, sf = hf_map[name] if i > 0: hf.Extend(hfs[i-1])", "'f23m1', 'cmdivorcx', 'cmstphsbx', 'fmarno'] colspecs = [(2568-1, 2574), (36-1, 37),", "'cmintvw', 'ager', 'evrmarry', 'parity', 'wgt2015_2017', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno',", "Jitter(sample, 'agemarry', jitter=jitter) DigitizeResp(resp) return sample def ResampleRowsWeighted(df, column='finalwgt'): \"\"\"Resamples", "= np.where(df.evrmarry, df.agemarry.isnull(), df.age.isnull()) month0 = pd.to_datetime('1899-12-15') dates = [month0", "resp in resps] # then join the cycles into one", "= 0 year_max = 120 year_step = 10 year_bins =", "(14-1, 16), (12350-1, 12359), (4713-1, 4713), (4718-1, 4721), (4722-1, 4725),", "Groups each of these variables into bins and then assigns", "'cmintvw'] -= 90000 df.loc[df.cmbirth>90000, 'cmbirth'] -= 90000 df.loc[df.firstcm>90000, 'firstcm'] -=", "\"\"\"Computes indices for age, agemarry, and birth year. Groups each", "is the number of resampling runs to make for i", "return df def ReadFemResp2002(): \"\"\"Reads respondent data from NSFG Cycle", "\"\"\"Reads respondent data from NSFG Cycle 5. returns: DataFrame \"\"\"", "weights = df['finalwgt'].copy() weights /= sum(weights) indices = np.random.choice(df.index, len(df),", "(df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.timesmar==1)", "#age of respondent at interview: C3 #final weight: C1 #marital", "column. group: DataFrame colname: string \"\"\" null = group[group[missing_colname]] if", "-= 9000 df.loc[df.cmstphsbx>9000, 'cmstphsbx'] -= 9000 df['evrmarry'] = (df.fmarno >", "error_rate) AddErrors(group, 'ongoing_missing', error_rate) # the amount of missing data", "year_bins) * year_step df.birth_index += year_min - year_step def ReadCanadaCycle5():", "df[column] += np.random.uniform(-jitter, jitter, size=len(df)) def EstimateSurvival(resp, cutoff=None): \"\"\"Estimates the", "make predictions if desired if predict_flag: MakePredictions(hf_map) # extract the", "(df.f18m1 == 5) df['widowed'] = (df.f18m1 == 3) df['stillma'] =", "9000 indicate month unknown df.loc[df.cmintvw>90000, 'cmintvw'] -= 90000 df.loc[df.cmbirth>90000, 'cmbirth']", "= sample[~sample.missing] # jittering the ages reflects the idea that", "import thinkplot import survival def ResampleResps(resps, remove_missing=False, jitter=0): \"\"\"Resamples each", "4) df['separated'] = (df.f18m1 == 5) df['widowed'] = (df.f18m1 ==", "df.firstcm.replace([0, 99999], np.nan, inplace=True) df.currentcm.replace([0, 99999], np.nan, inplace=True) df.cmdivorcx.replace([0, 99999],", "resp.year // 5 DigitizeResp(resp) def DigitizeResp(df): \"\"\"Computes indices for age,", "resp8 = ReadFemResp2013() Validate2013(resp8) print('Cycle 7') resp7 = ReadFemResp2010() Validate2010(resp7)", "df['stillma'] = (df.fmarno==1) & (df.f23m1.isnull()) df['cycle'] = 4 CleanResp(df) return", "df.timesmar.replace([98, 99], np.nan, inplace=True) df['evrmarry'] = (df.timesmar > 0) df['divorced']", "Cycle 5. returns: DataFrame \"\"\" dat_file = '1995FemRespData.dat.gz' names =", "sample def ResampleRowsWeighted(df, column='finalwgt'): \"\"\"Resamples the rows in df in", "and first marriage df['cmmarrhx'] = df.firstcm df.cmmarrhx.fillna(df.currentcm, inplace=True) # define", "age_min - age_step df.loc[df.agemarry.isnull(), 'agemarry_index'] = np.nan df['birth_index'] = np.digitize(df.year,", "df['cycle'] = 9 CleanResp(df) return df def ReadMaleResp2017(): \"\"\"Reads respondent", "percents: list of percentiles to select, like [5, 95] returns:", "df def ReadFemResp2010(): \"\"\"Reads respondent data from NSFG Cycle 7.", "resp.loc[resp.complete, 'complete_var'].dropna() ongoing = resp.loc[~resp.complete, 'ongoing_var'].dropna() hf = survival.EstimateHazardFunction(complete, ongoing)", "first marriage df['cmmarrhx'] = df.firstcm df.cmmarrhx.fillna(df.currentcm, inplace=True) # define evrmarry", "90000 df.loc[df.firstcm>90000, 'firstcm'] -= 90000 df.loc[df.currentcm>90000, 'currentcm'] -= 90000 df.loc[df.cmdivorcx>90000,", "cutoff: where to truncate the estimated functions returns: pair of", "1) & (df.rmarital==1) df['finalwgt'] = df.wgt2015_2017 df['cycle'] = 10 #", "inplace=True) #df.marrend6.replace([8,9], np.nan, inplace=True) df.timesmar.replace([98,99], np.nan, inplace=True) # the way", "if cutoffs == None: cutoffs = {} sf_map = defaultdict(list)", "data from the previous cohort, # and update the survival", "we extend hf and recompute sf. hf_map: map from group", "# the amount of missing data is small; I think", "CleanResp(df) return df def ReadFemResp2010(): \"\"\"Reads respondent data from NSFG", "100) hf_map[name] = EstimateSurvival(group, cutoff) # make predictions if desired", "'mar1diss'] df = ReadResp('2011_2013_MaleSetup.dct', '2011_2013_MaleData.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry']", "5) df['widowed'] = (df.f18m1 == 3) df['stillma'] = (df.fmarno==1) &", "ReadResp('2013_2015_FemRespSetup.dct', '2013_2015_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan,", "extend each hazard function using data from the previous cohort,", "number of resampling runs to make for i in range(iters):", "in resp.cmbirth] resp['year'] = (pd.DatetimeIndex(dates).year - 1900) #resp['decade'] = resp.year", "np.digitize(df.age, age_bins) * age_step df.age_index += age_min - age_step df.loc[df.age.isnull(),", "['finalwgt', 'ageint', 'mar2p', 'cmmarrhx', 'fmarital', 'cmintvw', 'cmbirth', 'f18m1', 'cmdivorcx', 'cmstphsbx',", "we need age resp['missing'] = np.where(resp.evrmarry, resp.agemarry.isnull(), resp.age.isnull()) month0 =", "df.cmbirth.replace([0, 99999], np.nan, inplace=True) df.firstcm.replace([0, 99999], np.nan, inplace=True) df.currentcm.replace([0, 99999],", "label='%ds'%name) def MakePredictions(hf_map): \"\"\"Extends a set of hazard functions and", "with a weight column. df: DataFrame returns: DataFrame \"\"\" weights", "np.nan, inplace=True) df.cmstphsbx.replace([9797, 9898, 9999], np.nan, inplace=True) df.f18m1.replace([7, 8, 9],", "#final weight: C1 #marital status: C5 #Respondent every married: CC227", "License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html \"\"\" from __future__ import print_function, division", "Cycle 4. Read as if were a standard ascii file", "90]) thinkplot.FillBetween(ts, rows[0], rows[2], color='gray', alpha=0.2) if not predict_flag: if", "'agemarry', jitter=jitter) DigitizeResp(resp) return sample def ResampleRowsWeighted(df, column='finalwgt'): \"\"\"Resamples the", "recomputes survival functions. For each group in hf_map, we extend", "+= age_min - age_step df.loc[df.agemarry.isnull(), 'agemarry_index'] = np.nan df['birth_index'] =", "group by decade grouped = sample.groupby('birth_index') if prop_match: last =", "'fmarno', 'mar1diss'] df = ReadResp('2013_2015_FemRespSetup.dct', '2013_2015_FemRespData.dat.gz', usecols=usecols) invalid = [9997,", "'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2006_2010_FemRespSetup.dct', '2006_2010_FemResp.dat.gz', usecols=usecols) invalid", "from __future__ import print_function, division import bisect import numpy as", "> 0) df['divorced'] = (df.f23m1==2) df['separated'] = (df.f23m1==3) df['widowed'] =", "rows contains one row of values for each percent \"\"\"", "values above 9000 indicate month unknown df.loc[df.cmintvw>90000, 'cmintvw'] -= 90000", "weights /= sum(weights) indices = np.random.choice(df.index, len(df), replace=True, p=weights) return", "rv = scipy.stats.norm(scale=1) values = group[colname].fillna(100) def ChooseIndex(value): weights =", "predict_flag: whether to also plot predictions cutoffs: map from cohort", "return the requested percentiles from each column rows = thinkstats2.PercentileRows(ss_seq,", "usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'finalwgt',", "12.0 # if married, we need agemarry; if not married,", "+ pd.DateOffset(months=cm) for cm in resp.cmbirth] resp['year'] = (pd.DatetimeIndex(dates).year -", "33) def Validate2015(df): assert(len(df) == 5699) assert(sum(df.evrmarry) == 2401) assert(df.agemarry.value_counts().max()", "np.nan, inplace=True) df.firstcm.replace([0, 99999], np.nan, inplace=True) df.currentcm.replace([0, 99999], np.nan, inplace=True)", "9], np.nan, inplace=True) # CM values above 9000 indicate month", "pd.to_datetime('1899-12-15') dates = [month0 + pd.DateOffset(months=cm) for cm in df.cmbirth]", "need age resp['missing'] = np.where(resp.evrmarry, resp.agemarry.isnull(), resp.age.isnull()) month0 = pd.to_datetime('1899-12-15')", "= ResampleResps(resps) # group by decade grouped = sample.groupby('birth_index') if", "indicate month unknown df.loc[df.cmintvw>9000, 'cmintvw'] -= 9000 df.loc[df.cmbirth>9000, 'cmbirth'] -=", "confusing, # but it looks like marrend4 is the end", "fill.index = null.index group[colname].fillna(fill, inplace=True) def PlotSurvivalFunctions(sf_map, predict_flag=False, colormap=None): \"\"\"Plot", "0) df['divorced'] = (df.f18m1 == 4) df['separated'] = (df.f18m1 ==", "= pd.read_fwf(filename, colspecs=colspecs, names=names, header=None, compression='gzip') df.cmintvw.replace([0, 99999], np.nan, inplace=True)", "# return the requested percentiles from each column rows =", "(1570-1, 1574), (2441-1, 2442), ] df = pd.read_fwf(filename, colspecs=colspecs, names=names,", "columns: agemarry, age, decade, fives \"\"\" resp['agemarry'] = (resp.cmmarrhx -", "df['finalwgt'].copy() weights /= sum(weights) indices = np.random.choice(df.index, len(df), replace=True, p=weights)", "7 CleanResp(df) return df def ReadFemResp2013(): \"\"\"Reads respondent data from", "marrend5', 'marrend6', ] df = ReadResp('2002Male.dct', '2002Male.dat.gz', usecols=usecols) #df.marrend.replace([8,9], np.nan,", "df: DataFrame column: string column name jitter: standard deviation of", "= pd.to_datetime('1899-12-15') dates = [month0 + pd.DateOffset(months=cm) for cm in", "For example, anyone between 30 and 30.99 year old is", "= ['cmintvw', 'timesmar', 'cmmarrhx', 'cmbirth', 'finalwgt', 'marend01', 'cmdivorcx', 'cmstphsbx', 'marstat']", "= ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'finalwgt', 'fmarit', 'timesmar',", "(df.f18m1 == 3) df['stillma'] = (df.fmarno==1) & (df.fmarital==1) df['cycle'] =", "<NAME>, available from greenteapress.com Copyright 2014 <NAME> License: GNU GPLv3", "\"\"\"Reads respondent data from NSFG Cycle 9. returns: DataFrame \"\"\"", "DataFrame. resp: DataFrame of respondents Adds columns: agemarry, age, decade,", "= np.nan df['birth_index'] = np.digitize(df.year, year_bins) * year_step df.birth_index +=", "column. df: DataFrame returns: DataFrame \"\"\" weights = df['finalwgt'].copy() weights", "names=names, header=None, nrows=7969, compression='gzip') df.cmintvw.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmbirth.replace([9797,", "def ReadFemResp2013(): \"\"\"Reads respondent data from NSFG Cycle 8. returns:", "5290) assert(df.agemarry.value_counts().max() == 73) def Validate1995(df): assert(len(df) == 10847) assert(len(df[df.evrmarry])", "CM values above 9000 indicate month unknown df.loc[df.cmintvw>9000, 'cmintvw'] -=", "df def ReadFemResp2013(): \"\"\"Reads respondent data from NSFG Cycle 8.", "hf.MakeSurvival() return hf, sf def PropensityMatch(target, group, colname='agemarry'): \"\"\"Choose a", "DataFrame \"\"\" usecols = ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry',", "# we have to compute them based on other variables;", "dct_file: string file name dat_file: string file name returns: DataFrame", "age, agemarry, and birth year. Groups each of these variables", "functions. sf_seq: list of SurvivalFunction percents: list of percentiles to", "ts.sort() # evaluate each sf at all times ss_seq =", "inplace=True) df.timesmar.replace([98, 99], np.nan, inplace=True) df['evrmarry'] = (df.timesmar > 0)", "it looks like marrend4 is the end of the first", "Validate2002(resp6) print('Cycle 5') resp5 = ReadFemResp1995() Validate1995(resp5) print('Cycle 4') resp4", "= (df.timesmar > 0) df['divorced'] = (df.marend01==2) | (df.marend01==3) df['separated']", "\"Think Stats\", by <NAME>, available from greenteapress.com Copyright 2014 <NAME>", "pd.to_datetime('1899-12-15') dates = [month0 + pd.DateOffset(months=cm) for cm in resp.cmbirth]", "\"\"\" resp['agemarry'] = (resp.cmmarrhx - resp.cmbirth) / 12.0 resp['age'] =", "'wgt2011_2013', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2011_2013_FemRespSetup.dct',", "to compute them based on other variables; # the result", "the way marriage ends are recorded is really confusing, #", "df['divorced'] = (df.f23m1==2) df['separated'] = (df.f23m1==3) df['widowed'] = (df.f23m1==1) df['stillma']", "'2002Male.dat.gz', usecols=usecols) #df.marrend.replace([8,9], np.nan, inplace=True) #df.marrend2.replace([8,9], np.nan, inplace=True) #df.marrend3.replace([8,9], np.nan,", "colspecs=colspecs, names=names) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True)", "thinkplot.FillBetween(ts, rows[0], rows[2], color='gray', alpha=0.2) if not predict_flag: if colormap:", "= (df.f18m1 == 3) df['stillma'] = (df.fmarno==1) & (df.fmarital==1) df['cycle']", "standard deviation of noise \"\"\" df[column] += np.random.uniform(-jitter, jitter, size=len(df))", "= (df.timesmar==1) & (df.marend01.isnull()) df['cycle'] = 5 CleanResp(df) return df", "of these variables into bins and then assigns an index", "\"\"\" filename = '1988FemRespDataLines.dat.gz' names = ['finalwgt', 'ageint', 'currentcm', 'firstcm',", "people with unknown marriage dates if remove_missing: sample = sample[~sample.missing]", "each hazard function using data from the previous cohort, #", "\"\"\"Extends a set of hazard functions and recomputes survival functions.", "Validate1995(df): assert(len(df) == 10847) assert(len(df[df.evrmarry]) == 6841) assert(df.agemarry.value_counts().max() == 79)", "from group name to sequence of survival functions predict_flag: whether", "# the way marriage ends are recorded is really confusing,", "55 age_step = 1 age_bins = np.arange(age_min, age_max, age_step) year_min", "df['year'] = (pd.DatetimeIndex(dates).year - 1900) DigitizeResp(df) return df def Validate1982(df):", "1, p=weights)[0] indices = [ChooseIndex(value) for value in target[colname]] return", "FillMissingColumn(group, colname, missing_colname): \"\"\"Fills missing values of the given column.", "DataFrame \"\"\" # we have to resample the data from", "import numpy as np import pandas as pd import scipy.stats", "ongoing) if cutoff: hf.Truncate(cutoff) sf = hf.MakeSurvival() return hf, sf", "'cmdivorcx', 'cmstphsbx', 'marstat'] colspecs = [(12360-1, 12363), (4637-1, 4638), (11759-1,", "= ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgtq1q16', 'mardat01',", "ascii file returns: DataFrame \"\"\" filename = '1988FemRespDataLines.dat.gz' names =", "is assigned age_index 30. Anyone born in the 80s is", "for use with \"Think Stats\", by <NAME>, available from greenteapress.com", "\"\"\"Choose a random subset of `group` to matches propensity with", "df.cmdivorcx.replace([0, 99999], np.nan, inplace=True) df.cmstphsbx.replace([0, 99999], np.nan, inplace=True) # CM", "'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2011_2013_MaleSetup.dct', '2011_2013_MaleData.dat.gz', usecols=usecols) df['cmmarrhx']", "in df in accordance with a weight column. df: DataFrame", "/ 12.0 # if married, we need agemarry; if not", "curves for resampled data. resps: list of DataFrames iters: number", "def ReadFemResp2015(): \"\"\"Reads respondent data from NSFG Cycle 9. returns:", "(df.marend01==1) df['stillma'] = (df.timesmar== 1) & (df.fmarit==1) df['cycle'] = 6", "prop_match=None, error_rate=0): \"\"\"Makes survival curves for resampled data. resps: list", "DataFrame colname: string \"\"\" null = group[group[missing_colname]] if len(null) ==", "the 80s is given the year_index 80. This function allows", "sequence of survival functions predict_flag: whether the lines are predicted", "them based on other variables; # the result can be", "name, sf_seq in sorted(sf_map.items(), reverse=True): if len(sf_seq) == 0: continue", "= group[group[missing_colname]] if len(null) == 0: return # print(len(null), len(group))", "if error_rate: AddErrors(group, 'complete_missing', error_rate) AddErrors(group, 'ongoing_missing', error_rate) # the", "will not work if there are actual missing values! \"\"\"", "a column. df: DataFrame column: string column name jitter: standard", "and recomputes survival functions. For each group in hf_map, we", "= (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2013_2015 df['cycle']", "of survival functions predict_flag: whether the lines are predicted or", "= thinkstats2.ReadStataDct(dct_file, encoding='iso-8859-1') df = dct.ReadFixedWidth(dat_file, compression='gzip', **options) return df", "Validate1995(resp5) print('Cycle 4') resp4 = ReadFemResp1988() Validate1988(resp4) print('Cycle 3') resp3", "import gzip import matplotlib.pyplot as plt from collections import defaultdict", "(df.marend01==3) df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] =", "= ReadResp('2006_2010_FemRespSetup.dct', '2006_2010_FemResp.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid,", "with different levels of granularity. df: DataFrame \"\"\" age_min =", "data. resps: list of DataFrames iters: number of resamples to", "Jitter(df, column, jitter=1): \"\"\"Adds random noise to a column. df:", "len(group)) valid = group[colname].dropna() fill = valid.sample(len(null), replace=True) fill.index =", "= cutoffs.get(name, 100) hf_map[name] = EstimateSurvival(group, cutoff) # make predictions", "set of hazard functions and recomputes survival functions. For each", "CleanResp, we have to customize #CleanResp(df) df['agemarry'] = (df.cmmarrhx -", "between 30 and 30.99 year old is assigned age_index 30.", "#FillMissingColumn(group, 'complete_var', 'complete_missing') #FillMissingColumn(group, 'ongoing_var', 'ongoing_missing') cutoff = cutoffs.get(name, 100)", "for cm in resp.cmbirth] resp['year'] = (pd.DatetimeIndex(dates).year - 1900) #resp['decade']", "5554) assert(sum(df.evrmarry) == 2582) assert(df.agemarry.value_counts().max() == 29) def main(): print('Cycle", "values = group[colname].fillna(100) def ChooseIndex(value): weights = rv.pdf(values-value) weights /=", "\"\"\" #age at first marriage: CC232 #age of respondent at", "'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2002FemResp.dct', '2002FemResp.dat.gz', usecols=usecols)", "'complete_var'].dropna() ongoing = resp.loc[~resp.complete, 'ongoing_var'].dropna() hf = survival.EstimateHazardFunction(complete, ongoing) if", "random noise to a column. df: DataFrame column: string column", "work if there are actual missing values! \"\"\" group[colname] =", "compression='gzip') df.cmintvw.replace([0, 99999], np.nan, inplace=True) df.cmbirth.replace([0, 99999], np.nan, inplace=True) df.firstcm.replace([0,", "unknown df.loc[df.cmintvw>90000, 'cmintvw'] -= 90000 df.loc[df.cmbirth>90000, 'cmbirth'] -= 90000 df.loc[df.firstcm>90000,", "return df def ReadMaleResp2010(): \"\"\"Reads respondent data from NSFG Cycle", "== 71) def Validate1988(df): assert(len(df) == 8450) assert(len(df[df.evrmarry]) == 5290)", "last = grouped.get_group(prop_match) # and estimate (hf, sf) for each", "(4713-1, 4713), (4718-1, 4721), (4722-1, 4725), (17-1, 17)] df =", "in target[colname]] return group.loc[indices] def EstimateSurvivalByCohort(resps, iters=101, cutoffs=None, predict_flag=False, prop_match=None,", "4638), (11759-1, 11762), (14-1, 16), (12350-1, 12359), (4713-1, 4713), (4718-1,", "df['cycle'] = 10 # Instead of calling CleanResp, we have", "== 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2011_2013 df['cycle'] = 8", "survival curve. resp: DataFrame of respondents cutoff: where to truncate", "return # print(len(null), len(group)) valid = group[colname].dropna() fill = valid.sample(len(null),", "def EstimateSurvival(resp, cutoff=None): \"\"\"Estimates the survival curve. resp: DataFrame of", "(df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.fmarno", "= '1982NSFGData.dat.gz' names = ['finalwgt', 'ageint', 'mar2p', 'cmmarrhx', 'fmarital', 'cmintvw',", "sf from each pair and accumulate the results for name,", "unreliable age_index returns: map from group name to list of", "df in accordance with a weight column. df: DataFrame returns:", "inplace=True) df.marrend4.replace([8,9], np.nan, inplace=True) #df.marrend5.replace([8,9], np.nan, inplace=True) #df.marrend6.replace([8,9], np.nan, inplace=True)", "pair and accumulate the results for name, (hf, sf) in", "df = ReadResp('2011_2013_FemRespSetup.dct', '2011_2013_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999]", "a respondent DataFrame. resp: DataFrame of respondents Adds columns: agemarry,", "sf = hf_map[name] if i > 0: hf.Extend(hfs[i-1]) sf =", "month unknown df.loc[df.cmintvw>9000, 'cmintvw'] -= 9000 df.loc[df.cmbirth>9000, 'cmbirth'] -= 9000", "'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2015_2017_FemRespSetup.dct', '2015_2017_FemRespData.dat.gz',", "3) df['stillma'] = (df.fmarno==1) & (df.fmarital==1) df['cycle'] = 3 CleanResp(df)", "currentcm or firstcm is non-zero df['evrmarry'] = (df.fmarno > 0)", "from NSFG Cycle 7. returns: DataFrame \"\"\" usecols = ['caseid',", "'evrmarry', 'wgt2013_2015', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2013_2015_MaleSetup.dct', '2013_2015_MaleData.dat.gz',", "'cmmarrhx', 'cmbirth', 'finalwgt', 'marend01', 'cmdivorcx', 'cmstphsbx', 'marstat'] colspecs = [(12360-1,", "Cycle 6. returns: DataFrame \"\"\" usecols = ['caseid', 'cmmarrhx', 'cmdivorcx',", "[hf_map[name][0] for name in names] # extend each hazard function", "'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgt2011_2013', 'mardat01', 'marend01', 'mardis01',", "greenteapress.com Copyright 2014 <NAME> License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html \"\"\" from", "from NSFG Cycle 3. returns: DataFrame \"\"\" dat_file = '1982NSFGData.dat.gz'", "'cmintvw', 'ager', 'evrmarry', 'wgt2015_2017', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df =", "== 4126) assert(df.agemarry.value_counts().max() == 45) def Validate2010(df): assert(len(df) == 12279)", "10 year_bins = np.arange(year_min, year_max, year_step) df['age_index'] = np.digitize(df.age, age_bins)", "ReadMaleResp2002(): \"\"\"Reads respondent data from NSFG Cycle 6. returns: DataFrame", "desired if predict_flag: MakePredictions(hf_map) # extract the sf from each", "rows[0], rows[2], color='gray', alpha=0.2) if not predict_flag: if colormap: color", "whether to also plot predictions cutoffs: map from cohort to", "\"\"\"Reads respondent data from NSFG Cycle 8. returns: DataFrame \"\"\"", "np.nan, inplace=True) df.cmbirth.replace(invalid, np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df['evrmarry'] =", "'cmdivorcx', 'cmstphsbx', 'fmarno'] colspecs = [(976-1, 982), (1001-1, 1002), (1268-1,", "is the end of the first marriage. df['marend01'] = df.marrend4", "6841) assert(df.agemarry.value_counts().max() == 79) def Validate2002(df): assert(len(df) == 7643) assert(sum(df.evrmarry)", "2452) assert(df.agemarry.value_counts().max() == 33) def Validate2015(df): assert(len(df) == 5699) assert(sum(df.evrmarry)", "one row of values for each percent \"\"\" # find", "df.marrend4.replace([8,9], np.nan, inplace=True) #df.marrend5.replace([8,9], np.nan, inplace=True) #df.marrend6.replace([8,9], np.nan, inplace=True) df.timesmar.replace([98,99],", "`target`. target: DataFrame group: DataFrame colname: string name of column", "'mar1diss'] df = ReadResp('2013_2015_FemRespSetup.dct', '2013_2015_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998,", "= np.random.choice(df.index, len(df), replace=True, p=weights) return df.loc[indices] def Jitter(df, column,", "evaluated ts = set() for sf in sf_seq: ts |=", "#marital status: C5 #Respondent every married: CC227 pass def ReadCanadaCycle6():", "colname, missing_colname): \"\"\"Fills missing values of the given column. group:", "606), (619-1, 622), (625-1, 628), (1142-1, 1143), ] df =", "df['separated'] = (df.f18m1 == 5) df['widowed'] = (df.f18m1 == 3)", "= [ChooseIndex(value) for value in target[colname]] return group.loc[indices] def EstimateSurvivalByCohort(resps,", "hf_map = OrderedDict() for name, group in iter(grouped): if prop_match:", "name to sequence of survival functions predict_flag: whether the lines", "'age', jitter=jitter) Jitter(sample, 'agemarry', jitter=jitter) DigitizeResp(resp) return sample def ResampleRowsWeighted(df,", "is better # to drop it than to fill with", "'evrmarry', 'parity', 'wgt2013_2015', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df", "HazardFunction, SurvivalFunction \"\"\" complete = resp.loc[resp.complete, 'complete_var'].dropna() ongoing = resp.loc[~resp.complete,", "of values for each percent \"\"\" # find the union", "4126) assert(df.agemarry.value_counts().max() == 45) def Validate2010(df): assert(len(df) == 12279) assert(sum(df.evrmarry)", "= resp.year // 10 #resp['fives'] = resp.year // 5 DigitizeResp(resp)", "= 10 # Instead of calling CleanResp, we have to", "if there are actual missing values! \"\"\" group[colname] = np.random.random(len(group))", "'fmarno'] colspecs = [(976-1, 982), (1001-1, 1002), (1268-1, 1271), (1037-1,", "no longer included, # we have to compute them based", "(df.rmarital==1) df['finalwgt'] = df.wgt2015_2017 df['cycle'] = 10 # Instead of", "CleanResp(resp): \"\"\"Cleans a respondent DataFrame. resp: DataFrame of respondents Adds", "(df.rmarital==1) df['cycle'] = 6 CleanResp(df) return df def ReadFemResp2010(): \"\"\"Reads", "-= 90000 df.loc[df.cmdivorcx>90000, 'cmdivorcx'] -= 90000 df.loc[df.cmstphsbx>90000, 'cmstphsbx'] -= 90000", "def ReadFemResp1988(): \"\"\"Reads respondent data from NSFG Cycle 4. Read", "4. Read as if were a standard ascii file returns:", "def ReadFemResp1982(): \"\"\"Reads respondent data from NSFG Cycle 3. returns:", "= df.wgt2013_2015 df['cycle'] = 9 CleanResp(df) return df def ReadMaleResp2017():", "np.nan, inplace=True) df['evrmarry'] = (df.timesmar > 0) df['divorced'] = (df.marend01==1)", "not predict_flag: if colormap: color = colormap[name] thinkplot.Plot(ts, rows[1], label='%ds'%name,", "data from NSFG Cycle 9. returns: DataFrame \"\"\" usecols =", "from group name to list of survival functions \"\"\" if", "# remove married people with unknown marriage dates if remove_missing:", "inplace=True) df.cmdivorcx.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmstphsbx.replace([9797, 9898, 9999], np.nan,", "ReadResp('2015_2017_FemRespSetup.dct', '2015_2017_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan,", "into one big sample sample = pd.concat(samples, ignore_index=True, sort=False) #", "hf_map[name] = hf, sf def MakeSurvivalCI(sf_seq, percents): \"\"\"Makes confidence intervals", "# and update the survival function for i, name in", "age, decade, fives \"\"\" resp['agemarry'] = (resp.cmmarrhx - resp.cmbirth) /", "df def ReadMaleResp2010(): \"\"\"Reads respondent data from NSFG Cycle 7.", "data from NSFG Cycle 3. returns: DataFrame \"\"\" dat_file =", "of column with propensity scores returns: DataFrame with sample of", "9000 df.loc[df.cmmarrhx>9000, 'cmmarrhx'] -= 9000 df.loc[df.cmdivorcx>9000, 'cmdivorcx'] -= 9000 df.loc[df.cmstphsbx>9000,", "'2006_2010_Male.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.evrmarry==1) df['divorced'] =", "ReadFemResp2013(): \"\"\"Reads respondent data from NSFG Cycle 8. returns: DataFrame", "print('Cycle 7') resp7 = ReadFemResp2010() Validate2010(resp7) print('Cycle 6') resp6 =", "= df.wgt2015_2017 df['cycle'] = 10 # Instead of calling CleanResp,", "import pandas as pd import scipy.stats import gzip import matplotlib.pyplot", "NSFG Cycle 9. returns: DataFrame \"\"\" usecols = ['caseid', 'cmmarrhx',", "the given column. group: DataFrame colname: string \"\"\" null =", "def PlotSurvivalFunctions(sf_map, predict_flag=False, colormap=None): \"\"\"Plot estimated survival functions. sf_map: map", "resp.cmbirth) / 12.0 # if married, we need agemarry; if", "color = colormap[name] thinkplot.Plot(ts, rows[1], label='%ds'%name, color=color) else: thinkplot.Plot(ts, rows[1],", "remove married people with unknown marriage dates if remove_missing: sample", "df.wgt2013_2015 df['cycle'] = 9 CleanResp(df) return df def ReadMaleResp2017(): \"\"\"Reads", "allows me to run the analysis with different levels of", "1) & (df.rmarital==1) df['finalwgt'] = df.wgt2013_2015 df['cycle'] = 9 CleanResp(df)", "df['widowed'] = (df.marend01==3) df['stillma'] = (df.fmarno == 1) & (df.rmarital==1)", "print('Cycle 3') resp3 = ReadFemResp1982() Validate1982(resp3) if __name__ == '__main__':", "names = ['finalwgt', 'ageint', 'currentcm', 'firstcm', 'cmintvw', 'cmbirth', 'f23m1', 'cmdivorcx',", "& (df.rmarital==1) df['finalwgt'] = df.wgtq1q16 df['cycle'] = 7 CleanResp(df) return", "def ReadResp(dct_file, dat_file, **options): \"\"\"Reads the NSFG respondent data. dct_file:", "(625-1, 628), (1142-1, 1143), ] df = pd.read_fwf(dat_file, colspecs=colspecs, names=names,", "df.cmintvw.replace([0, 99999], np.nan, inplace=True) df.cmbirth.replace([0, 99999], np.nan, inplace=True) df.firstcm.replace([0, 99999],", "colormap=None): \"\"\"Plot estimated survival functions. sf_map: map from group name", "'cmbirth', 'cmintvw', 'evrmarry', 'wgt2011_2013', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df =", "30.99 year old is assigned age_index 30. Anyone born in", "'2015_2017_MaleData.dat.gz', usecols=usecols) # since cmbirth and cmmarrhx are no longer", "\"\"\" weights = df['finalwgt'].copy() weights /= sum(weights) indices = np.random.choice(df.index,", "every married: CC227 pass def ReadMaleResp2002(): \"\"\"Reads respondent data from", "resp.year // 10 #resp['fives'] = resp.year // 5 DigitizeResp(resp) def", "- df.ager*12 df['cmmarrhx'] = (df.mardat01-1900) * 12 df['evrmarry'] = (df.evrmarry==1)", "\"\"\"Plot estimated survival functions. sf_map: map from group name to", "recompute sf. hf_map: map from group name to (HazardFunction, SurvivalFunction)", "'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgt2011_2013', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno',", "agemarry; if not married, we need age df['missing'] = np.where(df.evrmarry,", "age_index 30. Anyone born in the 80s is given the", "assert(df.agemarry.value_counts().max() == 25) def Validate2017(df): assert(len(df) == 5554) assert(sum(df.evrmarry) ==", "small; I think it is better # to drop it", "= [sf.Probs(ts) for sf in sf_seq if len(sf) > 0]", "'ongoing_missing') cutoff = cutoffs.get(name, 100) hf_map[name] = EstimateSurvival(group, cutoff) #", "np.digitize(df.year, year_bins) * year_step df.birth_index += year_min - year_step def", "80. This function allows me to run the analysis with", "return group.loc[indices] def EstimateSurvivalByCohort(resps, iters=101, cutoffs=None, predict_flag=False, prop_match=None, error_rate=0): \"\"\"Makes", "# if married, we need agemarry; if not married, we", "df['stillma'] = (df.timesmar== 1) & (df.fmarit==1) df['cycle'] = 6 CleanResp(df)", "cutoff=None): \"\"\"Estimates the survival curve. resp: DataFrame of respondents cutoff:", "percentiles to select, like [5, 95] returns: (ts, rows) where", "random subset of `group` to matches propensity with `target`. target:", "[ResampleRowsWeighted(resp) for resp in resps] # then join the cycles", "hf_map: map from group name to (HazardFunction, SurvivalFunction) \"\"\" names", "df.cmstphsbx.replace([9797, 9898, 9999], np.nan, inplace=True) df.f18m1.replace([7, 8, 9], np.nan, inplace=True)", "the survival curve. resp: DataFrame of respondents cutoff: where to", "think it is better # to drop it than to", "#marital status: C5 #Respondent every married: CC227 pass def ReadMaleResp2002():", "names=names, header=None, compression='gzip') df.cmintvw.replace([0, 99999], np.nan, inplace=True) df.cmbirth.replace([0, 99999], np.nan,", "import bisect import numpy as np import pandas as pd", "AddErrors(group, colname, error_rate): \"\"\" NOTE: This will not work if", "subset of `group` to matches propensity with `target`. target: DataFrame", "import print_function, division import bisect import numpy as np import", "to list of survival functions \"\"\" if cutoffs == None:", "of all ts where the sfs are evaluated ts =", "\"\"\"Reads respondent data from NSFG Cycle 6. returns: DataFrame \"\"\"", "each of these variables into bins and then assigns an", "names=names) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) df.cmbirth.replace(invalid,", "for name, (hf, sf) in hf_map.items(): sf_map[name].append(sf) return sf_map def", "9898, 9999], np.nan, inplace=True) df.cmstphsbx.replace([9797, 9898, 9999], np.nan, inplace=True) df.f18m1.replace([7,", "different levels of granularity. df: DataFrame \"\"\" age_min = 10", "group, colname='agemarry'): \"\"\"Choose a random subset of `group` to matches", "= hf.MakeSurvival() return hf, sf def PropensityMatch(target, group, colname='agemarry'): \"\"\"Choose", "CleanResp(df) return df def ReadMaleResp2010(): \"\"\"Reads respondent data from NSFG", "end of the first marriage. df['marend01'] = df.marrend4 df['cmmarrhx'] =", "return sf_map def AddErrors(group, colname, error_rate): \"\"\" NOTE: This will", "`group` \"\"\" rv = scipy.stats.norm(scale=1) values = group[colname].fillna(100) def ChooseIndex(value):", "def ReadFemResp2017(): \"\"\"Reads respondent data from NSFG Cycle 10. returns:", "= [month0 + pd.DateOffset(months=cm) for cm in resp.cmbirth] resp['year'] =", "predict_flag: if colormap: color = colormap[name] thinkplot.Plot(ts, rows[1], label='%ds'%name, color=color)", "inplace=True) #df.cmbirth.replace(invalid, np.nan, inplace=True) #df.cmmarrhx.replace(invalid, np.nan, inplace=True) # since cmbirth", "'cmmarrhx', 'cmdivorcx', 'cmbirth', usecols = ['caseid', 'cmintvw', 'ager', 'evrmarry', 'parity',", "contains code for use with \"Think Stats\", by <NAME>, available", "DataFrames iters: number of resamples to plot predict_flag: whether to", "resps: list of DataFrames iters: number of resamples to plot", "'evrmarry', 'parity', 'wgt2015_2017', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df", "respondents if jitter: Jitter(sample, 'age', jitter=jitter) Jitter(sample, 'agemarry', jitter=jitter) DigitizeResp(resp)", "df = pd.read_fwf(dat_file, compression='gzip', colspecs=colspecs, names=names) invalid = [9997, 9998,", "== 7643) assert(sum(df.evrmarry) == 4126) assert(df.agemarry.value_counts().max() == 45) def Validate2010(df):", "(841-1, 844), (12-1, 15), (606-1, 606), (619-1, 622), (625-1, 628),", "assert(len(df) == 8450) assert(len(df[df.evrmarry]) == 5290) assert(df.agemarry.value_counts().max() == 73) def", "returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01', 'cmintvw', 'ager', 'evrmarry',", "['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'finalwgt', 'fmarit', 'timesmar', 'marrend4',", "'cmbirth', 'f18m1', 'cmdivorcx', 'cmstphsbx', 'fmarno'] colspecs = [(976-1, 982), (1001-1,", "'complete_missing') #FillMissingColumn(group, 'ongoing_var', 'ongoing_missing') cutoff = cutoffs.get(name, 100) hf_map[name] =", "'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2006_2010_FemRespSetup.dct', '2006_2010_FemResp.dat.gz',", "age_step) year_min = 0 year_max = 120 year_step = 10", "= df.marrend4 df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.timesmar > 0)", "99999], np.nan, inplace=True) df.cmstphsbx.replace([0, 99999], np.nan, inplace=True) # CM values", "ts |= set(sf.ts) ts = list(ts) ts.sort() # evaluate each", "than to fill with random data #FillMissingColumn(group, 'complete_var', 'complete_missing') #FillMissingColumn(group,", "up to 12 months df['cmbirth'] = df.cmintvw - df.ager*12 df['cmmarrhx']", "marriage ends are recorded is really confusing, # but it", "- age_step df.loc[df.agemarry.isnull(), 'agemarry_index'] = np.nan df['birth_index'] = np.digitize(df.year, year_bins)", "CleanResp(df) return df def ReadMaleResp2013(): \"\"\"Reads respondent data from NSFG", "(36-1, 37), (1521-1, 1525), (1538-1, 1542), (12-1, 16), (26-1, 30),", "\"\"\" age_min = 10 age_max = 55 age_step = 1", "np.random.uniform(-jitter, jitter, size=len(df)) def EstimateSurvival(resp, cutoff=None): \"\"\"Estimates the survival curve.", "resp: DataFrame of respondents Adds columns: agemarry, age, decade, fives", "ReadResp('2015_2017_MaleSetup.dct', '2015_2017_MaleData.dat.gz', usecols=usecols) # since cmbirth and cmmarrhx are no", "returns: (ts, rows) where ts is a sequence of times", "'mar1diss'] df = ReadResp('2015_2017_FemRespSetup.dct', '2015_2017_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998,", "2574), (36-1, 37), (1521-1, 1525), (1538-1, 1542), (12-1, 16), (26-1,", "30. Anyone born in the 80s is given the year_index", "np.nan, inplace=True) #df.marrend2.replace([8,9], np.nan, inplace=True) #df.marrend3.replace([8,9], np.nan, inplace=True) df.marrend4.replace([8,9], np.nan,", "not identical to the actual respondents if jitter: Jitter(sample, 'age',", "9999], np.nan, inplace=True) df.cmstphsbx.replace([9797, 9898, 9999], np.nan, inplace=True) df.f18m1.replace([7, 8,", "row of values for each percent \"\"\" # find the", "have to compute them based on other variables; # the", "ReadFemResp1988(): \"\"\"Reads respondent data from NSFG Cycle 4. Read as", "returns: DataFrame \"\"\" filename = '1988FemRespDataLines.dat.gz' names = ['finalwgt', 'ageint',", "print('Cycle 5') resp5 = ReadFemResp1995() Validate1995(resp5) print('Cycle 4') resp4 =", "Cycle 7. returns: DataFrame \"\"\" usecols = ['caseid', 'cmmarrhx', 'cmdivorcx',", "cmbirth and cmmarrhx are no longer included, # we have", "colspecs = [(12360-1, 12363), (4637-1, 4638), (11759-1, 11762), (14-1, 16),", "df.loc[df.firstcm>90000, 'firstcm'] -= 90000 df.loc[df.currentcm>90000, 'currentcm'] -= 90000 df.loc[df.cmdivorcx>90000, 'cmdivorcx']", "assert(len(df) == 5601) assert(sum(df.evrmarry) == 2452) assert(df.agemarry.value_counts().max() == 33) def", "remove_missing=False, jitter=0): \"\"\"Resamples each dataframe and then concats them. resps:", "'cmintvw', 'evrmarry', 'parity', 'wgt2011_2013', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss']", "# find the union of all ts where the sfs", "= ['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgt2011_2013', 'mardat01',", "result can be off by up to 12 months df['cmbirth']", "marriage df['cmmarrhx'] = df.firstcm df.cmmarrhx.fillna(df.currentcm, inplace=True) # define evrmarry if", "df = pd.read_fwf(dat_file, colspecs=colspecs, names=names, header=None, nrows=7969, compression='gzip') df.cmintvw.replace([9797, 9898,", "ReadFemResp1988() Validate1988(resp4) print('Cycle 3') resp3 = ReadFemResp1982() Validate1982(resp3) if __name__", "resp['missing'] = np.where(resp.evrmarry, resp.agemarry.isnull(), resp.age.isnull()) month0 = pd.to_datetime('1899-12-15') dates =", "(df.timesmar==1) & (df.marend01.isnull()) df['cycle'] = 5 CleanResp(df) return df def", "sum(weights) indices = np.random.choice(df.index, len(df), replace=True, p=weights) return df.loc[indices] def", "'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2002FemResp.dct', '2002FemResp.dat.gz',", "sample[~sample.missing] # jittering the ages reflects the idea that the", "1900) DigitizeResp(df) return df def Validate1982(df): assert(len(df) == 7969) assert(len(df[df.evrmarry])", "inplace=True) df.timesmar.replace([98,99], np.nan, inplace=True) # the way marriage ends are", "curve. resp: DataFrame of respondents cutoff: where to truncate the", "(1521-1, 1525), (1538-1, 1542), (12-1, 16), (26-1, 30), (1554-1, 1554),", "CC227 pass def ReadCanadaCycle6(): \"\"\" \"\"\" #age at first marriage:", "df['cmmarrhx'] = df.firstcm df.cmmarrhx.fillna(df.currentcm, inplace=True) # define evrmarry if either", "the result can be off by up to 12 months", "remove_missing: sample = sample[~sample.missing] # jittering the ages reflects the", "agemarry; if not married, we need age resp['missing'] = np.where(resp.evrmarry,", "DataFrame \"\"\" age_min = 10 age_max = 55 age_step =", "map from group name to list of survival functions \"\"\"", "DigitizeResp(df) return df def ReadResp(dct_file, dat_file, **options): \"\"\"Reads the NSFG", "CleanResp(df) return df def ReadFemResp2002(): \"\"\"Reads respondent data from NSFG", "were a standard ascii file returns: DataFrame \"\"\" filename =", "ReadResp('2006_2010_FemRespSetup.dct', '2006_2010_FemResp.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan,", "\"\"\"Adds random noise to a column. df: DataFrame column: string", "times and rows contains one row of values for each", "= df.cmintvw - df.ager*12 df['cmmarrhx'] = (df.mardat01-1900) * 12 df['evrmarry']", "Instead of calling CleanResp, we have to customize #CleanResp(df) df['agemarry']", "defaultdict from collections import OrderedDict from collections import Counter import", "predictions if desired if predict_flag: MakePredictions(hf_map) # extract the sf", "5 CleanResp(df) return df def ReadFemResp2002(): \"\"\"Reads respondent data from", "'1988FemRespDataLines.dat.gz' names = ['finalwgt', 'ageint', 'currentcm', 'firstcm', 'cmintvw', 'cmbirth', 'f23m1',", "= defaultdict(list) # iters is the number of resampling runs", "df['widowed'] = (df.marend01==1) df['stillma'] = (df.timesmar== 1) & (df.fmarit==1) df['cycle']", "Cycle 9. returns: DataFrame \"\"\" usecols = ['caseid', 'cmmarrhx', 'cmdivorcx',", "df['finalwgt'] = df.wgt2013_2015 df['cycle'] = 9 CleanResp(df) return df def", "for sf in sf_seq: ts |= set(sf.ts) ts = list(ts)", "year_step df.birth_index += year_min - year_step def ReadCanadaCycle5(): \"\"\" \"\"\"", "(606-1, 606), (619-1, 622), (625-1, 628), (1142-1, 1143), ] df", "returns: DataFrame \"\"\" dat_file = '1995FemRespData.dat.gz' names = ['cmintvw', 'timesmar',", "(hf, sf) for each group hf_map = OrderedDict() for name,", "first marriage. df['marend01'] = df.marrend4 df['cmmarrhx'] = df.mardat01 df['evrmarry'] =", "in hf_map.items(): sf_map[name].append(sf) return sf_map def AddErrors(group, colname, error_rate): \"\"\"", "\"\"\"Reads respondent data from NSFG Cycle 10. returns: DataFrame \"\"\"", "from NSFG Cycle 9. returns: DataFrame \"\"\" usecols = ['caseid',", "df['cycle'] = 8 CleanResp(df) return df def ReadMaleResp2015(): \"\"\"Reads respondent", "df.wgtq1q16 df['cycle'] = 7 CleanResp(df) return df def ReadMaleResp2013(): \"\"\"Reads", "list of percentiles to select, like [5, 95] returns: (ts,", "gzip import matplotlib.pyplot as plt from collections import defaultdict from", "'cmintvw', 'cmbirth', 'f23m1', 'cmdivorcx', 'cmstphsbx', 'fmarno'] colspecs = [(2568-1, 2574),", "'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2011_2013_MaleSetup.dct', '2011_2013_MaleData.dat.gz', usecols=usecols) df['cmmarrhx'] =", "\"\"\"Reads respondent data from NSFG Cycle 7. returns: DataFrame \"\"\"", "sf) for each group hf_map = OrderedDict() for name, group", "of percentiles to select, like [5, 95] returns: (ts, rows)", "year_bins = np.arange(year_min, year_max, year_step) df['age_index'] = np.digitize(df.age, age_bins) *", "inplace=True) df.cmbirth.replace(invalid, np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df.cmdivorcx.replace(invalid, np.nan, inplace=True)", "- 1900) DigitizeResp(df) return df def ReadResp(dct_file, dat_file, **options): \"\"\"Reads", "= ReadResp('2015_2017_FemRespSetup.dct', '2015_2017_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid,", "df.age_index += age_min - age_step df.loc[df.age.isnull(), 'age_index'] = np.nan df['agemarry_index']", "inplace=True) def PlotSurvivalFunctions(sf_map, predict_flag=False, colormap=None): \"\"\"Plot estimated survival functions. sf_map:", "returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw',", "return df def ReadFemResp2017(): \"\"\"Reads respondent data from NSFG Cycle", "ends are recorded is really confusing, # but it looks", "hf_map[name] if i > 0: hf.Extend(hfs[i-1]) sf = hf.MakeSurvival() hf_map[name]", "values for each percent \"\"\" # find the union of", "rows = thinkstats2.PercentileRows(ss_seq, percents) return ts, rows def ReadFemResp1982(): \"\"\"Reads", "also plot predictions cutoffs: map from cohort to the first", "4721), (4722-1, 4725), (17-1, 17)] df = pd.read_fwf(dat_file, compression='gzip', colspecs=colspecs,", "data from each cycle separately samples = [ResampleRowsWeighted(resp) for resp", "for name, group in iter(grouped): if prop_match: group = PropensityMatch(last,", "df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['finalwgt'] = df.wgt2015_2017", "me to run the analysis with different levels of granularity.", "in iter(grouped): if prop_match: group = PropensityMatch(last, group) if error_rate:", "value in target[colname]] return group.loc[indices] def EstimateSurvivalByCohort(resps, iters=101, cutoffs=None, predict_flag=False,", "Validate1982(df): assert(len(df) == 7969) assert(len(df[df.evrmarry]) == 4651) assert(df.agemarry.value_counts().max() == 71)", "previous cohort, # and update the survival function for i,", "pass def ReadCanadaCycle6(): \"\"\" \"\"\" #age at first marriage: CC232", "inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df.cmdivorcx.replace(invalid, np.nan, inplace=True) df.cmstphsbx.replace(invalid, np.nan, inplace=True)", "from collections import Counter import thinkstats2 import thinkplot import survival", "sf. hf_map: map from group name to (HazardFunction, SurvivalFunction) \"\"\"", "df.cmintvw.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmbirth.replace([9797, 9898, 9999], np.nan, inplace=True)", "11762), (14-1, 16), (12350-1, 12359), (4713-1, 4713), (4718-1, 4721), (4722-1,", "for resampled data. resps: list of DataFrames iters: number of", "'2011_2013_MaleData.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.evrmarry==1) df['divorced'] =", "in range(iters): sample = ResampleResps(resps) # group by decade grouped", "list of SurvivalFunction percents: list of percentiles to select, like", "'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2015_2017_MaleSetup.dct', '2015_2017_MaleData.dat.gz', usecols=usecols) # since", "50, 90]) thinkplot.FillBetween(ts, rows[0], rows[2], color='gray', alpha=0.2) if not predict_flag:", "sf = hf.MakeSurvival() return hf, sf def PropensityMatch(target, group, colname='agemarry'):", "# iters is the number of resampling runs to make", "df = ReadResp('2013_2015_FemRespSetup.dct', '2013_2015_FemRespData.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999]", "ReadResp('2002FemResp.dct', '2002FemResp.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan,", "np.nan, inplace=True) df.timesmar.replace([98,99], np.nan, inplace=True) # the way marriage ends", "an index to each bin. For example, anyone between 30", "in enumerate(names): hf, sf = hf_map[name] if i > 0:", "np.random.choice(group.index, 1, p=weights)[0] indices = [ChooseIndex(value) for value in target[colname]]", "df.loc[df.agemarry.isnull(), 'agemarry_index'] = np.nan df['birth_index'] = np.digitize(df.year, year_bins) * year_step", "= (df.f18m1 == 4) df['separated'] = (df.f18m1 == 5) df['widowed']", "\"\"\"Cleans a respondent DataFrame. resp: DataFrame of respondents Adds columns:", "np.nan, inplace=True) # since cmbirth and cmmarrhx are no longer", "analysis with different levels of granularity. df: DataFrame \"\"\" age_min", "AddErrors(group, 'ongoing_missing', error_rate) # the amount of missing data is", "\"\"\" usecols = ['caseid', 'mardat01', 'cmintvw', 'ager', 'evrmarry', 'wgt2015_2017', 'marend01',", "data from NSFG Cycle 8. returns: DataFrame \"\"\" usecols =", "'marstat'] colspecs = [(12360-1, 12363), (4637-1, 4638), (11759-1, 11762), (14-1,", "in names] # extend each hazard function using data from", "Copyright 2014 <NAME> License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html \"\"\" from __future__", "== 25) def Validate2017(df): assert(len(df) == 5554) assert(sum(df.evrmarry) == 2582)", "(df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] = (df.marend01==3)", "df['widowed'] = (df.f18m1 == 3) df['stillma'] = (df.fmarno==1) & (df.fmarital==1)", "def DigitizeResp(df): \"\"\"Computes indices for age, agemarry, and birth year.", "(df.f23m1.isnull()) df['cycle'] = 4 CleanResp(df) return df def ReadFemResp1995(): \"\"\"Reads", "i in range(iters): sample = ResampleResps(resps) # group by decade", "nrows=7969, compression='gzip') df.cmintvw.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmbirth.replace([9797, 9898, 9999],", "the year_index 80. This function allows me to run the", "compute them based on other variables; # the result can", "actual respondents if jitter: Jitter(sample, 'age', jitter=jitter) Jitter(sample, 'agemarry', jitter=jitter)", "def AddErrors(group, colname, error_rate): \"\"\" NOTE: This will not work", "from NSFG Cycle 5. returns: DataFrame \"\"\" dat_file = '1995FemRespData.dat.gz'", "other variables; # the result can be off by up", "year_max = 120 year_step = 10 year_bins = np.arange(year_min, year_max,", "= 9 CleanResp(df) return df def ReadFemResp2017(): \"\"\"Reads respondent data", "DataFrame returns: DataFrame \"\"\" # we have to resample the", "cutoffs == None: cutoffs = {} sf_map = defaultdict(list) #", "ReadCanadaCycle5(): \"\"\" \"\"\" #age at first marriage: CC232 #age of", "7 CleanResp(df) return df def ReadMaleResp2013(): \"\"\"Reads respondent data from", "99999], np.nan, inplace=True) df.cmbirth.replace([0, 99999], np.nan, inplace=True) df.firstcm.replace([0, 99999], np.nan,", "'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgtq1q16', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df", "map from group name to color \"\"\" for name, sf_seq", "#resp['decade'] = resp.year // 10 #resp['fives'] = resp.year // 5", "return hf, sf def PropensityMatch(target, group, colname='agemarry'): \"\"\"Choose a random", "as plt from collections import defaultdict from collections import OrderedDict", "'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2006_2010_MaleSetup.dct', '2006_2010_Male.dat.gz', usecols=usecols) df['cmmarrhx'] =", "= (df.f23m1==3) df['widowed'] = (df.f23m1==1) df['stillma'] = (df.fmarno==1) & (df.f23m1.isnull())", "\"\"\"Resamples each dataframe and then concats them. resps: list of", "== 2582) assert(df.agemarry.value_counts().max() == 29) def main(): print('Cycle 10') resp10", "29) def main(): print('Cycle 10') resp10 = ReadFemResp2017() Validate2017(resp10) print('Cycle", "color=color) else: thinkplot.Plot(ts, rows[1], label='%ds'%name) def MakePredictions(hf_map): \"\"\"Extends a set", "assert(df.agemarry.value_counts().max() == 33) def Validate2015(df): assert(len(df) == 5699) assert(sum(df.evrmarry) ==", "'mar1diss'] df = ReadResp('2002FemResp.dct', '2002FemResp.dat.gz', usecols=usecols) invalid = [9997, 9998,", "0) df['divorced'] = (df.f23m1==2) df['separated'] = (df.f23m1==3) df['widowed'] = (df.f23m1==1)", "of SurvivalFunction percents: list of percentiles to select, like [5,", "actual colormap: map from group name to color \"\"\" for", "= ReadResp('2011_2013_MaleSetup.dct', '2011_2013_MaleData.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.evrmarry==1)", "from group name to (HazardFunction, SurvivalFunction) \"\"\" names = list(hf_map.keys())", "like [5, 95] returns: (ts, rows) where ts is a", "= grouped.get_group(prop_match) # and estimate (hf, sf) for each group", "= [month0 + pd.DateOffset(months=cm) for cm in df.cmbirth] df['year'] =", "= (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed'] =", "np.arange(year_min, year_max, year_step) df['age_index'] = np.digitize(df.age, age_bins) * age_step df.age_index", "dates if remove_missing: sample = sample[~sample.missing] # jittering the ages", "# CM values above 9000 indicate month unknown df.loc[df.cmintvw>90000, 'cmintvw']", "string \"\"\" null = group[group[missing_colname]] if len(null) == 0: return", "group.loc[indices] def EstimateSurvivalByCohort(resps, iters=101, cutoffs=None, predict_flag=False, prop_match=None, error_rate=0): \"\"\"Makes survival", "return df.loc[indices] def Jitter(df, column, jitter=1): \"\"\"Adds random noise to", "= (pd.DatetimeIndex(dates).year - 1900) #resp['decade'] = resp.year // 10 #resp['fives']", "string file name dat_file: string file name returns: DataFrame \"\"\"", "group name to list of survival functions \"\"\" if cutoffs", "'finalwgt', 'fmarit', 'timesmar', 'marrend4', #'marrend', 'marrend2', 'marrend3', marrend5', 'marrend6', ]", "usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid, np.nan, inplace=True) df.cmbirth.replace(invalid,", "jitter=1): \"\"\"Adds random noise to a column. df: DataFrame column:", "= [ResampleRowsWeighted(resp) for resp in resps] # then join the", "for each group hf_map = OrderedDict() for name, group in", "= 8 CleanResp(df) return df def ReadFemResp2015(): \"\"\"Reads respondent data", "] df = ReadResp('2002Male.dct', '2002Male.dat.gz', usecols=usecols) #df.marrend.replace([8,9], np.nan, inplace=True) #df.marrend2.replace([8,9],", "DigitizeResp(resp) return sample def ResampleRowsWeighted(df, column='finalwgt'): \"\"\"Resamples the rows in", "= pd.read_fwf(dat_file, colspecs=colspecs, names=names, header=None, nrows=7969, compression='gzip') df.cmintvw.replace([9797, 9898, 9999],", "from the previous cohort, # and update the survival function", "colspecs=colspecs, names=names, header=None, compression='gzip') df.cmintvw.replace([0, 99999], np.nan, inplace=True) df.cmbirth.replace([0, 99999],", "(resp.cmmarrhx - resp.cmbirth) / 12.0 resp['age'] = (resp.cmintvw - resp.cmbirth)", "rows[2], color='gray', alpha=0.2) if not predict_flag: if colormap: color =", "#FillMissingColumn(group, 'ongoing_var', 'ongoing_missing') cutoff = cutoffs.get(name, 100) hf_map[name] = EstimateSurvival(group,", "== 2401) assert(df.agemarry.value_counts().max() == 25) def Validate2017(df): assert(len(df) == 5554)", "df['cycle'] = 5 CleanResp(df) return df def ReadFemResp2002(): \"\"\"Reads respondent", "rows = MakeSurvivalCI(sf_seq, [10, 50, 90]) thinkplot.FillBetween(ts, rows[0], rows[2], color='gray',", "resampling runs to make for i in range(iters): sample =", "target: DataFrame group: DataFrame colname: string name of column with", "DataFrame of respondents cutoff: where to truncate the estimated functions", "to drop it than to fill with random data #FillMissingColumn(group,", "np.nan, inplace=True) df.cmbirth.replace(invalid, np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True) df.cmdivorcx.replace(invalid, np.nan,", "1) & (df.rmarital==1) df['finalwgt'] = df.wgt2011_2013 df['cycle'] = 8 CleanResp(df)", "Cycle 8. returns: DataFrame \"\"\" usecols = ['caseid', 'mardat01', 'cmdivw',", "functions. For each group in hf_map, we extend hf and", "df.cmmarrhx.replace(invalid, np.nan, inplace=True) df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated']", "are actual missing values! \"\"\" group[colname] = np.random.random(len(group)) < error_rate", "(1565-1, 1569), (1570-1, 1574), (2441-1, 2442), ] df = pd.read_fwf(filename,", "using data from the previous cohort, # and update the", "= ReadResp('2002FemResp.dct', '2002FemResp.dat.gz', usecols=usecols) invalid = [9997, 9998, 9999] df.cmintvw.replace(invalid,", "respondent data from NSFG Cycle 9. returns: DataFrame \"\"\" usecols", "then join the cycles into one big sample sample =", "accordance with a weight column. df: DataFrame returns: DataFrame \"\"\"", "usecols = ['caseid', 'mardat01', 'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgt2011_2013', 'marend01',", "== 8450) assert(len(df[df.evrmarry]) == 5290) assert(df.agemarry.value_counts().max() == 73) def Validate1995(df):", "cutoffs.get(name, 100) hf_map[name] = EstimateSurvival(group, cutoff) # make predictions if", "== 0: continue sf = sf_seq[0] if len(sf) == 0:", "not work if there are actual missing values! \"\"\" group[colname]", "CleanResp(df) return df def ReadFemResp1988(): \"\"\"Reads respondent data from NSFG", "np.nan, inplace=True) # the way marriage ends are recorded is", "ReadMaleResp2013(): \"\"\"Reads respondent data from NSFG Cycle 8. returns: DataFrame", "values of the given column. group: DataFrame colname: string \"\"\"", "the NSFG respondent data. dct_file: string file name dat_file: string", "of survival functions \"\"\" if cutoffs == None: cutoffs =", "returns: DataFrame \"\"\" weights = df['finalwgt'].copy() weights /= sum(weights) indices", "NSFG Cycle 7. returns: DataFrame \"\"\" usecols = ['caseid', 'cmmarrhx',", "9000 indicate month unknown df.loc[df.cmintvw>9000, 'cmintvw'] -= 9000 df.loc[df.cmbirth>9000, 'cmbirth']", "status: C5 #Respondent every married: CC227 pass def ReadCanadaCycle6(): \"\"\"", "name, group in iter(grouped): if prop_match: group = PropensityMatch(last, group)", "sf_map def AddErrors(group, colname, error_rate): \"\"\" NOTE: This will not", "= 55 age_step = 1 age_bins = np.arange(age_min, age_max, age_step)", "DataFrame \"\"\" # removed 'cmmarrhx', 'cmdivorcx', 'cmbirth', usecols = ['caseid',", "> 0] # return the requested percentiles from each column", "(df.fmarno==1) & (df.f23m1.isnull()) df['cycle'] = 4 CleanResp(df) return df def", "pair of HazardFunction, SurvivalFunction \"\"\" complete = resp.loc[resp.complete, 'complete_var'].dropna() ongoing", "'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'finalwgt', 'mardat01', 'marend01', 'mardis01',", "by decade grouped = sample.groupby('birth_index') if prop_match: last = grouped.get_group(prop_match)", "ResampleRowsWeighted(df, column='finalwgt'): \"\"\"Resamples the rows in df in accordance with", "# to drop it than to fill with random data", "or actual colormap: map from group name to color \"\"\"", "#df.cmbirth.replace(invalid, np.nan, inplace=True) #df.cmmarrhx.replace(invalid, np.nan, inplace=True) # since cmbirth and", "2014 <NAME> License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html \"\"\" from __future__ import", "to plot predict_flag: whether to also plot predictions cutoffs: map", "'parity', 'wgtq1q16', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df =", "'marend01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2015_2017_MaleSetup.dct', '2015_2017_MaleData.dat.gz', usecols=usecols) #", "'cmintvw', 'evrmarry', 'parity', 'finalwgt', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss']", "= ReadFemResp2017() Validate2017(resp10) print('Cycle 9') resp9 = ReadFemResp2015() Validate2015(resp9) print('Cycle", "survival functions \"\"\" if cutoffs == None: cutoffs = {}", "the sfs are evaluated ts = set() for sf in", "45) def Validate2010(df): assert(len(df) == 12279) assert(sum(df.evrmarry) == 5534) assert(df.agemarry.value_counts().max()", "'parity', 'wgt2015_2017', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df =", "'mar1diss'] df = ReadResp('2006_2010_MaleSetup.dct', '2006_2010_Male.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry']", "NSFG Cycle 10. returns: DataFrame \"\"\" # removed 'cmmarrhx', 'cmdivorcx',", "usecols=usecols) #df.marrend.replace([8,9], np.nan, inplace=True) #df.marrend2.replace([8,9], np.nan, inplace=True) #df.marrend3.replace([8,9], np.nan, inplace=True)", "for i in range(iters): sample = ResampleResps(resps) # group by", "assert(df.agemarry.value_counts().max() == 45) def Validate2010(df): assert(len(df) == 12279) assert(sum(df.evrmarry) ==", "usecols=usecols) df['cmmarrhx'] = df.mardat01 df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1)", "df.loc[df.cmdivorcx>9000, 'cmdivorcx'] -= 9000 df.loc[df.cmstphsbx>9000, 'cmstphsbx'] -= 9000 df['evrmarry'] =", "concats them. resps: list of DataFrame returns: DataFrame \"\"\" #", "1002), (1268-1, 1271), (1037-1, 1040), (1041-1, 1041), (841-1, 844), (12-1,", "DataFrame \"\"\" dat_file = '1982NSFGData.dat.gz' names = ['finalwgt', 'ageint', 'mar2p',", "names] # extend each hazard function using data from the", "71) def Validate1988(df): assert(len(df) == 8450) assert(len(df[df.evrmarry]) == 5290) assert(df.agemarry.value_counts().max()", "respondent data from NSFG Cycle 5. returns: DataFrame \"\"\" dat_file", "df.cmmarrhx.replace([9797, 9898, 9999], np.nan, inplace=True) df.cmdivorcx.replace([9797, 9898, 9999], np.nan, inplace=True)", "\"\"\" # find the union of all ts where the", "resp9 = ReadFemResp2015() Validate2015(resp9) print('Cycle 8') resp8 = ReadFemResp2013() Validate2013(resp8)", "(df.timesmar== 1) & (df.fmarit==1) df['cycle'] = 6 CleanResp(df) return df", "#CleanResp(df) df['agemarry'] = (df.cmmarrhx - df.cmbirth) / 12.0 df['age'] =", "'fmarno', 'mar1diss'] df = ReadResp('2011_2013_MaleSetup.dct', '2011_2013_MaleData.dat.gz', usecols=usecols) df['cmmarrhx'] = df.mardat01", "MakePredictions(hf_map) # extract the sf from each pair and accumulate", "(HazardFunction, SurvivalFunction) \"\"\" names = list(hf_map.keys()) names.sort() hfs = [hf_map[name][0]", "MakeSurvivalCI(sf_seq, [10, 50, 90]) thinkplot.FillBetween(ts, rows[0], rows[2], color='gray', alpha=0.2) if", "df def ReadFemResp2015(): \"\"\"Reads respondent data from NSFG Cycle 9.", "'cmstphsbx', 'fmarno'] colspecs = [(2568-1, 2574), (36-1, 37), (1521-1, 1525),", "sample.groupby('birth_index') if prop_match: last = grouped.get_group(prop_match) # and estimate (hf,", "[month0 + pd.DateOffset(months=cm) for cm in resp.cmbirth] resp['year'] = (pd.DatetimeIndex(dates).year", "(12350-1, 12359), (4713-1, 4713), (4718-1, 4721), (4722-1, 4725), (17-1, 17)]", "to truncate the estimated functions returns: pair of HazardFunction, SurvivalFunction", "each group in hf_map, we extend hf and recompute sf.", "year. Groups each of these variables into bins and then", "['caseid', 'mardat01', 'cmintvw', 'ager', 'evrmarry', 'wgt2015_2017', 'marend01', 'rmarital', 'fmarno', 'mar1diss']", "**options): \"\"\"Reads the NSFG respondent data. dct_file: string file name", "== 5534) assert(df.agemarry.value_counts().max() == 64) def Validate2013(df): assert(len(df) == 5601)", "10') resp10 = ReadFemResp2017() Validate2017(resp10) print('Cycle 9') resp9 = ReadFemResp2015()", "to sequence of survival functions predict_flag: whether the lines are", "# evaluate each sf at all times ss_seq = [sf.Probs(ts)", "combine current and first marriage df['cmmarrhx'] = df.firstcm df.cmmarrhx.fillna(df.currentcm, inplace=True)", "name of column with propensity scores returns: DataFrame with sample", "hf, sf = hf_map[name] if i > 0: hf.Extend(hfs[i-1]) sf", "EstimateSurvival(group, cutoff) # make predictions if desired if predict_flag: MakePredictions(hf_map)", "cutoffs: map from cohort to the first unreliable age_index returns:", "'wgtq1q16', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2006_2010_FemRespSetup.dct',", "respondent data from NSFG Cycle 3. returns: DataFrame \"\"\" dat_file", "'cmdivw', 'cmbirth', 'cmintvw', 'evrmarry', 'wgt2013_2015', 'marend01', 'rmarital', 'fmarno', 'mar1diss'] df", "for name, sf_seq in sorted(sf_map.items(), reverse=True): if len(sf_seq) == 0:", "inplace=True) #df.marrend5.replace([8,9], np.nan, inplace=True) #df.marrend6.replace([8,9], np.nan, inplace=True) df.timesmar.replace([98,99], np.nan, inplace=True)", "to select, like [5, 95] returns: (ts, rows) where ts", "= np.nan df['agemarry_index'] = np.digitize(df.agemarry, age_bins) * age_step df.agemarry_index +=", "df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] = (df.marend01==2) df['widowed']", "9999] df.cmintvw.replace(invalid, np.nan, inplace=True) df.cmbirth.replace(invalid, np.nan, inplace=True) df.cmmarrhx.replace(invalid, np.nan, inplace=True)", "respondent data from NSFG Cycle 4. Read as if were", "== 5601) assert(sum(df.evrmarry) == 2452) assert(df.agemarry.value_counts().max() == 33) def Validate2015(df):", "= (resp.cmmarrhx - resp.cmbirth) / 12.0 resp['age'] = (resp.cmintvw -", "* 12 df['evrmarry'] = (df.evrmarry==1) df['divorced'] = (df.marend01==1) df['separated'] =", "== 0: continue ts, rows = MakeSurvivalCI(sf_seq, [10, 50, 90])", "respondent data from NSFG Cycle 10. returns: DataFrame \"\"\" usecols", "file contains code for use with \"Think Stats\", by <NAME>,", "'wgt2015_2017', 'mardat01', 'marend01', 'mardis01', 'rmarital', 'fmarno', 'mar1diss'] df = ReadResp('2015_2017_FemRespSetup.dct',", "survival function for i, name in enumerate(names): hf, sf =", "color='gray', alpha=0.2) if not predict_flag: if colormap: color = colormap[name]", "with \"Think Stats\", by <NAME>, available from greenteapress.com Copyright 2014", "C5 #Respondent every married: CC227 pass def ReadCanadaCycle6(): \"\"\" \"\"\"", "column, jitter=1): \"\"\"Adds random noise to a column. df: DataFrame", "['caseid', 'cmmarrhx', 'cmdivorcx', 'cmbirth', 'cmintvw', 'evrmarry', 'parity', 'wgt2013_2015', 'mardat01', 'marend01',", "assert(len(df) == 12279) assert(sum(df.evrmarry) == 5534) assert(df.agemarry.value_counts().max() == 64) def", "- df.cmbirth) / 12.0 df['age'] = (df.cmintvw - df.cmbirth) /", "at first marriage: CC232 #age of respondent at interview: C3", "df['agemarry'] = (df.cmmarrhx - df.cmbirth) / 12.0 df['age'] = (df.cmintvw", "(df.marend01==3) df['stillma'] = (df.fmarno == 1) & (df.rmarital==1) df['cycle'] =", "(df.marend01==2) df['widowed'] = (df.marend01==3) df['stillma'] = (df.fmarno == 1) &", "np.nan, inplace=True) df.cmstphsbx.replace([0, 99999], np.nan, inplace=True) # CM values above", "(resp.cmintvw - resp.cmbirth) / 12.0 # if married, we need", "-= 90000 df.loc[df.currentcm>90000, 'currentcm'] -= 90000 df.loc[df.cmdivorcx>90000, 'cmdivorcx'] -= 90000", "= df.mardat01 df['evrmarry'] = (df.timesmar > 0) df['divorced'] = (df.marend01==2)" ]
[ "'intensity.sum.variance', 'miller_index', 'miller_index_asymmetric', 'exp_id', 'odd_frame', 's1']: if not key in", "merged_reflections.append( {'miller_index' : hkl, 'intensity' : weighted_mean_intensity, 'sigma' : standard_error_of_weighted_mean_intensity,", "continue else: yield reflections[i_begin:i] i_begin = i hkl_ref = hkl", "refls.size() >= min_multiplicity: weighted_intensity_array = refls['intensity.sum.value'] / refls['intensity.sum.variance'] weights_array =", "table keys: either inclusive or exclusive''' if len(reflections) != 0:", "all_keys = list() for key in reflections[0]: all_keys.append(key) if keys_to_delete", "odd ids. An experiment id must be a string representing", "= flex.miller_index() table['intensity'] = flex.double() table['sigma'] = flex.double() table['multiplicity'] =", "import math class reflection_table_utils(object): @staticmethod def get_next_hkl_reflection_table(reflections): '''Generate asu hkl", "i_begin = i hkl_ref = hkl yield reflections[i_begin:i+1] @staticmethod def", "reflections[key] elif keys_to_keep != None: for key in all_keys: #if", ": hkl, 'intensity' : weighted_mean_intensity, 'sigma' : standard_error_of_weighted_mean_intensity, 'multiplicity' :", "reflection_table_utils.merged_reflection_table() for refls in reflection_table_utils.get_next_hkl_reflection_table(reflections=reflections): if refls.size() == 0: break", "cannot be empty hkl = refls[0]['miller_index_asymmetric'] # This assert is", "from dials.array_family import flex import math class reflection_table_utils(object): @staticmethod def", "An experiment id must be a string representing a hexadecimal", "timeconsuming when using a small number of cores #assert not", "= 0 hkl_ref = reflections[0].get('miller_index_asymmetric') for i in range(reflections.size()): hkl", "either inclusive or exclusive''' if len(reflections) != 0: all_keys =", "= flex.double() table['sigma'] = flex.double() table['multiplicity'] = flex.int() return table", "0.0) if refls.size() >= min_multiplicity: weighted_intensity_array = refls['intensity.sum.value'] / refls['intensity.sum.variance']", "cores #assert not (hkl in merged_reflections['miller_index']) # i.e. assert that", "if refls.size() >= min_multiplicity: weighted_intensity_array = refls['intensity.sum.value'] / refls['intensity.sum.variance'] weights_array", "flex.bool() for refl in reflections: sel.append(int(refl['exp_id'], 16)%2 != 0) return", "return reflections.select(sel) @staticmethod def merged_reflection_table(): '''Create a reflection table for", "input reflection table came in sorted refls = refls.select(refls['intensity.sum.variance'] >", "'miller_index_asymmetric', 'exp_id', 'odd_frame', 's1']: if not key in keys_to_keep: del", "empty, generated \"refls\" lists cannot be empty hkl = refls[0]['miller_index_asymmetric']", "a string representing a hexadecimal number' sel = flex.bool() for", "experiment id must be a string representing a hexadecimal number'", "division, print_function from six.moves import range from dials.array_family import flex", "16)%2 == 0) return reflections.select(sel) @staticmethod def merged_reflection_table(): '''Create a", "with even ids. An experiment id must be a string", ": refls.size()}) return merged_reflections @staticmethod def prune_reflection_table_keys(reflections, keys_to_delete=None, keys_to_keep=None): '''Remove", "/ flex.sum(weights_array) standard_error_of_weighted_mean_intensity = 1.0/math.sqrt(flex.sum(weights_array)) merged_reflections.append( {'miller_index' : hkl, 'intensity'", "== 0) return reflections.select(sel) @staticmethod def merged_reflection_table(): '''Create a reflection", "standard_error_of_weighted_mean_intensity, 'multiplicity' : refls.size()}) return merged_reflections @staticmethod def prune_reflection_table_keys(reflections, keys_to_delete=None,", "'Select reflections from experiments with even ids. An experiment id", "merge_reflections(reflections, min_multiplicity): '''Merge intensities of multiply-measured symmetry-reduced HKLs''' merged_reflections =", "be a string representing a hexadecimal number' sel = flex.bool()", "reflections[0].get('miller_index_asymmetric') for i in range(reflections.size()): hkl = reflections[i].get('miller_index_asymmetric') if hkl", "all_keys.append(key) if keys_to_delete != None: for key in keys_to_delete: if", "# i.e. assert that the input reflection table came in", ": weighted_mean_intensity, 'sigma' : standard_error_of_weighted_mean_intensity, 'multiplicity' : refls.size()}) return merged_reflections", "== 0: break # unless the input \"reflections\" list is", "__future__ import absolute_import, division, print_function from six.moves import range from", "reflections: sel.append(int(refl['exp_id'], 16)%2 == 0) return reflections.select(sel) @staticmethod def merged_reflection_table():", "experiments with odd ids. An experiment id must be a", "weighted_mean_intensity, 'sigma' : standard_error_of_weighted_mean_intensity, 'multiplicity' : refls.size()}) return merged_reflections @staticmethod", "select_even_experiment_reflections(reflections): 'Select reflections from experiments with even ids. An experiment", "== 0: yield reflections i_begin = 0 hkl_ref = reflections[0].get('miller_index_asymmetric')", "i.e. assert that the input reflection table came in sorted", "yield reflections i_begin = 0 hkl_ref = reflections[0].get('miller_index_asymmetric') for i", "merged_reflection_table(): '''Create a reflection table for storing merged HKLs''' table", "hkl = reflections[i].get('miller_index_asymmetric') if hkl == hkl_ref: continue else: yield", "refls[0]['miller_index_asymmetric'] # This assert is timeconsuming when using a small", "dials.array_family import flex import math class reflection_table_utils(object): @staticmethod def get_next_hkl_reflection_table(reflections):", "refls.size()}) return merged_reflections @staticmethod def prune_reflection_table_keys(reflections, keys_to_delete=None, keys_to_keep=None): '''Remove reflection", "list() for key in reflections[0]: all_keys.append(key) if keys_to_delete != None:", "key in reflections[0]: all_keys.append(key) if keys_to_delete != None: for key", "= flex.bool() for refl in reflections: sel.append(int(refl['exp_id'], 16)%2 != 0)", "i_begin = 0 hkl_ref = reflections[0].get('miller_index_asymmetric') for i in range(reflections.size()):", "for storing merged HKLs''' table = flex.reflection_table() table['miller_index'] = flex.miller_index()", "sel = flex.bool() for refl in reflections: sel.append(int(refl['exp_id'], 16)%2 !=", "!= 0) return reflections.select(sel) @staticmethod def select_even_experiment_reflections(reflections): 'Select reflections from", "empty hkl = refls[0]['miller_index_asymmetric'] # This assert is timeconsuming when", "exclusive''' if len(reflections) != 0: all_keys = list() for key", "is empty, generated \"refls\" lists cannot be empty hkl =", "multiply-measured symmetry-reduced HKLs''' merged_reflections = reflection_table_utils.merged_reflection_table() for refls in reflection_table_utils.get_next_hkl_reflection_table(reflections=reflections):", "hkl yield reflections[i_begin:i+1] @staticmethod def select_odd_experiment_reflections(reflections): 'Select reflections from experiments", "min_multiplicity): '''Merge intensities of multiply-measured symmetry-reduced HKLs''' merged_reflections = reflection_table_utils.merged_reflection_table()", "= refls[0]['miller_index_asymmetric'] # This assert is timeconsuming when using a", "if refls.size() == 0: break # unless the input \"reflections\"", "else: yield reflections[i_begin:i] i_begin = i hkl_ref = hkl yield", "\"reflections\" list is empty, generated \"refls\" lists cannot be empty", "!= None: for key in all_keys: #if not key in", "number' sel = flex.bool() for refl in reflections: sel.append(int(refl['exp_id'], 16)%2", "for refl in reflections: sel.append(int(refl['exp_id'], 16)%2 != 0) return reflections.select(sel)", "reflection table for storing merged HKLs''' table = flex.reflection_table() table['miller_index']", "HKLs''' table = flex.reflection_table() table['miller_index'] = flex.miller_index() table['intensity'] = flex.double()", "a small number of cores #assert not (hkl in merged_reflections['miller_index'])", "keys_to_delete=None, keys_to_keep=None): '''Remove reflection table keys: either inclusive or exclusive'''", "#assert not (hkl in merged_reflections['miller_index']) # i.e. assert that the", "reflection table''' if reflections.size() == 0: yield reflections i_begin =", "table['intensity'] = flex.double() table['sigma'] = flex.double() table['multiplicity'] = flex.int() return", "{'miller_index' : hkl, 'intensity' : weighted_mean_intensity, 'sigma' : standard_error_of_weighted_mean_intensity, 'multiplicity'", "merged_reflections['miller_index']) # i.e. assert that the input reflection table came", "del reflections[key] elif keys_to_keep != None: for key in all_keys:", "in all_keys: #if not key in ['intensity.sum.value', 'intensity.sum.variance', 'miller_index', 'miller_index_asymmetric',", "'Select reflections from experiments with odd ids. An experiment id", "/ refls['intensity.sum.variance'] weighted_mean_intensity = flex.sum(weighted_intensity_array) / flex.sum(weights_array) standard_error_of_weighted_mean_intensity = 1.0/math.sqrt(flex.sum(weights_array))", "yield reflections[i_begin:i+1] @staticmethod def select_odd_experiment_reflections(reflections): 'Select reflections from experiments with", "keys: either inclusive or exclusive''' if len(reflections) != 0: all_keys", "reflections[i].get('miller_index_asymmetric') if hkl == hkl_ref: continue else: yield reflections[i_begin:i] i_begin", "reflections from experiments with even ids. An experiment id must", "keys_to_delete != None: for key in keys_to_delete: if key in", "= reflections[i].get('miller_index_asymmetric') if hkl == hkl_ref: continue else: yield reflections[i_begin:i]", "0) return reflections.select(sel) @staticmethod def select_even_experiment_reflections(reflections): 'Select reflections from experiments", "merged HKLs''' table = flex.reflection_table() table['miller_index'] = flex.miller_index() table['intensity'] =", "'odd_frame', 's1']: if not key in keys_to_keep: del reflections[key] return", "if len(reflections) != 0: all_keys = list() for key in", "yield reflections[i_begin:i] i_begin = i hkl_ref = hkl yield reflections[i_begin:i+1]", "@staticmethod def merge_reflections(reflections, min_multiplicity): '''Merge intensities of multiply-measured symmetry-reduced HKLs'''", "ids. An experiment id must be a string representing a", "flex.reflection_table() table['miller_index'] = flex.miller_index() table['intensity'] = flex.double() table['sigma'] = flex.double()", "in reflections[0]: all_keys.append(key) if keys_to_delete != None: for key in", "elif keys_to_keep != None: for key in all_keys: #if not", "= reflection_table_utils.merged_reflection_table() for refls in reflection_table_utils.get_next_hkl_reflection_table(reflections=reflections): if refls.size() == 0:", "== hkl_ref: continue else: yield reflections[i_begin:i] i_begin = i hkl_ref", "reflections[i_begin:i+1] @staticmethod def select_odd_experiment_reflections(reflections): 'Select reflections from experiments with odd", "inclusive or exclusive''' if len(reflections) != 0: all_keys = list()", "the input \"reflections\" list is empty, generated \"refls\" lists cannot", "> 0.0) if refls.size() >= min_multiplicity: weighted_intensity_array = refls['intensity.sum.value'] /", "break # unless the input \"reflections\" list is empty, generated", "for key in all_keys: #if not key in ['intensity.sum.value', 'intensity.sum.variance',", "refls = refls.select(refls['intensity.sum.variance'] > 0.0) if refls.size() >= min_multiplicity: weighted_intensity_array", "@staticmethod def prune_reflection_table_keys(reflections, keys_to_delete=None, keys_to_keep=None): '''Remove reflection table keys: either", "prune_reflection_table_keys(reflections, keys_to_delete=None, keys_to_keep=None): '''Remove reflection table keys: either inclusive or", "key in ['intensity.sum.value', 'intensity.sum.variance', 'miller_index', 'miller_index_asymmetric', 'exp_id', 'odd_frame', 's1']: if", "a reflection table for storing merged HKLs''' table = flex.reflection_table()", "hkl = refls[0]['miller_index_asymmetric'] # This assert is timeconsuming when using", "when using a small number of cores #assert not (hkl", "= hkl yield reflections[i_begin:i+1] @staticmethod def select_odd_experiment_reflections(reflections): 'Select reflections from", "i hkl_ref = hkl yield reflections[i_begin:i+1] @staticmethod def select_odd_experiment_reflections(reflections): 'Select", "HKLs''' merged_reflections = reflection_table_utils.merged_reflection_table() for refls in reflection_table_utils.get_next_hkl_reflection_table(reflections=reflections): if refls.size()", "flex.double() table['sigma'] = flex.double() table['multiplicity'] = flex.int() return table @staticmethod", "<gh_stars>0 from __future__ import absolute_import, division, print_function from six.moves import", "list is empty, generated \"refls\" lists cannot be empty hkl", "weights_array = flex.double(refls.size(), 1.0) / refls['intensity.sum.variance'] weighted_mean_intensity = flex.sum(weighted_intensity_array) /", "for i in range(reflections.size()): hkl = reflections[i].get('miller_index_asymmetric') if hkl ==", "class reflection_table_utils(object): @staticmethod def get_next_hkl_reflection_table(reflections): '''Generate asu hkl slices from", "flex.int() return table @staticmethod def merge_reflections(reflections, min_multiplicity): '''Merge intensities of", "hkl-sorted reflection table''' if reflections.size() == 0: yield reflections i_begin", "import flex import math class reflection_table_utils(object): @staticmethod def get_next_hkl_reflection_table(reflections): '''Generate", "all_keys: del reflections[key] elif keys_to_keep != None: for key in", "sel = flex.bool() for refl in reflections: sel.append(int(refl['exp_id'], 16)%2 ==", "six.moves import range from dials.array_family import flex import math class", "hkl == hkl_ref: continue else: yield reflections[i_begin:i] i_begin = i", "= flex.int() return table @staticmethod def merge_reflections(reflections, min_multiplicity): '''Merge intensities", "def merge_reflections(reflections, min_multiplicity): '''Merge intensities of multiply-measured symmetry-reduced HKLs''' merged_reflections", "key in keys_to_delete: if key in all_keys: del reflections[key] elif", "reflections[i_begin:i] i_begin = i hkl_ref = hkl yield reflections[i_begin:i+1] @staticmethod", "from experiments with odd ids. An experiment id must be", "in merged_reflections['miller_index']) # i.e. assert that the input reflection table", "/ refls['intensity.sum.variance'] weights_array = flex.double(refls.size(), 1.0) / refls['intensity.sum.variance'] weighted_mean_intensity =", "hkl slices from an asu hkl-sorted reflection table''' if reflections.size()", "select_odd_experiment_reflections(reflections): 'Select reflections from experiments with odd ids. An experiment", "0: break # unless the input \"reflections\" list is empty,", "an asu hkl-sorted reflection table''' if reflections.size() == 0: yield", "0: all_keys = list() for key in reflections[0]: all_keys.append(key) if", "get_next_hkl_reflection_table(reflections): '''Generate asu hkl slices from an asu hkl-sorted reflection", "in sorted refls = refls.select(refls['intensity.sum.variance'] > 0.0) if refls.size() >=", "asu hkl slices from an asu hkl-sorted reflection table''' if", "= 1.0/math.sqrt(flex.sum(weights_array)) merged_reflections.append( {'miller_index' : hkl, 'intensity' : weighted_mean_intensity, 'sigma'", "refls['intensity.sum.variance'] weighted_mean_intensity = flex.sum(weighted_intensity_array) / flex.sum(weights_array) standard_error_of_weighted_mean_intensity = 1.0/math.sqrt(flex.sum(weights_array)) merged_reflections.append(", "sel.append(int(refl['exp_id'], 16)%2 == 0) return reflections.select(sel) @staticmethod def merged_reflection_table(): '''Create", "refls['intensity.sum.value'] / refls['intensity.sum.variance'] weights_array = flex.double(refls.size(), 1.0) / refls['intensity.sum.variance'] weighted_mean_intensity", "assert is timeconsuming when using a small number of cores", "len(reflections) != 0: all_keys = list() for key in reflections[0]:", "0) return reflections.select(sel) @staticmethod def merged_reflection_table(): '''Create a reflection table", "This assert is timeconsuming when using a small number of", "assert that the input reflection table came in sorted refls", "string representing a hexadecimal number' sel = flex.bool() for refl", "'''Merge intensities of multiply-measured symmetry-reduced HKLs''' merged_reflections = reflection_table_utils.merged_reflection_table() for", "is timeconsuming when using a small number of cores #assert", "table['sigma'] = flex.double() table['multiplicity'] = flex.int() return table @staticmethod def", "@staticmethod def select_even_experiment_reflections(reflections): 'Select reflections from experiments with even ids.", ": standard_error_of_weighted_mean_intensity, 'multiplicity' : refls.size()}) return merged_reflections @staticmethod def prune_reflection_table_keys(reflections,", "in range(reflections.size()): hkl = reflections[i].get('miller_index_asymmetric') if hkl == hkl_ref: continue", "generated \"refls\" lists cannot be empty hkl = refls[0]['miller_index_asymmetric'] #", "a hexadecimal number' sel = flex.bool() for refl in reflections:", "i in range(reflections.size()): hkl = reflections[i].get('miller_index_asymmetric') if hkl == hkl_ref:", "in reflection_table_utils.get_next_hkl_reflection_table(reflections=reflections): if refls.size() == 0: break # unless the", "= flex.double(refls.size(), 1.0) / refls['intensity.sum.variance'] weighted_mean_intensity = flex.sum(weighted_intensity_array) / flex.sum(weights_array)", "def merged_reflection_table(): '''Create a reflection table for storing merged HKLs'''", "of cores #assert not (hkl in merged_reflections['miller_index']) # i.e. assert", "keys_to_keep=None): '''Remove reflection table keys: either inclusive or exclusive''' if", "from experiments with even ids. An experiment id must be", "'exp_id', 'odd_frame', 's1']: if not key in keys_to_keep: del reflections[key]", "reflection table came in sorted refls = refls.select(refls['intensity.sum.variance'] > 0.0)", "'''Generate asu hkl slices from an asu hkl-sorted reflection table'''", "id must be a string representing a hexadecimal number' sel", "flex.miller_index() table['intensity'] = flex.double() table['sigma'] = flex.double() table['multiplicity'] = flex.int()", "using a small number of cores #assert not (hkl in", "experiments with even ids. An experiment id must be a", "came in sorted refls = refls.select(refls['intensity.sum.variance'] > 0.0) if refls.size()", "= list() for key in reflections[0]: all_keys.append(key) if keys_to_delete !=", "reflections.select(sel) @staticmethod def select_even_experiment_reflections(reflections): 'Select reflections from experiments with even", "'''Remove reflection table keys: either inclusive or exclusive''' if len(reflections)", "reflection table keys: either inclusive or exclusive''' if len(reflections) !=", "that the input reflection table came in sorted refls =", "!= 0: all_keys = list() for key in reflections[0]: all_keys.append(key)", "def select_odd_experiment_reflections(reflections): 'Select reflections from experiments with odd ids. An", "refl in reflections: sel.append(int(refl['exp_id'], 16)%2 != 0) return reflections.select(sel) @staticmethod", "table for storing merged HKLs''' table = flex.reflection_table() table['miller_index'] =", "all_keys: #if not key in ['intensity.sum.value', 'intensity.sum.variance', 'miller_index', 'miller_index_asymmetric', 'exp_id',", "hkl, 'intensity' : weighted_mean_intensity, 'sigma' : standard_error_of_weighted_mean_intensity, 'multiplicity' : refls.size()})", "even ids. An experiment id must be a string representing", "'intensity' : weighted_mean_intensity, 'sigma' : standard_error_of_weighted_mean_intensity, 'multiplicity' : refls.size()}) return", "range(reflections.size()): hkl = reflections[i].get('miller_index_asymmetric') if hkl == hkl_ref: continue else:", "not key in ['intensity.sum.value', 'intensity.sum.variance', 'miller_index', 'miller_index_asymmetric', 'exp_id', 'odd_frame', 's1']:", "in ['intensity.sum.value', 'intensity.sum.variance', 'miller_index', 'miller_index_asymmetric', 'exp_id', 'odd_frame', 's1']: if not", "1.0/math.sqrt(flex.sum(weights_array)) merged_reflections.append( {'miller_index' : hkl, 'intensity' : weighted_mean_intensity, 'sigma' :", "lists cannot be empty hkl = refls[0]['miller_index_asymmetric'] # This assert", "for refl in reflections: sel.append(int(refl['exp_id'], 16)%2 == 0) return reflections.select(sel)", "= flex.double() table['multiplicity'] = flex.int() return table @staticmethod def merge_reflections(reflections,", "from __future__ import absolute_import, division, print_function from six.moves import range", "table['miller_index'] = flex.miller_index() table['intensity'] = flex.double() table['sigma'] = flex.double() table['multiplicity']", "sorted refls = refls.select(refls['intensity.sum.variance'] > 0.0) if refls.size() >= min_multiplicity:", "None: for key in all_keys: #if not key in ['intensity.sum.value',", "absolute_import, division, print_function from six.moves import range from dials.array_family import", "reflections i_begin = 0 hkl_ref = reflections[0].get('miller_index_asymmetric') for i in", "merged_reflections = reflection_table_utils.merged_reflection_table() for refls in reflection_table_utils.get_next_hkl_reflection_table(reflections=reflections): if refls.size() ==", "1.0) / refls['intensity.sum.variance'] weighted_mean_intensity = flex.sum(weighted_intensity_array) / flex.sum(weights_array) standard_error_of_weighted_mean_intensity =", "import range from dials.array_family import flex import math class reflection_table_utils(object):", "representing a hexadecimal number' sel = flex.bool() for refl in", "from an asu hkl-sorted reflection table''' if reflections.size() == 0:", "@staticmethod def get_next_hkl_reflection_table(reflections): '''Generate asu hkl slices from an asu", "print_function from six.moves import range from dials.array_family import flex import", "\"refls\" lists cannot be empty hkl = refls[0]['miller_index_asymmetric'] # This", "'s1']: if not key in keys_to_keep: del reflections[key] return reflections", "reflections[0]: all_keys.append(key) if keys_to_delete != None: for key in keys_to_delete:", "in reflections: sel.append(int(refl['exp_id'], 16)%2 != 0) return reflections.select(sel) @staticmethod def", "def select_even_experiment_reflections(reflections): 'Select reflections from experiments with even ids. An", "hkl_ref = hkl yield reflections[i_begin:i+1] @staticmethod def select_odd_experiment_reflections(reflections): 'Select reflections", "of multiply-measured symmetry-reduced HKLs''' merged_reflections = reflection_table_utils.merged_reflection_table() for refls in", "'miller_index', 'miller_index_asymmetric', 'exp_id', 'odd_frame', 's1']: if not key in keys_to_keep:", "math class reflection_table_utils(object): @staticmethod def get_next_hkl_reflection_table(reflections): '''Generate asu hkl slices", "small number of cores #assert not (hkl in merged_reflections['miller_index']) #", "not (hkl in merged_reflections['miller_index']) # i.e. assert that the input", "reflections from experiments with odd ids. An experiment id must", "in all_keys: del reflections[key] elif keys_to_keep != None: for key", "'''Create a reflection table for storing merged HKLs''' table =", "asu hkl-sorted reflection table''' if reflections.size() == 0: yield reflections", "refls.select(refls['intensity.sum.variance'] > 0.0) if refls.size() >= min_multiplicity: weighted_intensity_array = refls['intensity.sum.value']", "= flex.sum(weighted_intensity_array) / flex.sum(weights_array) standard_error_of_weighted_mean_intensity = 1.0/math.sqrt(flex.sum(weights_array)) merged_reflections.append( {'miller_index' :", "return table @staticmethod def merge_reflections(reflections, min_multiplicity): '''Merge intensities of multiply-measured", "merged_reflections @staticmethod def prune_reflection_table_keys(reflections, keys_to_delete=None, keys_to_keep=None): '''Remove reflection table keys:", "for key in keys_to_delete: if key in all_keys: del reflections[key]", "= refls.select(refls['intensity.sum.variance'] > 0.0) if refls.size() >= min_multiplicity: weighted_intensity_array =", "reflections: sel.append(int(refl['exp_id'], 16)%2 != 0) return reflections.select(sel) @staticmethod def select_even_experiment_reflections(reflections):", "weighted_intensity_array = refls['intensity.sum.value'] / refls['intensity.sum.variance'] weights_array = flex.double(refls.size(), 1.0) /", "refl in reflections: sel.append(int(refl['exp_id'], 16)%2 == 0) return reflections.select(sel) @staticmethod", "refls['intensity.sum.variance'] weights_array = flex.double(refls.size(), 1.0) / refls['intensity.sum.variance'] weighted_mean_intensity = flex.sum(weighted_intensity_array)", "@staticmethod def select_odd_experiment_reflections(reflections): 'Select reflections from experiments with odd ids.", ">= min_multiplicity: weighted_intensity_array = refls['intensity.sum.value'] / refls['intensity.sum.variance'] weights_array = flex.double(refls.size(),", "return merged_reflections @staticmethod def prune_reflection_table_keys(reflections, keys_to_delete=None, keys_to_keep=None): '''Remove reflection table", "(hkl in merged_reflections['miller_index']) # i.e. assert that the input reflection", "key in all_keys: del reflections[key] elif keys_to_keep != None: for", "reflections.size() == 0: yield reflections i_begin = 0 hkl_ref =", "in keys_to_delete: if key in all_keys: del reflections[key] elif keys_to_keep", "reflection_table_utils.get_next_hkl_reflection_table(reflections=reflections): if refls.size() == 0: break # unless the input", "None: for key in keys_to_delete: if key in all_keys: del", "keys_to_delete: if key in all_keys: del reflections[key] elif keys_to_keep !=", "return reflections.select(sel) @staticmethod def select_even_experiment_reflections(reflections): 'Select reflections from experiments with", "flex.sum(weights_array) standard_error_of_weighted_mean_intensity = 1.0/math.sqrt(flex.sum(weights_array)) merged_reflections.append( {'miller_index' : hkl, 'intensity' :", "flex import math class reflection_table_utils(object): @staticmethod def get_next_hkl_reflection_table(reflections): '''Generate asu", "reflections.select(sel) @staticmethod def merged_reflection_table(): '''Create a reflection table for storing", "'multiplicity' : refls.size()}) return merged_reflections @staticmethod def prune_reflection_table_keys(reflections, keys_to_delete=None, keys_to_keep=None):", "table''' if reflections.size() == 0: yield reflections i_begin = 0", "table['multiplicity'] = flex.int() return table @staticmethod def merge_reflections(reflections, min_multiplicity): '''Merge", "!= None: for key in keys_to_delete: if key in all_keys:", "input \"reflections\" list is empty, generated \"refls\" lists cannot be", "hkl_ref = reflections[0].get('miller_index_asymmetric') for i in range(reflections.size()): hkl = reflections[i].get('miller_index_asymmetric')", "reflection_table_utils(object): @staticmethod def get_next_hkl_reflection_table(reflections): '''Generate asu hkl slices from an", "storing merged HKLs''' table = flex.reflection_table() table['miller_index'] = flex.miller_index() table['intensity']", "flex.bool() for refl in reflections: sel.append(int(refl['exp_id'], 16)%2 == 0) return", "refls in reflection_table_utils.get_next_hkl_reflection_table(reflections=reflections): if refls.size() == 0: break # unless", "'sigma' : standard_error_of_weighted_mean_intensity, 'multiplicity' : refls.size()}) return merged_reflections @staticmethod def", "keys_to_keep != None: for key in all_keys: #if not key", "0: yield reflections i_begin = 0 hkl_ref = reflections[0].get('miller_index_asymmetric') for", "@staticmethod def merged_reflection_table(): '''Create a reflection table for storing merged", "= i hkl_ref = hkl yield reflections[i_begin:i+1] @staticmethod def select_odd_experiment_reflections(reflections):", "hkl_ref: continue else: yield reflections[i_begin:i] i_begin = i hkl_ref =", "if hkl == hkl_ref: continue else: yield reflections[i_begin:i] i_begin =", "refls.size() == 0: break # unless the input \"reflections\" list", "import absolute_import, division, print_function from six.moves import range from dials.array_family", "intensities of multiply-measured symmetry-reduced HKLs''' merged_reflections = reflection_table_utils.merged_reflection_table() for refls", "if key in all_keys: del reflections[key] elif keys_to_keep != None:", "table @staticmethod def merge_reflections(reflections, min_multiplicity): '''Merge intensities of multiply-measured symmetry-reduced", "= reflections[0].get('miller_index_asymmetric') for i in range(reflections.size()): hkl = reflections[i].get('miller_index_asymmetric') if", "slices from an asu hkl-sorted reflection table''' if reflections.size() ==", "must be a string representing a hexadecimal number' sel =", "table = flex.reflection_table() table['miller_index'] = flex.miller_index() table['intensity'] = flex.double() table['sigma']", "range from dials.array_family import flex import math class reflection_table_utils(object): @staticmethod", "the input reflection table came in sorted refls = refls.select(refls['intensity.sum.variance']", "def get_next_hkl_reflection_table(reflections): '''Generate asu hkl slices from an asu hkl-sorted", "unless the input \"reflections\" list is empty, generated \"refls\" lists", "= flex.reflection_table() table['miller_index'] = flex.miller_index() table['intensity'] = flex.double() table['sigma'] =", "weighted_mean_intensity = flex.sum(weighted_intensity_array) / flex.sum(weights_array) standard_error_of_weighted_mean_intensity = 1.0/math.sqrt(flex.sum(weights_array)) merged_reflections.append( {'miller_index'", "or exclusive''' if len(reflections) != 0: all_keys = list() for", "symmetry-reduced HKLs''' merged_reflections = reflection_table_utils.merged_reflection_table() for refls in reflection_table_utils.get_next_hkl_reflection_table(reflections=reflections): if", "if reflections.size() == 0: yield reflections i_begin = 0 hkl_ref", "16)%2 != 0) return reflections.select(sel) @staticmethod def select_even_experiment_reflections(reflections): 'Select reflections", "table came in sorted refls = refls.select(refls['intensity.sum.variance'] > 0.0) if", "in reflections: sel.append(int(refl['exp_id'], 16)%2 == 0) return reflections.select(sel) @staticmethod def", "= flex.bool() for refl in reflections: sel.append(int(refl['exp_id'], 16)%2 == 0)", "flex.double(refls.size(), 1.0) / refls['intensity.sum.variance'] weighted_mean_intensity = flex.sum(weighted_intensity_array) / flex.sum(weights_array) standard_error_of_weighted_mean_intensity", "0 hkl_ref = reflections[0].get('miller_index_asymmetric') for i in range(reflections.size()): hkl =", "be empty hkl = refls[0]['miller_index_asymmetric'] # This assert is timeconsuming", "hexadecimal number' sel = flex.bool() for refl in reflections: sel.append(int(refl['exp_id'],", "min_multiplicity: weighted_intensity_array = refls['intensity.sum.value'] / refls['intensity.sum.variance'] weights_array = flex.double(refls.size(), 1.0)", "['intensity.sum.value', 'intensity.sum.variance', 'miller_index', 'miller_index_asymmetric', 'exp_id', 'odd_frame', 's1']: if not key", "flex.double() table['multiplicity'] = flex.int() return table @staticmethod def merge_reflections(reflections, min_multiplicity):", "sel.append(int(refl['exp_id'], 16)%2 != 0) return reflections.select(sel) @staticmethod def select_even_experiment_reflections(reflections): 'Select", "standard_error_of_weighted_mean_intensity = 1.0/math.sqrt(flex.sum(weights_array)) merged_reflections.append( {'miller_index' : hkl, 'intensity' : weighted_mean_intensity,", "for key in reflections[0]: all_keys.append(key) if keys_to_delete != None: for", "= refls['intensity.sum.value'] / refls['intensity.sum.variance'] weights_array = flex.double(refls.size(), 1.0) / refls['intensity.sum.variance']", "key in all_keys: #if not key in ['intensity.sum.value', 'intensity.sum.variance', 'miller_index',", "for refls in reflection_table_utils.get_next_hkl_reflection_table(reflections=reflections): if refls.size() == 0: break #", "# unless the input \"reflections\" list is empty, generated \"refls\"", "with odd ids. An experiment id must be a string", "# This assert is timeconsuming when using a small number", "from six.moves import range from dials.array_family import flex import math", "def prune_reflection_table_keys(reflections, keys_to_delete=None, keys_to_keep=None): '''Remove reflection table keys: either inclusive", "flex.sum(weighted_intensity_array) / flex.sum(weights_array) standard_error_of_weighted_mean_intensity = 1.0/math.sqrt(flex.sum(weights_array)) merged_reflections.append( {'miller_index' : hkl,", "number of cores #assert not (hkl in merged_reflections['miller_index']) # i.e.", "#if not key in ['intensity.sum.value', 'intensity.sum.variance', 'miller_index', 'miller_index_asymmetric', 'exp_id', 'odd_frame',", "if keys_to_delete != None: for key in keys_to_delete: if key" ]
[ "self.GC_CAN_MOVE def define_shrink_array(cls): from rpython.rtyper.lltypesystem.rstr import STR def f(): ptr", "def define_nongc_static_root_minor_collect(cls): T1 = lltype.GcStruct(\"C\", ('x', lltype.Signed)) T2 = lltype.Struct(\"C\",", "ourselves, otherwise this test takes ages llop.gc__collect(lltype.Void) tb = rgc._heap_stats()", "collect x = [] for i in range(20): x.append((1, lltype.malloc(S)))", "malloc_a_lot def test_llinterp_tuples(self): run = self.runner(\"llinterp_tuples\") run([]) def define_llinterp_dict(self): class", "StringBuilder(4) s.append(\"abcd\") s.append(\"defg\") s.append(\"rty\") s.append_multiple_char('y', 1000) gc.collect() s.append_multiple_char('y', 1000) res", "def test_tagged_simple(self): func = self.runner(\"tagged_simple\") res = func([]) assert res", "= UnboxedObject(47) def fn(n): rgc.collect() # check that a prebuilt", "+= 1 def f(x, y): a = AAA() i =", "test_write_barrier_direct(self): run = self.runner(\"write_barrier_direct\") res = run([]) assert res ==", "number above does not count # the number of prebuilt", "== ptr2) + ord(ptr2.chars[0]) + (ord(ptr2.chars[1]) << 8) + (len(ptr2.chars)", "test_finalizer_calls_malloc(self): run = self.runner(\"finalizer_calls_malloc\") res = run([5, 42]) #XXX pure", "8 def rtype(func, inputtypes, specialize=True, gcname='ref', backendopt=False, **extraconfigopts): from rpython.translator.translator", "name_to_func[name] = len(funcs0) if nargs == 2: funcs2.append(func) funcs0.append(None) elif", "f6()) assert func() == 111111 return func def test_interior_ptrs(self): run", "cause a minor collect all[i] = [i] * i i", "+= 1 def __del__(self): b.num_deleted += 1 def f(x, y):", "= 200 def define_malloc_array_of_gcptr(self): S = lltype.GcStruct('S', ('x', lltype.Signed)) A", "lltype.malloc(A, 5) return (lst[0] == lltype.nullptr(S) and lst[1] == lltype.nullptr(S)", "a = A() persistent_a3 = A() persistent_a4 = A() llop.gc__collect(lltype.Void)", "S1 = Struct(\"S1\", ('x', Signed)) T1 = GcStruct(\"T1\", ('s', S1))", "p.x = r.x return p.x def f(): i = 0", "is fine llop.gc__collect(lltype.Void) result = result and (ref() is None)", "lltype.nullptr(S) return f, cleanup, None def test_write_barrier_direct(self): run = self.runner(\"write_barrier_direct\")", "UnboxedValue): __slots__ = 'smallint' def meth(self, x): return self.smallint +", "while j < 30: b = B(somea) b.last = first", "mixlevelstuff = [] for fullname in dir(cls): if not fullname.startswith('define'):", "i] return 0 return fn def test_writebarrier_before_copy(self): run = self.runner(\"writebarrier_before_copy\")", "def define_string_concatenation(cls): def concat(j, dummy): lst = [] for i", "t = rtype(entrypoint, [s_args], gcname=cls.gcname, taggedpointers=cls.taggedpointers) for fixup in mixlevelstuff:", "a = somea = A() a.last = first first =", "a.count == 1 and (ref() is None) return result return", "fixup(t) cbuild = CStandaloneBuilder(t, entrypoint, config=t.config, gcpolicy=cls.gcpolicy) db = cbuild.generate_graphs_for_llinterp()", "= self.runner('instantiate_nonmovable') assert res([]) == 0 class TestIncrementalMiniMarkGC(TestMiniMarkGC): gcname =", "def sub(lst): lst[15] = lltype.malloc(S) # 'lst' is set the", "lst[3] == lltype.nullptr(S) and lst[4] == lltype.nullptr(S)) return f def", "u = Unrelated() u.x = UnboxedObject(47) def fn(n): rgc.collect() #", "6: # * all[0] # * all[1] # * parent.sub", "fn(): objects = [] hashes = [] for i in", "def malloc_a_lot(): i = 0 first = None while i", "= all[x] #all[x] = lltype.nullptr(T_PARENT.TO) return res.sub.field return f def", "in range(200): rgc.collect(0) # nursery-only collection, if possible obj =", "specialize=True, gcname='ref', backendopt=False, **extraconfigopts): from rpython.translator.translator import TranslationContext t =", "is None) return f def test_finalizer_resurrects(self): run = self.runner(\"finalizer_resurrects\") res", "1) u[0].s.x = 1 return u[0].s.x S5 = Struct(\"S5\", ('x',", "return func def test_can_move(self): run = self.runner(\"can_move\") res = run([])", "idarray[i] = compute_unique_id(alist[i]) i += 1 j = 0 while", "a = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted return f def", "10: a += 1 nr = i if tb[i].count >", "= self.runner(\"interior_ptrs\") res = run([]) assert res == 111111 def", "= 0 d = 0 e = 0 for i", "def test_static_root_minor_collect(self): run = self.runner(\"static_root_minor_collect\") res = run([]) assert res", "0 c = 0 d = 0 e = 0", "GcArray(S2) def f2(): t = malloc(T2, 1) t[0].x = 1", "0 while i < 40: g() i += q.x return", "== 20 + 20 def define_nongc_static_root_minor_collect(cls): T1 = lltype.GcStruct(\"C\", ('x',", "A() ref = weakref.ref(a) result = ref() is a ref", "static.p = lltype.nullptr(T1) return f, cleanup, None def test_nongc_static_root_minor_collect(self): run", "* 50) llop.gc__collect(lltype.Void) return box.lst[j][0] return append_to_list, None, None def", "= cls.marker def cleanup(): assert marker[0] > 0 marker[0] =", "gcname = \"semispace\" GC_CAN_SHRINK_ARRAY = True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer):", "import weakref class A: pass def f(): a = A()", "funcs0 = [] funcs2 = [] cleanups = [] name_to_func", "res == 123 def define_nursery_hash_base(cls): class A: pass def fn():", "A(object): pass def malloc_a_lot(): i = 0 while i <", "lambda_customtrace) tx = lltype.malloc(T) tx.z = 4243 s1 = lltype.malloc(S)", "return 0 return f def test_adr_of_nursery(self): run = self.runner(\"adr_of_nursery\") res", "import MiniMarkGC as GCClass GC_PARAMS = {'nursery_size': 32*WORD, 'page_size': 16*WORD,", "# The optimization find_clean_setarrayitems() in # gctransformer/framework.py does not work", "f2(): t = malloc(T2, 1) t[0].x = 1 return t[0].x", "class AAA(object): def __init__(self): self.id = b.nextid b.nextid += 1", "16*WORD, 'arena_size': 64*WORD, 'small_request_threshold': 5*WORD, 'large_object': 8*WORD, 'card_page_indices': 4, 'translated_to_c':", "lltype.Struct(\"C\", ('p', lltype.Ptr(T1))) static = lltype.malloc(T2, immortal=True) def f(): t1", "T3 = GcStruct(\"T3\", ('items', Array(S3))) def f3(): t = malloc(T3,", "return f def test_weakref_across_minor_collection(self): run = self.runner(\"weakref_across_minor_collection\") res = run([])", "('x', lltype.Signed)) def g(): r = lltype.malloc(P) r.x = 1", "= 0 else: cleanup = None def fix_graph_of_g(translator): from rpython.translator.translator", "100) for i in range(100): l[i] = lltype.malloc(S) rgc.ll_arraycopy(l, l2,", "_, name = fullname.split('_', 1) func_fixup = definefunc.im_func(cls) cleanup =", "j += 1 lltype.free(idarray, flavor='raw') return 0 return f def", "A = lltype.GcArray(lltype.Ptr(S)) def sub(lst): lst[15] = lltype.malloc(S) # 'lst'", "+ persistent_a3.id + persistent_a4.id # NB print would create a", "class A(object): pass def g(): a = A() return weakref.ref(a)", "llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted * 10 + aid + 100", "TestMiniMarkGC(TestHybridGC): gcname = \"minimark\" GC_CAN_TEST_ID = True class gcpolicy(gc.BasicFrameworkGcPolicy): class", "= [i] * i i += 1 i = static.p.x", "lst[0] rgc.collect() # -> crash return lst[0].x return f def", "A() static.p = None def f(): t1 = B() t1.x", "rpython.translator.c import gc from rpython.annotator import model as annmodel from", "3) ptr.hash = 0x62 ptr.chars[0] = '0' ptr.chars[1] = 'B'", "* size_of_int) % 4 == 0 # ^^^ a crude", "b.num_deleted return f def test_finalizer(self): run = self.runner(\"finalizer\") res =", "= False # collecting here is expected GenerationGC._teardown(self) GC_PARAMS =", "+= 1 a = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted return", "test_adr_of_nursery(self): run = self.runner(\"adr_of_nursery\") res = run([]) class TestGenerationalNoFullCollectGC(GCTest): #", "def test_llinterp_dict(self): run = self.runner(\"llinterp_dict\") run([]) def skipdefine_global_list(cls): gl =", "test takes ages llop.gc__collect(lltype.Void) tb = rgc._heap_stats() a = 0", "= malloc(T1) t.s.x = 1 return t.s.x S2 = Struct(\"S2\",", "gctransformer/framework.py does not work with card marking. # Check that", "has_finalizer Constant(False, lltype.Bool), # is_finalizer_light Constant(False, lltype.Bool)] # contains_weakptr break", "assert res == 0 def define_can_move(cls): TP = lltype.GcArray(lltype.Float) def", "null # clear, so that A() is only visible via", "test_collect_during_collect(self): run = self.runner(\"collect_during_collect\") # runs collect recursively 4 times", "'x') def customtrace(gc, obj, callback, arg): gc._trace_callback(callback, arg, obj +", "idarray[i] == compute_unique_id(alist[i]) i += 1 j += 1 lltype.free(idarray,", "return f def test_weakref_to_object_with_finalizer(self): run = self.runner(\"weakref_to_object_with_finalizer\") res = run([])", "l1 = [] l2 = [] l3 = [] l4", "+ i def cleanup(): static.p = None return f, cleanup,", "= 0 i = 0 while i < 40: lst", "ll_assert(not self.__ready, \"no full collect should occur in this test\")", "res = func([]) assert res == 205 def define_tagged_prebuilt(cls): class", "contains_weakptr break else: assert 0, \"oups, not found\" return f,", "gc.object_id_dict. def define_adr_of_nursery(cls): class A(object): pass def f(): # we", "1 def __del__(self): llop.gc__collect(lltype.Void) b.num_deleted += 1 C() C() class", "q.x = 1 i = 0 while i < 40:", "+ 20 def define_nongc_static_root_minor_collect(cls): T1 = lltype.GcStruct(\"C\", ('x', lltype.Signed)) T2", "rpython.memory.gc.incminimark import IncrementalMiniMarkGC \\ as GCClass GC_PARAMS = {'nursery_size': 32*WORD,", "def test_instantiate_nonmovable(self): res = self.runner('instantiate_nonmovable') assert res([]) == 0 class", "nf1 assert nt1 == nt0 return 0 return f def", "== 123 def define_nursery_hash_base(cls): class A: pass def fn(): objects", "= j*2 lst = lltype.malloc(A, j) # the following line", "P = lltype.GcStruct('P', ('x', lltype.Signed)) def g(): llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder", "lst[0] = lst[15] # that would be a \"clean_setarrayitem\" def", "rgc.collect(0) return s0.next.x def cleanup(): s0.next = lltype.nullptr(S) return f,", "None) return result return f def test_weakref(self): run = self.runner(\"weakref\")", "160 <= res <= 165 def define_custom_trace(cls): # S =", "len(''.join([str(x) for x in range(100)])) def define_interior_ptrs(cls): from rpython.rtyper.lltypesystem.lltype import", "here too assert 160 <= res <= 165 def define_custom_trace(cls):", "pass f = F() f.l = [UnboxedObject(10)] def fn(n): if", "ensure_layoutbuilder(cls, translator): jit2gc = getattr(translator, '_jit2gc', None) if jit2gc: assert", "50, 0, 50) # force nursery collect x = []", ">= 195 def define_instantiate_nonmovable(cls): from rpython.rlib import objectmodel from rpython.rtyper", "rpython.rtyper.lltypesystem import rffi alist = [A() for i in range(50)]", "x: i += 1 a = A() persistent_a3 = A()", "i in range(10): s = lltype.malloc(S) l1.append(s) l2.append(s) if i", "child = lltype.malloc(T_CHILD.TO) child2 = lltype.malloc(T_CHILD.TO) parent = lltype.malloc(T_PARENT.TO) parent2", "GcArray from rpython.rtyper.lltypesystem.lltype import Array, Signed, malloc S1 = Struct(\"S1\",", "that __del__ is not called again llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted", "pass b = B() b.nextid = 0 b.num_deleted = 0", "definefunc.im_func(cls) cleanup = None if isinstance(func_fixup, tuple): func, cleanup, fixup", "__slots__ = () def meth(self, x): raise NotImplementedError class BoxedObject(TaggedBase):", "cleanups = [] name_to_func = {} mixlevelstuff = [] for", "def f(): q = lltype.malloc(P) q.x = 1 i =", "marker[0] > 0 marker[0] = 0 else: cleanup = None", "number of locations # within prebuilt GC objects that are", "if nargs == 2: funcs2.append(func) funcs0.append(None) elif nargs == 0:", "parent2.sub = child2 child2.field = 8 T_ALL = lltype.Ptr(lltype.GcArray(T_PARENT)) all", "0 b.num_deleted = 0 class A(object): def __init__(self): self.id =", "= self.runner('malloc_array_of_gcptr') res = run([]) assert res def define_malloc_struct_of_gcptr(cls): S1", "assert res == 6 def define_finalizer_calls_malloc(cls): class B(object): pass b", "compute_unique_id(a1) id2 = compute_unique_id(a2) id3 = compute_unique_id(a3) llop.gc__collect(lltype.Void) error =", "42 def define_finalizer(cls): class B(object): pass b = B() b.nextid", "+= 1 a = A() persistent_a3 = A() persistent_a4 =", "rgc.collect() objectmodel.keepalive_until_here(a) return res return fn def test_instantiate_nonmovable(self): res =", "define_tagged_prebuilt(cls): class F: pass f = F() f.l = [UnboxedObject(10)]", "to allocate a nursery a = A() nf_a = llop.gc_adr_of_nursery_free(llmemory.Address)", "class TaggedPointerGCTests(GCTest): taggedpointers = True def define_tagged_simple(cls): class Unrelated(object): pass", "run([]) assert res == 84 def define_many_weakrefs(cls): # test for", "A = lltype.GcArray(lltype.Ptr(S)) def f(): lst = lltype.malloc(A, 5) return", "table which we later on # process ourselves, otherwise this", "for fullname in dir(cls): if not fullname.startswith('define'): continue definefunc =", "!= compute_unique_id(a3): error += 4 return error return func def", "run = self.runner(\"custom_trace\") res = run([]) assert res == 4243", "compute_identity_hash from rpython.translator.c import gc from rpython.annotator import model as", "# is needed when most allocated objects die quickly gcname", "that if the GC needs memory to # remember the", "b.num_deleted += 1 def f(x, y): a = A() i", "u[0].s.x S5 = Struct(\"S5\", ('x', Signed)) T5 = GcStruct(\"T5\", ('items',", "1 C() C() class C(A): def __del__(self): b.num_deleted += 1", "lltype.malloc(A, 16) # 16 > 10 rgc.collect() sub(lst) null =", "if option.view: t.viewcg() return t ARGS = lltype.FixedSizeArray(lltype.Signed, 3) class", "self.runner(\"can_move\") res = run([]) assert res == self.GC_CAN_MOVE def define_shrink_array(cls):", "setup => resets the gc llinterp.eval_graph(setupgraph, []) def run(args): ll_args", "define_llinterp_dict(self): class A(object): pass def malloc_a_lot(): i = 0 while", ":-(\") run = self.runner(\"many_ids\") run([]) @classmethod def ensure_layoutbuilder(cls, translator): jit2gc", "512*WORD, 'nursery_size': 32*WORD, 'large_object': 8*WORD, 'translated_to_c': False} root_stack_depth = 200", "False} root_stack_depth = 200 def define_ref_from_rawmalloced_to_regular(cls): import gc S =", "False): teardowngraph = gct.frameworkgc__teardown_ptr.value._obj.graph llinterp.eval_graph(teardowngraph, []) self.__class__._used = True #", "b.a.id b.a = None # check that __del__ is not", "________________________________________________________________ # tagged pointers class TaggedPointerGCTests(GCTest): taggedpointers = True def", "lltype.Signed)) l1 = [] l2 = [] l3 = []", "self.runner(\"nongc_static_root_minor_collect\") res = run([]) assert res == 84 def define_static_root_minor_collect(cls):", "= self.db name_to_func = self.name_to_func entrygraph = self.entrygraph from rpython.rtyper.llinterp", "= lltype.GcStruct('S', ('x', lltype.Char)) TP = lltype.GcArray(lltype.Ptr(S)) def fn(): l", "1 total += len(lst) i += 1 return total return", "i = 0 while i < len(alist): assert idarray[i] ==", "= self.runner(\"finalizer_calls_malloc\") res = run([5, 42]) #XXX pure lazyness here", "count = 0 a = A() class B(object): def __del__(self):", "= None def fix_graph_of_g(translator): from rpython.translator.translator import graphof from rpython.flowspace.model", "for a minor collection a = A() a.foo = x", "i += 1 return total return f def test_working_nursery(self): run", "j = 0 while j < 20: j += 1", "lltype.Ptr(S1))) s0 = lltype.malloc(S) def f(): return (s0.filed1 == lltype.nullptr(S1)", "def test_custom_trace(self): run = self.runner(\"custom_trace\") res = run([]) assert res", "res def define_malloc_struct_of_gcptr(cls): S1 = lltype.GcStruct('S', ('x', lltype.Signed)) S =", "if specialize: t.buildrtyper().specialize() if backendopt: from rpython.translator.backendopt.all import backend_optimizations backend_optimizations(t)", "lltype.malloc(rffi.CArray(lltype.Signed), 1, flavor='raw', zero=True) funcs0 = [] funcs2 = []", "= lltype.malloc(S) def f(): return (s0.filed1 == lltype.nullptr(S1) and s0.filed2", "+ f3() * 1000 + f4() * 100 + f5()", "+= 1 a = AAA() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted return", "run([]) class TestGenerationalNoFullCollectGC(GCTest): # test that nursery is doing its", "too\") run = self.runner(\"global_list\") res = run([0, 0]) assert res", "= lltype.malloc(S) rgc.ll_arraycopy(l, l2, 50, 0, 50) # force nursery", "if backendopt: from rpython.translator.backendopt.all import backend_optimizations backend_optimizations(t) if option.view: t.viewcg()", "check that a further collection is fine llop.gc__collect(lltype.Void) result =", "return t.items[0].x S4 = Struct(\"S4\", ('x', Signed)) T4 = Struct(\"T4\",", "def __del__(self): a.count += 1 def g(): b = B()", "('field', lltype.Signed))) T_PARENT = lltype.Ptr(lltype.GcStruct('Parent', ('sub', T_CHILD))) child = lltype.malloc(T_CHILD.TO)", "llop.gc__collect(lltype.Void) b.num_deleted += 1 C() C() class C(A): def __del__(self):", "+= 1 def __del__(self): llop.gc__collect(lltype.Void) b.num_deleted += 1 C() C()", "i += 1 return 0 if cls.gcname == 'incminimark': marker", "1 return t.s[0] def func(): return (f1() * 100000 +", "is_finalizer_light Constant(False, lltype.Bool)] # contains_weakptr break else: assert 0, \"oups,", "the elements of the list. The goal is # to", "d * 1000 + c * 100 + b *", "j < 2: if j == 1: # allocate some", "# tagged pointers class TaggedPointerGCTests(GCTest): taggedpointers = True def define_tagged_simple(cls):", "import LLInterpreter llinterp = LLInterpreter(self.rtyper) gct = db.gctransformer if self.__class__.__dict__.get('_used',", "- varsize would be dividable by 4 # (and give", "= F() f.l = [UnboxedObject(10)] def fn(n): if n >", "# remember the ids, it will trigger some collections itself", "i < len(alist): idarray[i] = compute_unique_id(alist[i]) i += 1 j", "= lst[15] # that would be a \"clean_setarrayitem\" def f():", "offset_of_x = llmemory.offsetof(S, 'x') def customtrace(gc, obj, callback, arg): gc._trace_callback(callback,", "f(x, y): a = A() i = 0 while i", "assert compute_identity_hash(objects[i]) == hashes[i] unique[hashes[i]] = None return len(unique) return", "self.entrygraph from rpython.rtyper.llinterp import LLInterpreter llinterp = LLInterpreter(self.rtyper) gct =", "= run([]) assert res == 42 class TestMiniMarkGC(TestHybridGC): gcname =", "0 if cls.gcname == 'incminimark': marker = cls.marker def cleanup():", "1 assert ref() is a llop.gc__collect(lltype.Void) assert ref() is a", "assert res == -1999 def define_gettypeid(cls): class A(object): pass def", "for i in range(len(tb)): if tb[i].count == 10: a +=", "T_ALL = lltype.Ptr(lltype.GcArray(T_PARENT)) all = lltype.malloc(T_ALL.TO, 2) all[0] = parent", "i = 0 while i < len(alist): idarray[i] = compute_unique_id(alist[i])", "class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.semispace import SemiSpaceGC as GCClass GC_PARAMS =", "func = self.runner(\"tagged_simple\") res = func([]) assert res == 205", "b.num_deleted * 10 + aid + 100 * (b.a is", "result = a.count == 1 and (ref() is None) return", "def __del__(self): b.num_deleted += 1 b.num_deleted_c += 1 def f(x,", "assert func() == 111111 return func def test_interior_ptrs(self): run =", "run = self.runner(\"malloc_struct_of_gcptr\") res = run([]) assert res # ________________________________________________________________", "= func([]) assert res == 205 def define_tagged_prebuilt(cls): class F:", "attrvalue = 66 def __init__(self, normalint): self.normalint = normalint def", "assert func() == -1999 return func def test_tagged_prebuilt(self): func =", "def define_tagged_simple(cls): class Unrelated(object): pass u = Unrelated() u.x =", "test_gettypeid(self): func = self.runner(\"gettypeid\") res = func([]) print res from", "if op.opname == 'do_malloc_fixedsize': op.args = [Constant(type_id, llgroup.HALFWORD), Constant(llmemory.sizeof(P), lltype.Signed),", "class A(object): pass class B(A): def __init__(self, something): self.something =", "res = run([100, 0]) assert res == len(''.join([str(x) for x", "512*WORD, 'translated_to_c': False} root_stack_depth = 200 class TestGenerationGC(GenericMovingGCTests): gcname =", "S2 = Struct(\"S2\", ('x', Signed)) T2 = GcArray(S2) def f2():", "generates a write_barrier call at the moment, # which is", "j == 1: # allocate some stuff between the two", "C() class C(A): def __del__(self): b.num_deleted += 1 b.num_deleted_c +=", "while i < 40: g() i += q.x return 0", "res == 84 def define_static_root_minor_collect(cls): class A: pass class B:", "name if cleanup: cleanup.func_name = \"clean_%s\" % name nargs =", "in lltype.py :-(\") run = self.runner(\"many_ids\") run([]) @classmethod def ensure_layoutbuilder(cls,", "= 0 while j < 20: j += 1 b[1,", "rgc.collect() # -> crash return lst[0].x return f def test_no_clean_setarrayitems(self):", "db.gctransformer if self.__class__.__dict__.get('_used', False): teardowngraph = gct.frameworkgc__teardown_ptr.value._obj.graph llinterp.eval_graph(teardowngraph, []) self.__class__._used", "- 1 # crashes if constants are not considered roots", "id3 = compute_unique_id(a3) llop.gc__collect(lltype.Void) error = 0 if id1 !=", "None) if jit2gc: assert 'invoke_after_minor_collection' in jit2gc return jit2gc['layoutbuilder'] marker", "10000 + f3() * 1000 + f4() * 100 +", "def test_do_malloc_operations_in_call(self): run = self.runner(\"do_malloc_operations_in_call\") run([]) def define_gc_heap_stats(cls): S =", "obj = A() objects.append(obj) hashes.append(compute_identity_hash(obj)) unique = {} for i", "via lst[0] rgc.collect() # -> crash return lst[0].x return f", "while j < 20: j += 1 b[1, j, i]", "+= 1 return 0 return f def test_many_weakrefs(self): run =", "pure lazyness here too assert res == 6 def define_finalizer_calls_malloc(cls):", "return total return f def test_working_nursery(self): run = self.runner(\"working_nursery\") res", "GenerationGC.setup(self) self.__ready = True def semispace_collect(self, size_changing=False): ll_assert(not self.__ready, \"no", "t.config.translation.gc = gcname t.config.translation.gcremovetypeptr = True t.config.set(**extraconfigopts) ann = t.buildannotator()", "pure lazyness here too assert 160 <= res <= 165", "run = self.runner(\"shrink_array\") if self.GC_CAN_SHRINK_ARRAY: expected = 0x62024231 else: expected", "j < 5: lst.append(i*j) j += 1 total += len(lst)", "static root! llop.debug_print(lltype.Void, b.num_deleted_c) return b.num_deleted return f def test_collect_during_collect(self):", "200 def define_working_nursery(cls): def f(): total = 0 i =", "fn def test_string_builder_over_allocation(self): fn = self.runner(\"string_builder_over_allocation\") res = fn([]) assert", "50: d += 1 for i in range(len(tb)): if tb[i].count", "i = 0 while i < 10: i += 1", "* 10 + f6()) assert func() == 111111 return func", "ref = weakref.ref(a) result = ref() is a ref =", "inputtypes, specialize=True, gcname='ref', backendopt=False, **extraconfigopts): from rpython.translator.translator import TranslationContext t", "12 def define_collect_0(cls): def concat(j, dummy): lst = [] for", "cls.marker def cleanup(): assert marker[0] > 0 marker[0] = 0", "x = [] for i in range(20): x.append((1, lltype.malloc(S))) for", "define_do_malloc_operations_in_call(cls): P = lltype.GcStruct('P', ('x', lltype.Signed)) def g(): llop.do_malloc_fixedsize(llmemory.GCREF) #", "give fixedsize) def define_writebarrier_before_copy(cls): S = lltype.GcStruct('S', ('x', lltype.Char)) TP", "lltype.nullptr(T1) return f, cleanup, None def test_nongc_static_root_minor_collect(self): run = self.runner(\"nongc_static_root_minor_collect\")", "self.runner('malloc_array_of_gcptr') res = run([]) assert res def define_malloc_struct_of_gcptr(cls): S1 =", "BoxedObject(TaggedBase): attrvalue = 66 def __init__(self, normalint): self.normalint = normalint", "raise NotImplementedError class BoxedObject(TaggedBase): attrvalue = 66 def __init__(self, normalint):", "define_gc_heap_stats(cls): S = lltype.GcStruct('S', ('x', lltype.Signed)) l1 = [] l2", "# Check that it is turned off. S = lltype.GcStruct('S',", "return 0 return malloc_a_lot def test_instances(self): run = self.runner(\"instances\") run([])", "lst = [] for i in range(j): lst.append(str(i)) result =", "res == 0 def define_can_move(cls): TP = lltype.GcArray(lltype.Float) def func():", "run([]) assert res == 42 def define_finalizer(cls): class B(object): pass", "run([5, 42]) #XXX pure lazyness here too assert 160 <=", "\"f_%s\" % name if cleanup: cleanup.func_name = \"clean_%s\" % name", "func() == 111111 return func def test_interior_ptrs(self): run = self.runner(\"interior_ptrs\")", "= lltype.malloc(T1) t1.x = 42 static.p = t1 llop.gc__collect(lltype.Void) return", "concat def test_collect_0(self): run = self.runner(\"collect_0\") res = run([100, 0])", "a += 1 nr = i if tb[i].count > 50:", "crash. Investigate.\") run = self.runner(\"gc_heap_stats\") res = run([]) assert res", "def fn(n): rgc.collect() # check that a prebuilt tagged pointer", "rgc.can_move(lltype.malloc(TP, 1)) return func def test_can_move(self): run = self.runner(\"can_move\") res", "Compute the id of all the elements of the list.", "define_tagged_simple(cls): class Unrelated(object): pass u = Unrelated() u.x = UnboxedObject(47)", "+= 1 return total return f def test_working_nursery(self): run =", "= lltype.GcStruct(\"C\", ('x', lltype.Signed)) T2 = lltype.Struct(\"C\", ('p', lltype.Ptr(T1))) static", "entrygraph = entrypointptr._obj.graph if option.view: t.viewcg() cls.name_to_func = name_to_func cls.entrygraph", "assert res([]) >= 195 def define_instantiate_nonmovable(cls): from rpython.rlib import objectmodel", "framework, shadowstack from rpython.rtyper.lltypesystem.lloperation import llop, void from rpython.rlib.objectmodel import", "= self.runner(\"can_move\") res = run([]) assert res == self.GC_CAN_MOVE def", "= \"minimark\" GC_CAN_TEST_ID = True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from", "as annmodel from rpython.rtyper.llannotation import SomePtr from rpython.rtyper.lltypesystem import lltype,", "GcArray pointer from gc.object_id_dict. def define_adr_of_nursery(cls): class A(object): pass def", "fn(n): if n > 0: x = BoxedObject(n) else: x", "A(object): def __init__(self): self.id = b.nextid b.nextid += 1 def", "= run([i, i - 1]) assert res == i -", "func def test_interior_ptrs(self): run = self.runner(\"interior_ptrs\") res = run([]) assert", "f def test_many_ids(self): if not self.GC_CAN_TEST_ID: py.test.skip(\"fails for bad reasons", "'nursery_size': 32*WORD, 'translated_to_c': False} root_stack_depth = 200 def define_weakref_across_minor_collection(cls): import", "offset_of_x) lambda_customtrace = lambda: customtrace # def setup(): rgc.register_custom_trace_hook(S, lambda_customtrace)", "setup(self): from rpython.memory.gc.generation import GenerationGC GenerationGC.setup(self) self.__ready = True def", "while i < len(alist): idarray[i] = compute_unique_id(alist[i]) i += 1", "lltype.Ptr(S1)), ('filed2', lltype.Ptr(S1))) s0 = lltype.malloc(S) def f(): return (s0.filed1", "x = 20 # for GenerationGC, enough for a minor", "'large_object': 8*WORD, 'translated_to_c': False} root_stack_depth = 200 def define_ref_from_rawmalloced_to_regular(cls): import", "('filed1', lltype.Ptr(S1)), ('filed2', lltype.Ptr(S1))) s0 = lltype.malloc(S) def f(): return", "= func(args[1], args[2]) cleanup = cleanups[num] if cleanup: cleanup() return", "0 return f def test_many_weakrefs(self): run = self.runner(\"many_weakrefs\") run([]) def", "0 for i in range(1, 5): res = run([i, i", "def f3(): t = malloc(T3, 1) t.items[0].x = 1 return", "for op in graph.startblock.operations: if op.opname == 'do_malloc_fixedsize': op.args =", "flavor='raw', zero=True) funcs0 = [] funcs2 = [] cleanups =", "(totsize - 26 * size_of_int) % 4 == 0 #", "test_many_ids(self): if not self.GC_CAN_TEST_ID: py.test.skip(\"fails for bad reasons in lltype.py", "above does not count # the number of prebuilt GC", "define_llinterp_lists(cls): def malloc_a_lot(): i = 0 while i < 10:", "def func(): return (f1() * 100000 + f2() * 10000", "lltype.Signed)) A = lltype.GcStruct('A', ('p', lltype.Ptr(S)), ('a', lltype.Array(lltype.Char))) def setup(j):", "* 10000 + f3() * 1000 + f4() * 100", "def define_weakref_across_minor_collection(cls): import weakref class A: pass def f(): x", "== 42 class TestMiniMarkGC(TestHybridGC): gcname = \"minimark\" GC_CAN_TEST_ID = True", "= GcArray(T4) def f4(): u = malloc(U4, 1) u[0].s.x =", "name, transformer=False): db = self.db name_to_func = self.name_to_func entrygraph =", "following test crash. Investigate.\") run = self.runner(\"gc_heap_stats\") res = run([])", "total return f def test_working_nursery(self): run = self.runner(\"working_nursery\") res =", "cleanup.func_name = \"clean_%s\" % name nargs = len(inspect.getargspec(func)[0]) name_to_func[name] =", "llop.gc__collect(lltype.Void) result = a.count == 1 and (ref() is None)", "import gc from rpython.annotator import model as annmodel from rpython.rtyper.llannotation", "run = self.runner(\"llinterp_tuples\") run([]) def define_llinterp_dict(self): class A(object): pass def", "j = 0 while j < 30: j += 1", "i in range(j): lst.append(str(i)) return len(\"\".join(lst)) return concat def test_string_concatenation(self):", "rpython.rtyper.lltypesystem.lltype import Struct, GcStruct, GcArray from rpython.rtyper.lltypesystem.lltype import Array, Signed,", "all[i] = [i] * i i += 1 assert ref()", "llop.gc__collect(lltype.Void) return static.p.x def cleanup(): static.p = lltype.nullptr(T1) return f,", "s1.x = llmemory.cast_ptr_to_adr(tx) return s1 def f(): s1 = setup()", "'nursery_size': 128*WORD, 'translated_to_c': False} root_stack_depth = 200 def define_working_nursery(cls): def", "it will trigger some collections itself i = 0 while", "j += 1 a.append(j) return 0 return malloc_a_lot def test_llinterp_lists(self):", "pass class B: pass static = A() static.p = None", "test for the case where allocating the weakref itself triggers", "class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.incminimark import IncrementalMiniMarkGC \\ as GCClass GC_PARAMS", "('filed2', lltype.Ptr(S1))) s0 = lltype.malloc(S) def f(): return (s0.filed1 ==", "not allocate memory, so that if the GC needs memory", "lltype.malloc(S) # 'lst' is set the single mark \"12-15\" lst[15].x", "rpython.memory.gc.hybrid import HybridGC as GCClass GC_PARAMS = {'space_size': 512*WORD, 'nursery_size':", "10000 == 2611 totsize = (res / 10000) size_of_int =", "i < x: i += 1 a = A() llop.gc__collect(lltype.Void)", "gcname = \"generation\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import", "'lst' can be allocated directly # in generation 2. This", "return fn def test_instantiate_nonmovable(self): res = self.runner('instantiate_nonmovable') assert res([]) ==", "t1 llop.gc__collect(lltype.Void) return static.p.x def cleanup(): static.p = lltype.nullptr(T1) return", "x.append((1, lltype.malloc(S))) for i in range(50): assert l2[i] == l[50", "entrypointptr = cbuild.getentrypointptr() entrygraph = entrypointptr._obj.graph if option.view: t.viewcg() cls.name_to_func", "b.num_deleted += 1 b.a = self def f(x, y): a", "gc from rpython.annotator import model as annmodel from rpython.rtyper.llannotation import", "fix_graph_of_g def test_do_malloc_operations(self): run = self.runner(\"do_malloc_operations\") run([]) def define_do_malloc_operations_in_call(cls): P", "________________________________________________________________ class TestSemiSpaceGC(GenericMovingGCTests): gcname = \"semispace\" GC_CAN_SHRINK_ARRAY = True class", "while j < 2: if j == 1: # allocate", "too assert res == 12 def define_collect_0(cls): def concat(j, dummy):", "WORD = LONG_BIT // 8 def rtype(func, inputtypes, specialize=True, gcname='ref',", "def define_llinterp_lists(cls): def malloc_a_lot(): i = 0 while i <", "from rpython.rlib.rarithmetic import LONG_BIT WORD = LONG_BIT // 8 def", "s = lltype.malloc(S) l1.append(s) l2.append(s) if i < 3: l3.append(s)", "test_custom_trace(self): run = self.runner(\"custom_trace\") res = run([]) assert res ==", "self.runner(\"tagged_simple\") res = func([]) assert res == 205 def define_tagged_prebuilt(cls):", "return f def test_malloc_struct_of_gcptr(self): run = self.runner(\"malloc_struct_of_gcptr\") res = run([])", "# NB. Remember that the number above does not count", "cleanups[num] if cleanup: cleanup() return res from rpython.translator.c.genc import CStandaloneBuilder", "S3 = Struct(\"S3\", ('x', Signed)) T3 = GcStruct(\"T3\", ('items', Array(S3)))", "= run([]) assert res == 40 * 5 class TestHybridGC(TestGenerationGC):", "= static.p.x llop.gc__collect(lltype.Void) return static.p.x + i def cleanup(): static.p", "weakref.ref(a) def f(): a = A() ref = weakref.ref(a) result", "marker[0] = 0 else: cleanup = None def fix_graph_of_g(translator): from", "pass def f(): from rpython.rtyper.lltypesystem import rffi alist = [A()", "gc.wr_to_objects_with_id # * the GcArray pointer from gc.object_id_dict. def define_adr_of_nursery(cls):", "else: expected = 0x62024230 assert run([]) == expected def define_string_builder_over_allocation(cls):", "in generation 2. This can only occur with varsized mallocs.", "py import inspect from rpython.rlib.objectmodel import compute_hash, compute_identity_hash from rpython.translator.c", "for i in range(100): l[i] = lltype.malloc(S) rgc.ll_arraycopy(l, l2, 50,", "lltype.malloc(T) tx.z = 4243 s1 = lltype.malloc(S) s1.x = llmemory.cast_ptr_to_adr(tx)", "s0.next.x def cleanup(): s0.next = lltype.nullptr(S) return f, cleanup, None", "len(alist): assert idarray[i] == compute_unique_id(alist[i]) i += 1 j +=", "b.nextid b.nextid += 1 def __del__(self): b.num_deleted += 1 C()", "while j < 5: lst.append(i*j) j += 1 total +=", "mixlevelstuff.append(fixup) else: func = func_fixup func.func_name = \"f_%s\" % name", "return len(\"\".join(lst)) return concat def test_string_concatenation(self): run = self.runner(\"string_concatenation\") res", "= b.nextid b.nextid += 1 def __del__(self): llop.gc__collect(lltype.Void) b.num_deleted +=", "0 while i < x: all[i] = [i] * i", "self.runner(\"llinterp_lists\") run([]) def define_llinterp_tuples(cls): def malloc_a_lot(): i = 0 while", "write barrier emitted res = rgc.can_move(annlowlevel.cast_instance_to_base_ptr(a)) rgc.collect() objectmodel.keepalive_until_here(a) return res", "self.__ready = False # collecting here is expected GenerationGC._teardown(self) GC_PARAMS", "+= 1 def g(): b = B() return weakref.ref(b) def", "py.test.skip(\"doesn't fit in the model, tested elsewhere too\") run =", "rpython.rlib import objectmodel from rpython.rtyper import annlowlevel class A: pass", "= a j = 0 while j < 30: b", "= 0x62024230 assert run([]) == expected def define_string_builder_over_allocation(cls): import gc", "marker[0] += 1 translator._jit2gc = { 'layoutbuilder': layoutbuilder, 'invoke_after_minor_collection': seeme,", "NotImplementedError class BoxedObject(TaggedBase): attrvalue = 66 def __init__(self, normalint): self.normalint", "to runtime # allocated stuff cleanups.append(cleanup) def entrypoint(args): num =", "5): res = run([i, i - 1]) assert res ==", "arg): gc._trace_callback(callback, arg, obj + offset_of_x) lambda_customtrace = lambda: customtrace", "return fn def test_string_builder_over_allocation(self): fn = self.runner(\"string_builder_over_allocation\") res = fn([])", "+ x + 3 class TestHybridTaggedPointerGC(TaggedPointerGCTests): gcname = \"hybrid\" class", "= compute_unique_id(a3) llop.gc__collect(lltype.Void) error = 0 if id1 != compute_unique_id(a1):", "if we_are_translated(): llop.gc__collect(lltype.Void, 0) return result return concat def test_collect_0(self):", "def test_weakref_across_minor_collection(self): run = self.runner(\"weakref_across_minor_collection\") res = run([]) assert res", "= ref() is a ref = g() llop.gc__collect(lltype.Void) result =", "= self.runner(\"do_malloc_operations\") run([]) def define_do_malloc_operations_in_call(cls): P = lltype.GcStruct('P', ('x', lltype.Signed))", "rtype(entrypoint, [s_args], gcname=cls.gcname, taggedpointers=cls.taggedpointers) for fixup in mixlevelstuff: if fixup:", "i i += 1 assert ref() is a llop.gc__collect(lltype.Void) assert", "rpython.rlib.rstring import StringBuilder from rpython.rlib.rarithmetic import LONG_BIT WORD = LONG_BIT", "== 1 and (ref() is None) return result return f", "test_working_nursery(self): run = self.runner(\"working_nursery\") res = run([]) assert res ==", "('x', lltype.Signed), ('filed1', lltype.Ptr(S1)), ('filed2', lltype.Ptr(S1))) s0 = lltype.malloc(S) def", "in range(100): l[i] = lltype.malloc(S) rgc.ll_arraycopy(l, l2, 50, 0, 50)", "t.viewcg() return t ARGS = lltype.FixedSizeArray(lltype.Signed, 3) class GCTest(object): gcpolicy", "__del__(self): llop.gc__collect(lltype.Void) b.num_deleted += 1 C() C() class C(A): def", "is a i += 1 return 0 return f def", "res == 42 class TestMiniMarkGC(TestHybridGC): gcname = \"minimark\" GC_CAN_TEST_ID =", "16 > 10 rgc.collect() sub(lst) null = lltype.nullptr(S) lst[15] =", "gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import GenerationGC as \\ GCClass", "None, None def test_global_list(self): py.test.skip(\"doesn't fit in the model, tested", "= setup() llop.gc__collect(lltype.Void) return llmemory.cast_adr_to_ptr(s1.x, lltype.Ptr(T)).z return f def test_custom_trace(self):", "class C(A): def __del__(self): b.num_deleted += 1 b.num_deleted_c += 1", "* the GcArray pointer from gc.wr_to_objects_with_id # * the GcArray", "gc.collect() return lst.p.x return f def test_ref_from_rawmalloced_to_regular(self): run = self.runner(\"ref_from_rawmalloced_to_regular\")", "sub(lst): lst[15] = lltype.malloc(S) # 'lst' is set the single", "== lltype.nullptr(S) and lst[4] == lltype.nullptr(S)) return f def test_malloc_array_of_gcptr(self):", "weakref class A: pass def f(): a = A() i", "test_do_malloc_operations(self): run = self.runner(\"do_malloc_operations\") run([]) def define_do_malloc_operations_in_call(cls): P = lltype.GcStruct('P',", "cheat here and only read the table which we later", "and lst[3] == lltype.nullptr(S) and lst[4] == lltype.nullptr(S)) return f", "return self.smallint + x + 3 class TestHybridTaggedPointerGC(TaggedPointerGCTests): gcname =", "None) return result return f def test_weakref_to_object_with_finalizer(self): run = self.runner(\"weakref_to_object_with_finalizer\")", "= 4243 s1 = lltype.malloc(S) s1.x = llmemory.cast_ptr_to_adr(tx) return s1", "a = AAA() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted return f def", "not self.GC_CAN_TEST_ID: py.test.skip(\"fails for bad reasons in lltype.py :-(\") run", "123 lst[0] = lst[15] # that would be a \"clean_setarrayitem\"", "return res return fn def test_instantiate_nonmovable(self): res = self.runner('instantiate_nonmovable') assert", "class A: pass def f(): a = A() i =", "'translated_to_c': False} root_stack_depth = 200 def define_working_nursery(cls): def f(): total", "return func def test_tagged_simple(self): func = self.runner(\"tagged_simple\") res = func([])", "+= 1 b[1, j, i] = A() return 0 return", "\"hybrid\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.hybrid import HybridGC as", "layoutbuilder = framework.TransformerLayoutBuilder(translator, GCClass) layoutbuilder.delay_encoding() def seeme(): marker[0] += 1", "+ persistent_a2.id + persistent_a3.id + persistent_a4.id # NB print would", "from rpython.rlib import rgc S = lltype.GcForwardReference() S.become(lltype.GcStruct('S', ('x', lltype.Signed),", "== 205 def define_tagged_prebuilt(cls): class F: pass f = F()", "llmemory.offsetof(S, 'x') def customtrace(gc, obj, callback, arg): gc._trace_callback(callback, arg, obj", "def setup(self): from rpython.memory.gc.generation import GenerationGC GenerationGC.setup(self) self.__ready = True", "= A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) b.bla = persistent_a1.id + persistent_a2.id +", "is needed when most allocated objects die quickly gcname =", "{'space_size': 512*WORD, 'translated_to_c': False} root_stack_depth = 200 class TestGenerationGC(GenericMovingGCTests): gcname", "30: j += 1 a.append(j) return 0 return malloc_a_lot def", "return s1 def f(): s1 = setup() llop.gc__collect(lltype.Void) return llmemory.cast_adr_to_ptr(s1.x,", "for i in range(200): rgc.collect(0) # nursery-only collection, if possible", "B() b.nextid = 1 b.num_deleted = 0 b.num_deleted_c = 0", "= 0x62024231 else: expected = 0x62024230 assert run([]) == expected", "test_ref_from_rawmalloced_to_regular(self): run = self.runner(\"ref_from_rawmalloced_to_regular\") res = run([100, 100]) assert res", "def test_nongc_static_root(self): run = self.runner(\"nongc_static_root\") res = run([]) assert res", "static = lltype.malloc(T2, immortal=True) def f(): t1 = lltype.malloc(T1) t1.x", "is None) # check that a further collection is fine", "T2 = lltype.Struct(\"C\", ('p', lltype.Ptr(T1))) static = lltype.malloc(T2, immortal=True) def", "class B(object): pass b = B() b.nextid = 0 b.num_deleted", "hashes = [] for i in range(200): rgc.collect(0) # nursery-only", "test_instantiate_nonmovable(self): res = self.runner('instantiate_nonmovable') assert res([]) == 0 class TestIncrementalMiniMarkGC(TestMiniMarkGC):", "1 p = llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder p = lltype.cast_opaque_ptr(lltype.Ptr(P), p)", "lltype.Signed)) T2 = lltype.Struct(\"C\", ('p', lltype.Ptr(T1))) static = lltype.malloc(T2, immortal=True)", "define_malloc_array_of_gcptr(self): S = lltype.GcStruct('S', ('x', lltype.Signed)) A = lltype.GcArray(lltype.Ptr(S)) def", "0 while i < 40: g() i += 1 return", "TestGenerationGC(GenericMovingGCTests): gcname = \"generation\" GC_CAN_SHRINK_ARRAY = True class gcpolicy(gc.BasicFrameworkGcPolicy): class", "res # ________________________________________________________________ # tagged pointers class TaggedPointerGCTests(GCTest): taggedpointers =", "= None def f(): t1 = B() t1.x = 42", "f(): return (s0.filed1 == lltype.nullptr(S1) and s0.filed2 == lltype.nullptr(S1)) return", "= 0 while j < 30: b = B(somea) b.last", "S = lltype.GcForwardReference() S.become(lltype.GcStruct('S', ('x', lltype.Signed), ('prev', lltype.Ptr(S)), ('next', lltype.Ptr(S))))", "pass def g(): a = A() return weakref.ref(a) def f():", "rtype(func, inputtypes, specialize=True, gcname='ref', backendopt=False, **extraconfigopts): from rpython.translator.translator import TranslationContext", "run([0, 0]) assert res == 0 for i in range(1,", "import gc def fn(): s = StringBuilder(4) s.append(\"abcd\") s.append(\"defg\") s.append(\"rty\")", "prebuilt GC objects that are of type Ptr(Gc). # At", "__slots__ = 'smallint' def meth(self, x): return self.smallint + x", "iterations [A() for i in range(20)] i = 0 while", "= self.runner(\"weakref_across_minor_collection\") res = run([]) assert res == 20 +", "s.append_multiple_char('y', 1000) res = s.build()[1000] gc.collect() return ord(res) return fn", "expected GenerationGC._teardown(self) GC_PARAMS = {'space_size': 512*WORD, 'nursery_size': 128*WORD, 'translated_to_c': False}", "= True def semispace_collect(self, size_changing=False): ll_assert(not self.__ready, \"no full collect", "Remember that the number above does not count # the", "'card_page_indices': 4, 'translated_to_c': False, } root_stack_depth = 200 def define_malloc_array_of_gcptr(self):", "((ptr == ptr2) + ord(ptr2.chars[0]) + (ord(ptr2.chars[1]) << 8) +", "cleanup() return res from rpython.translator.c.genc import CStandaloneBuilder s_args = SomePtr(lltype.Ptr(ARGS))", "parent.sub = child child.field = 3 parent2.sub = child2 child2.field", "from rpython.memory.gc.generation import GenerationGC class GCClass(GenerationGC): __ready = False def", "== 'incminimark': marker = cls.marker def cleanup(): assert marker[0] >", "\"no full collect should occur in this test\") def _teardown(self):", "the do_malloc_fixedsize in the graph of g graph = graphof(translator,", "lltype.Signed)) def g(): r = lltype.malloc(P) r.x = 1 p", "nf_a.address[0] nt1 = nt_a.address[0] assert nf1 > nf0 assert nt1", "40 * 5 class TestHybridGC(TestGenerationGC): gcname = \"hybrid\" class gcpolicy(gc.BasicFrameworkGcPolicy):", "self.__class__._used = True # FIIIIISH setupgraph = gct.frameworkgc_setup_ptr.value._obj.graph # setup", "4243 s1 = lltype.malloc(S) s1.x = llmemory.cast_ptr_to_adr(tx) return s1 def", "jit2gc = getattr(translator, '_jit2gc', None) if jit2gc: assert 'invoke_after_minor_collection' in", "enough for a minor collection a = A() a.foo =", "gc llinterp.eval_graph(setupgraph, []) def run(args): ll_args = lltype.malloc(ARGS, immortal=True) ll_args[0]", "run([]) # ________________________________________________________________ class TestSemiSpaceGC(GenericMovingGCTests): gcname = \"semispace\" GC_CAN_SHRINK_ARRAY =", "res == 205 def define_tagged_prebuilt(cls): class F: pass f =", "+= 1 if id2 != compute_unique_id(a2): error += 2 if", "t = malloc(T2, 1) t[0].x = 1 return t[0].x S3", "cleanup: cleanup.func_name = \"clean_%s\" % name nargs = len(inspect.getargspec(func)[0]) name_to_func[name]", "= llinterp.eval_graph(entrygraph, [ll_args]) return res if transformer: return run, gct", "if tb[i].count == 10: a += 1 nr = i", "i += 1 j += 1 lltype.free(idarray, flavor='raw') return 0", "= llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder p = lltype.cast_opaque_ptr(lltype.Ptr(P), p) p.x =", "d = 0 e = 0 for i in range(len(tb)):", "b[1, j, i] = A() return 0 return malloc_a_lot def", "if cls.gcname == 'incminimark': marker = cls.marker def cleanup(): assert", "= lltype.malloc(rffi.CArray(lltype.Signed), 1, flavor='raw', zero=True) funcs0 = [] funcs2 =", "i def cleanup(): static.p = None return f, cleanup, None", "db = cbuild.generate_graphs_for_llinterp() entrypointptr = cbuild.getentrypointptr() entrygraph = entrypointptr._obj.graph if", "s0, void('next'), s) llop.gc_writebarrier(lltype.Void, llmemory.cast_ptr_to_adr(s0)) rgc.collect(0) return s0.next.x def cleanup():", "= t1 llop.gc__collect(lltype.Void) return static.p.x def cleanup(): static.p = lltype.nullptr(T1)", "Struct(\"S5\", ('x', Signed)) T5 = GcStruct(\"T5\", ('items', Array(S5))) def f5():", "return 0 return f def test_many_weakrefs(self): run = self.runner(\"many_weakrefs\") run([])", "func = self.runner(\"tagged_prebuilt\") res = func([]) assert res == -1999", "func([]) assert res == -1999 def define_gettypeid(cls): class A(object): pass", "def define_finalizer_calls_malloc(cls): class B(object): pass b = B() b.nextid =", "directly # in generation 2. This can only occur with", "('x', lltype.Signed)) A = lltype.GcStruct('A', ('p', lltype.Ptr(S)), ('a', lltype.Array(lltype.Char))) def", "run([]) assert res # ________________________________________________________________ # tagged pointers class TaggedPointerGCTests(GCTest):", "test_gc_heap_stats(self): py.test.skip(\"this test makes the following test crash. Investigate.\") run", "x = UnboxedObject(n) u.x = x # invoke write barrier", "GenerationGC, enough for a minor collection a = A() a.foo", "fn([]) assert res == ord('y') class GenericMovingGCTests(GenericGCTests): GC_CAN_MOVE = True", "l2 = lltype.malloc(TP, 100) for i in range(100): l[i] =", "does not work with card marking. # Check that it", "= 1 b.num_deleted = 0 b.num_deleted_c = 0 class A(object):", "= self def f(x, y): a = A() i =", "def define_gc_heap_stats(cls): S = lltype.GcStruct('S', ('x', lltype.Signed)) l1 = []", "l2[i] == l[50 + i] return 0 return fn def", "== i - 1 # crashes if constants are not", "Constant(False, lltype.Bool), # is_finalizer_light Constant(False, lltype.Bool)] # contains_weakptr break else:", "static.p.x + i def cleanup(): static.p = None return f,", "} return layoutbuilder def define_do_malloc_operations(cls): P = lltype.GcStruct('P', ('x', lltype.Signed))", "llmemory.Address)) T = lltype.GcStruct('T', ('z', lltype.Signed)) offset_of_x = llmemory.offsetof(S, 'x')", "def define_adr_of_nursery(cls): class A(object): pass def f(): # we need", "f def test_ref_from_rawmalloced_to_regular(self): run = self.runner(\"ref_from_rawmalloced_to_regular\") res = run([100, 100])", "% 10000 == 2611 totsize = (res / 10000) size_of_int", "gcname = \"incminimark\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.incminimark import", "lltype.malloc(T1) t1.x = 42 static.p = t1 llop.gc__collect(lltype.Void) return static.p.x", "pass a1 = A() def func(): a2 = A() a3", "self.runner(\"string_concatenation\") res = run([100, 0]) assert res == len(''.join([str(x) for", "= weakref.ref(a) all = [None] * x i = 0", "else: x = UnboxedObject(n) u.x = x # invoke write", "ARGS = lltype.FixedSizeArray(lltype.Signed, 3) class GCTest(object): gcpolicy = None GC_CAN_MOVE", "== self.GC_CAN_MOVE def define_shrink_array(cls): from rpython.rtyper.lltypesystem.rstr import STR def f():", "GcArray pointer from gc.wr_to_objects_with_id # * the GcArray pointer from", "40: g() i += q.x return 0 def fix_graph_of_g(translator): from", "crashes if constants are not considered roots def define_string_concatenation(cls): def", "1 j = 0 while j < 2: if j", "return box.lst[j][0] return append_to_list, None, None def test_global_list(self): py.test.skip(\"doesn't fit", "def __del__(self): llop.gc__collect(lltype.Void) b.num_deleted += 1 C() C() class C(A):", "job and that no full collection # is needed when", "static.p = None return f, cleanup, None def test_static_root_minor_collect(self): run", "[] l3 = [] l4 = [] def f(): for", "= llmemory.cast_ptr_to_adr(tx) return s1 def f(): s1 = setup() llop.gc__collect(lltype.Void)", "assert idarray[i] == compute_unique_id(alist[i]) i += 1 j += 1", "within prebuilt GC objects that are of type Ptr(Gc). #", "return (f1() * 100000 + f2() * 10000 + f3()", "i = 0 while i < x: # enough to", "assert res == 111111 def define_id(cls): class A(object): pass a1", "rpython.rtyper.llinterp import LLInterpreter llinterp = LLInterpreter(self.rtyper) gct = db.gctransformer if", "= malloc(T6, 1) t.s[0] = 1 return t.s[0] def func():", "translator._jit2gc = { 'layoutbuilder': layoutbuilder, 'invoke_after_minor_collection': seeme, } return layoutbuilder", "1 i = 0 while i < 40: g() i", "GenericGCTests(GCTest): GC_CAN_SHRINK_ARRAY = False def define_instances(cls): class A(object): pass class", "i < 10: i += 1 a = (1, 2,", "pointer from gc.object_id_dict. def define_adr_of_nursery(cls): class A(object): pass def f():", "occur in this test\") def _teardown(self): self.__ready = False #", "= lltype.GcStruct('A', ('p', lltype.Ptr(S)), ('a', lltype.Array(lltype.Char))) def setup(j): p =", "a.next = a1 # 'a' is known young here, so", "res = rgc.can_move(annlowlevel.cast_instance_to_base_ptr(a)) rgc.collect() objectmodel.keepalive_until_here(a) return res return fn def", "> 0: x = BoxedObject(n) else: x = UnboxedObject(n) f.l.append(x)", "lazyness here too assert 160 <= res <= 165 def", "llop.gc_writebarrier(lltype.Void, llmemory.cast_ptr_to_adr(s0)) rgc.collect(0) return s0.next.x def cleanup(): s0.next = lltype.nullptr(S)", "8) + (len(ptr2.chars) << 16) + (ptr2.hash << 24)) return", "from rpython.rtyper.lltypesystem.lltype import Struct, GcStruct, GcArray from rpython.rtyper.lltypesystem.lltype import Array,", "= rgc._heap_stats() a = 0 nr = 0 b =", "def define_write_barrier_direct(cls): from rpython.rlib import rgc S = lltype.GcForwardReference() S.become(lltype.GcStruct('S',", "len(alist), flavor='raw') # Compute the id of all the elements", "j = 0 while j < 30: b = B(somea)", "= 1 return t.s.x S2 = Struct(\"S2\", ('x', Signed)) T2", "pass def malloc_a_lot(): i = 0 while i < 10:", "define_immutable_to_old_promotion(cls): T_CHILD = lltype.Ptr(lltype.GcStruct('Child', ('field', lltype.Signed))) T_PARENT = lltype.Ptr(lltype.GcStruct('Parent', ('sub',", "funcs0.append(func) funcs2.append(None) else: raise NotImplementedError( \"defined test functions should have", "Unrelated() u.x = UnboxedObject(47) def fn(n): rgc.collect() # check that", "and lst[4] == lltype.nullptr(S)) return f def test_malloc_array_of_gcptr(self): run =", "is # to not allocate memory, so that if the", "= lltype.nullptr(T1) return f, cleanup, None def test_nongc_static_root(self): run =", "res == 4243 def define_weakref(cls): import weakref, gc class A(object):", "graphof from rpython.flowspace.model import Constant from rpython.rtyper.lltypesystem import rffi layoutbuilder", "return res.sub.field return f def test_immutable_to_old_promotion(self): run, transformer = self.runner(\"immutable_to_old_promotion\",", "T2 = GcArray(S2) def f2(): t = malloc(T2, 1) t[0].x", "pointing to runtime # allocated stuff cleanups.append(cleanup) def entrypoint(args): num", "cleanup, None def test_nongc_static_root(self): run = self.runner(\"nongc_static_root\") res = run([])", "= run([]) class TestGenerationalNoFullCollectGC(GCTest): # test that nursery is doing", "200 class TestGenerationGC(GenericMovingGCTests): gcname = \"generation\" GC_CAN_SHRINK_ARRAY = True class", "GC_CAN_SHRINK_ARRAY = False def define_instances(cls): class A(object): pass class B(A):", "run = self.runner(\"adr_of_nursery\") res = run([]) class TestGenerationalNoFullCollectGC(GCTest): # test", "to let test cleanup static root pointing to runtime #", "res if transformer: return run, gct else: return run class", "0 while j < 30: b = B(somea) b.last =", "are not considered roots def define_string_concatenation(cls): def concat(j, dummy): lst", "llop.gc_adr_of_nursery_top(llmemory.Address) nf0 = nf_a.address[0] nt0 = nt_a.address[0] a0 = A()", "def f(): s = lltype.malloc(S) s.x = 42 llop.bare_setfield(lltype.Void, s0,", "doesn't explode if n > 0: x = BoxedObject(n) else:", "else: assert 0, \"oups, not found\" return f, None, fix_graph_of_g", "t1 = B() t1.x = 42 static.p = t1 x", "define_string_builder_over_allocation(cls): import gc def fn(): s = StringBuilder(4) s.append(\"abcd\") s.append(\"defg\")", "lst = [] for i in range(j): lst.append(str(i)) return len(\"\".join(lst))", "0 while j < 2: if j == 1: #", "f(): t1 = lltype.malloc(T1) t1.x = 42 static.p = t1", "< 40: g() i += 1 return 0 if cls.gcname", "= rffi.sizeof(lltype.Signed) assert (totsize - 26 * size_of_int) % 4", "i < 10: i += 1 a = [1] *", "i += 1 a = A() persistent_a3 = A() persistent_a4", "that it is turned off. S = lltype.GcStruct('S', ('x', lltype.Signed))", "return f, cleanup, None def test_nongc_static_root_minor_collect(self): run = self.runner(\"nongc_static_root_minor_collect\") res", "f def test_immutable_to_old_promotion(self): run, transformer = self.runner(\"immutable_to_old_promotion\", transformer=True) run([1, 4])", "e = 0 for i in range(len(tb)): if tb[i].count ==", "x i = 0 while i < x: # enough", "b.nextid += 1 def __del__(self): llop.gc__collect(lltype.Void) b.num_deleted += 1 C()", "200 def define_weakref_across_minor_collection(cls): import weakref class A: pass def f():", "ll_args[1+i] = args[i] res = llinterp.eval_graph(entrygraph, [ll_args]) return res if", "def __del__(self): b.num_deleted += 1 C() class C(AAA): def __del__(self):", "return f def test_many_weakrefs(self): run = self.runner(\"many_weakrefs\") run([]) def define_immutable_to_old_promotion(cls):", "class A(object): pass def f(): from rpython.rtyper.lltypesystem import rffi alist", "GcStruct, GcArray from rpython.rtyper.lltypesystem.lltype import Array, Signed, malloc S1 =", "takes ages llop.gc__collect(lltype.Void) tb = rgc._heap_stats() a = 0 nr", "__del__(self): b.num_deleted += 1 b.num_deleted_c += 1 def f(x, y):", "b = B(somea) b.last = first j += 1 return", "= lltype.malloc(A, 16) # 16 > 10 rgc.collect() sub(lst) null", "x = BoxedObject(n) else: x = UnboxedObject(n) f.l.append(x) rgc.collect() return", "nt0 = nt_a.address[0] a0 = A() a1 = A() nf1", "rpython.memory.gc.generation import GenerationGC as \\ GCClass GC_PARAMS = {'space_size': 512*WORD,", "return f, cleanup, None def test_static_root_minor_collect(self): run = self.runner(\"static_root_minor_collect\") res", "print res from rpython.rlib.objectmodel import UnboxedValue class TaggedBase(object): __slots__ =", "# contains_weakptr break else: assert 0, \"oups, not found\" return", "= first j += 1 return 0 return malloc_a_lot def", "def setup(j): p = lltype.malloc(S) p.x = j*2 lst =", "8*WORD, 'card_page_indices': 4, 'translated_to_c': False, } root_stack_depth = 200 def", "import rgc from rpython.conftest import option from rpython.rlib.rstring import StringBuilder", "in the model, tested elsewhere too\") run = self.runner(\"global_list\") res", "assert l2[i] == l[50 + i] return 0 return fn", "Array(Signed))) def f6(): t = malloc(T6, 1) t.s[0] = 1", "100) l2 = lltype.malloc(TP, 100) for i in range(100): l[i]", "to not allocate memory, so that if the GC needs", "if constants are not considered roots def define_string_concatenation(cls): def concat(j,", "0 while i < len(alist): assert idarray[i] == compute_unique_id(alist[i]) i", "42]) #XXX pure lazyness here too assert 160 <= res", "= lltype.GcArray(lltype.Ptr(S)) def f(): lst = lltype.malloc(A, 5) return (lst[0]", "return jit2gc['layoutbuilder'] marker = cls.marker GCClass = cls.gcpolicy.transformerclass.GCClass layoutbuilder =", "= x # invoke write barrier rgc.collect() return x.meth(100) def", "define_collect_0(cls): def concat(j, dummy): lst = [] for i in", "= 0 b.num_deleted = 0 class A(object): def __init__(self): self.id", "this test takes ages llop.gc__collect(lltype.Void) tb = rgc._heap_stats() a =", "while i < x: # enough to cause a minor", "fix the do_malloc_fixedsize in the graph of g graph =", "2611 totsize = (res / 10000) size_of_int = rffi.sizeof(lltype.Signed) assert", "cleanup(): static.p = lltype.nullptr(T1) return f, cleanup, None def test_nongc_static_root(self):", "test_global_list(self): py.test.skip(\"doesn't fit in the model, tested elsewhere too\") run", "T_CHILD = lltype.Ptr(lltype.GcStruct('Child', ('field', lltype.Signed))) T_PARENT = lltype.Ptr(lltype.GcStruct('Parent', ('sub', T_CHILD)))", "gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.incminimark import IncrementalMiniMarkGC \\ as GCClass", "result and (ref() is None) # check that a further", "0 while i < 40: lst = [] j =", "= compute_unique_id(a1) id2 = compute_unique_id(a2) id3 = compute_unique_id(a3) llop.gc__collect(lltype.Void) error", "Box() def append_to_list(i, j): box.lst.append([i] * 50) llop.gc__collect(lltype.Void) return box.lst[j][0]", "ptr.chars[2] = 'C' ptr2 = rgc.ll_shrink_array(ptr, 2) return ((ptr ==", "res = run([]) assert res % 10000 == 2611 totsize", "func_fixup = definefunc.im_func(cls) cleanup = None if isinstance(func_fixup, tuple): func,", "a = A() i = 0 while i < 17:", "totsize = (res / 10000) size_of_int = rffi.sizeof(lltype.Signed) assert (totsize", "llinterp = LLInterpreter(self.rtyper) gct = db.gctransformer if self.__class__.__dict__.get('_used', False): teardowngraph", "result and (ref() is None) return result return f def", "the case where allocating the weakref itself triggers # a", "1 def __del__(self): b.num_deleted += 1 C() class C(AAA): def", "Signed)) T4 = Struct(\"T4\", ('s', S4)) U4 = GcArray(T4) def", "void from rpython.rlib.objectmodel import compute_unique_id, we_are_translated from rpython.rlib.debug import ll_assert", "lazyness here too assert res == 12 def define_collect_0(cls): def", "A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted return f def test_finalizer(self): run", "f, cleanup, None def test_nongc_static_root_minor_collect(self): run = self.runner(\"nongc_static_root_minor_collect\") res =", "lltype.Signed)) offset_of_x = llmemory.offsetof(S, 'x') def customtrace(gc, obj, callback, arg):", "+ b * 10 + a return f def test_gc_heap_stats(self):", "llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) b.bla = persistent_a1.id + persistent_a2.id + persistent_a3.id +", "= fn([]) assert res == ord('y') class GenericMovingGCTests(GenericGCTests): GC_CAN_MOVE =", "f, cleanup, None def test_write_barrier_direct(self): run = self.runner(\"write_barrier_direct\") res =", "= 8 T_ALL = lltype.Ptr(lltype.GcArray(T_PARENT)) all = lltype.malloc(T_ALL.TO, 2) all[0]", "b = {a: A()} j = 0 while j <", "something): self.something = something def malloc_a_lot(): i = 0 first", "in mixlevelstuff: if fixup: fixup(t) cbuild = CStandaloneBuilder(t, entrypoint, config=t.config,", "= self.runner(\"string_builder_over_allocation\") res = fn([]) assert res == ord('y') class", "[a] * 10 j = 0 while j < 20:", "('x', Signed)) T4 = Struct(\"T4\", ('s', S4)) U4 = GcArray(T4)", "result return f def test_weakref_to_object_with_finalizer(self): run = self.runner(\"weakref_to_object_with_finalizer\") res =", "return func def test_interior_ptrs(self): run = self.runner(\"interior_ptrs\") res = run([])", "= 0 e = 0 for i in range(len(tb)): if", "rpython.memory.gc.semispace import SemiSpaceGC as GCClass GC_PARAMS = {'space_size': 512*WORD, 'translated_to_c':", "run = self.runner(\"finalizer_calls_malloc\") res = run([5, 42]) #XXX pure lazyness", "= persistent_a1.id + persistent_a2.id + persistent_a3.id + persistent_a4.id # NB", "does not count # the number of prebuilt GC objects,", "None def test_global_list(self): py.test.skip(\"doesn't fit in the model, tested elsewhere", "inspect from rpython.rlib.objectmodel import compute_hash, compute_identity_hash from rpython.translator.c import gc", "lst = [] j = 0 while j < 5:", "found\" return f, None, fix_graph_of_g def test_do_malloc_operations_in_call(self): run = self.runner(\"do_malloc_operations_in_call\")", "lst = setup(j) gc.collect() return lst.p.x return f def test_ref_from_rawmalloced_to_regular(self):", "import py import inspect from rpython.rlib.objectmodel import compute_hash, compute_identity_hash from", "1 c += tb[i].links[nr] e += tb[i].size return d *", "rgc.collect() # check that a prebuilt tagged pointer doesn't explode", "< 20: j += 1 b[1, j, i] = A()", "in range(len(tb)): if tb[i].count == 10: a += 1 nr", "= A() objects.append(obj) hashes.append(compute_identity_hash(obj)) unique = {} for i in", "if fixup: fixup(t) cbuild = CStandaloneBuilder(t, entrypoint, config=t.config, gcpolicy=cls.gcpolicy) db", "('x', llmemory.Address)) T = lltype.GcStruct('T', ('z', lltype.Signed)) offset_of_x = llmemory.offsetof(S,", "f(): ref = g() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) result = a.count ==", "// 8 def rtype(func, inputtypes, specialize=True, gcname='ref', backendopt=False, **extraconfigopts): from", "the graph of g graph = graphof(translator, g) for op", "< 5: lst.append(i*j) j += 1 total += len(lst) i", "rpython.rtyper.lltypesystem.lltype import Array, Signed, malloc S1 = Struct(\"S1\", ('x', Signed))", "taggedpointers=cls.taggedpointers) for fixup in mixlevelstuff: if fixup: fixup(t) cbuild =", "ord(res) return fn def test_string_builder_over_allocation(self): fn = self.runner(\"string_builder_over_allocation\") res =", "the number of prebuilt GC objects, but the number of", "return f.l[-1].meth(100) def func(): return fn(1000) ^ fn(-1000) assert func()", "B(A): def __init__(self, something): self.something = something def malloc_a_lot(): i", "lltype.GcStruct(\"C\", ('x', lltype.Signed)) T2 = lltype.Struct(\"C\", ('p', lltype.Ptr(T1))) static =", "32*WORD, 'translated_to_c': False} root_stack_depth = 200 def define_weakref_across_minor_collection(cls): import weakref", "1 for i in range(len(tb)): if tb[i].count == 4: b", "nt_a = llop.gc_adr_of_nursery_top(llmemory.Address) nf0 = nf_a.address[0] nt0 = nt_a.address[0] a0", "= None # check that __del__ is not called again", "TestIncrementalMiniMarkGC(TestMiniMarkGC): gcname = \"incminimark\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.incminimark", "10 + aid + 100 * (b.a is None) return", "res == ord('y') class GenericMovingGCTests(GenericGCTests): GC_CAN_MOVE = True GC_CAN_TEST_ID =", "define_malloc_struct_of_gcptr(cls): S1 = lltype.GcStruct('S', ('x', lltype.Signed)) S = lltype.GcStruct('S', ('x',", "f def test_custom_trace(self): run = self.runner(\"custom_trace\") res = run([]) assert", "graphof(translator, g) for op in graph.startblock.operations: if op.opname == 'do_malloc_fixedsize':", "f(): total = 0 i = 0 while i <", "cls.ensure_layoutbuilder(translator) type_id = layoutbuilder.get_type_id(P) # # now fix the do_malloc_fixedsize", "# S = lltype.GcStruct('S', ('x', llmemory.Address)) T = lltype.GcStruct('T', ('z',", "42 llop.bare_setfield(lltype.Void, s0, void('next'), s) llop.gc_writebarrier(lltype.Void, llmemory.cast_ptr_to_adr(s0)) rgc.collect(0) return s0.next.x", "r = lltype.malloc(P) r.x = 1 p = llop.do_malloc_fixedsize(llmemory.GCREF) #", "ref = weakref.ref(a) all = [None] * x i =", "while i < 10: i += 1 a = somea", "= 0 b.num_deleted_c = 0 class A(object): def __init__(self): self.id", "i < x: i += 1 a = A() persistent_a3", "res = func([]) assert res == -1999 def define_gettypeid(cls): class", "x): return self.smallint + x + 3 class TestHybridTaggedPointerGC(TaggedPointerGCTests): gcname", "ref = g() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) result = a.count == 1", "= result and (ref() is None) # check that a", "# process ourselves, otherwise this test takes ages llop.gc__collect(lltype.Void) tb", "func(): a2 = A() a3 = A() id1 = compute_unique_id(a1)", "= 20 # for GenerationGC, enough for a minor collection", "A = lltype.GcStruct('A', ('p', lltype.Ptr(S)), ('a', lltype.Array(lltype.Char))) def setup(j): p", "null = lltype.nullptr(S) lst[15] = null # clear, so that", "range(100)])) def define_nongc_static_root(cls): T1 = lltype.GcStruct(\"C\", ('x', lltype.Signed)) T2 =", "goal is # to not allocate memory, so that if", "< 2: if j == 1: # allocate some stuff", "only visible via lst[0] rgc.collect() # -> crash return lst[0].x", "LONG_BIT // 8 def rtype(func, inputtypes, specialize=True, gcname='ref', backendopt=False, **extraconfigopts):", "self.runner(\"finalizer\") res = run([5, 42]) #XXX pure lazyness here too", "lltype.Signed))) T_PARENT = lltype.Ptr(lltype.GcStruct('Parent', ('sub', T_CHILD))) child = lltype.malloc(T_CHILD.TO) child2", "Signed)) T3 = GcStruct(\"T3\", ('items', Array(S3))) def f3(): t =", "pointer doesn't explode if n > 0: x = BoxedObject(n)", "compute_hash, compute_identity_hash from rpython.translator.c import gc from rpython.annotator import model", "#all[x] = lltype.nullptr(T_PARENT.TO) return res.sub.field return f def test_immutable_to_old_promotion(self): run,", "turned off. S = lltype.GcStruct('S', ('x', lltype.Signed)) A = lltype.GcArray(lltype.Ptr(S))", "def f(): ref = g() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) result = a.count", "lazyness here too assert res == 6 def define_finalizer_calls_malloc(cls): class", "while i < len(alist): assert idarray[i] == compute_unique_id(alist[i]) i +=", "assert len(transformer.layoutbuilder.addresses_of_static_ptrs) == 0 else: assert len(transformer.layoutbuilder.addresses_of_static_ptrs) >= 4 #", "full collect should occur in this test\") def _teardown(self): self.__ready", "name nargs = len(inspect.getargspec(func)[0]) name_to_func[name] = len(funcs0) if nargs ==", "= g() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) result = a.count == 1 and", "= lltype.malloc(TP, 100) l2 = lltype.malloc(TP, 100) for i in", "the GC needs memory to # remember the ids, it", "prebuilt GC objects, but the number of locations # within", "full collection # is needed when most allocated objects die", "def define_instances(cls): class A(object): pass class B(A): def __init__(self, something):", "= a1 # 'a' is known young here, so no", "S1 = lltype.GcStruct('S', ('x', lltype.Signed)) S = lltype.GcStruct('S', ('x', lltype.Signed),", "def f(): # we need at least 1 obj to", "32*WORD, 'large_object': 8*WORD, 'translated_to_c': False} root_stack_depth = 200 def define_ref_from_rawmalloced_to_regular(cls):", "= \"generation\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import GenerationGC", "def test_working_nursery(self): run = self.runner(\"working_nursery\") res = run([]) assert res", "assert res == 200 def define_write_barrier_direct(cls): from rpython.rlib import rgc", "run class GenericGCTests(GCTest): GC_CAN_SHRINK_ARRAY = False def define_instances(cls): class A(object):", "self.runner(\"interior_ptrs\") res = run([]) assert res == 111111 def define_id(cls):", "0 return f def test_adr_of_nursery(self): run = self.runner(\"adr_of_nursery\") res =", "(and give fixedsize) def define_writebarrier_before_copy(cls): S = lltype.GcStruct('S', ('x', lltype.Char))", "# collecting here is expected GenerationGC._teardown(self) GC_PARAMS = {'space_size': 512*WORD,", "def fn(): a = A() return rgc.get_typeid(a) return fn def", "a = objectmodel.instantiate(A, nonmovable=True) a.next = a1 # 'a' is", "#XXX pure lazyness here too assert res == 12 def", "for i in range(20): x.append((1, lltype.malloc(S))) for i in range(50):", "in # gctransformer/framework.py does not work with card marking. #", "rpython.translator.backendopt.all import backend_optimizations backend_optimizations(t) if option.view: t.viewcg() return t ARGS", "= cleanups[num] if cleanup: cleanup() return res from rpython.translator.c.genc import", "gc.collect() s.append_multiple_char('y', 1000) res = s.build()[1000] gc.collect() return ord(res) return", "len(lst) i += 1 return total return f def test_working_nursery(self):", "Signed)) T1 = GcStruct(\"T1\", ('s', S1)) def f1(): t =", "XXX mess t.config.translation.gc = gcname t.config.translation.gcremovetypeptr = True t.config.set(**extraconfigopts) ann", "== expected def define_string_builder_over_allocation(cls): import gc def fn(): s =", "memory, so that if the GC needs memory to #", "from rpython.rtyper.lltypesystem.rstr import STR def f(): ptr = lltype.malloc(STR, 3)", "assert nf1 > nf0 assert nt1 > nf1 assert nt1", "('x', lltype.Signed)) S = lltype.GcStruct('S', ('x', lltype.Signed), ('filed1', lltype.Ptr(S1)), ('filed2',", "A: pass class B: pass static = A() static.p =", "flavor='raw') # Compute the id of all the elements of", "test_nongc_static_root(self): run = self.runner(\"nongc_static_root\") res = run([]) assert res ==", "S4 = Struct(\"S4\", ('x', Signed)) T4 = Struct(\"T4\", ('s', S4))", "= self.runner(\"many_ids\") run([]) @classmethod def ensure_layoutbuilder(cls, translator): jit2gc = getattr(translator,", "all[1] # * parent.sub # * parent2.sub # * the", "+ f5() * 10 + f6()) assert func() == 111111", "pass def fn(): objects = [] hashes = [] for", "if id3 != compute_unique_id(a3): error += 4 return error return", "GCTest(object): gcpolicy = None GC_CAN_MOVE = False taggedpointers = False", "GC_PARAMS = {'space_size': 512*WORD, 'nursery_size': 32*WORD, 'translated_to_c': False} root_stack_depth =", "= llmemory.offsetof(S, 'x') def customtrace(gc, obj, callback, arg): gc._trace_callback(callback, arg,", "args[i] res = llinterp.eval_graph(entrygraph, [ll_args]) return res if transformer: return", "cleanup static root pointing to runtime # allocated stuff cleanups.append(cleanup)", "42 static.p = t1 llop.gc__collect(lltype.Void) return static.p.x def cleanup(): static.p", "op.opname == 'do_malloc_fixedsize': op.args = [Constant(type_id, llgroup.HALFWORD), Constant(llmemory.sizeof(P), lltype.Signed), Constant(False,", "unique[hashes[i]] = None return len(unique) return fn def test_nursery_hash_base(self): res", "None, fix_graph_of_g def test_do_malloc_operations_in_call(self): run = self.runner(\"do_malloc_operations_in_call\") run([]) def define_gc_heap_stats(cls):", "size_of_int) % 4 == 0 # ^^^ a crude assumption", "GcStruct(\"T1\", ('s', S1)) def f1(): t = malloc(T1) t.s.x =", "malloc_a_lot(): i = 0 first = None while i <", "run = self.runner(\"many_weakrefs\") run([]) def define_immutable_to_old_promotion(cls): T_CHILD = lltype.Ptr(lltype.GcStruct('Child', ('field',", "self.__class__.__dict__.get('_used', False): teardowngraph = gct.frameworkgc__teardown_ptr.value._obj.graph llinterp.eval_graph(teardowngraph, []) self.__class__._used = True", "[] j = 0 while j < 5: lst.append(i*j) j", "return (s0.filed1 == lltype.nullptr(S1) and s0.filed2 == lltype.nullptr(S1)) return f", "= 0 while i < len(alist): idarray[i] = compute_unique_id(alist[i]) i", "('x', lltype.Signed), ('prev', lltype.Ptr(S)), ('next', lltype.Ptr(S)))) s0 = lltype.malloc(S, immortal=True)", "f def test_malloc_array_of_gcptr(self): run = self.runner('malloc_array_of_gcptr') res = run([]) assert", "1 and (ref() is None) return result return f def", "rpython.rlib.rarithmetic import LONG_BIT WORD = LONG_BIT // 8 def rtype(func,", "import model as annmodel from rpython.rtyper.llannotation import SomePtr from rpython.rtyper.lltypesystem", "import graphof from rpython.flowspace.model import Constant from rpython.rtyper.lltypesystem import rffi", "alist = [A() for i in range(50)] idarray = lltype.malloc(rffi.SIGNEDP.TO,", "a = A() ref = weakref.ref(a) result = ref() is", "205 def define_tagged_prebuilt(cls): class F: pass f = F() f.l", "meth(self, x): return self.smallint + x + 3 class TestHybridTaggedPointerGC(TaggedPointerGCTests):", "= run([0, 0]) assert res == 0 for i in", "cleanup, fixup = func_fixup mixlevelstuff.append(fixup) else: func = func_fixup func.func_name", "+= 1 a.append(j) return 0 return malloc_a_lot def test_llinterp_lists(self): run", "{a: A()} j = 0 while j < 20: j", "{'space_size': 512*WORD, 'nursery_size': 32*WORD, 'large_object': 8*WORD, 'translated_to_c': False} root_stack_depth =", "j): box.lst.append([i] * 50) llop.gc__collect(lltype.Void) return box.lst[j][0] return append_to_list, None,", "i in range(len(objects)): assert compute_identity_hash(objects[i]) == hashes[i] unique[hashes[i]] = None", "option.view: t.viewcg() cls.name_to_func = name_to_func cls.entrygraph = entrygraph cls.rtyper =", "self.runner(\"many_ids\") run([]) @classmethod def ensure_layoutbuilder(cls, translator): jit2gc = getattr(translator, '_jit2gc',", "= 1 return t.items[0].x S4 = Struct(\"S4\", ('x', Signed)) T4", "rgc.collect(0) # nursery-only collection, if possible obj = A() objects.append(obj)", "run([]) assert res == 84 def define_static_root_minor_collect(cls): class A: pass", "return f def test_malloc_array_of_gcptr(self): run = self.runner('malloc_array_of_gcptr') res = run([])", "B(object): pass b = B() b.nextid = 0 b.num_deleted =", "= [] for i in range(200): rgc.collect(0) # nursery-only collection,", "class C(AAA): def __del__(self): b.num_deleted += 1 def f(x, y):", "3: l3.append(s) l4.append(s) # We cheat here and only read", "getattr(cls, fullname) _, name = fullname.split('_', 1) func_fixup = definefunc.im_func(cls)", "1 b.append((1, j, i)) return 0 return malloc_a_lot def test_llinterp_tuples(self):", "'invoke_after_minor_collection' in jit2gc return jit2gc['layoutbuilder'] marker = cls.marker GCClass =", "= self.runner(\"collect_0\") res = run([100, 0]) assert res == len(''.join([str(x)", "* parent2.sub # * the GcArray pointer from gc.wr_to_objects_with_id #", "ptr = lltype.malloc(STR, 3) ptr.hash = 0x62 ptr.chars[0] = '0'", "def f(x, y): a = A() i = 0 while", "b = B() b.nextid = 1 b.num_deleted = 0 b.num_deleted_c", "() def meth(self, x): raise NotImplementedError class BoxedObject(TaggedBase): attrvalue =", "res == self.GC_CAN_MOVE def define_shrink_array(cls): from rpython.rtyper.lltypesystem.rstr import STR def", "= t1 x = 20 all = [None] * x", "assert nt1 > nf1 assert nt1 == nt0 return 0", "def meth(self, x): return self.smallint + x + 3 class", "gcpolicy = None GC_CAN_MOVE = False taggedpointers = False def", "= A() persistent_a2 = A() i = 0 while i", "= 0 while i < x: i += 1 a", "# check that a further collection is fine llop.gc__collect(lltype.Void) result", "= [] def f(): for i in range(10): s =", "def g(): r = lltype.malloc(P) r.x = 1 p =", "= \"f_%s\" % name if cleanup: cleanup.func_name = \"clean_%s\" %", "len(inspect.getargspec(func)[0]) name_to_func[name] = len(funcs0) if nargs == 2: funcs2.append(func) funcs0.append(None)", "a.foo + len(all) return f def test_weakref_across_minor_collection(self): run = self.runner(\"weakref_across_minor_collection\")", "res = run([]) assert res == 84 def define_many_weakrefs(cls): #", "True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.minimark import MiniMarkGC as", "type_id = layoutbuilder.get_type_id(P) # # now fix the do_malloc_fixedsize in", "card marking. # Check that it is turned off. S", "<< 8) + (len(ptr2.chars) << 16) + (ptr2.hash << 24))", "a minor collect all[i] = [i] * i i +=", "import STR def f(): ptr = lltype.malloc(STR, 3) ptr.hash =", "GC_PARAMS = {'nursery_size': 32*WORD, 'page_size': 16*WORD, 'arena_size': 64*WORD, 'small_request_threshold': 5*WORD,", "f4(): u = malloc(U4, 1) u[0].s.x = 1 return u[0].s.x", "[] hashes = [] for i in range(200): rgc.collect(0) #", "tb[i].count == 10: a += 1 nr = i if", "for i in range(len(tb)): if tb[i].count == 4: b +=", "funcs2.append(None) else: raise NotImplementedError( \"defined test functions should have 0/2", "run([]) assert res == 20 + 20 def define_nongc_static_root_minor_collect(cls): T1", "f def test_shrink_array(self): run = self.runner(\"shrink_array\") if self.GC_CAN_SHRINK_ARRAY: expected =", "b.nextid b.nextid += 1 def __del__(self): b.num_deleted += 1 b.a", "t.s.x S2 = Struct(\"S2\", ('x', Signed)) T2 = GcArray(S2) def", "+= 1 j = 0 while j < 2: if", "x ref = weakref.ref(a) all = [None] * x i", "= A() i = 0 while i < 17: ref", "b.num_deleted_c += 1 def f(x, y): persistent_a1 = A() persistent_a2", "allocated stuff cleanups.append(cleanup) def entrypoint(args): num = args[0] func =", "GCClass GC_PARAMS = {'space_size': 512*WORD, 'translated_to_c': False} root_stack_depth = 200", "= self.entrygraph from rpython.rtyper.llinterp import LLInterpreter llinterp = LLInterpreter(self.rtyper) gct", "llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder def f(): q = lltype.malloc(P) q.x =", "llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted return f def test_finalizer(self): run =", "return run, gct else: return run class GenericGCTests(GCTest): GC_CAN_SHRINK_ARRAY =", "tb = rgc._heap_stats() a = 0 nr = 0 b", "= null # clear, so that A() is only visible", "f(): a = A() ref = weakref.ref(a) result = ref()", "= BoxedObject(n) else: x = UnboxedObject(n) f.l.append(x) rgc.collect() return f.l[-1].meth(100)", "f def test_working_nursery(self): run = self.runner(\"working_nursery\") res = run([]) assert", "test_nursery_hash_base(self): res = self.runner('nursery_hash_base') assert res([]) >= 195 def define_instantiate_nonmovable(cls):", "def fn(): objects = [] hashes = [] for i", "parent2 def f(x, y): res = all[x] #all[x] = lltype.nullptr(T_PARENT.TO)", "= 1 i = 0 while i < 40: g()", "10 + a return f def test_gc_heap_stats(self): py.test.skip(\"this test makes", "S = lltype.GcStruct('S', ('x', lltype.Signed)) l1 = [] l2 =", "assert 160 <= res <= 165 def define_custom_trace(cls): # S", "lltype.nullptr(T_PARENT.TO) return res.sub.field return f def test_immutable_to_old_promotion(self): run, transformer =", "define_nursery_hash_base(cls): class A: pass def fn(): objects = [] hashes", "assert run([]) == expected def define_string_builder_over_allocation(cls): import gc def fn():", "TestHybridGC(TestGenerationGC): gcname = \"hybrid\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.hybrid", "res == 6 def define_finalizer_calls_malloc(cls): class B(object): pass b =", "objectmodel.instantiate(A, nonmovable=True) a.next = a1 # 'a' is known young", "\"incminimark\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.incminimark import IncrementalMiniMarkGC \\", "('s', Array(Signed))) def f6(): t = malloc(T6, 1) t.s[0] =", "= self.runner(\"nongc_static_root\") res = run([]) assert res == 42 def", "trigger some collections itself i = 0 while i <", "are of type Ptr(Gc). # At the moment we get", "= lltype.cast_opaque_ptr(lltype.Ptr(P), p) p.x = r.x return p.x def f():", "('prev', lltype.Ptr(S)), ('next', lltype.Ptr(S)))) s0 = lltype.malloc(S, immortal=True) def f():", "-> crash return lst[0].x return f def test_no_clean_setarrayitems(self): run =", "res == 200 def define_write_barrier_direct(cls): from rpython.rlib import rgc S", "return u[0].s.x S5 = Struct(\"S5\", ('x', Signed)) T5 = GcStruct(\"T5\",", "root_stack_depth = 200 class TestGenerationGC(GenericMovingGCTests): gcname = \"generation\" GC_CAN_SHRINK_ARRAY =", "_teardown(self): self.__ready = False # collecting here is expected GenerationGC._teardown(self)", "i in range(20): x.append((1, lltype.malloc(S))) for i in range(50): assert", "first = a j = 0 while j < 30:", "res = run([]) assert res == 20 + 20 def", "marker = cls.marker GCClass = cls.gcpolicy.transformerclass.GCClass layoutbuilder = framework.TransformerLayoutBuilder(translator, GCClass)", "= TranslationContext() # XXX XXX XXX mess t.config.translation.gc = gcname", "def test_no_clean_setarrayitems(self): run = self.runner(\"no_clean_setarrayitems\") res = run([]) assert res", "- 26 * size_of_int) % 4 == 0 # ^^^", "= False def define_instances(cls): class A(object): pass class B(A): def", "# * all[1] # * parent.sub # * parent2.sub #", "j += 1 total += len(lst) i += 1 return", "1 a = A() persistent_a3 = A() persistent_a4 = A()", "= \"hybrid\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import GenerationGC", "* all[0] # * all[1] # * parent.sub # *", "assert res == self.GC_CAN_MOVE def define_shrink_array(cls): from rpython.rtyper.lltypesystem.rstr import STR", "get additional_roots_sources == 6: # * all[0] # * all[1]", "lltype.malloc(S) l1.append(s) l2.append(s) if i < 3: l3.append(s) l4.append(s) #", "= lltype.GcStruct('S', ('x', lltype.Signed)) A = lltype.GcArray(lltype.Ptr(S)) def sub(lst): lst[15]", "= True def define_tagged_simple(cls): class Unrelated(object): pass u = Unrelated()", "x = BoxedObject(n) else: x = UnboxedObject(n) u.x = x", "\"hybrid\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import GenerationGC as", "return lst[0].x return f def test_no_clean_setarrayitems(self): run = self.runner(\"no_clean_setarrayitems\") res", "in range(100)])) def define_interior_ptrs(cls): from rpython.rtyper.lltypesystem.lltype import Struct, GcStruct, GcArray", "run = self.runner(\"interior_ptrs\") res = run([]) assert res == 111111", "= 0 while i < x: all[i] = [i] *", "run([]) assert res == 40 * 5 class TestHybridGC(TestGenerationGC): gcname", "run([]) @classmethod def ensure_layoutbuilder(cls, translator): jit2gc = getattr(translator, '_jit2gc', None)", "as GCClass GC_PARAMS = {'nursery_size': 32*WORD, 'page_size': 16*WORD, 'arena_size': 64*WORD,", "llop.gc__collect(lltype.Void) result = result and (ref() is None) # check", "write barrier rgc.collect() return x.meth(100) def func(): return fn(1000) +", "return res from rpython.translator.c.genc import CStandaloneBuilder s_args = SomePtr(lltype.Ptr(ARGS)) t", "def f(): from rpython.rtyper.lltypesystem import rffi alist = [A() for", "assert len(transformer.layoutbuilder.addresses_of_static_ptrs) >= 4 # NB. Remember that the number", "def define_can_move(cls): TP = lltype.GcArray(lltype.Float) def func(): return rgc.can_move(lltype.malloc(TP, 1))", "it is turned off. S = lltype.GcStruct('S', ('x', lltype.Signed)) A", "res == i - 1 # crashes if constants are", "llop.gc__collect(lltype.Void, 0) return result return concat def test_collect_0(self): run =", "transformer: return run, gct else: return run class GenericGCTests(GCTest): GC_CAN_SHRINK_ARRAY", "{ 'layoutbuilder': layoutbuilder, 'invoke_after_minor_collection': seeme, } return layoutbuilder def define_do_malloc_operations(cls):", "run = self.runner(\"writebarrier_before_copy\") run([]) # ________________________________________________________________ class TestSemiSpaceGC(GenericMovingGCTests): gcname =", "f def test_many_weakrefs(self): run = self.runner(\"many_weakrefs\") run([]) def define_immutable_to_old_promotion(cls): T_CHILD", "define_finalizer(cls): class B(object): pass b = B() b.nextid = 0", "= result and (ref() is None) return result return f", "a further collection is fine llop.gc__collect(lltype.Void) result = result and", "for i in range(20)] i = 0 while i <", "+ aid + 100 * (b.a is None) return f", "box = Box() def append_to_list(i, j): box.lst.append([i] * 50) llop.gc__collect(lltype.Void)", "= { 'layoutbuilder': layoutbuilder, 'invoke_after_minor_collection': seeme, } return layoutbuilder def", "is a return a.foo + len(all) return f def test_weakref_across_minor_collection(self):", "== ord('y') class GenericMovingGCTests(GenericGCTests): GC_CAN_MOVE = True GC_CAN_TEST_ID = False", "return b.num_deleted * 10 + aid + 100 * (b.a", "fn def test_nursery_hash_base(self): res = self.runner('nursery_hash_base') assert res([]) >= 195", "be dividable by 4 # (and give fixedsize) def define_writebarrier_before_copy(cls):", "static.p.x def cleanup(): static.p = lltype.nullptr(T1) return f, cleanup, None", "llop.gc__collect(lltype.Void) return box.lst[j][0] return append_to_list, None, None def test_global_list(self): py.test.skip(\"doesn't", "4243 def define_weakref(cls): import weakref, gc class A(object): pass def", "jit2gc: assert 'invoke_after_minor_collection' in jit2gc return jit2gc['layoutbuilder'] marker = cls.marker", "run([]) assert res def define_collect_during_collect(cls): class B(object): pass b =", "A() id1 = compute_unique_id(a1) id2 = compute_unique_id(a2) id3 = compute_unique_id(a3)", "= GcStruct(\"T3\", ('items', Array(S3))) def f3(): t = malloc(T3, 1)", "i] = A() return 0 return malloc_a_lot def test_llinterp_dict(self): run", "def test_finalizer_resurrects(self): run = self.runner(\"finalizer_resurrects\") res = run([5, 42]) #XXX", "= weakref.ref(a) result = ref() is a ref = g()", "would be dividable by 4 # (and give fixedsize) def", "A() a1 = A() nf1 = nf_a.address[0] nt1 = nt_a.address[0]", "run = self.runner(\"do_malloc_operations_in_call\") run([]) def define_gc_heap_stats(cls): S = lltype.GcStruct('S', ('x',", "= lltype.GcStruct('T', ('z', lltype.Signed)) offset_of_x = llmemory.offsetof(S, 'x') def customtrace(gc,", "that a prebuilt tagged pointer doesn't explode if n >", "import llop, void from rpython.rlib.objectmodel import compute_unique_id, we_are_translated from rpython.rlib.debug", "ptr.hash = 0x62 ptr.chars[0] = '0' ptr.chars[1] = 'B' ptr.chars[2]", "self.runner(\"many_weakrefs\") run([]) def define_immutable_to_old_promotion(cls): T_CHILD = lltype.Ptr(lltype.GcStruct('Child', ('field', lltype.Signed))) T_PARENT", "= A() return weakref.ref(a) def f(): a = A() ref", "considered roots def define_string_concatenation(cls): def concat(j, dummy): lst = []", "the ids, it will trigger some collections itself i =", "tx.z = 4243 s1 = lltype.malloc(S) s1.x = llmemory.cast_ptr_to_adr(tx) return", "GenerationGC as \\ GCClass GC_PARAMS = {'space_size': 512*WORD, 'nursery_size': 32*WORD,", "lltype.Ptr(T1))) static = lltype.malloc(T2, immortal=True) def f(): t1 = lltype.malloc(T1)", "return weakref.ref(b) def f(): ref = g() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) result", "f def test_finalizer_resurrects(self): run = self.runner(\"finalizer_resurrects\") res = run([5, 42])", "self.runner(\"gc_heap_stats\") res = run([]) assert res % 10000 == 2611", "objects that are of type Ptr(Gc). # At the moment", "= self.runner(\"no_clean_setarrayitems\") res = run([]) assert res == 123 def", "class TestIncrementalMiniMarkGC(TestMiniMarkGC): gcname = \"incminimark\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from", "# def setup(): rgc.register_custom_trace_hook(S, lambda_customtrace) tx = lltype.malloc(T) tx.z =", "== 0 # ^^^ a crude assumption that totsize -", "range(len(tb)): if tb[i].count == 4: b += 1 c +=", "def skipdefine_global_list(cls): gl = [] class Box: def __init__(self): self.lst", "f def test_malloc_struct_of_gcptr(self): run = self.runner(\"malloc_struct_of_gcptr\") res = run([]) assert", "= B() b.nextid = 1 b.num_deleted = 0 b.num_deleted_c =", "res = run([]) assert res == self.GC_CAN_MOVE def define_shrink_array(cls): from", "c = 0 d = 0 e = 0 for", "of g graph = graphof(translator, g) for op in graph.startblock.operations:", "+= 1 C() class C(AAA): def __del__(self): b.num_deleted += 1", "res = run([]) assert res def define_malloc_struct_of_gcptr(cls): S1 = lltype.GcStruct('S',", "('x', Signed)) T3 = GcStruct(\"T3\", ('items', Array(S3))) def f3(): t", "b = B() return weakref.ref(b) def f(): ref = g()", "gl box = Box() def append_to_list(i, j): box.lst.append([i] * 50)", "self.runner(\"collect_0\") res = run([100, 0]) assert res == len(''.join([str(x) for", "lltype.malloc(A, j) # the following line generates a write_barrier call", "Signed, malloc S1 = Struct(\"S1\", ('x', Signed)) T1 = GcStruct(\"T1\",", "res = fn([]) assert res == ord('y') class GenericMovingGCTests(GenericGCTests): GC_CAN_MOVE", "0 else: assert len(transformer.layoutbuilder.addresses_of_static_ptrs) >= 4 # NB. Remember that", "return f def test_immutable_to_old_promotion(self): run, transformer = self.runner(\"immutable_to_old_promotion\", transformer=True) run([1,", "= self.runner(\"instances\") run([]) def define_llinterp_lists(cls): def malloc_a_lot(): i = 0", "= [] l4 = [] def f(): for i in", "py.test.skip(\"fails for bad reasons in lltype.py :-(\") run = self.runner(\"many_ids\")", "= lltype.malloc(T_PARENT.TO) parent2 = lltype.malloc(T_PARENT.TO) parent.sub = child child.field =", "= run([]) assert res == 0 def define_can_move(cls): TP =", "res = run([]) assert res == 0 def define_can_move(cls): TP", "def g(): b = B() return weakref.ref(b) def f(): ref", "customtrace(gc, obj, callback, arg): gc._trace_callback(callback, arg, obj + offset_of_x) lambda_customtrace", "we get additional_roots_sources == 6: # * all[0] # *", "class Unrelated(object): pass u = Unrelated() u.x = UnboxedObject(47) def", "True def define_tagged_simple(cls): class Unrelated(object): pass u = Unrelated() u.x", "t.config.translation.gcremovetypeptr = True t.config.set(**extraconfigopts) ann = t.buildannotator() ann.build_types(func, inputtypes) if", "#XXX pure lazyness here too assert 160 <= res <=", "all[1] = parent2 def f(x, y): res = all[x] #all[x]", "GC_CAN_MOVE = True GC_CAN_TEST_ID = False def define_many_ids(cls): class A(object):", "func = funcs0[num] if func: res = func() else: func", "= args[i] res = llinterp.eval_graph(entrygraph, [ll_args]) return res if transformer:", "that the number above does not count # the number", "= {a: A()} j = 0 while j < 20:", "import annlowlevel class A: pass def fn(): a1 = A()", "run([]) assert res == 4243 def define_weakref(cls): import weakref, gc", "= run([4, 42]) #XXX pure lazyness here too assert res", "def run(args): ll_args = lltype.malloc(ARGS, immortal=True) ll_args[0] = name_to_func[name] for", "= s.build()[1000] gc.collect() return ord(res) return fn def test_string_builder_over_allocation(self): fn", "> 50: d += 1 for i in range(len(tb)): if", "a.append(j) return 0 return malloc_a_lot def test_llinterp_lists(self): run = self.runner(\"llinterp_lists\")", "i += 1 a = (1, 2, i) b =", "entrypoint(args): num = args[0] func = funcs0[num] if func: res", "= [1] * 10 j = 0 while j <", "TaggedBase(object): __slots__ = () def meth(self, x): raise NotImplementedError class", "and (ref() is None) return result return f def test_weakref(self):", "('x', lltype.Signed)) A = lltype.GcArray(lltype.Ptr(S)) def sub(lst): lst[15] = lltype.malloc(S)", "1 def __del__(self): b.num_deleted += 1 b.a = self def", "200 def define_write_barrier_direct(cls): from rpython.rlib import rgc S = lltype.GcForwardReference()", "= cls.ensure_layoutbuilder(translator) type_id = layoutbuilder.get_type_id(P) # # now fix the", "16) + (ptr2.hash << 24)) return f def test_shrink_array(self): run", "x in range(100)])) def define_interior_ptrs(cls): from rpython.rtyper.lltypesystem.lltype import Struct, GcStruct,", "class TestGenerationalNoFullCollectGC(GCTest): # test that nursery is doing its job", "as \\ GCClass GC_PARAMS = {'space_size': 512*WORD, 'nursery_size': 32*WORD, 'translated_to_c':", "# has_finalizer Constant(False, lltype.Bool), # is_finalizer_light Constant(False, lltype.Bool)] # contains_weakptr", "(ref() is None) # check that a further collection is", "= A() class B(object): def __del__(self): a.count += 1 def", "[1] * 10 j = 0 while j < 30:", "s.x = 42 llop.bare_setfield(lltype.Void, s0, void('next'), s) llop.gc_writebarrier(lltype.Void, llmemory.cast_ptr_to_adr(s0)) rgc.collect(0)", "= lltype.GcArray(lltype.Float) def func(): return rgc.can_move(lltype.malloc(TP, 1)) return func def", "0]) assert res == len(''.join([str(x) for x in range(100)])) def", "= compute_unique_id(a2) id3 = compute_unique_id(a3) llop.gc__collect(lltype.Void) error = 0 if", "rgc.collect() return f.l[-1].meth(100) def func(): return fn(1000) ^ fn(-1000) assert", "= 42 static.p = t1 llop.gc__collect(lltype.Void) return static.p.x def cleanup():", "# force nursery collect x = [] for i in", "0 # ^^^ a crude assumption that totsize - varsize", "import rgc S = lltype.GcForwardReference() S.become(lltype.GcStruct('S', ('x', lltype.Signed), ('prev', lltype.Ptr(S)),", "= Struct(\"S5\", ('x', Signed)) T5 = GcStruct(\"T5\", ('items', Array(S5))) def", "func() else: func = funcs2[num] res = func(args[1], args[2]) cleanup", "tagged pointer doesn't explode if n > 0: x =", "1) t.s[0] = 1 return t.s[0] def func(): return (f1()", "self.runner('nursery_hash_base') assert res([]) >= 195 def define_instantiate_nonmovable(cls): from rpython.rlib import", "j, i] = A() return 0 return malloc_a_lot def test_llinterp_dict(self):", "gl = [] class Box: def __init__(self): self.lst = gl", "def define_interior_ptrs(cls): from rpython.rtyper.lltypesystem.lltype import Struct, GcStruct, GcArray from rpython.rtyper.lltypesystem.lltype", "lst = lltype.malloc(A, 16) # 16 > 10 rgc.collect() sub(lst)", "= lltype.malloc(A, j) # the following line generates a write_barrier", "from rpython.rtyper.lltypesystem.lltype import Array, Signed, malloc S1 = Struct(\"S1\", ('x',", "lltype.malloc(S) s1.x = llmemory.cast_ptr_to_adr(tx) return s1 def f(): s1 =", "# -> crash return lst[0].x return f def test_no_clean_setarrayitems(self): run", "f def test_finalizer(self): run = self.runner(\"finalizer\") res = run([5, 42])", "this test\") def _teardown(self): self.__ready = False # collecting here", "1 a = (1, 2, i) b = [a] *", "S5 = Struct(\"S5\", ('x', Signed)) T5 = GcStruct(\"T5\", ('items', Array(S5)))", "memory to # remember the ids, it will trigger some", "llop.gc__collect(lltype.Void) assert ref() is a return a.foo + len(all) return", "0 class A(object): def __init__(self): self.id = b.nextid b.nextid +=", "TranslationContext t = TranslationContext() # XXX XXX XXX mess t.config.translation.gc", "return d * 1000 + c * 100 + b", "= lltype.GcStruct('P', ('x', lltype.Signed)) def g(): r = lltype.malloc(P) r.x", "TranslationContext() # XXX XXX XXX mess t.config.translation.gc = gcname t.config.translation.gcremovetypeptr", "return weakref.ref(a) def f(): a = A() ref = weakref.ref(a)", "id of all the elements of the list. The goal", "some collections itself i = 0 while i < len(alist):", "layoutbuilder.delay_encoding() def seeme(): marker[0] += 1 translator._jit2gc = { 'layoutbuilder':", "= lltype.GcStruct('P', ('x', lltype.Signed)) def g(): llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder def", "= lltype.GcStruct('S', ('x', llmemory.Address)) T = lltype.GcStruct('T', ('z', lltype.Signed)) offset_of_x", "in range(10): s = lltype.malloc(S) l1.append(s) l2.append(s) if i <", "llmemory.cast_adr_to_ptr(s1.x, lltype.Ptr(T)).z return f def test_custom_trace(self): run = self.runner(\"custom_trace\") res", "def meth(self, x): raise NotImplementedError class BoxedObject(TaggedBase): attrvalue = 66", "from rpython.rtyper.llinterp import LLInterpreter llinterp = LLInterpreter(self.rtyper) gct = db.gctransformer", "off. S = lltype.GcStruct('S', ('x', lltype.Signed)) A = lltype.GcArray(lltype.Ptr(S)) def", "print would create a static root! llop.debug_print(lltype.Void, b.num_deleted_c) return b.num_deleted", "i in range(1, 5): res = run([i, i - 1])", "name = fullname.split('_', 1) func_fixup = definefunc.im_func(cls) cleanup = None", ">= 4 # NB. Remember that the number above does", "res = run([5, 42]) #XXX pure lazyness here too assert", "== 42 def define_finalizer(cls): class B(object): pass b = B()", "weakref.ref(a) all = [None] * x i = 0 while", "GenericMovingGCTests(GenericGCTests): GC_CAN_MOVE = True GC_CAN_TEST_ID = False def define_many_ids(cls): class", "= len(funcs0) if nargs == 2: funcs2.append(func) funcs0.append(None) elif nargs", "2: funcs2.append(func) funcs0.append(None) elif nargs == 0: funcs0.append(func) funcs2.append(None) else:", "a ref = g() llop.gc__collect(lltype.Void) result = result and (ref()", "= 200 def define_no_clean_setarrayitems(cls): # The optimization find_clean_setarrayitems() in #", "= A() a3 = A() id1 = compute_unique_id(a1) id2 =", "0 i = 0 while i < 40: lst =", "lst[15] = lltype.malloc(S) # 'lst' is set the single mark", "B: pass static = A() static.p = None def f():", "= {'space_size': 512*WORD, 'nursery_size': 32*WORD, 'translated_to_c': False} root_stack_depth = 200", "def define_instantiate_nonmovable(cls): from rpython.rlib import objectmodel from rpython.rtyper import annlowlevel", "tuple): func, cleanup, fixup = func_fixup mixlevelstuff.append(fixup) else: func =", "= 0 while j < 5: lst.append(i*j) j += 1", "{} for i in range(len(objects)): assert compute_identity_hash(objects[i]) == hashes[i] unique[hashes[i]]", "LLInterpreter llinterp = LLInterpreter(self.rtyper) gct = db.gctransformer if self.__class__.__dict__.get('_used', False):", "17: ref = weakref.ref(a) assert ref() is a i +=", "< x: # enough to cause a minor collect all[i]", "=> resets the gc llinterp.eval_graph(setupgraph, []) def run(args): ll_args =", "= self.runner(\"id\") res = run([]) assert res == 0 def", "define_weakref_across_minor_collection(cls): import weakref class A: pass def f(): x =", "= compute_unique_id(alist[i]) i += 1 j = 0 while j", "{'nursery_size': 32*WORD, 'page_size': 16*WORD, 'arena_size': 64*WORD, 'small_request_threshold': 5*WORD, 'large_object': 8*WORD,", "t = malloc(T3, 1) t.items[0].x = 1 return t.items[0].x S4", "lst[2] == lltype.nullptr(S) and lst[3] == lltype.nullptr(S) and lst[4] ==", "x): raise NotImplementedError class BoxedObject(TaggedBase): attrvalue = 66 def __init__(self,", "compute_unique_id(a1): error += 1 if id2 != compute_unique_id(a2): error +=", "res == 0 for i in range(1, 5): res =", "raise NotImplementedError( \"defined test functions should have 0/2 arguments\") #", "1 a = [1] * 10 j = 0 while", "def f4(): u = malloc(U4, 1) u[0].s.x = 1 return", "0x62024231 else: expected = 0x62024230 assert run([]) == expected def", "ann.build_types(func, inputtypes) if specialize: t.buildrtyper().specialize() if backendopt: from rpython.translator.backendopt.all import", "res = run([]) assert res == 123 def define_nursery_hash_base(cls): class", "fixup in mixlevelstuff: if fixup: fixup(t) cbuild = CStandaloneBuilder(t, entrypoint,", "A(object): count = 0 a = A() class B(object): def", "db = self.db name_to_func = self.name_to_func entrygraph = self.entrygraph from", "< 30: b = B(somea) b.last = first j +=", "assert res == ord('y') class GenericMovingGCTests(GenericGCTests): GC_CAN_MOVE = True GC_CAN_TEST_ID", "if jit2gc: assert 'invoke_after_minor_collection' in jit2gc return jit2gc['layoutbuilder'] marker =", "T_PARENT = lltype.Ptr(lltype.GcStruct('Parent', ('sub', T_CHILD))) child = lltype.malloc(T_CHILD.TO) child2 =", "= lltype.Ptr(lltype.GcArray(T_PARENT)) all = lltype.malloc(T_ALL.TO, 2) all[0] = parent all[1]", "rgc._heap_stats() a = 0 nr = 0 b = 0", "A() return 0 return malloc_a_lot def test_llinterp_dict(self): run = self.runner(\"llinterp_dict\")", "llop.gc__collect(lltype.Void) return static.p.x + i def cleanup(): static.p = None", "= func([]) print res from rpython.rlib.objectmodel import UnboxedValue class TaggedBase(object):", "self.runner(\"no_clean_setarrayitems\") res = run([]) assert res == 123 def define_nursery_hash_base(cls):", "= [] l3 = [] l4 = [] def f():", "test_interior_ptrs(self): run = self.runner(\"interior_ptrs\") res = run([]) assert res ==", "obj, callback, arg): gc._trace_callback(callback, arg, obj + offset_of_x) lambda_customtrace =", "import Constant from rpython.rtyper.lltypesystem import rffi layoutbuilder = cls.ensure_layoutbuilder(translator) type_id", "res == 84 def define_many_weakrefs(cls): # test for the case", "= cbuild.generate_graphs_for_llinterp() entrypointptr = cbuild.getentrypointptr() entrygraph = entrypointptr._obj.graph if option.view:", "AAA() i = 0 while i < x: i +=", "assert marker[0] > 0 marker[0] = 0 else: cleanup =", "= gl box = Box() def append_to_list(i, j): box.lst.append([i] *", "g() i += q.x return 0 def fix_graph_of_g(translator): from rpython.translator.translator", "hashes.append(compute_identity_hash(obj)) unique = {} for i in range(len(objects)): assert compute_identity_hash(objects[i])", "False} root_stack_depth = 200 def define_working_nursery(cls): def f(): total =", "locations # within prebuilt GC objects that are of type", "# XXX XXX XXX mess t.config.translation.gc = gcname t.config.translation.gcremovetypeptr =", "return rgc.get_typeid(a) return fn def test_gettypeid(self): func = self.runner(\"gettypeid\") res", "= None while i < 10: i += 1 a", "f.l.append(x) rgc.collect() return f.l[-1].meth(100) def func(): return fn(1000) ^ fn(-1000)", "mixlevelstuff: if fixup: fixup(t) cbuild = CStandaloneBuilder(t, entrypoint, config=t.config, gcpolicy=cls.gcpolicy)", "= 'smallint' def meth(self, x): return self.smallint + x +", "__init__(self): self.id = b.nextid b.nextid += 1 def __del__(self): b.num_deleted", "s.append(\"rty\") s.append_multiple_char('y', 1000) gc.collect() s.append_multiple_char('y', 1000) res = s.build()[1000] gc.collect()", "== l[50 + i] return 0 return fn def test_writebarrier_before_copy(self):", "cls.gcname == 'incminimark': marker = cls.marker def cleanup(): assert marker[0]", "* 100 + b * 10 + a return f", "rpython.memory.gctransform import framework, shadowstack from rpython.rtyper.lltypesystem.lloperation import llop, void from", "def define_ref_from_rawmalloced_to_regular(cls): import gc S = lltype.GcStruct('S', ('x', lltype.Signed)) A", "ann = t.buildannotator() ann.build_types(func, inputtypes) if specialize: t.buildrtyper().specialize() if backendopt:", "A() objects.append(obj) hashes.append(compute_identity_hash(obj)) unique = {} for i in range(len(objects)):", "SomePtr(lltype.Ptr(ARGS)) t = rtype(entrypoint, [s_args], gcname=cls.gcname, taggedpointers=cls.taggedpointers) for fixup in", "Struct(\"S3\", ('x', Signed)) T3 = GcStruct(\"T3\", ('items', Array(S3))) def f3():", "1 # crashes if constants are not considered roots def", "lst.append(i*j) j += 1 total += len(lst) i += 1", "False # collecting here is expected GenerationGC._teardown(self) GC_PARAMS = {'space_size':", "lltype.GcArray(lltype.Ptr(S)) def sub(lst): lst[15] = lltype.malloc(S) # 'lst' is set", "j += 1 b.append((1, j, i)) return 0 return malloc_a_lot", "+= 1 b.append((1, j, i)) return 0 return malloc_a_lot def", "= True GC_CAN_TEST_ID = False def define_many_ids(cls): class A(object): pass", "= gct.frameworkgc__teardown_ptr.value._obj.graph llinterp.eval_graph(teardowngraph, []) self.__class__._used = True # FIIIIISH setupgraph", "from rpython.translator.translator import TranslationContext t = TranslationContext() # XXX XXX", "res([]) == 0 class TestIncrementalMiniMarkGC(TestMiniMarkGC): gcname = \"incminimark\" class gcpolicy(gc.BasicFrameworkGcPolicy):", "t[0].x = 1 return t[0].x S3 = Struct(\"S3\", ('x', Signed))", "False def setup_class(cls): cls.marker = lltype.malloc(rffi.CArray(lltype.Signed), 1, flavor='raw', zero=True) funcs0", "prebuilt tagged pointer doesn't explode if n > 0: x", "* i i += 1 assert ref() is a llop.gc__collect(lltype.Void)", "S = lltype.GcStruct('S', ('x', lltype.Char)) TP = lltype.GcArray(lltype.Ptr(S)) def fn():", "StringBuilder from rpython.rlib.rarithmetic import LONG_BIT WORD = LONG_BIT // 8", "= somea = A() a.last = first first = a", "test_can_move(self): run = self.runner(\"can_move\") res = run([]) assert res ==", "rffi, llgroup from rpython.memory.gctransform import framework, shadowstack from rpython.rtyper.lltypesystem.lloperation import", "llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) result = a.count == 1 and (ref() is", "compute_identity_hash(objects[i]) == hashes[i] unique[hashes[i]] = None return len(unique) return fn", "= self.runner('nursery_hash_base') assert res([]) >= 195 def define_instantiate_nonmovable(cls): from rpython.rlib", "UnboxedObject(47) def fn(n): rgc.collect() # check that a prebuilt tagged", "gcname='ref', backendopt=False, **extraconfigopts): from rpython.translator.translator import TranslationContext t = TranslationContext()", "result = result and (ref() is None) # check that", "define_no_clean_setarrayitems(cls): # The optimization find_clean_setarrayitems() in # gctransformer/framework.py does not", "GenerationGC class GCClass(GenerationGC): __ready = False def setup(self): from rpython.memory.gc.generation", "2, i) b = [a] * 10 j = 0", "+ offset_of_x) lambda_customtrace = lambda: customtrace # def setup(): rgc.register_custom_trace_hook(S,", "def define_collect_during_collect(cls): class B(object): pass b = B() b.nextid =", "class A(object): count = 0 a = A() class B(object):", "lltype.nullptr(S1)) return f def test_malloc_struct_of_gcptr(self): run = self.runner(\"malloc_struct_of_gcptr\") res =", "123 def define_nursery_hash_base(cls): class A: pass def fn(): objects =", "('a', lltype.Array(lltype.Char))) def setup(j): p = lltype.malloc(S) p.x = j*2", "4, 'translated_to_c': False, } root_stack_depth = 200 def define_malloc_array_of_gcptr(self): S", "t1.x = 42 static.p = t1 llop.gc__collect(lltype.Void) return static.p.x def", "idarray = lltype.malloc(rffi.SIGNEDP.TO, len(alist), flavor='raw') # Compute the id of", "UnboxedObject(n) f.l.append(x) rgc.collect() return f.l[-1].meth(100) def func(): return fn(1000) ^", "and (ref() is None) # check that a further collection", "This can only occur with varsized mallocs. lst.p = p", "return run class GenericGCTests(GCTest): GC_CAN_SHRINK_ARRAY = False def define_instances(cls): class", "backendopt: from rpython.translator.backendopt.all import backend_optimizations backend_optimizations(t) if option.view: t.viewcg() return", "A() persistent_a2 = A() i = 0 while i <", "= gcname t.config.translation.gcremovetypeptr = True t.config.set(**extraconfigopts) ann = t.buildannotator() ann.build_types(func,", "\"generation\" GC_CAN_SHRINK_ARRAY = True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation", "a1 = A() a = objectmodel.instantiate(A, nonmovable=True) a.next = a1", "a = (1, 2, i) b = [a] * 10", "all = [None] * x i = 0 while i", "run = self.runner(\"global_list\") res = run([0, 0]) assert res ==", "= run([5, 42]) #XXX pure lazyness here too assert 160", "= UnboxedObject(n) f.l.append(x) rgc.collect() return f.l[-1].meth(100) def func(): return fn(1000)", "return malloc_a_lot def test_instances(self): run = self.runner(\"instances\") run([]) def define_llinterp_lists(cls):", "return t[0].x S3 = Struct(\"S3\", ('x', Signed)) T3 = GcStruct(\"T3\",", "die quickly gcname = \"generation\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from", "rgc.collect() sub(lst) null = lltype.nullptr(S) lst[15] = null # clear,", "3 class TestHybridTaggedPointerGC(TaggedPointerGCTests): gcname = \"hybrid\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer):", "Struct(\"S2\", ('x', Signed)) T2 = GcArray(S2) def f2(): t =", "young here, so no write barrier emitted res = rgc.can_move(annlowlevel.cast_instance_to_base_ptr(a))", "run([]) def define_do_malloc_operations_in_call(cls): P = lltype.GcStruct('P', ('x', lltype.Signed)) def g():", "# setup => resets the gc llinterp.eval_graph(setupgraph, []) def run(args):", "llinterp.eval_graph(setupgraph, []) def run(args): ll_args = lltype.malloc(ARGS, immortal=True) ll_args[0] =", "<< 16) + (ptr2.hash << 24)) return f def test_shrink_array(self):", "test_collect_0(self): run = self.runner(\"collect_0\") res = run([100, 0]) assert res", "= A() a.last = first first = a j =", "collections itself i = 0 while i < len(alist): idarray[i]", "compute_unique_id(a3): error += 4 return error return func def test_id(self):", "fn(): s = StringBuilder(4) s.append(\"abcd\") s.append(\"defg\") s.append(\"rty\") s.append_multiple_char('y', 1000) gc.collect()", "test_tagged_simple(self): func = self.runner(\"tagged_simple\") res = func([]) assert res ==", "a = 0 nr = 0 b = 0 c", "from rpython.rtyper.lltypesystem.lloperation import llop, void from rpython.rlib.objectmodel import compute_unique_id, we_are_translated", "= 0 while j < 30: j += 1 a.append(j)", "b.nextid = 1 b.num_deleted = 0 b.num_deleted_c = 0 class", "a \"clean_setarrayitem\" def f(): lst = lltype.malloc(A, 16) # 16", "p = lltype.malloc(S) p.x = j*2 lst = lltype.malloc(A, j)", "def fn(): a1 = A() a = objectmodel.instantiate(A, nonmovable=True) a.next", "a1 = A() def func(): a2 = A() a3 =", "t.items[0].x S4 = Struct(\"S4\", ('x', Signed)) T4 = Struct(\"T4\", ('s',", "rpython.translator.translator import graphof from rpython.flowspace.model import Constant from rpython.rtyper.lltypesystem import", "class A(object): def __init__(self): self.id = b.nextid b.nextid += 1", "s.build()[1000] gc.collect() return ord(res) return fn def test_string_builder_over_allocation(self): fn =", "is None) return result return f def test_weakref(self): run =", "True GC_CAN_TEST_ID = False def define_many_ids(cls): class A(object): pass def", "def __init__(self, normalint): self.normalint = normalint def meth(self, x): return", "for x in range(100)])) def define_interior_ptrs(cls): from rpython.rtyper.lltypesystem.lltype import Struct,", "llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder p = lltype.cast_opaque_ptr(lltype.Ptr(P), p) p.x = r.x", "on # process ourselves, otherwise this test takes ages llop.gc__collect(lltype.Void)", "from rpython.memory.gc.semispace import SemiSpaceGC as GCClass GC_PARAMS = {'space_size': 512*WORD,", "+ 100 * (b.a is None) return f def test_finalizer_resurrects(self):", "assert res == 20 + 20 def define_nongc_static_root_minor_collect(cls): T1 =", "func.func_name = \"f_%s\" % name if cleanup: cleanup.func_name = \"clean_%s\"", "nt1 == nt0 return 0 return f def test_adr_of_nursery(self): run", "A() is only visible via lst[0] rgc.collect() # -> crash", "= A() return rgc.get_typeid(a) return fn def test_gettypeid(self): func =", "= run([]) assert res def define_collect_during_collect(cls): class B(object): pass b", "from rpython.rlib import rgc from rpython.conftest import option from rpython.rlib.rstring", "compute_unique_id(alist[i]) i += 1 j += 1 lltype.free(idarray, flavor='raw') return", "B(object): pass b = B() b.nextid = 1 b.num_deleted =", "def fix_graph_of_g(translator): from rpython.translator.translator import graphof from rpython.flowspace.model import Constant", "dummy): lst = [] for i in range(j): lst.append(str(i)) return", "class GCClass(GenerationGC): __ready = False def setup(self): from rpython.memory.gc.generation import", "write_barrier call at the moment, # which is important because", "zero=True) funcs0 = [] funcs2 = [] cleanups = []", "i += 1 a = somea = A() a.last =", "A(object): pass def f(): from rpython.rtyper.lltypesystem import rffi alist =", "rpython.annotator import model as annmodel from rpython.rtyper.llannotation import SomePtr from", "else: assert 0, \"oups, not found\" return f, cleanup, fix_graph_of_g", "self.runner('instantiate_nonmovable') assert res([]) == 0 class TestIncrementalMiniMarkGC(TestMiniMarkGC): gcname = \"incminimark\"", "layoutbuilder = cls.ensure_layoutbuilder(translator) type_id = layoutbuilder.get_type_id(P) # # now fix", "b.nextid b.nextid += 1 def __del__(self): b.num_deleted += 1 def", "elements of the list. The goal is # to not", "0 return f def test_many_ids(self): if not self.GC_CAN_TEST_ID: py.test.skip(\"fails for", "while i < x: i += 1 a = AAA()", "ll_args[0] = name_to_func[name] for i in range(len(args)): ll_args[1+i] = args[i]", "0 while i < x: i += 1 a =", "CStandaloneBuilder s_args = SomePtr(lltype.Ptr(ARGS)) t = rtype(entrypoint, [s_args], gcname=cls.gcname, taggedpointers=cls.taggedpointers)", "None if isinstance(func_fixup, tuple): func, cleanup, fixup = func_fixup mixlevelstuff.append(fixup)", "= A() nf1 = nf_a.address[0] nt1 = nt_a.address[0] assert nf1", "= objectmodel.instantiate(A, nonmovable=True) a.next = a1 # 'a' is known", "= True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.semispace import SemiSpaceGC", "def f(x, y): res = all[x] #all[x] = lltype.nullptr(T_PARENT.TO) return", "setup(j): p = lltype.malloc(S) p.x = j*2 lst = lltype.malloc(A,", "2. This can only occur with varsized mallocs. lst.p =", "4, 'translated_to_c': False, } root_stack_depth = 200 def define_no_clean_setarrayitems(cls): #", "'lst' is set the single mark \"12-15\" lst[15].x = 123", "first j += 1 return 0 return malloc_a_lot def test_instances(self):", "define_id(cls): class A(object): pass a1 = A() def func(): a2", "func: res = func() else: func = funcs2[num] res =", "range(j): lst.append(str(i)) return len(\"\".join(lst)) return concat def test_string_concatenation(self): run =", "emitted res = rgc.can_move(annlowlevel.cast_instance_to_base_ptr(a)) rgc.collect() objectmodel.keepalive_until_here(a) return res return fn", "return result return f def test_weakref(self): run = self.runner(\"weakref\") res", "def setup_class(cls): cls.marker = lltype.malloc(rffi.CArray(lltype.Signed), 1, flavor='raw', zero=True) funcs0 =", "S = lltype.GcStruct('S', ('x', lltype.Signed)) A = lltype.GcArray(lltype.Ptr(S)) def f():", "1 obj to allocate a nursery a = A() nf_a", "known young here, so no write barrier emitted res =", "# We cheat here and only read the table which", "assert 0, \"oups, not found\" return f, None, fix_graph_of_g def", "b.last = first j += 1 return 0 return malloc_a_lot", "1 return 0 return f def test_many_weakrefs(self): run = self.runner(\"many_weakrefs\")", "1 a = somea = A() a.last = first first", "fullname in dir(cls): if not fullname.startswith('define'): continue definefunc = getattr(cls,", "in this test\") def _teardown(self): self.__ready = False # collecting", "fixedsize) def define_writebarrier_before_copy(cls): S = lltype.GcStruct('S', ('x', lltype.Char)) TP =", "i += 1 j = 0 while j < 2:", "('sub', T_CHILD))) child = lltype.malloc(T_CHILD.TO) child2 = lltype.malloc(T_CHILD.TO) parent =", "size_changing=False): ll_assert(not self.__ready, \"no full collect should occur in this", "= 0 while j < 2: if j == 1:", "+= 1 assert ref() is a llop.gc__collect(lltype.Void) assert ref() is", "10 j = 0 while j < 20: j +=", "HybridGC as GCClass GC_PARAMS = {'space_size': 512*WORD, 'nursery_size': 32*WORD, 'large_object':", "F: pass f = F() f.l = [UnboxedObject(10)] def fn(n):", "graph.startblock.operations: if op.opname == 'do_malloc_fixedsize': op.args = [Constant(type_id, llgroup.HALFWORD), Constant(llmemory.sizeof(P),", "test_nongc_static_root_minor_collect(self): run = self.runner(\"nongc_static_root_minor_collect\") res = run([]) assert res ==", "fn(): a = A() return rgc.get_typeid(a) return fn def test_gettypeid(self):", "< 40: lst = [] j = 0 while j", "# gctransformer/framework.py does not work with card marking. # Check", "fullname.split('_', 1) func_fixup = definefunc.im_func(cls) cleanup = None if isinstance(func_fixup,", "a = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) aid = b.a.id b.a =", "= db.gctransformer if self.__class__.__dict__.get('_used', False): teardowngraph = gct.frameworkgc__teardown_ptr.value._obj.graph llinterp.eval_graph(teardowngraph, [])", "import rffi alist = [A() for i in range(50)] idarray", "= llop.gc_adr_of_nursery_top(llmemory.Address) nf0 = nf_a.address[0] nt0 = nt_a.address[0] a0 =", "least 1 obj to allocate a nursery a = A()", "res = self.runner('nursery_hash_base') assert res([]) >= 195 def define_instantiate_nonmovable(cls): from", "# placeholder p = lltype.cast_opaque_ptr(lltype.Ptr(P), p) p.x = r.x return", "0: funcs0.append(func) funcs2.append(None) else: raise NotImplementedError( \"defined test functions should", "import lltype, llmemory, rffi, llgroup from rpython.memory.gctransform import framework, shadowstack", "[i] * i i += 1 assert ref() is a", "self.runner(\"llinterp_tuples\") run([]) def define_llinterp_dict(self): class A(object): pass def malloc_a_lot(): i", "= framework.TransformerLayoutBuilder(translator, GCClass) layoutbuilder.delay_encoding() def seeme(): marker[0] += 1 translator._jit2gc", "b.num_deleted = 0 class A(object): def __init__(self): self.id = b.nextid", "g(): llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder def f(): q = lltype.malloc(P) q.x", "persistent_a1.id + persistent_a2.id + persistent_a3.id + persistent_a4.id # NB print", "lltype.GcStruct('A', ('p', lltype.Ptr(S)), ('a', lltype.Array(lltype.Char))) def setup(j): p = lltype.malloc(S)", "lltype.Ptr(S)))) s0 = lltype.malloc(S, immortal=True) def f(): s = lltype.malloc(S)", "possible obj = A() objects.append(obj) hashes.append(compute_identity_hash(obj)) unique = {} for", "import framework, shadowstack from rpython.rtyper.lltypesystem.lloperation import llop, void from rpython.rlib.objectmodel", "GC_PARAMS = {'space_size': 512*WORD, 'nursery_size': 32*WORD, 'large_object': 8*WORD, 'translated_to_c': False}", "rpython.translator.translator import TranslationContext t = TranslationContext() # XXX XXX XXX", "from rpython.rtyper.lltypesystem import rffi layoutbuilder = cls.ensure_layoutbuilder(translator) type_id = layoutbuilder.get_type_id(P)", "semispace_collect(self, size_changing=False): ll_assert(not self.__ready, \"no full collect should occur in", "20 # for GenerationGC, enough for a minor collection a", "something def malloc_a_lot(): i = 0 first = None while", "= 0 nr = 0 b = 0 c =", "rgc.register_custom_trace_hook(S, lambda_customtrace) tx = lltype.malloc(T) tx.z = 4243 s1 =", "in range(len(objects)): assert compute_identity_hash(objects[i]) == hashes[i] unique[hashes[i]] = None return", "== 0 class TestIncrementalMiniMarkGC(TestMiniMarkGC): gcname = \"incminimark\" class gcpolicy(gc.BasicFrameworkGcPolicy): class", "def rtype(func, inputtypes, specialize=True, gcname='ref', backendopt=False, **extraconfigopts): from rpython.translator.translator import", "= run([5, 42]) #XXX pure lazyness here too assert res", "0 while j < 5: lst.append(i*j) j += 1 total", "barrier emitted res = rgc.can_move(annlowlevel.cast_instance_to_base_ptr(a)) rgc.collect() objectmodel.keepalive_until_here(a) return res return", "= run([]) assert res == 42 def define_finalizer(cls): class B(object):", "fn(1000) ^ fn(-1000) assert func() == -1999 return func def", "if transformer: return run, gct else: return run class GenericGCTests(GCTest):", "= len(\"\".join(lst)) if we_are_translated(): llop.gc__collect(lltype.Void, 0) return result return concat", "t.s[0] def func(): return (f1() * 100000 + f2() *", "1000) gc.collect() s.append_multiple_char('y', 1000) res = s.build()[1000] gc.collect() return ord(res)", "Investigate.\") run = self.runner(\"gc_heap_stats\") res = run([]) assert res %", "def f(x, y): a = AAA() i = 0 while", "test_immutable_to_old_promotion(self): run, transformer = self.runner(\"immutable_to_old_promotion\", transformer=True) run([1, 4]) if not", "= {'space_size': 512*WORD, 'translated_to_c': False} root_stack_depth = 200 class TestGenerationGC(GenericMovingGCTests):", "gct else: return run class GenericGCTests(GCTest): GC_CAN_SHRINK_ARRAY = False def", "def define_custom_trace(cls): # S = lltype.GcStruct('S', ('x', llmemory.Address)) T =", "f(i, j): lst = setup(j) gc.collect() return lst.p.x return f", "S.become(lltype.GcStruct('S', ('x', lltype.Signed), ('prev', lltype.Ptr(S)), ('next', lltype.Ptr(S)))) s0 = lltype.malloc(S,", "100]) assert res == 200 def define_write_barrier_direct(cls): from rpython.rlib import", "GCClass(GenerationGC): __ready = False def setup(self): from rpython.memory.gc.generation import GenerationGC", "# invoke write barrier rgc.collect() return x.meth(100) def func(): return", "func(args[1], args[2]) cleanup = cleanups[num] if cleanup: cleanup() return res", "from rpython.translator.c.genc import CStandaloneBuilder s_args = SomePtr(lltype.Ptr(ARGS)) t = rtype(entrypoint,", "= A() id1 = compute_unique_id(a1) id2 = compute_unique_id(a2) id3 =", "if i < 3: l3.append(s) l4.append(s) # We cheat here", "p.x = j*2 lst = lltype.malloc(A, j) # the following", "= [] cleanups = [] name_to_func = {} mixlevelstuff =", "b += 1 c += tb[i].links[nr] e += tb[i].size return", "'do_malloc_fixedsize': op.args = [Constant(type_id, llgroup.HALFWORD), Constant(llmemory.sizeof(P), lltype.Signed), Constant(False, lltype.Bool), #", "f3() * 1000 + f4() * 100 + f5() *", "run = self.runner(\"string_concatenation\") res = run([100, 0]) assert res ==", "res == len(''.join([str(x) for x in range(100)])) def define_interior_ptrs(cls): from", "self def f(x, y): a = A() i = 0", "l[i] = lltype.malloc(S) rgc.ll_arraycopy(l, l2, 50, 0, 50) # force", "static.p = t1 x = 20 all = [None] *", "from rpython.memory.gctransform import framework, shadowstack from rpython.rtyper.lltypesystem.lloperation import llop, void", "Box: def __init__(self): self.lst = gl box = Box() def", "return s0.next.x def cleanup(): s0.next = lltype.nullptr(S) return f, cleanup,", "test_llinterp_tuples(self): run = self.runner(\"llinterp_tuples\") run([]) def define_llinterp_dict(self): class A(object): pass", "+= 1 def __del__(self): b.num_deleted += 1 b.a = self", "i < 40: g() i += q.x return 0 def", "nr = 0 b = 0 c = 0 d", "tb[i].links[nr] e += tb[i].size return d * 1000 + c", "T1 = lltype.GcStruct(\"C\", ('x', lltype.Signed)) T2 = lltype.Struct(\"C\", ('p', lltype.Ptr(T1)))", "moment, # which is important because the 'lst' can be", "return res if transformer: return run, gct else: return run", "test functions should have 0/2 arguments\") # used to let", "gcname=cls.gcname, taggedpointers=cls.taggedpointers) for fixup in mixlevelstuff: if fixup: fixup(t) cbuild", "assert res == len(''.join([str(x) for x in range(100)])) def define_nongc_static_root(cls):", "0 return malloc_a_lot def test_llinterp_lists(self): run = self.runner(\"llinterp_lists\") run([]) def", "= BoxedObject(n) else: x = UnboxedObject(n) u.x = x #", "\"minimark\" GC_CAN_TEST_ID = True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.minimark", "A() persistent_a4 = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) b.bla = persistent_a1.id +", "= UnboxedObject(n) u.x = x # invoke write barrier rgc.collect()", "t ARGS = lltype.FixedSizeArray(lltype.Signed, 3) class GCTest(object): gcpolicy = None", "100000 + f2() * 10000 + f3() * 1000 +", "allocating the weakref itself triggers # a collection import weakref", "= self.runner(\"write_barrier_direct\") res = run([]) assert res == 42 class", "= A() nf_a = llop.gc_adr_of_nursery_free(llmemory.Address) nt_a = llop.gc_adr_of_nursery_top(llmemory.Address) nf0 =", "('x', lltype.Signed)) A = lltype.GcArray(lltype.Ptr(S)) def f(): lst = lltype.malloc(A,", "lltype.GcStruct('S', ('x', lltype.Signed), ('filed1', lltype.Ptr(S1)), ('filed2', lltype.Ptr(S1))) s0 = lltype.malloc(S)", "= A() persistent_a3 = A() persistent_a4 = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void)", "S4)) U4 = GcArray(T4) def f4(): u = malloc(U4, 1)", "define_static_root_minor_collect(cls): class A: pass class B: pass static = A()", "lambda: customtrace # def setup(): rgc.register_custom_trace_hook(S, lambda_customtrace) tx = lltype.malloc(T)", "GcArray(T4) def f4(): u = malloc(U4, 1) u[0].s.x = 1", "a collection import weakref class A: pass def f(): a", "func, cleanup, fixup = func_fixup mixlevelstuff.append(fixup) else: func = func_fixup", "None GC_CAN_MOVE = False taggedpointers = False def setup_class(cls): cls.marker", "f(x, y): persistent_a1 = A() persistent_a2 = A() i =", "= rgc.ll_shrink_array(ptr, 2) return ((ptr == ptr2) + ord(ptr2.chars[0]) +", "2 if id3 != compute_unique_id(a3): error += 4 return error", "child2 child2.field = 8 T_ALL = lltype.Ptr(lltype.GcArray(T_PARENT)) all = lltype.malloc(T_ALL.TO,", "assert res == i - 1 # crashes if constants", "= {} mixlevelstuff = [] for fullname in dir(cls): if", "= AAA() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted return f def test_finalizer_calls_malloc(self):", "define_writebarrier_before_copy(cls): S = lltype.GcStruct('S', ('x', lltype.Char)) TP = lltype.GcArray(lltype.Ptr(S)) def", "GC_CAN_TEST_ID = True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.minimark import", "('x', lltype.Signed)) T2 = lltype.Struct(\"C\", ('p', lltype.Ptr(T1))) static = lltype.malloc(T2,", "self.runner(\"immutable_to_old_promotion\", transformer=True) run([1, 4]) if not transformer.GCClass.prebuilt_gc_objects_are_static_roots: assert len(transformer.layoutbuilder.addresses_of_static_ptrs) ==", "205 return func def test_tagged_simple(self): func = self.runner(\"tagged_simple\") res =", "import SomePtr from rpython.rtyper.lltypesystem import lltype, llmemory, rffi, llgroup from", "pass class B(A): def __init__(self, something): self.something = something def", "here too assert res == 12 def define_finalizer_resurrects(cls): class B(object):", "def test_string_builder_over_allocation(self): fn = self.runner(\"string_builder_over_allocation\") res = fn([]) assert res", "objects.append(obj) hashes.append(compute_identity_hash(obj)) unique = {} for i in range(len(objects)): assert", "func_fixup mixlevelstuff.append(fixup) else: func = func_fixup func.func_name = \"f_%s\" %", "5 class TestHybridGC(TestGenerationGC): gcname = \"hybrid\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer):", "from rpython.memory.gc.minimark import MiniMarkGC as GCClass GC_PARAMS = {'nursery_size': 32*WORD,", "res = run([]) assert res def define_collect_during_collect(cls): class B(object): pass", "= lltype.malloc(P) r.x = 1 p = llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder", "SemiSpaceGC as GCClass GC_PARAMS = {'space_size': 512*WORD, 'translated_to_c': False} root_stack_depth", "from rpython.rtyper import annlowlevel class A: pass def fn(): a1", "The goal is # to not allocate memory, so that", "gcname = \"generation\" GC_CAN_SHRINK_ARRAY = True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer):", "g(): b = B() return weakref.ref(b) def f(): ref =", "b.num_deleted += 1 C() C() class C(A): def __del__(self): b.num_deleted", "return f, None, fix_graph_of_g def test_do_malloc_operations_in_call(self): run = self.runner(\"do_malloc_operations_in_call\") run([])", "import GenerationGC as \\ GCClass GC_PARAMS = {'space_size': 512*WORD, 'nursery_size':", "+= 1 i = static.p.x llop.gc__collect(lltype.Void) return static.p.x + i", "class TaggedBase(object): __slots__ = () def meth(self, x): raise NotImplementedError", "weakref class A: pass def f(): x = 20 #", "Ptr(Gc). # At the moment we get additional_roots_sources == 6:", "def define_do_malloc_operations_in_call(cls): P = lltype.GcStruct('P', ('x', lltype.Signed)) def g(): llop.do_malloc_fixedsize(llmemory.GCREF)", "range(len(args)): ll_args[1+i] = args[i] res = llinterp.eval_graph(entrygraph, [ll_args]) return res", "= self.runner(\"working_nursery\") res = run([]) assert res == 40 *", "= \"clean_%s\" % name nargs = len(inspect.getargspec(func)[0]) name_to_func[name] = len(funcs0)", "def test_can_move(self): run = self.runner(\"can_move\") res = run([]) assert res", "lltype.malloc(STR, 3) ptr.hash = 0x62 ptr.chars[0] = '0' ptr.chars[1] =", "== 2611 totsize = (res / 10000) size_of_int = rffi.sizeof(lltype.Signed)", "* x i = 0 while i < x: #", "lltype.malloc(P) q.x = 1 i = 0 while i <", "backend_optimizations backend_optimizations(t) if option.view: t.viewcg() return t ARGS = lltype.FixedSizeArray(lltype.Signed,", "is doing its job and that no full collection #", "0 a = A() class B(object): def __del__(self): a.count +=", "len(\"\".join(lst)) return concat def test_string_concatenation(self): run = self.runner(\"string_concatenation\") res =", "create a static root! llop.debug_print(lltype.Void, b.num_deleted_c) return b.num_deleted return f", "return 0 if cls.gcname == 'incminimark': marker = cls.marker def", "T = lltype.GcStruct('T', ('z', lltype.Signed)) offset_of_x = llmemory.offsetof(S, 'x') def", "llop.gc__collect(lltype.Void) return b.num_deleted return f def test_finalizer_calls_malloc(self): run = self.runner(\"finalizer_calls_malloc\")", "= B() b.nextid = 0 b.num_deleted = 0 class A(object):", "skipdefine_global_list(cls): gl = [] class Box: def __init__(self): self.lst =", "that would be a \"clean_setarrayitem\" def f(): lst = lltype.malloc(A,", "= self.runner(\"tagged_simple\") res = func([]) assert res == 205 def", "= graphof(translator, g) for op in graph.startblock.operations: if op.opname ==", "to # remember the ids, it will trigger some collections", "persistent_a4 = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) b.bla = persistent_a1.id + persistent_a2.id", "static.p.x llop.gc__collect(lltype.Void) return static.p.x + i def cleanup(): static.p =", "child2 = lltype.malloc(T_CHILD.TO) parent = lltype.malloc(T_PARENT.TO) parent2 = lltype.malloc(T_PARENT.TO) parent.sub", "check that __del__ is not called again llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return", "1 if id2 != compute_unique_id(a2): error += 2 if id3", "hashes[i] unique[hashes[i]] = None return len(unique) return fn def test_nursery_hash_base(self):", "res == len(''.join([str(x) for x in range(100)])) def define_nongc_static_root(cls): T1", "at the moment, # which is important because the 'lst'", "[]) def run(args): ll_args = lltype.malloc(ARGS, immortal=True) ll_args[0] = name_to_func[name]", "None def fix_graph_of_g(translator): from rpython.translator.translator import graphof from rpython.flowspace.model import", "pass u = Unrelated() u.x = UnboxedObject(47) def fn(n): rgc.collect()", "[] funcs2 = [] cleanups = [] name_to_func = {}", "class B: pass static = A() static.p = None def", "lltype.Ptr(lltype.GcArray(T_PARENT)) all = lltype.malloc(T_ALL.TO, 2) all[0] = parent all[1] =", "def customtrace(gc, obj, callback, arg): gc._trace_callback(callback, arg, obj + offset_of_x)", "not transformer.GCClass.prebuilt_gc_objects_are_static_roots: assert len(transformer.layoutbuilder.addresses_of_static_ptrs) == 0 else: assert len(transformer.layoutbuilder.addresses_of_static_ptrs) >=", "* 100 + f5() * 10 + f6()) assert func()", "= [Constant(type_id, llgroup.HALFWORD), Constant(llmemory.sizeof(P), lltype.Signed), Constant(False, lltype.Bool), # has_finalizer Constant(False,", "= self.runner(\"llinterp_tuples\") run([]) def define_llinterp_dict(self): class A(object): pass def malloc_a_lot():", "not considered roots def define_string_concatenation(cls): def concat(j, dummy): lst =", "= 0 while i < 40: g() i += q.x", "transformer=False): db = self.db name_to_func = self.name_to_func entrygraph = self.entrygraph", "def define_many_weakrefs(cls): # test for the case where allocating the", "__init__(self): self.id = b.nextid b.nextid += 1 def __del__(self): llop.gc__collect(lltype.Void)", "define_nongc_static_root_minor_collect(cls): T1 = lltype.GcStruct(\"C\", ('x', lltype.Signed)) T2 = lltype.Struct(\"C\", ('p',", "for i in range(j): lst.append(str(i)) result = len(\"\".join(lst)) if we_are_translated():", "while i < 40: lst = [] j = 0", "# allocated stuff cleanups.append(cleanup) def entrypoint(args): num = args[0] func", "= self.runner(\"do_malloc_operations_in_call\") run([]) def define_gc_heap_stats(cls): S = lltype.GcStruct('S', ('x', lltype.Signed))", "nf0 assert nt1 > nf1 assert nt1 == nt0 return", "= 0 while j < 20: j += 1 b.append((1,", "f(): # we need at least 1 obj to allocate", "== 205 return func def test_tagged_simple(self): func = self.runner(\"tagged_simple\") res", "the id of all the elements of the list. The", "a = A() return rgc.get_typeid(a) return fn def test_gettypeid(self): func", "+= tb[i].links[nr] e += tb[i].size return d * 1000 +", "obj + offset_of_x) lambda_customtrace = lambda: customtrace # def setup():", "def test_collect_0(self): run = self.runner(\"collect_0\") res = run([100, 0]) assert", "lltype.malloc(T_CHILD.TO) child2 = lltype.malloc(T_CHILD.TO) parent = lltype.malloc(T_PARENT.TO) parent2 = lltype.malloc(T_PARENT.TO)", "id2 != compute_unique_id(a2): error += 2 if id3 != compute_unique_id(a3):", "here and only read the table which we later on", "j += 1 b[1, j, i] = A() return 0", "0 else: cleanup = None def fix_graph_of_g(translator): from rpython.translator.translator import", "lltype.GcStruct('P', ('x', lltype.Signed)) def g(): llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder def f():", "LLInterpreter(self.rtyper) gct = db.gctransformer if self.__class__.__dict__.get('_used', False): teardowngraph = gct.frameworkgc__teardown_ptr.value._obj.graph", "from rpython.memory.gc.generation import GenerationGC as \\ GCClass GC_PARAMS = {'space_size':", "32*WORD, 'page_size': 16*WORD, 'arena_size': 64*WORD, 'small_request_threshold': 5*WORD, 'large_object': 8*WORD, 'card_page_indices':", "+ len(all) return f def test_weakref_across_minor_collection(self): run = self.runner(\"weakref_across_minor_collection\") res", "return f def test_gc_heap_stats(self): py.test.skip(\"this test makes the following test", "F() f.l = [UnboxedObject(10)] def fn(n): if n > 0:", "__del__ is not called again llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted *", "None) return f def test_finalizer_resurrects(self): run = self.runner(\"finalizer_resurrects\") res =", "return ((ptr == ptr2) + ord(ptr2.chars[0]) + (ord(ptr2.chars[1]) << 8)", "< 30: j += 1 a.append(j) return 0 return malloc_a_lot", "func def test_tagged_simple(self): func = self.runner(\"tagged_simple\") res = func([]) assert", "= lltype.malloc(S, immortal=True) def f(): s = lltype.malloc(S) s.x =", "= nf_a.address[0] nt0 = nt_a.address[0] a0 = A() a1 =", "i < x: i += 1 a = AAA() llop.gc__collect(lltype.Void)", "assert res def define_weakref_to_object_with_finalizer(cls): import weakref, gc class A(object): count", "= getattr(translator, '_jit2gc', None) if jit2gc: assert 'invoke_after_minor_collection' in jit2gc", "class BoxedObject(TaggedBase): attrvalue = 66 def __init__(self, normalint): self.normalint =", "run = self.runner(\"weakref\") res = run([]) assert res def define_weakref_to_object_with_finalizer(cls):", "= lltype.malloc(P) q.x = 1 i = 0 while i", "list. The goal is # to not allocate memory, so", "ref() is a return a.foo + len(all) return f def", "the following line generates a write_barrier call at the moment,", "self.runner(\"adr_of_nursery\") res = run([]) class TestGenerationalNoFullCollectGC(GCTest): # test that nursery", "p) p.x = r.x return p.x def f(): i =", "class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import GenerationGC class GCClass(GenerationGC): __ready =", "roots def define_string_concatenation(cls): def concat(j, dummy): lst = [] for", "f1(): t = malloc(T1) t.s.x = 1 return t.s.x S2", "= [] for i in range(j): lst.append(str(i)) result = len(\"\".join(lst))", "lltype, llmemory, rffi, llgroup from rpython.memory.gctransform import framework, shadowstack from", "where allocating the weakref itself triggers # a collection import", "__init__(self): self.lst = gl box = Box() def append_to_list(i, j):", "def f(): ptr = lltype.malloc(STR, 3) ptr.hash = 0x62 ptr.chars[0]", "* 10 j = 0 while j < 30: j", "T6 = GcStruct(\"T6\", ('s', Array(Signed))) def f6(): t = malloc(T6,", "'translated_to_c': False} root_stack_depth = 200 def define_weakref_across_minor_collection(cls): import weakref class", "+= 1 b.num_deleted_c += 1 def f(x, y): persistent_a1 =", "< x: all[i] = [i] * i i += 1", "define_ref_from_rawmalloced_to_regular(cls): import gc S = lltype.GcStruct('S', ('x', lltype.Signed)) A =", "rpython.rlib import rgc S = lltype.GcForwardReference() S.become(lltype.GcStruct('S', ('x', lltype.Signed), ('prev',", "tx = lltype.malloc(T) tx.z = 4243 s1 = lltype.malloc(S) s1.x", "test that nursery is doing its job and that no", "find_clean_setarrayitems() in # gctransformer/framework.py does not work with card marking.", "None) # check that a further collection is fine llop.gc__collect(lltype.Void)", "self.id = b.nextid b.nextid += 1 def __del__(self): b.num_deleted +=", "itself triggers # a collection import weakref class A: pass", "ll_assert from rpython.rlib import rgc from rpython.conftest import option from", "assert res == 84 def define_many_weakrefs(cls): # test for the", "l2.append(s) if i < 3: l3.append(s) l4.append(s) # We cheat", "= 0x62 ptr.chars[0] = '0' ptr.chars[1] = 'B' ptr.chars[2] =", "# crashes if constants are not considered roots def define_string_concatenation(cls):", "return func def test_id(self): run = self.runner(\"id\") res = run([])", "def f(): lst = lltype.malloc(A, 16) # 16 > 10", "taggedpointers = True def define_tagged_simple(cls): class Unrelated(object): pass u =", "self.GC_CAN_SHRINK_ARRAY: expected = 0x62024231 else: expected = 0x62024230 assert run([])", "that A() is only visible via lst[0] rgc.collect() # ->", "f(): s = lltype.malloc(S) s.x = 42 llop.bare_setfield(lltype.Void, s0, void('next'),", "<= 165 def define_custom_trace(cls): # S = lltype.GcStruct('S', ('x', llmemory.Address))", "100 + b * 10 + a return f def", "(b.a is None) return f def test_finalizer_resurrects(self): run = self.runner(\"finalizer_resurrects\")", "from rpython.rlib import objectmodel from rpython.rtyper import annlowlevel class A:", "i < 40: lst = [] j = 0 while", "y): a = AAA() i = 0 while i <", "= Box() def append_to_list(i, j): box.lst.append([i] * 50) llop.gc__collect(lltype.Void) return", "child child.field = 3 parent2.sub = child2 child2.field = 8", "def define_gettypeid(cls): class A(object): pass def fn(): a = A()", "= LLInterpreter(self.rtyper) gct = db.gctransformer if self.__class__.__dict__.get('_used', False): teardowngraph =", "pass def f(): x = 20 # for GenerationGC, enough", "'translated_to_c': False} root_stack_depth = 200 def define_ref_from_rawmalloced_to_regular(cls): import gc S", "= lltype.GcForwardReference() S.become(lltype.GcStruct('S', ('x', lltype.Signed), ('prev', lltype.Ptr(S)), ('next', lltype.Ptr(S)))) s0", "objectmodel from rpython.rtyper import annlowlevel class A: pass def fn():", "< 40: g() i += q.x return 0 def fix_graph_of_g(translator):", "ref() is a i += 1 return 0 return f", "= args[0] func = funcs0[num] if func: res = func()", "x.meth(100) def func(): return fn(1000) + fn(-1000) assert func() ==", "ages llop.gc__collect(lltype.Void) tb = rgc._heap_stats() a = 0 nr =", "= self.runner(\"collect_during_collect\") # runs collect recursively 4 times res =", "= lltype.nullptr(S) return f, cleanup, None def test_write_barrier_direct(self): run =", "0 def define_can_move(cls): TP = lltype.GcArray(lltype.Float) def func(): return rgc.can_move(lltype.malloc(TP,", "called again llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted * 10 + aid", "jit2gc return jit2gc['layoutbuilder'] marker = cls.marker GCClass = cls.gcpolicy.transformerclass.GCClass layoutbuilder", "== len(''.join([str(x) for x in range(100)])) def define_interior_ptrs(cls): from rpython.rtyper.lltypesystem.lltype", "llinterp.eval_graph(teardowngraph, []) self.__class__._used = True # FIIIIISH setupgraph = gct.frameworkgc_setup_ptr.value._obj.graph", "size_of_int = rffi.sizeof(lltype.Signed) assert (totsize - 26 * size_of_int) %", "define_weakref(cls): import weakref, gc class A(object): pass def g(): a", "from rpython.rlib.objectmodel import UnboxedValue class TaggedBase(object): __slots__ = () def", "= 0 a = A() class B(object): def __del__(self): a.count", "llinterp.eval_graph(entrygraph, [ll_args]) return res if transformer: return run, gct else:", "b.nextid b.nextid += 1 def __del__(self): llop.gc__collect(lltype.Void) b.num_deleted += 1", "s1 def f(): s1 = setup() llop.gc__collect(lltype.Void) return llmemory.cast_adr_to_ptr(s1.x, lltype.Ptr(T)).z", "def malloc_a_lot(): i = 0 while i < 10: i", "in graph.startblock.operations: if op.opname == 'do_malloc_fixedsize': op.args = [Constant(type_id, llgroup.HALFWORD),", "== 0: funcs0.append(func) funcs2.append(None) else: raise NotImplementedError( \"defined test functions", "llop, void from rpython.rlib.objectmodel import compute_unique_id, we_are_translated from rpython.rlib.debug import", "we_are_translated from rpython.rlib.debug import ll_assert from rpython.rlib import rgc from", "cls.entrygraph = entrygraph cls.rtyper = t.rtyper cls.db = db def", "self.runner(\"id\") res = run([]) assert res == 0 def define_can_move(cls):", "root_stack_depth = 200 def define_malloc_array_of_gcptr(self): S = lltype.GcStruct('S', ('x', lltype.Signed))", "== 111111 return func def test_interior_ptrs(self): run = self.runner(\"interior_ptrs\") res", "run = self.runner(\"id\") res = run([]) assert res == 0", "if self.GC_CAN_SHRINK_ARRAY: expected = 0x62024231 else: expected = 0x62024230 assert", "lltype.Signed), ('filed1', lltype.Ptr(S1)), ('filed2', lltype.Ptr(S1))) s0 = lltype.malloc(S) def f():", "following line generates a write_barrier call at the moment, #", "len(unique) return fn def test_nursery_hash_base(self): res = self.runner('nursery_hash_base') assert res([])", "+= 1 for i in range(len(tb)): if tb[i].count == 4:", "1000) res = s.build()[1000] gc.collect() return ord(res) return fn def", "lltype.nullptr(S1) and s0.filed2 == lltype.nullptr(S1)) return f def test_malloc_struct_of_gcptr(self): run", "now fix the do_malloc_fixedsize in the graph of g graph", "backend_optimizations(t) if option.view: t.viewcg() return t ARGS = lltype.FixedSizeArray(lltype.Signed, 3)", "again llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted * 10 + aid +", "1 return 0 if cls.gcname == 'incminimark': marker = cls.marker", "len(transformer.layoutbuilder.addresses_of_static_ptrs) >= 4 # NB. Remember that the number above", "run = self.runner('malloc_array_of_gcptr') res = run([]) assert res def define_malloc_struct_of_gcptr(cls):", "+ (ord(ptr2.chars[1]) << 8) + (len(ptr2.chars) << 16) + (ptr2.hash", "for bad reasons in lltype.py :-(\") run = self.runner(\"many_ids\") run([])", "llop.gc__collect(lltype.Void) result = result and (ref() is None) return result", "res == 111111 def define_id(cls): class A(object): pass a1 =", "= [A() for i in range(50)] idarray = lltype.malloc(rffi.SIGNEDP.TO, len(alist),", "a = A() nf_a = llop.gc_adr_of_nursery_free(llmemory.Address) nt_a = llop.gc_adr_of_nursery_top(llmemory.Address) nf0", "= False def define_many_ids(cls): class A(object): pass def f(): from", "0 return fn def test_writebarrier_before_copy(self): run = self.runner(\"writebarrier_before_copy\") run([]) #", "@classmethod def ensure_layoutbuilder(cls, translator): jit2gc = getattr(translator, '_jit2gc', None) if", "= funcs0[num] if func: res = func() else: func =", "1 b.num_deleted = 0 b.num_deleted_c = 0 class A(object): def", "+ persistent_a4.id # NB print would create a static root!", "assert ref() is a return a.foo + len(all) return f", "rpython.conftest import option from rpython.rlib.rstring import StringBuilder from rpython.rlib.rarithmetic import", "run([]) def define_llinterp_dict(self): class A(object): pass def malloc_a_lot(): i =", "= GcStruct(\"T6\", ('s', Array(Signed))) def f6(): t = malloc(T6, 1)", "# for GenerationGC, enough for a minor collection a =", "10: i += 1 a = (1, 2, i) b", "1 translator._jit2gc = { 'layoutbuilder': layoutbuilder, 'invoke_after_minor_collection': seeme, } return", "callback, arg): gc._trace_callback(callback, arg, obj + offset_of_x) lambda_customtrace = lambda:", "len(funcs0) if nargs == 2: funcs2.append(func) funcs0.append(None) elif nargs ==", "+= q.x return 0 def fix_graph_of_g(translator): from rpython.translator.translator import graphof", "res = func(args[1], args[2]) cleanup = cleanups[num] if cleanup: cleanup()", "= CStandaloneBuilder(t, entrypoint, config=t.config, gcpolicy=cls.gcpolicy) db = cbuild.generate_graphs_for_llinterp() entrypointptr =", "= None return f, cleanup, None def test_static_root_minor_collect(self): run =", "return 0 return malloc_a_lot def test_llinterp_tuples(self): run = self.runner(\"llinterp_tuples\") run([])", "1 a = AAA() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted return f", "= [a] * 10 j = 0 while j <", "f6(): t = malloc(T6, 1) t.s[0] = 1 return t.s[0]", "lltype.malloc(S) def f(): return (s0.filed1 == lltype.nullptr(S1) and s0.filed2 ==", "define_working_nursery(cls): def f(): total = 0 i = 0 while", "t = TranslationContext() # XXX XXX XXX mess t.config.translation.gc =", "static.p = t1 llop.gc__collect(lltype.Void) return static.p.x def cleanup(): static.p =", "[] class Box: def __init__(self): self.lst = gl box =", "import UnboxedValue class TaggedBase(object): __slots__ = () def meth(self, x):", "+= 2 if id3 != compute_unique_id(a3): error += 4 return", "def __init__(self, something): self.something = something def malloc_a_lot(): i =", "run([100, 100]) assert res == 200 def define_write_barrier_direct(cls): from rpython.rlib", "lltype.nullptr(S) lst[15] = null # clear, so that A() is", "S1)) def f1(): t = malloc(T1) t.s.x = 1 return", "run([]) == expected def define_string_builder_over_allocation(cls): import gc def fn(): s", "# we need at least 1 obj to allocate a", "= B() return weakref.ref(b) def f(): ref = g() llop.gc__collect(lltype.Void)", "rgc.collect() return x.meth(100) def func(): return fn(1000) + fn(-1000) assert", "mark \"12-15\" lst[15].x = 123 lst[0] = lst[15] # that", "self.GC_CAN_TEST_ID: py.test.skip(\"fails for bad reasons in lltype.py :-(\") run =", "__del__(self): b.num_deleted += 1 def f(x, y): a = AAA()", "self.runner(\"weakref\") res = run([]) assert res def define_weakref_to_object_with_finalizer(cls): import weakref,", "from rpython.annotator import model as annmodel from rpython.rtyper.llannotation import SomePtr", "tested elsewhere too\") run = self.runner(\"global_list\") res = run([0, 0])", "a0 = A() a1 = A() nf1 = nf_a.address[0] nt1", "GCClass) layoutbuilder.delay_encoding() def seeme(): marker[0] += 1 translator._jit2gc = {", "res = run([]) assert res == 42 class TestMiniMarkGC(TestHybridGC): gcname", "lltype.GcStruct('S', ('x', lltype.Signed)) A = lltype.GcArray(lltype.Ptr(S)) def sub(lst): lst[15] =", "but the number of locations # within prebuilt GC objects", "fullname) _, name = fullname.split('_', 1) func_fixup = definefunc.im_func(cls) cleanup", "lltype.cast_opaque_ptr(lltype.Ptr(P), p) p.x = r.x return p.x def f(): i", "collection is fine llop.gc__collect(lltype.Void) result = result and (ref() is", "def test_many_weakrefs(self): run = self.runner(\"many_weakrefs\") run([]) def define_immutable_to_old_promotion(cls): T_CHILD =", "i += 1 a = [1] * 10 j =", "i = 0 while i < 40: lst = []", "x): return self.normalint + x + 2 class UnboxedObject(TaggedBase, UnboxedValue):", "x: all[i] = [i] * i i += 1 assert", "'smallint' def meth(self, x): return self.smallint + x + 3", "!= compute_unique_id(a2): error += 2 if id3 != compute_unique_id(a3): error", "run = self.runner(\"llinterp_dict\") run([]) def skipdefine_global_list(cls): gl = [] class", "+ ord(ptr2.chars[0]) + (ord(ptr2.chars[1]) << 8) + (len(ptr2.chars) << 16)", "for i in range(len(objects)): assert compute_identity_hash(objects[i]) == hashes[i] unique[hashes[i]] =", "tb[i].count == 4: b += 1 c += tb[i].links[nr] e", "12 def define_finalizer_resurrects(cls): class B(object): pass b = B() b.nextid", "return result return f def test_weakref_to_object_with_finalizer(self): run = self.runner(\"weakref_to_object_with_finalizer\") res", "('p', lltype.Ptr(T1))) static = lltype.malloc(T2, immortal=True) def f(): t1 =", "while j < 20: j += 1 b.append((1, j, i))", "root! llop.debug_print(lltype.Void, b.num_deleted_c) return b.num_deleted return f def test_collect_during_collect(self): run", "weakref, gc class A(object): pass def g(): a = A()", "l2 = [] l3 = [] l4 = [] def", "res = run([]) assert res == 84 def define_static_root_minor_collect(cls): class", "= AAA() i = 0 while i < x: i", "1: # allocate some stuff between the two iterations [A()", "case where allocating the weakref itself triggers # a collection", "crash return lst[0].x return f def test_no_clean_setarrayitems(self): run = self.runner(\"no_clean_setarrayitems\")", "important because the 'lst' can be allocated directly # in", "persistent_a3 = A() persistent_a4 = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) b.bla =", "1) t[0].x = 1 return t[0].x S3 = Struct(\"S3\", ('x',", "class A(object): pass def fn(): a = A() return rgc.get_typeid(a)", "= lltype.GcStruct('S', ('x', lltype.Signed), ('filed1', lltype.Ptr(S1)), ('filed2', lltype.Ptr(S1))) s0 =", "\"oups, not found\" return f, None, fix_graph_of_g def test_do_malloc_operations_in_call(self): run", "persistent_a3.id + persistent_a4.id # NB print would create a static", "else: x = UnboxedObject(n) f.l.append(x) rgc.collect() return f.l[-1].meth(100) def func():", "gcname = \"hybrid\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import", "return f, cleanup, None def test_nongc_static_root(self): run = self.runner(\"nongc_static_root\") res", "f4() * 100 + f5() * 10 + f6()) assert", "objects die quickly gcname = \"generation\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer):", "check that a prebuilt tagged pointer doesn't explode if n", "rpython.rtyper.lltypesystem.rstr import STR def f(): ptr = lltype.malloc(STR, 3) ptr.hash", "tagged pointers class TaggedPointerGCTests(GCTest): taggedpointers = True def define_tagged_simple(cls): class", "class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.hybrid import HybridGC as GCClass", "def test_id(self): run = self.runner(\"id\") res = run([]) assert res", "if self.__class__.__dict__.get('_used', False): teardowngraph = gct.frameworkgc__teardown_ptr.value._obj.graph llinterp.eval_graph(teardowngraph, []) self.__class__._used =", "True def semispace_collect(self, size_changing=False): ll_assert(not self.__ready, \"no full collect should", "('x', Signed)) T5 = GcStruct(\"T5\", ('items', Array(S5))) def f5(): t", "def f5(): t = malloc(T5, 1) return len(t.items) T6 =", "+= 1 def __del__(self): b.num_deleted += 1 C() class C(AAA):", "gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.hybrid import HybridGC as GCClass GC_PARAMS", "def test_nursery_hash_base(self): res = self.runner('nursery_hash_base') assert res([]) >= 195 def", "t.rtyper cls.db = db def runner(self, name, transformer=False): db =", "read the table which we later on # process ourselves,", "GC_CAN_MOVE = False taggedpointers = False def setup_class(cls): cls.marker =", "i) b = [a] * 10 j = 0 while", "self.runner(\"weakref_across_minor_collection\") res = run([]) assert res == 20 + 20", "i < 40: g() i += 1 return 0 if", "nonmovable=True) a.next = a1 # 'a' is known young here,", "runtime # allocated stuff cleanups.append(cleanup) def entrypoint(args): num = args[0]", "run = self.runner(\"finalizer_resurrects\") res = run([5, 42]) #XXX pure lazyness", "return f def test_finalizer_calls_malloc(self): run = self.runner(\"finalizer_calls_malloc\") res = run([5,", "class Box: def __init__(self): self.lst = gl box = Box()", "in range(100)])) def define_nongc_static_root(cls): T1 = lltype.GcStruct(\"C\", ('x', lltype.Signed)) T2", "line generates a write_barrier call at the moment, # which", "def define_do_malloc_operations(cls): P = lltype.GcStruct('P', ('x', lltype.Signed)) def g(): r", "[UnboxedObject(10)] def fn(n): if n > 0: x = BoxedObject(n)", "cleanup = None def fix_graph_of_g(translator): from rpython.translator.translator import graphof from", "from rpython.rlib.objectmodel import compute_hash, compute_identity_hash from rpython.translator.c import gc from", "= B() b.nextid = 0 b.num_deleted = 0 class AAA(object):", "30: b = B(somea) b.last = first j += 1", "if isinstance(func_fixup, tuple): func, cleanup, fixup = func_fixup mixlevelstuff.append(fixup) else:", "def test_shrink_array(self): run = self.runner(\"shrink_array\") if self.GC_CAN_SHRINK_ARRAY: expected = 0x62024231", "range(10): s = lltype.malloc(S) l1.append(s) l2.append(s) if i < 3:", "GCClass GC_PARAMS = {'space_size': 512*WORD, 'nursery_size': 32*WORD, 'translated_to_c': False} root_stack_depth", "1) func_fixup = definefunc.im_func(cls) cleanup = None if isinstance(func_fixup, tuple):", "lltype.Signed)) S = lltype.GcStruct('S', ('x', lltype.Signed), ('filed1', lltype.Ptr(S1)), ('filed2', lltype.Ptr(S1)))", "0 d = 0 e = 0 for i in", "fn = self.runner(\"string_builder_over_allocation\") res = fn([]) assert res == ord('y')", "= 20 all = [None] * x i = 0", "Struct, GcStruct, GcArray from rpython.rtyper.lltypesystem.lltype import Array, Signed, malloc S1", "= lltype.malloc(STR, 3) ptr.hash = 0x62 ptr.chars[0] = '0' ptr.chars[1]", "# within prebuilt GC objects that are of type Ptr(Gc).", "else: raise NotImplementedError( \"defined test functions should have 0/2 arguments\")", "test_finalizer(self): run = self.runner(\"finalizer\") res = run([5, 42]) #XXX pure", "= False def setup_class(cls): cls.marker = lltype.malloc(rffi.CArray(lltype.Signed), 1, flavor='raw', zero=True)", "def test_string_concatenation(self): run = self.runner(\"string_concatenation\") res = run([100, 0]) assert", "q.x return 0 def fix_graph_of_g(translator): from rpython.translator.translator import graphof from", "l4 = [] def f(): for i in range(10): s", "import StringBuilder from rpython.rlib.rarithmetic import LONG_BIT WORD = LONG_BIT //", "return static.p.x def cleanup(): static.p = lltype.nullptr(T1) return f, cleanup,", "= A() return 0 return malloc_a_lot def test_llinterp_dict(self): run =", "= self.runner(\"writebarrier_before_copy\") run([]) # ________________________________________________________________ class TestSemiSpaceGC(GenericMovingGCTests): gcname = \"semispace\"", "assert (totsize - 26 * size_of_int) % 4 == 0", "static.p.x + i def cleanup(): static.p = lltype.nullptr(T1) return f,", "from rpython.memory.gc.generation import GenerationGC GenerationGC.setup(self) self.__ready = True def semispace_collect(self,", "3 parent2.sub = child2 child2.field = 8 T_ALL = lltype.Ptr(lltype.GcArray(T_PARENT))", "195 def define_instantiate_nonmovable(cls): from rpython.rlib import objectmodel from rpython.rtyper import", "40: lst = [] j = 0 while j <", "cbuild = CStandaloneBuilder(t, entrypoint, config=t.config, gcpolicy=cls.gcpolicy) db = cbuild.generate_graphs_for_llinterp() entrypointptr", "res == 42 def define_finalizer(cls): class B(object): pass b =", "fixup = func_fixup mixlevelstuff.append(fixup) else: func = func_fixup func.func_name =", "= [] funcs2 = [] cleanups = [] name_to_func =", "= cls.marker GCClass = cls.gcpolicy.transformerclass.GCClass layoutbuilder = framework.TransformerLayoutBuilder(translator, GCClass) layoutbuilder.delay_encoding()", "x + 3 class TestHybridTaggedPointerGC(TaggedPointerGCTests): gcname = \"hybrid\" class gcpolicy(gc.BasicFrameworkGcPolicy):", "res == 40 * 5 class TestHybridGC(TestGenerationGC): gcname = \"hybrid\"", "= x ref = weakref.ref(a) all = [None] * x", "return b.num_deleted return f def test_finalizer(self): run = self.runner(\"finalizer\") res", "normalint def meth(self, x): return self.normalint + x + 2", "GcStruct(\"T5\", ('items', Array(S5))) def f5(): t = malloc(T5, 1) return", "= 3 parent2.sub = child2 child2.field = 8 T_ALL =", "= run([]) assert res % 10000 == 2611 totsize =", "# in generation 2. This can only occur with varsized", "root_stack_depth = 200 def define_weakref_across_minor_collection(cls): import weakref class A: pass", "def test_write_barrier_direct(self): run = self.runner(\"write_barrier_direct\") res = run([]) assert res", "= A() ref = weakref.ref(a) result = ref() is a", "lltype.Bool), # has_finalizer Constant(False, lltype.Bool), # is_finalizer_light Constant(False, lltype.Bool)] #", "= cls.gcpolicy.transformerclass.GCClass layoutbuilder = framework.TransformerLayoutBuilder(translator, GCClass) layoutbuilder.delay_encoding() def seeme(): marker[0]", "assert res == 40 * 5 class TestHybridGC(TestGenerationGC): gcname =", "run = self.runner(\"nongc_static_root_minor_collect\") res = run([]) assert res == 84", "IncrementalMiniMarkGC \\ as GCClass GC_PARAMS = {'nursery_size': 32*WORD, 'page_size': 16*WORD,", "test_weakref_to_object_with_finalizer(self): run = self.runner(\"weakref_to_object_with_finalizer\") res = run([]) assert res def", "BoxedObject(n) else: x = UnboxedObject(n) u.x = x # invoke", "UnboxedObject(TaggedBase, UnboxedValue): __slots__ = 'smallint' def meth(self, x): return self.smallint", "i = 0 while i < x: all[i] = [i]", "1, flavor='raw', zero=True) funcs0 = [] funcs2 = [] cleanups", "f, cleanup, None def test_static_root_minor_collect(self): run = self.runner(\"static_root_minor_collect\") res =", "__del__(self): b.num_deleted += 1 C() class C(AAA): def __del__(self): b.num_deleted", "definefunc = getattr(cls, fullname) _, name = fullname.split('_', 1) func_fixup", "allocate memory, so that if the GC needs memory to", "of all the elements of the list. The goal is", "#XXX pure lazyness here too assert res == 6 def", "4 # (and give fixedsize) def define_writebarrier_before_copy(cls): S = lltype.GcStruct('S',", "i - 1 # crashes if constants are not considered", "t.buildannotator() ann.build_types(func, inputtypes) if specialize: t.buildrtyper().specialize() if backendopt: from rpython.translator.backendopt.all", "def f(): a = A() i = 0 while i", "bad reasons in lltype.py :-(\") run = self.runner(\"many_ids\") run([]) @classmethod", "NotImplementedError( \"defined test functions should have 0/2 arguments\") # used", "def define_working_nursery(cls): def f(): total = 0 i = 0", "define_custom_trace(cls): # S = lltype.GcStruct('S', ('x', llmemory.Address)) T = lltype.GcStruct('T',", "# check that __del__ is not called again llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void)", "for i in range(50): assert l2[i] == l[50 + i]", "def fn(): s = StringBuilder(4) s.append(\"abcd\") s.append(\"defg\") s.append(\"rty\") s.append_multiple_char('y', 1000)", "# check that a prebuilt tagged pointer doesn't explode if", "return 0 return f def test_many_ids(self): if not self.GC_CAN_TEST_ID: py.test.skip(\"fails", "num = args[0] func = funcs0[num] if func: res =", "= t.buildannotator() ann.build_types(func, inputtypes) if specialize: t.buildrtyper().specialize() if backendopt: from", "False} root_stack_depth = 200 def test_gettypeid(self): py.test.skip(\"fails for obscure reasons\")", "(ref() is None) return result return f def test_weakref(self): run", "allocated directly # in generation 2. This can only occur", "< len(alist): assert idarray[i] == compute_unique_id(alist[i]) i += 1 j", "# FIIIIISH setupgraph = gct.frameworkgc_setup_ptr.value._obj.graph # setup => resets the", "a write_barrier call at the moment, # which is important", "= lltype.malloc(ARGS, immortal=True) ll_args[0] = name_to_func[name] for i in range(len(args)):", "= 0 class A(object): def __init__(self): self.id = b.nextid b.nextid", "l3.append(s) l4.append(s) # We cheat here and only read the", "return f def test_finalizer(self): run = self.runner(\"finalizer\") res = run([5,", "< 10: i += 1 a = (1, 2, i)", "GcStruct(\"T6\", ('s', Array(Signed))) def f6(): t = malloc(T6, 1) t.s[0]", "< 10: i += 1 a = somea = A()", "meth(self, x): return self.normalint + x + 2 class UnboxedObject(TaggedBase,", "def test_llinterp_tuples(self): run = self.runner(\"llinterp_tuples\") run([]) def define_llinterp_dict(self): class A(object):", "fn(-1000) assert func() == -1999 return func def test_tagged_prebuilt(self): func", "aid = b.a.id b.a = None # check that __del__", "expected def define_string_builder_over_allocation(cls): import gc def fn(): s = StringBuilder(4)", "lltype.free(idarray, flavor='raw') return 0 return f def test_many_ids(self): if not", "j += 1 return 0 return malloc_a_lot def test_instances(self): run", "= malloc(U4, 1) u[0].s.x = 1 return u[0].s.x S5 =", "lst[0].x return f def test_no_clean_setarrayitems(self): run = self.runner(\"no_clean_setarrayitems\") res =", "50) llop.gc__collect(lltype.Void) return box.lst[j][0] return append_to_list, None, None def test_global_list(self):", "j, i)) return 0 return malloc_a_lot def test_llinterp_tuples(self): run =", "aid + 100 * (b.a is None) return f def", "+= 1 total += len(lst) i += 1 return total", "f(): t1 = B() t1.x = 42 static.p = t1", "= A() a = objectmodel.instantiate(A, nonmovable=True) a.next = a1 #", "range(100): l[i] = lltype.malloc(S) rgc.ll_arraycopy(l, l2, 50, 0, 50) #", "'card_page_indices': 4, 'translated_to_c': False, } root_stack_depth = 200 def define_no_clean_setarrayitems(cls):", "[] name_to_func = {} mixlevelstuff = [] for fullname in", "for i in range(1, 5): res = run([i, i -", "def func(): a2 = A() a3 = A() id1 =", "'translated_to_c': False} root_stack_depth = 200 class TestGenerationGC(GenericMovingGCTests): gcname = \"generation\"", "= [] class Box: def __init__(self): self.lst = gl box", "name_to_func cls.entrygraph = entrygraph cls.rtyper = t.rtyper cls.db = db", "rpython.rtyper.lltypesystem import lltype, llmemory, rffi, llgroup from rpython.memory.gctransform import framework,", "True # FIIIIISH setupgraph = gct.frameworkgc_setup_ptr.value._obj.graph # setup => resets", "the gc llinterp.eval_graph(setupgraph, []) def run(args): ll_args = lltype.malloc(ARGS, immortal=True)", "1 i = static.p.x llop.gc__collect(lltype.Void) return static.p.x + i def", "is expected GenerationGC._teardown(self) GC_PARAMS = {'space_size': 512*WORD, 'nursery_size': 128*WORD, 'translated_to_c':", "None while i < 10: i += 1 a =", "+ i] return 0 return fn def test_writebarrier_before_copy(self): run =", "= nf_a.address[0] nt1 = nt_a.address[0] assert nf1 > nf0 assert", "lst[15] = null # clear, so that A() is only", "define_instantiate_nonmovable(cls): from rpython.rlib import objectmodel from rpython.rtyper import annlowlevel class", "res = llinterp.eval_graph(entrygraph, [ll_args]) return res if transformer: return run,", "def define_many_ids(cls): class A(object): pass def f(): from rpython.rtyper.lltypesystem import", "rffi alist = [A() for i in range(50)] idarray =", "= run([]) assert res == 123 def define_nursery_hash_base(cls): class A:", "from rpython.rtyper.lltypesystem import rffi alist = [A() for i in", "return append_to_list, None, None def test_global_list(self): py.test.skip(\"doesn't fit in the", "= self.runner(\"ref_from_rawmalloced_to_regular\") res = run([100, 100]) assert res == 200", "layoutbuilder.get_type_id(P) # # now fix the do_malloc_fixedsize in the graph", "weakref.ref(a) result = ref() is a ref = g() llop.gc__collect(lltype.Void)", "stuff between the two iterations [A() for i in range(20)]", "all[0] # * all[1] # * parent.sub # * parent2.sub", "setup(): rgc.register_custom_trace_hook(S, lambda_customtrace) tx = lltype.malloc(T) tx.z = 4243 s1", "= [] for fullname in dir(cls): if not fullname.startswith('define'): continue", "lltype.nullptr(S) and lst[3] == lltype.nullptr(S) and lst[4] == lltype.nullptr(S)) return", "{'space_size': 512*WORD, 'nursery_size': 32*WORD, 'translated_to_c': False} root_stack_depth = 200 def", "return f def test_shrink_array(self): run = self.runner(\"shrink_array\") if self.GC_CAN_SHRINK_ARRAY: expected", "root_stack_depth = 200 def define_no_clean_setarrayitems(cls): # The optimization find_clean_setarrayitems() in", "* (b.a is None) return f def test_finalizer_resurrects(self): run =", "too assert res == 6 def define_finalizer_calls_malloc(cls): class B(object): pass", "option.view: t.viewcg() return t ARGS = lltype.FixedSizeArray(lltype.Signed, 3) class GCTest(object):", "t.items[0].x = 1 return t.items[0].x S4 = Struct(\"S4\", ('x', Signed))", "force nursery collect x = [] for i in range(20):", "t1 x = 20 all = [None] * x i", "occur with varsized mallocs. lst.p = p return lst def", "is not called again llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted * 10", "elsewhere too\") run = self.runner(\"global_list\") res = run([0, 0]) assert", "class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import GenerationGC class GCClass(GenerationGC):", "optimization find_clean_setarrayitems() in # gctransformer/framework.py does not work with card", "test_no_clean_setarrayitems(self): run = self.runner(\"no_clean_setarrayitems\") res = run([]) assert res ==", "* the GcArray pointer from gc.object_id_dict. def define_adr_of_nursery(cls): class A(object):", "annlowlevel class A: pass def fn(): a1 = A() a", "* 10 + a return f def test_gc_heap_stats(self): py.test.skip(\"this test", "nargs == 2: funcs2.append(func) funcs0.append(None) elif nargs == 0: funcs0.append(func)", "a = AAA() i = 0 while i < x:", "total += len(lst) i += 1 return total return f", "so that A() is only visible via lst[0] rgc.collect() #", "entrypointptr._obj.graph if option.view: t.viewcg() cls.name_to_func = name_to_func cls.entrygraph = entrygraph", "GcStruct(\"T3\", ('items', Array(S3))) def f3(): t = malloc(T3, 1) t.items[0].x", "return concat def test_collect_0(self): run = self.runner(\"collect_0\") res = run([100,", "def f(): t1 = B() t1.x = 42 static.p =", "('x', lltype.Signed)) l1 = [] l2 = [] l3 =", "class A: pass def f(): x = 20 # for", "flavor='raw') return 0 return f def test_many_ids(self): if not self.GC_CAN_TEST_ID:", "s0 = lltype.malloc(S, immortal=True) def f(): s = lltype.malloc(S) s.x", "res = run([0, 0]) assert res == 0 for i", "that nursery is doing its job and that no full", "[Constant(type_id, llgroup.HALFWORD), Constant(llmemory.sizeof(P), lltype.Signed), Constant(False, lltype.Bool), # has_finalizer Constant(False, lltype.Bool),", "return malloc_a_lot def test_llinterp_tuples(self): run = self.runner(\"llinterp_tuples\") run([]) def define_llinterp_dict(self):", "def test_llinterp_lists(self): run = self.runner(\"llinterp_lists\") run([]) def define_llinterp_tuples(cls): def malloc_a_lot():", "= malloc(T5, 1) return len(t.items) T6 = GcStruct(\"T6\", ('s', Array(Signed)))", "define_llinterp_tuples(cls): def malloc_a_lot(): i = 0 while i < 10:", "rpython.rlib.objectmodel import UnboxedValue class TaggedBase(object): __slots__ = () def meth(self,", "200 def define_no_clean_setarrayitems(cls): # The optimization find_clean_setarrayitems() in # gctransformer/framework.py", "i += 1 i = static.p.x llop.gc__collect(lltype.Void) return static.p.x +", "== 0 def define_can_move(cls): TP = lltype.GcArray(lltype.Float) def func(): return", "def define_llinterp_tuples(cls): def malloc_a_lot(): i = 0 while i <", "1 C() class C(AAA): def __del__(self): b.num_deleted += 1 def", "64*WORD, 'small_request_threshold': 5*WORD, 'large_object': 8*WORD, 'card_page_indices': 4, 'translated_to_c': False, }", "% 4 == 0 # ^^^ a crude assumption that", "+= tb[i].size return d * 1000 + c * 100", "s_args = SomePtr(lltype.Ptr(ARGS)) t = rtype(entrypoint, [s_args], gcname=cls.gcname, taggedpointers=cls.taggedpointers) for", "# 'a' is known young here, so no write barrier", "lltype.py :-(\") run = self.runner(\"many_ids\") run([]) @classmethod def ensure_layoutbuilder(cls, translator):", "+= len(lst) i += 1 return total return f def", "concat def test_string_concatenation(self): run = self.runner(\"string_concatenation\") res = run([100, 0])", "when most allocated objects die quickly gcname = \"generation\" class", "# # now fix the do_malloc_fixedsize in the graph of", "malloc_a_lot def test_llinterp_lists(self): run = self.runner(\"llinterp_lists\") run([]) def define_llinterp_tuples(cls): def", "self.runner(\"working_nursery\") res = run([]) assert res == 40 * 5", "return lst def f(i, j): lst = setup(j) gc.collect() return", "+ i def cleanup(): static.p = lltype.nullptr(T1) return f, cleanup,", "= 0 b.num_deleted = 0 class AAA(object): def __init__(self): self.id", "lltype.Ptr(S)), ('a', lltype.Array(lltype.Char))) def setup(j): p = lltype.malloc(S) p.x =", "= self.runner(\"adr_of_nursery\") res = run([]) class TestGenerationalNoFullCollectGC(GCTest): # test that", "\"generation\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import GenerationGC class", "(s0.filed1 == lltype.nullptr(S1) and s0.filed2 == lltype.nullptr(S1)) return f def", "+= 1 translator._jit2gc = { 'layoutbuilder': layoutbuilder, 'invoke_after_minor_collection': seeme, }", "j < 30: b = B(somea) b.last = first j", "f(): i = 0 while i < 40: g() i", "i += 1 a = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted", "50) # force nursery collect x = [] for i", "seeme, } return layoutbuilder def define_do_malloc_operations(cls): P = lltype.GcStruct('P', ('x',", "self.id = b.nextid b.nextid += 1 def __del__(self): llop.gc__collect(lltype.Void) b.num_deleted", "== 0 for i in range(1, 5): res = run([i,", "'layoutbuilder': layoutbuilder, 'invoke_after_minor_collection': seeme, } return layoutbuilder def define_do_malloc_operations(cls): P", "py.test.skip(\"this test makes the following test crash. Investigate.\") run =", "0 while j < 20: j += 1 b.append((1, j,", "= llop.gc_adr_of_nursery_free(llmemory.Address) nt_a = llop.gc_adr_of_nursery_top(llmemory.Address) nf0 = nf_a.address[0] nt0 =", "continue definefunc = getattr(cls, fullname) _, name = fullname.split('_', 1)", "return fn(1000) ^ fn(-1000) assert func() == -1999 return func", "fn def test_instantiate_nonmovable(self): res = self.runner('instantiate_nonmovable') assert res([]) == 0", "= self.runner(\"nongc_static_root_minor_collect\") res = run([]) assert res == 84 def", "s.append(\"defg\") s.append(\"rty\") s.append_multiple_char('y', 1000) gc.collect() s.append_multiple_char('y', 1000) res = s.build()[1000]", "rpython.rtyper import annlowlevel class A: pass def fn(): a1 =", "self.lst = gl box = Box() def append_to_list(i, j): box.lst.append([i]", "have 0/2 arguments\") # used to let test cleanup static", "def test_gc_heap_stats(self): py.test.skip(\"this test makes the following test crash. Investigate.\")", "llop.gc__collect(lltype.Void) return b.num_deleted * 10 + aid + 100 *", "We cheat here and only read the table which we", "= A() a1 = A() nf1 = nf_a.address[0] nt1 =", "'nursery_size': 32*WORD, 'large_object': 8*WORD, 'translated_to_c': False} root_stack_depth = 200 def", "i += 1 assert ref() is a llop.gc__collect(lltype.Void) assert ref()", "{} mixlevelstuff = [] for fullname in dir(cls): if not", "return f def test_ref_from_rawmalloced_to_regular(self): run = self.runner(\"ref_from_rawmalloced_to_regular\") res = run([100,", "} root_stack_depth = 200 def define_no_clean_setarrayitems(cls): # The optimization find_clean_setarrayitems()", "a1 = A() nf1 = nf_a.address[0] nt1 = nt_a.address[0] assert", "def test_nongc_static_root_minor_collect(self): run = self.runner(\"nongc_static_root_minor_collect\") res = run([]) assert res", "< x: i += 1 a = AAA() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void)", "llop.gc__collect(lltype.Void) return b.num_deleted return f def test_finalizer(self): run = self.runner(\"finalizer\")", "TP = lltype.GcArray(lltype.Ptr(S)) def fn(): l = lltype.malloc(TP, 100) l2", "i def cleanup(): static.p = lltype.nullptr(T1) return f, cleanup, None", "for i in range(j): lst.append(str(i)) return len(\"\".join(lst)) return concat def", "0 if id1 != compute_unique_id(a1): error += 1 if id2", "= False def setup(self): from rpython.memory.gc.generation import GenerationGC GenerationGC.setup(self) self.__ready", "= lltype.malloc(T_ALL.TO, 2) all[0] = parent all[1] = parent2 def", "call at the moment, # which is important because the", "if option.view: t.viewcg() cls.name_to_func = name_to_func cls.entrygraph = entrygraph cls.rtyper", "entrygraph = self.entrygraph from rpython.rtyper.llinterp import LLInterpreter llinterp = LLInterpreter(self.rtyper)", "= self.runner(\"tagged_prebuilt\") res = func([]) assert res == -1999 def", "self.runner(\"write_barrier_direct\") res = run([]) assert res == 42 class TestMiniMarkGC(TestHybridGC):", "run([i, i - 1]) assert res == i - 1", "assert res == 4243 def define_weakref(cls): import weakref, gc class", "class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import GenerationGC as \\", "pure lazyness here too assert res == 12 def define_collect_0(cls):", "# now fix the do_malloc_fixedsize in the graph of g", "transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import GenerationGC as \\ GCClass GC_PARAMS =", "func def test_tagged_prebuilt(self): func = self.runner(\"tagged_prebuilt\") res = func([]) assert", "g() llop.gc__collect(lltype.Void) result = result and (ref() is None) #", "GCClass = cls.gcpolicy.transformerclass.GCClass layoutbuilder = framework.TransformerLayoutBuilder(translator, GCClass) layoutbuilder.delay_encoding() def seeme():", "= run([]) assert res def define_malloc_struct_of_gcptr(cls): S1 = lltype.GcStruct('S', ('x',", "= b.a.id b.a = None # check that __del__ is", "tb[i].size return d * 1000 + c * 100 +", "i < len(alist): assert idarray[i] == compute_unique_id(alist[i]) i += 1", "def f(): x = 20 # for GenerationGC, enough for", "range(200): rgc.collect(0) # nursery-only collection, if possible obj = A()", "for i in range(50)] idarray = lltype.malloc(rffi.SIGNEDP.TO, len(alist), flavor='raw') #", "run(args): ll_args = lltype.malloc(ARGS, immortal=True) ll_args[0] = name_to_func[name] for i", "break else: assert 0, \"oups, not found\" return f, cleanup,", "assert ref() is a llop.gc__collect(lltype.Void) assert ref() is a return", "annmodel from rpython.rtyper.llannotation import SomePtr from rpython.rtyper.lltypesystem import lltype, llmemory,", "meth(self, x): raise NotImplementedError class BoxedObject(TaggedBase): attrvalue = 66 def", "# nursery-only collection, if possible obj = A() objects.append(obj) hashes.append(compute_identity_hash(obj))", "u = malloc(U4, 1) u[0].s.x = 1 return u[0].s.x S5", "lltype.malloc(T_PARENT.TO) parent.sub = child child.field = 3 parent2.sub = child2", "fix_graph_of_g(translator): from rpython.translator.translator import graphof from rpython.flowspace.model import Constant from", "= funcs2[num] res = func(args[1], args[2]) cleanup = cleanups[num] if", "[] for i in range(j): lst.append(str(i)) return len(\"\".join(lst)) return concat", "nursery-only collection, if possible obj = A() objects.append(obj) hashes.append(compute_identity_hash(obj)) unique", "1 nr = i if tb[i].count > 50: d +=", "= lltype.malloc(T_CHILD.TO) parent = lltype.malloc(T_PARENT.TO) parent2 = lltype.malloc(T_PARENT.TO) parent.sub =", "0 b = 0 c = 0 d = 0", "1000 + c * 100 + b * 10 +", "cls.name_to_func = name_to_func cls.entrygraph = entrygraph cls.rtyper = t.rtyper cls.db", "rpython.rlib import rgc from rpython.conftest import option from rpython.rlib.rstring import", "1) t.items[0].x = 1 return t.items[0].x S4 = Struct(\"S4\", ('x',", "f.l[-1].meth(100) def func(): return fn(1000) ^ fn(-1000) assert func() ==", "run([]) def skipdefine_global_list(cls): gl = [] class Box: def __init__(self):", "which is important because the 'lst' can be allocated directly", "single mark \"12-15\" lst[15].x = 123 lst[0] = lst[15] #", "minor collection a = A() a.foo = x ref =", "0 while i < len(alist): idarray[i] = compute_unique_id(alist[i]) i +=", "pure lazyness here too assert res == 12 def define_finalizer_resurrects(cls):", "return 0 return malloc_a_lot def test_llinterp_lists(self): run = self.runner(\"llinterp_lists\") run([])", "i if tb[i].count > 50: d += 1 for i", "config=t.config, gcpolicy=cls.gcpolicy) db = cbuild.generate_graphs_for_llinterp() entrypointptr = cbuild.getentrypointptr() entrygraph =", "# allocate some stuff between the two iterations [A() for", "= lltype.malloc(S) l1.append(s) l2.append(s) if i < 3: l3.append(s) l4.append(s)", "is set the single mark \"12-15\" lst[15].x = 123 lst[0]", "f(): x = 20 # for GenerationGC, enough for a", "i in range(len(args)): ll_args[1+i] = args[i] res = llinterp.eval_graph(entrygraph, [ll_args])", "GenerationGC GenerationGC.setup(self) self.__ready = True def semispace_collect(self, size_changing=False): ll_assert(not self.__ready,", "return concat def test_string_concatenation(self): run = self.runner(\"string_concatenation\") res = run([100,", "def test_interior_ptrs(self): run = self.runner(\"interior_ptrs\") res = run([]) assert res", "FIIIIISH setupgraph = gct.frameworkgc_setup_ptr.value._obj.graph # setup => resets the gc", "lltype.malloc(T_CHILD.TO) parent = lltype.malloc(T_PARENT.TO) parent2 = lltype.malloc(T_PARENT.TO) parent.sub = child", "would be a \"clean_setarrayitem\" def f(): lst = lltype.malloc(A, 16)", "\"clean_setarrayitem\" def f(): lst = lltype.malloc(A, 16) # 16 >", "from gc.object_id_dict. def define_adr_of_nursery(cls): class A(object): pass def f(): #", "[A() for i in range(20)] i = 0 while i", "return fn def test_writebarrier_before_copy(self): run = self.runner(\"writebarrier_before_copy\") run([]) # ________________________________________________________________", "res = run([]) assert res == 40 * 5 class", "fn(n): rgc.collect() # check that a prebuilt tagged pointer doesn't", "if id1 != compute_unique_id(a1): error += 1 if id2 !=", "= lltype.GcArray(lltype.Ptr(S)) def fn(): l = lltype.malloc(TP, 100) l2 =", "f(x, y): res = all[x] #all[x] = lltype.nullptr(T_PARENT.TO) return res.sub.field", "a static root! llop.debug_print(lltype.Void, b.num_deleted_c) return b.num_deleted return f def", "165 def define_custom_trace(cls): # S = lltype.GcStruct('S', ('x', llmemory.Address)) T", "42 class TestMiniMarkGC(TestHybridGC): gcname = \"minimark\" GC_CAN_TEST_ID = True class", "run = self.runner(\"nongc_static_root\") res = run([]) assert res == 42", "return static.p.x + i def cleanup(): static.p = lltype.nullptr(T1) return", "in range(j): lst.append(str(i)) return len(\"\".join(lst)) return concat def test_string_concatenation(self): run", "test_string_concatenation(self): run = self.runner(\"string_concatenation\") res = run([100, 0]) assert res", "of the list. The goal is # to not allocate", "= B() t1.x = 42 static.p = t1 x =", "nt1 = nt_a.address[0] assert nf1 > nf0 assert nt1 >", "placeholder p = lltype.cast_opaque_ptr(lltype.Ptr(P), p) p.x = r.x return p.x", "BoxedObject(n) else: x = UnboxedObject(n) f.l.append(x) rgc.collect() return f.l[-1].meth(100) def", "+ f2() * 10000 + f3() * 1000 + f4()", "< len(alist): idarray[i] = compute_unique_id(alist[i]) i += 1 j =", "llmemory.cast_ptr_to_adr(s0)) rgc.collect(0) return s0.next.x def cleanup(): s0.next = lltype.nullptr(S) return", "= lltype.malloc(T2, immortal=True) def f(): t1 = lltype.malloc(T1) t1.x =", "y): a = A() i = 0 while i <", "s1 = setup() llop.gc__collect(lltype.Void) return llmemory.cast_adr_to_ptr(s1.x, lltype.Ptr(T)).z return f def", "transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.hybrid import HybridGC as GCClass GC_PARAMS = {'space_size':", "name_to_func = {} mixlevelstuff = [] for fullname in dir(cls):", "cls.gcpolicy.transformerclass.GCClass layoutbuilder = framework.TransformerLayoutBuilder(translator, GCClass) layoutbuilder.delay_encoding() def seeme(): marker[0] +=", "def cleanup(): static.p = None return f, cleanup, None def", "return llmemory.cast_adr_to_ptr(s1.x, lltype.Ptr(T)).z return f def test_custom_trace(self): run = self.runner(\"custom_trace\")", "= 0 if id1 != compute_unique_id(a1): error += 1 if", "**extraconfigopts): from rpython.translator.translator import TranslationContext t = TranslationContext() # XXX", "transformer = self.runner(\"immutable_to_old_promotion\", transformer=True) run([1, 4]) if not transformer.GCClass.prebuilt_gc_objects_are_static_roots: assert", "> nf0 assert nt1 > nf1 assert nt1 == nt0", "args[0] func = funcs0[num] if func: res = func() else:", "cleanup: cleanup() return res from rpython.translator.c.genc import CStandaloneBuilder s_args =", "self.runner(\"static_root_minor_collect\") res = run([]) assert res == 84 def define_many_weakrefs(cls):", "rpython.translator.c.genc import CStandaloneBuilder s_args = SomePtr(lltype.Ptr(ARGS)) t = rtype(entrypoint, [s_args],", "j < 20: j += 1 b[1, j, i] =", "if n > 0: x = BoxedObject(n) else: x =", "42]) #XXX pure lazyness here too assert res == 12", "= len(inspect.getargspec(func)[0]) name_to_func[name] = len(funcs0) if nargs == 2: funcs2.append(func)", "1 j += 1 lltype.free(idarray, flavor='raw') return 0 return f", "lltype.malloc(T_ALL.TO, 2) all[0] = parent all[1] = parent2 def f(x,", "a nursery a = A() nf_a = llop.gc_adr_of_nursery_free(llmemory.Address) nt_a =", "objectmodel.keepalive_until_here(a) return res return fn def test_instantiate_nonmovable(self): res = self.runner('instantiate_nonmovable')", "class A(object): pass def f(): # we need at least", "s = lltype.malloc(S) s.x = 42 llop.bare_setfield(lltype.Void, s0, void('next'), s)", "test_weakref(self): run = self.runner(\"weakref\") res = run([]) assert res def", "return x.meth(100) def func(): return fn(1000) + fn(-1000) assert func()", "def define_no_clean_setarrayitems(cls): # The optimization find_clean_setarrayitems() in # gctransformer/framework.py does", "import IncrementalMiniMarkGC \\ as GCClass GC_PARAMS = {'nursery_size': 32*WORD, 'page_size':", "= Unrelated() u.x = UnboxedObject(47) def fn(n): rgc.collect() # check", "# * the GcArray pointer from gc.object_id_dict. def define_adr_of_nursery(cls): class", "clear, so that A() is only visible via lst[0] rgc.collect()", "A() nf_a = llop.gc_adr_of_nursery_free(llmemory.Address) nt_a = llop.gc_adr_of_nursery_top(llmemory.Address) nf0 = nf_a.address[0]", "class A(object): pass a1 = A() def func(): a2 =", "child.field = 3 parent2.sub = child2 child2.field = 8 T_ALL", "def test_ref_from_rawmalloced_to_regular(self): run = self.runner(\"ref_from_rawmalloced_to_regular\") res = run([100, 100]) assert", "mess t.config.translation.gc = gcname t.config.translation.gcremovetypeptr = True t.config.set(**extraconfigopts) ann =", "func(): return rgc.can_move(lltype.malloc(TP, 1)) return func def test_can_move(self): run =", "cleanup, None def test_nongc_static_root_minor_collect(self): run = self.runner(\"nongc_static_root_minor_collect\") res = run([])", "class B(object): def __del__(self): a.count += 1 def g(): b", "# used to let test cleanup static root pointing to", "= func_fixup func.func_name = \"f_%s\" % name if cleanup: cleanup.func_name", "ptr2) + ord(ptr2.chars[0]) + (ord(ptr2.chars[1]) << 8) + (len(ptr2.chars) <<", "count # the number of prebuilt GC objects, but the", "from rpython.translator.backendopt.all import backend_optimizations backend_optimizations(t) if option.view: t.viewcg() return t", "def test_malloc_array_of_gcptr(self): run = self.runner('malloc_array_of_gcptr') res = run([]) assert res", "A()} j = 0 while j < 20: j +=", "static root pointing to runtime # allocated stuff cleanups.append(cleanup) def", "res = func([]) print res from rpython.rlib.objectmodel import UnboxedValue class", "4 times res = run([4, 42]) #XXX pure lazyness here", "test_do_malloc_operations_in_call(self): run = self.runner(\"do_malloc_operations_in_call\") run([]) def define_gc_heap_stats(cls): S = lltype.GcStruct('S',", "f def test_weakref(self): run = self.runner(\"weakref\") res = run([]) assert", "res def define_weakref_to_object_with_finalizer(cls): import weakref, gc class A(object): count =", "1 b.num_deleted_c += 1 def f(x, y): persistent_a1 = A()", "quickly gcname = \"generation\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation", "def test_writebarrier_before_copy(self): run = self.runner(\"writebarrier_before_copy\") run([]) # ________________________________________________________________ class TestSemiSpaceGC(GenericMovingGCTests):", "name_to_func = self.name_to_func entrygraph = self.entrygraph from rpython.rtyper.llinterp import LLInterpreter", "= self.runner(\"finalizer\") res = run([5, 42]) #XXX pure lazyness here", "class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.minimark import MiniMarkGC as GCClass", "lltype.malloc(rffi.SIGNEDP.TO, len(alist), flavor='raw') # Compute the id of all the", "the table which we later on # process ourselves, otherwise", "26 * size_of_int) % 4 == 0 # ^^^ a", "can only occur with varsized mallocs. lst.p = p return", "t = malloc(T6, 1) t.s[0] = 1 return t.s[0] def", "= None GC_CAN_MOVE = False taggedpointers = False def setup_class(cls):", "= [None] * x i = 0 while i <", "1 def f(x, y): a = A() i = 0", "pass def f(): a = A() i = 0 while", "512*WORD, 'nursery_size': 32*WORD, 'translated_to_c': False} root_stack_depth = 200 def define_weakref_across_minor_collection(cls):", "from rpython.rlib.rstring import StringBuilder from rpython.rlib.rarithmetic import LONG_BIT WORD =", "return p.x def f(): i = 0 while i <", "total = 0 i = 0 while i < 40:", "result = ref() is a ref = g() llop.gc__collect(lltype.Void) result", "llop.debug_print(lltype.Void, b.num_deleted_c) return b.num_deleted return f def test_collect_during_collect(self): run =", "0) return result return concat def test_collect_0(self): run = self.runner(\"collect_0\")", "shadowstack from rpython.rtyper.lltypesystem.lloperation import llop, void from rpython.rlib.objectmodel import compute_unique_id,", "test_writebarrier_before_copy(self): run = self.runner(\"writebarrier_before_copy\") run([]) # ________________________________________________________________ class TestSemiSpaceGC(GenericMovingGCTests): gcname", "= lltype.Ptr(lltype.GcStruct('Parent', ('sub', T_CHILD))) child = lltype.malloc(T_CHILD.TO) child2 = lltype.malloc(T_CHILD.TO)", "'_jit2gc', None) if jit2gc: assert 'invoke_after_minor_collection' in jit2gc return jit2gc['layoutbuilder']", "j = 0 while j < 2: if j ==", "test makes the following test crash. Investigate.\") run = self.runner(\"gc_heap_stats\")", "llop.gc__collect(lltype.Void) return llmemory.cast_adr_to_ptr(s1.x, lltype.Ptr(T)).z return f def test_custom_trace(self): run =", "from rpython.memory.gc.hybrid import HybridGC as GCClass GC_PARAMS = {'space_size': 512*WORD,", "import backend_optimizations backend_optimizations(t) if option.view: t.viewcg() return t ARGS =", "\"semispace\" GC_CAN_SHRINK_ARRAY = True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.semispace", "A() def func(): a2 = A() a3 = A() id1", "lltype.GcStruct('P', ('x', lltype.Signed)) def g(): r = lltype.malloc(P) r.x =", "malloc_a_lot def test_llinterp_dict(self): run = self.runner(\"llinterp_dict\") run([]) def skipdefine_global_list(cls): gl", "x: i += 1 a = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) aid", "Struct(\"S1\", ('x', Signed)) T1 = GcStruct(\"T1\", ('s', S1)) def f1():", "1 return t[0].x S3 = Struct(\"S3\", ('x', Signed)) T3 =", "* 1000 + c * 100 + b * 10", "l1.append(s) l2.append(s) if i < 3: l3.append(s) l4.append(s) # We", "[] l4 = [] def f(): for i in range(10):", "b.num_deleted += 1 C() class C(AAA): def __del__(self): b.num_deleted +=", "for the case where allocating the weakref itself triggers #", "def f(i, j): lst = setup(j) gc.collect() return lst.p.x return", "A(object): pass def fn(): a = A() return rgc.get_typeid(a) return", "all the elements of the list. The goal is #", "= gct.frameworkgc_setup_ptr.value._obj.graph # setup => resets the gc llinterp.eval_graph(setupgraph, [])", "10000) size_of_int = rffi.sizeof(lltype.Signed) assert (totsize - 26 * size_of_int)", "0x62 ptr.chars[0] = '0' ptr.chars[1] = 'B' ptr.chars[2] = 'C'", "= \"hybrid\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.hybrid import HybridGC", "('x', Signed)) T1 = GcStruct(\"T1\", ('s', S1)) def f1(): t", "A() a3 = A() id1 = compute_unique_id(a1) id2 = compute_unique_id(a2)", "def f(x, y): persistent_a1 = A() persistent_a2 = A() i", "class TestHybridGC(TestGenerationGC): gcname = \"hybrid\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from", "i < x: all[i] = [i] * i i +=", "1]) assert res == i - 1 # crashes if", "GC_PARAMS = {'space_size': 512*WORD, 'translated_to_c': False} root_stack_depth = 200 class", "lltype.Ptr(T)).z return f def test_custom_trace(self): run = self.runner(\"custom_trace\") res =", "lltype.malloc(T1) t1.x = 42 static.p = t1 x = 20", "nf_a = llop.gc_adr_of_nursery_free(llmemory.Address) nt_a = llop.gc_adr_of_nursery_top(llmemory.Address) nf0 = nf_a.address[0] nt0", "customtrace # def setup(): rgc.register_custom_trace_hook(S, lambda_customtrace) tx = lltype.malloc(T) tx.z", "rgc S = lltype.GcForwardReference() S.become(lltype.GcStruct('S', ('x', lltype.Signed), ('prev', lltype.Ptr(S)), ('next',", "the moment we get additional_roots_sources == 6: # * all[0]", "def fn(n): if n > 0: x = BoxedObject(n) else:", "return lst.p.x return f def test_ref_from_rawmalloced_to_regular(self): run = self.runner(\"ref_from_rawmalloced_to_regular\") res", "Signed)) T5 = GcStruct(\"T5\", ('items', Array(S5))) def f5(): t =", "return malloc_a_lot def test_llinterp_dict(self): run = self.runner(\"llinterp_dict\") run([]) def skipdefine_global_list(cls):", "assert res == 0 for i in range(1, 5): res", "is only visible via lst[0] rgc.collect() # -> crash return", "while j < 30: j += 1 a.append(j) return 0", "[] for i in range(200): rgc.collect(0) # nursery-only collection, if", "1) return len(t.items) T6 = GcStruct(\"T6\", ('s', Array(Signed))) def f6():", "in range(len(tb)): if tb[i].count == 4: b += 1 c", "10 j = 0 while j < 30: j +=", "only read the table which we later on # process", "if id2 != compute_unique_id(a2): error += 2 if id3 !=", "= \"semispace\" GC_CAN_SHRINK_ARRAY = True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from", "llmemory, rffi, llgroup from rpython.memory.gctransform import framework, shadowstack from rpython.rtyper.lltypesystem.lloperation", "i += 1 return 0 return f def test_many_weakrefs(self): run", "llop.gc__collect(lltype.Void) b.bla = persistent_a1.id + persistent_a2.id + persistent_a3.id + persistent_a4.id", "def __init__(self): self.lst = gl box = Box() def append_to_list(i,", "j*2 lst = lltype.malloc(A, j) # the following line generates", "define_many_ids(cls): class A(object): pass def f(): from rpython.rtyper.lltypesystem import rffi", "'page_size': 16*WORD, 'arena_size': 64*WORD, 'small_request_threshold': 5*WORD, 'large_object': 8*WORD, 'card_page_indices': 4,", "f(x, y): a = AAA() i = 0 while i", "f(): s1 = setup() llop.gc__collect(lltype.Void) return llmemory.cast_adr_to_ptr(s1.x, lltype.Ptr(T)).z return f", "a = A() class B(object): def __del__(self): a.count += 1", "24)) return f def test_shrink_array(self): run = self.runner(\"shrink_array\") if self.GC_CAN_SHRINK_ARRAY:", "Struct(\"T4\", ('s', S4)) U4 = GcArray(T4) def f4(): u =", "lltype.Char)) TP = lltype.GcArray(lltype.Ptr(S)) def fn(): l = lltype.malloc(TP, 100)", "class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.minimark import MiniMarkGC as GCClass GC_PARAMS =", "0 b.num_deleted_c = 0 class A(object): def __init__(self): self.id =", "fixup: fixup(t) cbuild = CStandaloneBuilder(t, entrypoint, config=t.config, gcpolicy=cls.gcpolicy) db =", "= definefunc.im_func(cls) cleanup = None if isinstance(func_fixup, tuple): func, cleanup,", "the two iterations [A() for i in range(20)] i =", "True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import GenerationGC as", "class GCTest(object): gcpolicy = None GC_CAN_MOVE = False taggedpointers =", "+= 1 C() C() class C(A): def __del__(self): b.num_deleted +=", "lazyness here too assert res == 12 def define_finalizer_resurrects(cls): class", "= 200 def define_weakref_across_minor_collection(cls): import weakref class A: pass def", "gcname t.config.translation.gcremovetypeptr = True t.config.set(**extraconfigopts) ann = t.buildannotator() ann.build_types(func, inputtypes)", "tb[i].count > 50: d += 1 for i in range(len(tb)):", "+= 1 j += 1 lltype.free(idarray, flavor='raw') return 0 return", "func([]) assert res == 205 def define_tagged_prebuilt(cls): class F: pass", "20: j += 1 b.append((1, j, i)) return 0 return", "a1 # 'a' is known young here, so no write", "def concat(j, dummy): lst = [] for i in range(j):", "1 def f(x, y): a = AAA() i = 0", "import Array, Signed, malloc S1 = Struct(\"S1\", ('x', Signed)) T1", "self.something = something def malloc_a_lot(): i = 0 first =", "# ^^^ a crude assumption that totsize - varsize would", "pass def fn(): a = A() return rgc.get_typeid(a) return fn", "a3 = A() id1 = compute_unique_id(a1) id2 = compute_unique_id(a2) id3", "0 nr = 0 b = 0 c = 0", "return b.num_deleted return f def test_collect_during_collect(self): run = self.runner(\"collect_during_collect\") #", "< x: i += 1 a = A() persistent_a3 =", "a.foo = x ref = weakref.ref(a) all = [None] *", "if tb[i].count > 50: d += 1 for i in", "from gc.wr_to_objects_with_id # * the GcArray pointer from gc.object_id_dict. def", "i += 1 a = AAA() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted", "with varsized mallocs. lst.p = p return lst def f(i,", "('x', Signed)) T2 = GcArray(S2) def f2(): t = malloc(T2,", "10 rgc.collect() sub(lst) null = lltype.nullptr(S) lst[15] = null #", "barrier rgc.collect() return x.meth(100) def func(): return fn(1000) + fn(-1000)", "= lltype.FixedSizeArray(lltype.Signed, 3) class GCTest(object): gcpolicy = None GC_CAN_MOVE =", "marker = cls.marker def cleanup(): assert marker[0] > 0 marker[0]", "# ________________________________________________________________ class TestSemiSpaceGC(GenericMovingGCTests): gcname = \"semispace\" GC_CAN_SHRINK_ARRAY = True", "setup() llop.gc__collect(lltype.Void) return llmemory.cast_adr_to_ptr(s1.x, lltype.Ptr(T)).z return f def test_custom_trace(self): run", "== 10: a += 1 nr = i if tb[i].count", "C() C() class C(A): def __del__(self): b.num_deleted += 1 b.num_deleted_c", "from rpython.conftest import option from rpython.rlib.rstring import StringBuilder from rpython.rlib.rarithmetic", "lltype.GcStruct('S', ('x', lltype.Signed)) A = lltype.GcStruct('A', ('p', lltype.Ptr(S)), ('a', lltype.Array(lltype.Char)))", "A() class B(object): def __del__(self): a.count += 1 def g():", "recursively 4 times res = run([4, 42]) #XXX pure lazyness", "parent2 = lltype.malloc(T_PARENT.TO) parent.sub = child child.field = 3 parent2.sub", "run([1, 4]) if not transformer.GCClass.prebuilt_gc_objects_are_static_roots: assert len(transformer.layoutbuilder.addresses_of_static_ptrs) == 0 else:", "B(somea) b.last = first j += 1 return 0 return", "* x i = 0 while i < x: all[i]", "= nt_a.address[0] a0 = A() a1 = A() nf1 =", "self.runner(\"nongc_static_root\") res = run([]) assert res == 42 def define_finalizer(cls):", "(len(ptr2.chars) << 16) + (ptr2.hash << 24)) return f def", "t.buildrtyper().specialize() if backendopt: from rpython.translator.backendopt.all import backend_optimizations backend_optimizations(t) if option.view:", "i)) return 0 return malloc_a_lot def test_llinterp_tuples(self): run = self.runner(\"llinterp_tuples\")", "Signed)) T2 = GcArray(S2) def f2(): t = malloc(T2, 1)", "funcs2 = [] cleanups = [] name_to_func = {} mixlevelstuff", "from rpython.memory.gc.incminimark import IncrementalMiniMarkGC \\ as GCClass GC_PARAMS = {'nursery_size':", "gcpolicy=cls.gcpolicy) db = cbuild.generate_graphs_for_llinterp() entrypointptr = cbuild.getentrypointptr() entrygraph = entrypointptr._obj.graph", "assumption that totsize - varsize would be dividable by 4", "# 16 > 10 rgc.collect() sub(lst) null = lltype.nullptr(S) lst[15]", "= lltype.malloc(S) p.x = j*2 lst = lltype.malloc(A, j) #", "84 def define_many_weakrefs(cls): # test for the case where allocating", "= cbuild.getentrypointptr() entrygraph = entrypointptr._obj.graph if option.view: t.viewcg() cls.name_to_func =", "lst.append(str(i)) result = len(\"\".join(lst)) if we_are_translated(): llop.gc__collect(lltype.Void, 0) return result", "of locations # within prebuilt GC objects that are of", "0]) assert res == 0 for i in range(1, 5):", "functions should have 0/2 arguments\") # used to let test", "== compute_unique_id(alist[i]) i += 1 j += 1 lltype.free(idarray, flavor='raw')", "the number of locations # within prebuilt GC objects that", "self.normalint + x + 2 class UnboxedObject(TaggedBase, UnboxedValue): __slots__ =", "from rpython.rlib.objectmodel import compute_unique_id, we_are_translated from rpython.rlib.debug import ll_assert from", "+ (len(ptr2.chars) << 16) + (ptr2.hash << 24)) return f", "0x62024230 assert run([]) == expected def define_string_builder_over_allocation(cls): import gc def", "enough to cause a minor collect all[i] = [i] *", "collect should occur in this test\") def _teardown(self): self.__ready =", "TaggedPointerGCTests(GCTest): taggedpointers = True def define_tagged_simple(cls): class Unrelated(object): pass u", "else: cleanup = None def fix_graph_of_g(translator): from rpython.translator.translator import graphof", "set the single mark \"12-15\" lst[15].x = 123 lst[0] =", "child2.field = 8 T_ALL = lltype.Ptr(lltype.GcArray(T_PARENT)) all = lltype.malloc(T_ALL.TO, 2)", "a return a.foo + len(all) return f def test_weakref_across_minor_collection(self): run", "NB print would create a static root! llop.debug_print(lltype.Void, b.num_deleted_c) return", "'nursery_size': 32*WORD, 'translated_to_c': False} root_stack_depth = 200 def test_gettypeid(self): py.test.skip(\"fails", "append_to_list, None, None def test_global_list(self): py.test.skip(\"doesn't fit in the model,", "llop.gc__collect(lltype.Void) tb = rgc._heap_stats() a = 0 nr = 0", "= self.runner(\"gettypeid\") res = func([]) print res from rpython.rlib.objectmodel import", "resets the gc llinterp.eval_graph(setupgraph, []) def run(args): ll_args = lltype.malloc(ARGS,", "== lltype.nullptr(S) and lst[3] == lltype.nullptr(S) and lst[4] == lltype.nullptr(S))", "func = funcs2[num] res = func(args[1], args[2]) cleanup = cleanups[num]", "= False taggedpointers = False def setup_class(cls): cls.marker = lltype.malloc(rffi.CArray(lltype.Signed),", "define_nongc_static_root(cls): T1 = lltype.GcStruct(\"C\", ('x', lltype.Signed)) T2 = lltype.Struct(\"C\", ('p',", "'arena_size': 64*WORD, 'small_request_threshold': 5*WORD, 'large_object': 8*WORD, 'card_page_indices': 4, 'translated_to_c': False,", "= [] j = 0 while j < 5: lst.append(i*j)", "res = run([]) assert res def define_weakref_to_object_with_finalizer(cls): import weakref, gc", "collection import weakref class A: pass def f(): a =", "= \"generation\" GC_CAN_SHRINK_ARRAY = True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from", "further collection is fine llop.gc__collect(lltype.Void) result = result and (ref()", "1 return t.s.x S2 = Struct(\"S2\", ('x', Signed)) T2 =", "run([4, 42]) #XXX pure lazyness here too assert res ==", "10 + f6()) assert func() == 111111 return func def", "rpython.memory.gc.minimark import MiniMarkGC as GCClass GC_PARAMS = {'nursery_size': 32*WORD, 'page_size':", "assert res == 123 def define_nursery_hash_base(cls): class A: pass def", "its job and that no full collection # is needed", "define_adr_of_nursery(cls): class A(object): pass def f(): # we need at", "== 6 def define_finalizer_calls_malloc(cls): class B(object): pass b = B()", "test_finalizer_resurrects(self): run = self.runner(\"finalizer_resurrects\") res = run([5, 42]) #XXX pure", "Array(S3))) def f3(): t = malloc(T3, 1) t.items[0].x = 1", "2, i) b = {a: A()} j = 0 while", "< x: i += 1 a = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void)", "= 1 return u[0].s.x S5 = Struct(\"S5\", ('x', Signed)) T5", "rffi.sizeof(lltype.Signed) assert (totsize - 26 * size_of_int) % 4 ==", "i < 17: ref = weakref.ref(a) assert ref() is a", "'translated_to_c': False, } root_stack_depth = 200 def define_no_clean_setarrayitems(cls): # The", "+ x + 2 class UnboxedObject(TaggedBase, UnboxedValue): __slots__ = 'smallint'", "= Struct(\"S1\", ('x', Signed)) T1 = GcStruct(\"T1\", ('s', S1)) def", "l = lltype.malloc(TP, 100) l2 = lltype.malloc(TP, 100) for i", "test_shrink_array(self): run = self.runner(\"shrink_array\") if self.GC_CAN_SHRINK_ARRAY: expected = 0x62024231 else:", "= True # FIIIIISH setupgraph = gct.frameworkgc_setup_ptr.value._obj.graph # setup =>", "run = self.runner(\"llinterp_lists\") run([]) def define_llinterp_tuples(cls): def malloc_a_lot(): i =", "A() i = 0 while i < x: i +=", "runner(self, name, transformer=False): db = self.db name_to_func = self.name_to_func entrygraph", "root_stack_depth = 200 def define_ref_from_rawmalloced_to_regular(cls): import gc S = lltype.GcStruct('S',", "llmemory.cast_ptr_to_adr(tx) return s1 def f(): s1 = setup() llop.gc__collect(lltype.Void) return", "concat(j, dummy): lst = [] for i in range(j): lst.append(str(i))", "== len(''.join([str(x) for x in range(100)])) def define_nongc_static_root(cls): T1 =", "res def define_collect_during_collect(cls): class B(object): pass b = B() b.nextid", "x: # enough to cause a minor collect all[i] =", "p = llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder p = lltype.cast_opaque_ptr(lltype.Ptr(P), p) p.x", "ptr.chars[0] = '0' ptr.chars[1] = 'B' ptr.chars[2] = 'C' ptr2", "= normalint def meth(self, x): return self.normalint + x +", "first = None while i < 10: i += 1", "not found\" return f, cleanup, fix_graph_of_g def test_do_malloc_operations(self): run =", "111111 return func def test_interior_ptrs(self): run = self.runner(\"interior_ptrs\") res =", "assert res == 12 def define_finalizer_resurrects(cls): class B(object): pass b", "run([]) def define_immutable_to_old_promotion(cls): T_CHILD = lltype.Ptr(lltype.GcStruct('Child', ('field', lltype.Signed))) T_PARENT =", "b.a = self def f(x, y): a = A() i", "self.runner(\"custom_trace\") res = run([]) assert res == 4243 def define_weakref(cls):", "('s', S1)) def f1(): t = malloc(T1) t.s.x = 1", "lst[1] == lltype.nullptr(S) and lst[2] == lltype.nullptr(S) and lst[3] ==", "res = run([]) class TestGenerationalNoFullCollectGC(GCTest): # test that nursery is", "== 84 def define_many_weakrefs(cls): # test for the case where", "totsize - varsize would be dividable by 4 # (and", "name_to_func[name] for i in range(len(args)): ll_args[1+i] = args[i] res =", "t = malloc(T1) t.s.x = 1 return t.s.x S2 =", "+= 1 c += tb[i].links[nr] e += tb[i].size return d", "i in range(50): assert l2[i] == l[50 + i] return", "lltype.GcStruct('S', ('x', lltype.Char)) TP = lltype.GcArray(lltype.Ptr(S)) def fn(): l =", "should have 0/2 arguments\") # used to let test cleanup", "gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import GenerationGC class GCClass(GenerationGC): __ready", "assert nt1 == nt0 return 0 return f def test_adr_of_nursery(self):", "all[0] = parent all[1] = parent2 def f(x, y): res", "l2, 50, 0, 50) # force nursery collect x =", "cls.marker = lltype.malloc(rffi.CArray(lltype.Signed), 1, flavor='raw', zero=True) funcs0 = [] funcs2", "return t ARGS = lltype.FixedSizeArray(lltype.Signed, 3) class GCTest(object): gcpolicy =", "# ________________________________________________________________ # tagged pointers class TaggedPointerGCTests(GCTest): taggedpointers = True", "f, None, fix_graph_of_g def test_do_malloc_operations_in_call(self): run = self.runner(\"do_malloc_operations_in_call\") run([]) def", "if not self.GC_CAN_TEST_ID: py.test.skip(\"fails for bad reasons in lltype.py :-(\")", "f(): for i in range(10): s = lltype.malloc(S) l1.append(s) l2.append(s)", "g() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) result = a.count == 1 and (ref()", "f(): q = lltype.malloc(P) q.x = 1 i = 0", "import inspect from rpython.rlib.objectmodel import compute_hash, compute_identity_hash from rpython.translator.c import", "and lst[1] == lltype.nullptr(S) and lst[2] == lltype.nullptr(S) and lst[3]", "t = malloc(T5, 1) return len(t.items) T6 = GcStruct(\"T6\", ('s',", "compute_unique_id(a3) llop.gc__collect(lltype.Void) error = 0 if id1 != compute_unique_id(a1): error", "dir(cls): if not fullname.startswith('define'): continue definefunc = getattr(cls, fullname) _,", "ids, it will trigger some collections itself i = 0", "class B(A): def __init__(self, something): self.something = something def malloc_a_lot():", "def f(): a = A() ref = weakref.ref(a) result =", "< 20: j += 1 b.append((1, j, i)) return 0", "return b.num_deleted return f def test_finalizer_calls_malloc(self): run = self.runner(\"finalizer_calls_malloc\") res", "100 * (b.a is None) return f def test_finalizer_resurrects(self): run", "persistent_a2.id + persistent_a3.id + persistent_a4.id # NB print would create", "= self.runner(\"gc_heap_stats\") res = run([]) assert res % 10000 ==", "gcname = \"minimark\" GC_CAN_TEST_ID = True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer):", "def define_finalizer_resurrects(cls): class B(object): pass b = B() b.nextid =", "to cause a minor collect all[i] = [i] * i", "def test_gettypeid(self): func = self.runner(\"gettypeid\") res = func([]) print res", "be a \"clean_setarrayitem\" def f(): lst = lltype.malloc(A, 16) #", "func def test_id(self): run = self.runner(\"id\") res = run([]) assert", "= GcArray(S2) def f2(): t = malloc(T2, 1) t[0].x =", "= (1, 2, i) b = [a] * 10 j", "setupgraph = gct.frameworkgc_setup_ptr.value._obj.graph # setup => resets the gc llinterp.eval_graph(setupgraph,", "[] cleanups = [] name_to_func = {} mixlevelstuff = []", "if cleanup: cleanup.func_name = \"clean_%s\" % name nargs = len(inspect.getargspec(func)[0])", "stuff cleanups.append(cleanup) def entrypoint(args): num = args[0] func = funcs0[num]", "= {'space_size': 512*WORD, 'nursery_size': 32*WORD, 'large_object': 8*WORD, 'translated_to_c': False} root_stack_depth", "= getattr(cls, fullname) _, name = fullname.split('_', 1) func_fixup =", "because the 'lst' can be allocated directly # in generation", "r.x return p.x def f(): i = 0 while i", "= lltype.malloc(S) s.x = 42 llop.bare_setfield(lltype.Void, s0, void('next'), s) llop.gc_writebarrier(lltype.Void,", "g(): r = lltype.malloc(P) r.x = 1 p = llop.do_malloc_fixedsize(llmemory.GCREF)", "cleanup(): assert marker[0] > 0 marker[0] = 0 else: cleanup", "[] for fullname in dir(cls): if not fullname.startswith('define'): continue definefunc", "test_llinterp_dict(self): run = self.runner(\"llinterp_dict\") run([]) def skipdefine_global_list(cls): gl = []", "persistent_a2 = A() i = 0 while i < x:", "rpython.rtyper.lltypesystem.lloperation import llop, void from rpython.rlib.objectmodel import compute_unique_id, we_are_translated from", "between the two iterations [A() for i in range(20)] i", "False def define_instances(cls): class A(object): pass class B(A): def __init__(self,", "200 def define_malloc_array_of_gcptr(self): S = lltype.GcStruct('S', ('x', lltype.Signed)) A =", "+= 1 a = (1, 2, i) b = [a]", "return 0 return malloc_a_lot def test_llinterp_dict(self): run = self.runner(\"llinterp_dict\") run([])", "+= 1 def f(x, y): persistent_a1 = A() persistent_a2 =", "range(50): assert l2[i] == l[50 + i] return 0 return", "4 return error return func def test_id(self): run = self.runner(\"id\")", "lltype.malloc(TP, 100) for i in range(100): l[i] = lltype.malloc(S) rgc.ll_arraycopy(l,", "from rpython.translator.translator import graphof from rpython.flowspace.model import Constant from rpython.rtyper.lltypesystem", "class TestGenerationGC(GenericMovingGCTests): gcname = \"generation\" GC_CAN_SHRINK_ARRAY = True class gcpolicy(gc.BasicFrameworkGcPolicy):", "all[i] = [i] * i i += 1 i =", "t1 = lltype.malloc(T1) t1.x = 42 static.p = t1 llop.gc__collect(lltype.Void)", "run = self.runner(\"weakref_to_object_with_finalizer\") res = run([]) assert res def define_collect_during_collect(cls):", "= 200 def define_ref_from_rawmalloced_to_regular(cls): import gc S = lltype.GcStruct('S', ('x',", "S = lltype.GcStruct('S', ('x', lltype.Signed)) A = lltype.GcArray(lltype.Ptr(S)) def sub(lst):", "the single mark \"12-15\" lst[15].x = 123 lst[0] = lst[15]", "def fn(): l = lltype.malloc(TP, 100) l2 = lltype.malloc(TP, 100)", "C() class C(AAA): def __del__(self): b.num_deleted += 1 def f(x,", "1 a.append(j) return 0 return malloc_a_lot def test_llinterp_lists(self): run =", "persistent_a1 = A() persistent_a2 = A() i = 0 while", "return result return concat def test_collect_0(self): run = self.runner(\"collect_0\") res", "'B' ptr.chars[2] = 'C' ptr2 = rgc.ll_shrink_array(ptr, 2) return ((ptr", "= 'C' ptr2 = rgc.ll_shrink_array(ptr, 2) return ((ptr == ptr2)", "f, cleanup, fix_graph_of_g def test_do_malloc_operations(self): run = self.runner(\"do_malloc_operations\") run([]) def", "g(): a = A() return weakref.ref(a) def f(): a =", "is turned off. S = lltype.GcStruct('S', ('x', lltype.Signed)) A =", "entrygraph cls.rtyper = t.rtyper cls.db = db def runner(self, name,", "\"clean_%s\" % name nargs = len(inspect.getargspec(func)[0]) name_to_func[name] = len(funcs0) if", "[] for i in range(20): x.append((1, lltype.malloc(S))) for i in", "range(100)])) def define_interior_ptrs(cls): from rpython.rtyper.lltypesystem.lltype import Struct, GcStruct, GcArray from", "def func(): return fn(1000) ^ fn(-1000) assert func() == -1999", "<< 24)) return f def test_shrink_array(self): run = self.runner(\"shrink_array\") if", "def func(): return rgc.can_move(lltype.malloc(TP, 1)) return func def test_can_move(self): run", "ref = weakref.ref(a) assert ref() is a i += 1", "GCClass GC_PARAMS = {'space_size': 512*WORD, 'nursery_size': 32*WORD, 'large_object': 8*WORD, 'translated_to_c':", "= run([]) assert res def define_weakref_to_object_with_finalizer(cls): import weakref, gc class", "define_string_concatenation(cls): def concat(j, dummy): lst = [] for i in", "* parent.sub # * parent2.sub # * the GcArray pointer", "= A() a.foo = x ref = weakref.ref(a) all =", "pointers class TaggedPointerGCTests(GCTest): taggedpointers = True def define_tagged_simple(cls): class Unrelated(object):", "in range(len(args)): ll_args[1+i] = args[i] res = llinterp.eval_graph(entrygraph, [ll_args]) return", "gc def fn(): s = StringBuilder(4) s.append(\"abcd\") s.append(\"defg\") s.append(\"rty\") s.append_multiple_char('y',", "= [] for i in range(j): lst.append(str(i)) return len(\"\".join(lst)) return", "y): persistent_a1 = A() persistent_a2 = A() i = 0", "while i < 10: i += 1 a = (1,", "0 while i < 17: ref = weakref.ref(a) assert ref()", "5: lst.append(i*j) j += 1 total += len(lst) i +=", "= 42 static.p = t1 x = 20 all =", "# which is important because the 'lst' can be allocated", "test_malloc_array_of_gcptr(self): run = self.runner('malloc_array_of_gcptr') res = run([]) assert res def", "range(j): lst.append(str(i)) result = len(\"\".join(lst)) if we_are_translated(): llop.gc__collect(lltype.Void, 0) return", "i i += 1 i = static.p.x llop.gc__collect(lltype.Void) return static.p.x", "= 200 def define_working_nursery(cls): def f(): total = 0 i", "visible via lst[0] rgc.collect() # -> crash return lst[0].x return", "= Struct(\"T4\", ('s', S4)) U4 = GcArray(T4) def f4(): u", "nr = i if tb[i].count > 50: d += 1", "transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.incminimark import IncrementalMiniMarkGC \\ as GCClass GC_PARAMS =", "= lltype.nullptr(S) lst[15] = null # clear, so that A()", "def test_weakref_to_object_with_finalizer(self): run = self.runner(\"weakref_to_object_with_finalizer\") res = run([]) assert res", "self.runner(\"llinterp_dict\") run([]) def skipdefine_global_list(cls): gl = [] class Box: def", "rpython.rlib.objectmodel import compute_unique_id, we_are_translated from rpython.rlib.debug import ll_assert from rpython.rlib", "class TestSemiSpaceGC(GenericMovingGCTests): gcname = \"semispace\" GC_CAN_SHRINK_ARRAY = True class gcpolicy(gc.BasicFrameworkGcPolicy):", "4 == 0 # ^^^ a crude assumption that totsize", "t.s[0] = 1 return t.s[0] def func(): return (f1() *", "l3 = [] l4 = [] def f(): for i", "run = self.runner(\"can_move\") res = run([]) assert res == self.GC_CAN_MOVE", "= A() i = 0 while i < x: i", "= run([]) assert res # ________________________________________________________________ # tagged pointers class", "return t.s.x S2 = Struct(\"S2\", ('x', Signed)) T2 = GcArray(S2)", "> 0 marker[0] = 0 else: cleanup = None def", "1 return 0 return malloc_a_lot def test_instances(self): run = self.runner(\"instances\")", "+= 1 def f(x, y): a = A() i =", "llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) aid = b.a.id b.a = None # check", "'large_object': 8*WORD, 'card_page_indices': 4, 'translated_to_c': False, } root_stack_depth = 200", "gc class A(object): count = 0 a = A() class", "import ll_assert from rpython.rlib import rgc from rpython.conftest import option", "lltype.Signed)) A = lltype.GcArray(lltype.Ptr(S)) def f(): lst = lltype.malloc(A, 5)", "minor collect all[i] = [i] * i i += 1", "func(): return fn(1000) + fn(-1000) assert func() == 205 return", "A() a.last = first first = a j = 0", "= self.runner(\"weakref_to_object_with_finalizer\") res = run([]) assert res def define_collect_during_collect(cls): class", "llop.gc__collect(lltype.Void) error = 0 if id1 != compute_unique_id(a1): error +=", "gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.minimark import MiniMarkGC as GCClass GC_PARAMS", "lltype.GcStruct('S', ('x', llmemory.Address)) T = lltype.GcStruct('T', ('z', lltype.Signed)) offset_of_x =", "def f(): t1 = lltype.malloc(T1) t1.x = 42 static.p =", "TP = lltype.GcArray(lltype.Float) def func(): return rgc.can_move(lltype.malloc(TP, 1)) return func", "class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.incminimark import IncrementalMiniMarkGC \\ as", "return 0 def fix_graph_of_g(translator): from rpython.translator.translator import graphof from rpython.flowspace.model", "res = run([]) assert res # ________________________________________________________________ # tagged pointers", "lltype.malloc(S) p.x = j*2 lst = lltype.malloc(A, j) # the", "run = self.runner(\"working_nursery\") res = run([]) assert res == 40", "(ref() is None) return result return f def test_weakref_to_object_with_finalizer(self): run", "False def define_many_ids(cls): class A(object): pass def f(): from rpython.rtyper.lltypesystem", "Unrelated(object): pass u = Unrelated() u.x = UnboxedObject(47) def fn(n):", "import HybridGC as GCClass GC_PARAMS = {'space_size': 512*WORD, 'nursery_size': 32*WORD,", "range(1, 5): res = run([i, i - 1]) assert res", "lltype.nullptr(S) and lst[1] == lltype.nullptr(S) and lst[2] == lltype.nullptr(S) and", "here too assert res == 6 def define_finalizer_calls_malloc(cls): class B(object):", "0 def fix_graph_of_g(translator): from rpython.translator.translator import graphof from rpython.flowspace.model import", "class TestHybridTaggedPointerGC(TaggedPointerGCTests): gcname = \"hybrid\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from", "2 class UnboxedObject(TaggedBase, UnboxedValue): __slots__ = 'smallint' def meth(self, x):", "= [] for i in range(20): x.append((1, lltype.malloc(S))) for i", "False, } root_stack_depth = 200 def define_no_clean_setarrayitems(cls): # The optimization", "66 def __init__(self, normalint): self.normalint = normalint def meth(self, x):", "class A: pass class B: pass static = A() static.p", "return malloc_a_lot def test_llinterp_lists(self): run = self.runner(\"llinterp_lists\") run([]) def define_llinterp_tuples(cls):", "self.runner(\"global_list\") res = run([0, 0]) assert res == 0 for", "pass b = B() b.nextid = 1 b.num_deleted = 0", "transformer.GCClass.prebuilt_gc_objects_are_static_roots: assert len(transformer.layoutbuilder.addresses_of_static_ptrs) == 0 else: assert len(transformer.layoutbuilder.addresses_of_static_ptrs) >= 4", "nursery collect x = [] for i in range(20): x.append((1,", "i in range(100): l[i] = lltype.malloc(S) rgc.ll_arraycopy(l, l2, 50, 0,", "of prebuilt GC objects, but the number of locations #", "rpython.rlib.objectmodel import compute_hash, compute_identity_hash from rpython.translator.c import gc from rpython.annotator", "static.p = lltype.nullptr(T1) return f, cleanup, None def test_nongc_static_root(self): run", "run = self.runner(\"finalizer\") res = run([5, 42]) #XXX pure lazyness", "assert 'invoke_after_minor_collection' in jit2gc return jit2gc['layoutbuilder'] marker = cls.marker GCClass", "and that no full collection # is needed when most", "test_tagged_prebuilt(self): func = self.runner(\"tagged_prebuilt\") res = func([]) assert res ==", "= weakref.ref(a) assert ref() is a i += 1 return", "return f def test_many_ids(self): if not self.GC_CAN_TEST_ID: py.test.skip(\"fails for bad", "layoutbuilder def define_do_malloc_operations(cls): P = lltype.GcStruct('P', ('x', lltype.Signed)) def g():", "= lltype.malloc(T_CHILD.TO) child2 = lltype.malloc(T_CHILD.TO) parent = lltype.malloc(T_PARENT.TO) parent2 =", "assert res == 42 class TestMiniMarkGC(TestHybridGC): gcname = \"minimark\" GC_CAN_TEST_ID", "framework.TransformerLayoutBuilder(translator, GCClass) layoutbuilder.delay_encoding() def seeme(): marker[0] += 1 translator._jit2gc =", "True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.semispace import SemiSpaceGC as", "assert res == len(''.join([str(x) for x in range(100)])) def define_interior_ptrs(cls):", "def f(): for i in range(10): s = lltype.malloc(S) l1.append(s)", "assert res == 84 def define_static_root_minor_collect(cls): class A: pass class", "res = all[x] #all[x] = lltype.nullptr(T_PARENT.TO) return res.sub.field return f", "immortal=True) def f(): t1 = lltype.malloc(T1) t1.x = 42 static.p", "ord(ptr2.chars[0]) + (ord(ptr2.chars[1]) << 8) + (len(ptr2.chars) << 16) +", "range(len(tb)): if tb[i].count == 10: a += 1 nr =", "if tb[i].count == 4: b += 1 c += tb[i].links[nr]", "20 all = [None] * x i = 0 while", "ref() is a ref = g() llop.gc__collect(lltype.Void) result = result", "def define_immutable_to_old_promotion(cls): T_CHILD = lltype.Ptr(lltype.GcStruct('Child', ('field', lltype.Signed))) T_PARENT = lltype.Ptr(lltype.GcStruct('Parent',", "= {'space_size': 512*WORD, 'nursery_size': 128*WORD, 'translated_to_c': False} root_stack_depth = 200", "gcname = \"hybrid\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.hybrid import", "def _teardown(self): self.__ready = False # collecting here is expected", "b.num_deleted = 0 class AAA(object): def __init__(self): self.id = b.nextid", "f def test_no_clean_setarrayitems(self): run = self.runner(\"no_clean_setarrayitems\") res = run([]) assert", "lltype.GcArray(lltype.Ptr(S)) def fn(): l = lltype.malloc(TP, 100) l2 = lltype.malloc(TP,", "j < 30: j += 1 a.append(j) return 0 return", "== 4243 def define_weakref(cls): import weakref, gc class A(object): pass", "rpython.flowspace.model import Constant from rpython.rtyper.lltypesystem import rffi layoutbuilder = cls.ensure_layoutbuilder(translator)", "= fullname.split('_', 1) func_fixup = definefunc.im_func(cls) cleanup = None if", "define_finalizer_calls_malloc(cls): class B(object): pass b = B() b.nextid = 0", "in range(20)] i = 0 while i < len(alist): assert", "GC_CAN_TEST_ID = False def define_many_ids(cls): class A(object): pass def f():", "b.nextid += 1 def __del__(self): b.num_deleted += 1 C() class", "rpython.rtyper.llannotation import SomePtr from rpython.rtyper.lltypesystem import lltype, llmemory, rffi, llgroup", "import compute_unique_id, we_are_translated from rpython.rlib.debug import ll_assert from rpython.rlib import", "a.last = first first = a j = 0 while", "self.runner(\"string_builder_over_allocation\") res = fn([]) assert res == ord('y') class GenericMovingGCTests(GenericGCTests):", "return f def test_collect_during_collect(self): run = self.runner(\"collect_during_collect\") # runs collect", "+ (ptr2.hash << 24)) return f def test_shrink_array(self): run =", "run([]) def define_gc_heap_stats(cls): S = lltype.GcStruct('S', ('x', lltype.Signed)) l1 =", "import objectmodel from rpython.rtyper import annlowlevel class A: pass def", "TestSemiSpaceGC(GenericMovingGCTests): gcname = \"semispace\" GC_CAN_SHRINK_ARRAY = True class gcpolicy(gc.BasicFrameworkGcPolicy): class", "{'space_size': 512*WORD, 'nursery_size': 128*WORD, 'translated_to_c': False} root_stack_depth = 200 def", "f5() * 10 + f6()) assert func() == 111111 return", "UnboxedObject(n) u.x = x # invoke write barrier rgc.collect() return", "define_gettypeid(cls): class A(object): pass def fn(): a = A() return", "= layoutbuilder.get_type_id(P) # # now fix the do_malloc_fixedsize in the", "GC needs memory to # remember the ids, it will", "assert func() == 205 return func def test_tagged_simple(self): func =", "42 static.p = t1 x = 20 all = [None]", "__init__(self, something): self.something = something def malloc_a_lot(): i = 0", "lltype.Array(lltype.Char))) def setup(j): p = lltype.malloc(S) p.x = j*2 lst", "= None return len(unique) return fn def test_nursery_hash_base(self): res =", "def entrypoint(args): num = args[0] func = funcs0[num] if func:", "weakref.ref(b) def f(): ref = g() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) result =", "def define_id(cls): class A(object): pass a1 = A() def func():", "and lst[2] == lltype.nullptr(S) and lst[3] == lltype.nullptr(S) and lst[4]", "self.runner(\"malloc_struct_of_gcptr\") res = run([]) assert res # ________________________________________________________________ # tagged", "C(AAA): def __del__(self): b.num_deleted += 1 def f(x, y): a", "i < 3: l3.append(s) l4.append(s) # We cheat here and", "d += 1 for i in range(len(tb)): if tb[i].count ==", "the GcArray pointer from gc.wr_to_objects_with_id # * the GcArray pointer", "= func_fixup mixlevelstuff.append(fixup) else: func = func_fixup func.func_name = \"f_%s\"", "llop.gc_adr_of_nursery_free(llmemory.Address) nt_a = llop.gc_adr_of_nursery_top(llmemory.Address) nf0 = nf_a.address[0] nt0 = nt_a.address[0]", "i = 0 while i < x: i += 1", "in range(j): lst.append(str(i)) result = len(\"\".join(lst)) if we_are_translated(): llop.gc__collect(lltype.Void, 0)", "= self.runner(\"static_root_minor_collect\") res = run([]) assert res == 84 def", "b.num_deleted_c) return b.num_deleted return f def test_collect_during_collect(self): run = self.runner(\"collect_during_collect\")", "== nt0 return 0 return f def test_adr_of_nursery(self): run =", "\"12-15\" lst[15].x = 123 lst[0] = lst[15] # that would", "res.sub.field return f def test_immutable_to_old_promotion(self): run, transformer = self.runner(\"immutable_to_old_promotion\", transformer=True)", "= A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) aid = b.a.id b.a = None", "test_weakref_across_minor_collection(self): run = self.runner(\"weakref_across_minor_collection\") res = run([]) assert res ==", "self.runner(\"do_malloc_operations_in_call\") run([]) def define_gc_heap_stats(cls): S = lltype.GcStruct('S', ('x', lltype.Signed)) l1", "2: if j == 1: # allocate some stuff between", "A() a.foo = x ref = weakref.ref(a) all = [None]", "rpython.rlib.debug import ll_assert from rpython.rlib import rgc from rpython.conftest import", "would create a static root! llop.debug_print(lltype.Void, b.num_deleted_c) return b.num_deleted return", "rgc.ll_arraycopy(l, l2, 50, 0, 50) # force nursery collect x", "i in range(len(tb)): if tb[i].count == 4: b += 1", "'translated_to_c': False, } root_stack_depth = 200 def define_malloc_array_of_gcptr(self): S =", "self.db name_to_func = self.name_to_func entrygraph = self.entrygraph from rpython.rtyper.llinterp import", "^^^ a crude assumption that totsize - varsize would be", "200 def define_ref_from_rawmalloced_to_regular(cls): import gc S = lltype.GcStruct('S', ('x', lltype.Signed))", "nt1 > nf1 assert nt1 == nt0 return 0 return", "# to not allocate memory, so that if the GC", "f(): lst = lltype.malloc(A, 5) return (lst[0] == lltype.nullptr(S) and", "lltype.GcStruct('S', ('x', lltype.Signed)) S = lltype.GcStruct('S', ('x', lltype.Signed), ('filed1', lltype.Ptr(S1)),", "option from rpython.rlib.rstring import StringBuilder from rpython.rlib.rarithmetic import LONG_BIT WORD", "[ll_args]) return res if transformer: return run, gct else: return", "is known young here, so no write barrier emitted res", "GC_CAN_SHRINK_ARRAY = True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.semispace import", "import weakref, gc class A(object): count = 0 a =", "seeme(): marker[0] += 1 translator._jit2gc = { 'layoutbuilder': layoutbuilder, 'invoke_after_minor_collection':", "(lst[0] == lltype.nullptr(S) and lst[1] == lltype.nullptr(S) and lst[2] ==", "def runner(self, name, transformer=False): db = self.db name_to_func = self.name_to_func", "b.num_deleted return f def test_collect_during_collect(self): run = self.runner(\"collect_during_collect\") # runs", "x in range(100)])) def define_nongc_static_root(cls): T1 = lltype.GcStruct(\"C\", ('x', lltype.Signed))", "== -1999 def define_gettypeid(cls): class A(object): pass def fn(): a", "j < 20: j += 1 b.append((1, j, i)) return", "compute_unique_id(alist[i]) i += 1 j = 0 while j <", "GC_PARAMS = {'space_size': 512*WORD, 'nursery_size': 128*WORD, 'translated_to_c': False} root_stack_depth =", "lltype.GcArray(lltype.Float) def func(): return rgc.can_move(lltype.malloc(TP, 1)) return func def test_can_move(self):", "is important because the 'lst' can be allocated directly #", "lltype.nullptr(S) and lst[4] == lltype.nullptr(S)) return f def test_malloc_array_of_gcptr(self): run", "x # invoke write barrier rgc.collect() return x.meth(100) def func():", "box.lst[j][0] return append_to_list, None, None def test_global_list(self): py.test.skip(\"doesn't fit in", "def f(): total = 0 i = 0 while i", "+= 1 lltype.free(idarray, flavor='raw') return 0 return f def test_many_ids(self):", "nf1 = nf_a.address[0] nt1 = nt_a.address[0] assert nf1 > nf0", "i = 0 while i < 17: ref = weakref.ref(a)", "let test cleanup static root pointing to runtime # allocated", "B() b.nextid = 0 b.num_deleted = 0 class A(object): def", "fine llop.gc__collect(lltype.Void) result = result and (ref() is None) return", "1 b[1, j, i] = A() return 0 return malloc_a_lot", "import CStandaloneBuilder s_args = SomePtr(lltype.Ptr(ARGS)) t = rtype(entrypoint, [s_args], gcname=cls.gcname,", "malloc S1 = Struct(\"S1\", ('x', Signed)) T1 = GcStruct(\"T1\", ('s',", "== 111111 def define_id(cls): class A(object): pass a1 = A()", "[None] * x i = 0 while i < x:", "('next', lltype.Ptr(S)))) s0 = lltype.malloc(S, immortal=True) def f(): s =", "assert res def define_malloc_struct_of_gcptr(cls): S1 = lltype.GcStruct('S', ('x', lltype.Signed)) S", "class A: pass def fn(): a1 = A() a =", "B() return weakref.ref(b) def f(): ref = g() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void)", "runs collect recursively 4 times res = run([4, 42]) #XXX", "A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) b.bla = persistent_a1.id + persistent_a2.id + persistent_a3.id", "ptr2 = rgc.ll_shrink_array(ptr, 2) return ((ptr == ptr2) + ord(ptr2.chars[0])", "A(object): pass def g(): a = A() return weakref.ref(a) def", "r.x = 1 p = llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder p =", "cleanup(): s0.next = lltype.nullptr(S) return f, cleanup, None def test_write_barrier_direct(self):", "weakref itself triggers # a collection import weakref class A:", "= lambda: customtrace # def setup(): rgc.register_custom_trace_hook(S, lambda_customtrace) tx =", "func(): return (f1() * 100000 + f2() * 10000 +", "= run([]) assert res == 20 + 20 def define_nongc_static_root_minor_collect(cls):", "the GcArray pointer from gc.object_id_dict. def define_adr_of_nursery(cls): class A(object): pass", "= lltype.malloc(T1) t1.x = 42 static.p = t1 x =", "0, \"oups, not found\" return f, cleanup, fix_graph_of_g def test_do_malloc_operations(self):", "= rtype(entrypoint, [s_args], gcname=cls.gcname, taggedpointers=cls.taggedpointers) for fixup in mixlevelstuff: if", "a.count += 1 def g(): b = B() return weakref.ref(b)", "as GCClass GC_PARAMS = {'space_size': 512*WORD, 'translated_to_c': False} root_stack_depth =", "assert res def define_collect_during_collect(cls): class B(object): pass b = B()", "a j = 0 while j < 30: b =", "run = self.runner(\"instances\") run([]) def define_llinterp_lists(cls): def malloc_a_lot(): i =", "def f2(): t = malloc(T2, 1) t[0].x = 1 return", "import GenerationGC GenerationGC.setup(self) self.__ready = True def semispace_collect(self, size_changing=False): ll_assert(not", "class TestMiniMarkGC(TestHybridGC): gcname = \"minimark\" GC_CAN_TEST_ID = True class gcpolicy(gc.BasicFrameworkGcPolicy):", "define_many_weakrefs(cls): # test for the case where allocating the weakref", "None return len(unique) return fn def test_nursery_hash_base(self): res = self.runner('nursery_hash_base')", "= lltype.malloc(T_PARENT.TO) parent.sub = child child.field = 3 parent2.sub =", "128*WORD, 'translated_to_c': False} root_stack_depth = 200 def define_working_nursery(cls): def f():", "i in range(j): lst.append(str(i)) result = len(\"\".join(lst)) if we_are_translated(): llop.gc__collect(lltype.Void,", "Constant(llmemory.sizeof(P), lltype.Signed), Constant(False, lltype.Bool), # has_finalizer Constant(False, lltype.Bool), # is_finalizer_light", "lltype.FixedSizeArray(lltype.Signed, 3) class GCTest(object): gcpolicy = None GC_CAN_MOVE = False", "def g(): llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder def f(): q = lltype.malloc(P)", "# the number of prebuilt GC objects, but the number", "normalint): self.normalint = normalint def meth(self, x): return self.normalint +", "pointer from gc.wr_to_objects_with_id # * the GcArray pointer from gc.object_id_dict.", "return self.normalint + x + 2 class UnboxedObject(TaggedBase, UnboxedValue): __slots__", "lltype.malloc(T_PARENT.TO) parent2 = lltype.malloc(T_PARENT.TO) parent.sub = child child.field = 3", "fn(): a1 = A() a = objectmodel.instantiate(A, nonmovable=True) a.next =", "j = 0 while j < 5: lst.append(i*j) j +=", "= p return lst def f(i, j): lst = setup(j)", "'0' ptr.chars[1] = 'B' ptr.chars[2] = 'C' ptr2 = rgc.ll_shrink_array(ptr,", "weakref, gc class A(object): count = 0 a = A()", "c += tb[i].links[nr] e += tb[i].size return d * 1000", "funcs0.append(None) elif nargs == 0: funcs0.append(func) funcs2.append(None) else: raise NotImplementedError(", "A() return weakref.ref(a) def f(): a = A() ref =", "84 def define_static_root_minor_collect(cls): class A: pass class B: pass static", "collection, if possible obj = A() objects.append(obj) hashes.append(compute_identity_hash(obj)) unique =", "T5 = GcStruct(\"T5\", ('items', Array(S5))) def f5(): t = malloc(T5,", "ref = g() llop.gc__collect(lltype.Void) result = result and (ref() is", "len(\"\".join(lst)) if we_are_translated(): llop.gc__collect(lltype.Void, 0) return result return concat def", "res([]) >= 195 def define_instantiate_nonmovable(cls): from rpython.rlib import objectmodel from", "return fn(1000) + fn(-1000) assert func() == 205 return func", "100 + f5() * 10 + f6()) assert func() ==", "return 0 return fn def test_writebarrier_before_copy(self): run = self.runner(\"writebarrier_before_copy\") run([])", "= rgc.can_move(annlowlevel.cast_instance_to_base_ptr(a)) rgc.collect() objectmodel.keepalive_until_here(a) return res return fn def test_instantiate_nonmovable(self):", "define_shrink_array(cls): from rpython.rtyper.lltypesystem.rstr import STR def f(): ptr = lltype.malloc(STR,", "lst.append(str(i)) return len(\"\".join(lst)) return concat def test_string_concatenation(self): run = self.runner(\"string_concatenation\")", "C(A): def __del__(self): b.num_deleted += 1 b.num_deleted_c += 1 def", "== 'do_malloc_fixedsize': op.args = [Constant(type_id, llgroup.HALFWORD), Constant(llmemory.sizeof(P), lltype.Signed), Constant(False, lltype.Bool),", "the model, tested elsewhere too\") run = self.runner(\"global_list\") res =", "Check that it is turned off. S = lltype.GcStruct('S', ('x',", "nt_a.address[0] assert nf1 > nf0 assert nt1 > nf1 assert", "= a.count == 1 and (ref() is None) return result", "lltype.nullptr(S)) return f def test_malloc_array_of_gcptr(self): run = self.runner('malloc_array_of_gcptr') res =", "res = run([i, i - 1]) assert res == i", "T4 = Struct(\"T4\", ('s', S4)) U4 = GcArray(T4) def f4():", "res = run([4, 42]) #XXX pure lazyness here too assert", "marking. # Check that it is turned off. S =", "+ fn(-1000) assert func() == 205 return func def test_tagged_simple(self):", "32*WORD, 'translated_to_c': False} root_stack_depth = 200 def test_gettypeid(self): py.test.skip(\"fails for", "immortal=True) def f(): s = lltype.malloc(S) s.x = 42 llop.bare_setfield(lltype.Void,", "id1 != compute_unique_id(a1): error += 1 if id2 != compute_unique_id(a2):", "explode if n > 0: x = BoxedObject(n) else: x", "lst def f(i, j): lst = setup(j) gc.collect() return lst.p.x", "SomePtr from rpython.rtyper.lltypesystem import lltype, llmemory, rffi, llgroup from rpython.memory.gctransform", "assert res % 10000 == 2611 totsize = (res /", "= [] name_to_func = {} mixlevelstuff = [] for fullname", "funcs2[num] res = func(args[1], args[2]) cleanup = cleanups[num] if cleanup:", "x + 2 class UnboxedObject(TaggedBase, UnboxedValue): __slots__ = 'smallint' def", "f2() * 10000 + f3() * 1000 + f4() *", "i in range(50)] idarray = lltype.malloc(rffi.SIGNEDP.TO, len(alist), flavor='raw') # Compute", "4: b += 1 c += tb[i].links[nr] e += tb[i].size", "= run([]) assert res == self.GC_CAN_MOVE def define_shrink_array(cls): from rpython.rtyper.lltypesystem.rstr", "op.args = [Constant(type_id, llgroup.HALFWORD), Constant(llmemory.sizeof(P), lltype.Signed), Constant(False, lltype.Bool), # has_finalizer", "= func() else: func = funcs2[num] res = func(args[1], args[2])", "= self.runner(\"custom_trace\") res = run([]) assert res == 4243 def", "else: return run class GenericGCTests(GCTest): GC_CAN_SHRINK_ARRAY = False def define_instances(cls):", "[] for i in range(j): lst.append(str(i)) result = len(\"\".join(lst)) if", "= lltype.nullptr(T_PARENT.TO) return res.sub.field return f def test_immutable_to_old_promotion(self): run, transformer", "= [] hashes = [] for i in range(200): rgc.collect(0)", "s0 = lltype.malloc(S) def f(): return (s0.filed1 == lltype.nullptr(S1) and", "XXX XXX XXX mess t.config.translation.gc = gcname t.config.translation.gcremovetypeptr = True", "'invoke_after_minor_collection': seeme, } return layoutbuilder def define_do_malloc_operations(cls): P = lltype.GcStruct('P',", "ord('y') class GenericMovingGCTests(GenericGCTests): GC_CAN_MOVE = True GC_CAN_TEST_ID = False def", "mallocs. lst.p = p return lst def f(i, j): lst", "a llop.gc__collect(lltype.Void) assert ref() is a return a.foo + len(all)", "a crude assumption that totsize - varsize would be dividable", "1 return t.items[0].x S4 = Struct(\"S4\", ('x', Signed)) T4 =", "box.lst.append([i] * 50) llop.gc__collect(lltype.Void) return box.lst[j][0] return append_to_list, None, None", "the list. The goal is # to not allocate memory,", "P = lltype.GcStruct('P', ('x', lltype.Signed)) def g(): r = lltype.malloc(P)", "def meth(self, x): return self.normalint + x + 2 class", "id3 != compute_unique_id(a3): error += 4 return error return func", "run([5, 42]) #XXX pure lazyness here too assert res ==", "f5(): t = malloc(T5, 1) return len(t.items) T6 = GcStruct(\"T6\",", "i = 0 first = None while i < 10:", "test_llinterp_lists(self): run = self.runner(\"llinterp_lists\") run([]) def define_llinterp_tuples(cls): def malloc_a_lot(): i", "1 return u[0].s.x S5 = Struct(\"S5\", ('x', Signed)) T5 =", "def test_instances(self): run = self.runner(\"instances\") run([]) def define_llinterp_lists(cls): def malloc_a_lot():", "'a' is known young here, so no write barrier emitted", "if possible obj = A() objects.append(obj) hashes.append(compute_identity_hash(obj)) unique = {}", "b.nextid = 0 b.num_deleted = 0 class A(object): def __init__(self):", "'C' ptr2 = rgc.ll_shrink_array(ptr, 2) return ((ptr == ptr2) +", "lst = lltype.malloc(A, j) # the following line generates a", "nargs == 0: funcs0.append(func) funcs2.append(None) else: raise NotImplementedError( \"defined test", "run = self.runner(\"collect_0\") res = run([100, 0]) assert res ==", "malloc(U4, 1) u[0].s.x = 1 return u[0].s.x S5 = Struct(\"S5\",", "be allocated directly # in generation 2. This can only", "in range(50): assert l2[i] == l[50 + i] return 0", "= lltype.malloc(S) # 'lst' is set the single mark \"12-15\"", "b.nextid = 0 b.num_deleted = 0 class AAA(object): def __init__(self):", "define_finalizer_resurrects(cls): class B(object): pass b = B() b.nextid = 0", "A: pass def fn(): objects = [] hashes = []", "doing its job and that no full collection # is", "GenerationGC._teardown(self) GC_PARAMS = {'space_size': 512*WORD, 'nursery_size': 128*WORD, 'translated_to_c': False} root_stack_depth", "# test for the case where allocating the weakref itself", "specialize: t.buildrtyper().specialize() if backendopt: from rpython.translator.backendopt.all import backend_optimizations backend_optimizations(t) if", "compute_unique_id, we_are_translated from rpython.rlib.debug import ll_assert from rpython.rlib import rgc", "def define_malloc_array_of_gcptr(self): S = lltype.GcStruct('S', ('x', lltype.Signed)) A = lltype.GcArray(lltype.Ptr(S))", "('s', S4)) U4 = GcArray(T4) def f4(): u = malloc(U4,", "work with card marking. # Check that it is turned", "lltype.malloc(T2, immortal=True) def f(): t1 = lltype.malloc(T1) t1.x = 42", "False def setup(self): from rpython.memory.gc.generation import GenerationGC GenerationGC.setup(self) self.__ready =", "i < 10: i += 1 a = somea =", "test_id(self): run = self.runner(\"id\") res = run([]) assert res ==", "None def test_nongc_static_root(self): run = self.runner(\"nongc_static_root\") res = run([]) assert", "while i < 17: ref = weakref.ref(a) assert ref() is", "< 3: l3.append(s) l4.append(s) # We cheat here and only", "b.num_deleted return f def test_finalizer_calls_malloc(self): run = self.runner(\"finalizer_calls_malloc\") res =", "+ c * 100 + b * 10 + a", "= lltype.malloc(TP, 100) for i in range(100): l[i] = lltype.malloc(S)", "llgroup from rpython.memory.gctransform import framework, shadowstack from rpython.rtyper.lltypesystem.lloperation import llop,", "as GCClass GC_PARAMS = {'space_size': 512*WORD, 'nursery_size': 32*WORD, 'large_object': 8*WORD,", "cbuild.getentrypointptr() entrygraph = entrypointptr._obj.graph if option.view: t.viewcg() cls.name_to_func = name_to_func", "process ourselves, otherwise this test takes ages llop.gc__collect(lltype.Void) tb =", "def define_collect_0(cls): def concat(j, dummy): lst = [] for i", "% name nargs = len(inspect.getargspec(func)[0]) name_to_func[name] = len(funcs0) if nargs", "later on # process ourselves, otherwise this test takes ages", "= True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.minimark import MiniMarkGC", "= None if isinstance(func_fixup, tuple): func, cleanup, fixup = func_fixup", "a prebuilt tagged pointer doesn't explode if n > 0:", "invoke write barrier rgc.collect() return x.meth(100) def func(): return fn(1000)", "func = self.runner(\"gettypeid\") res = func([]) print res from rpython.rlib.objectmodel", "* 10 j = 0 while j < 20: j", "res = run([]) assert res == 4243 def define_weakref(cls): import", "STR def f(): ptr = lltype.malloc(STR, 3) ptr.hash = 0x62", "('p', lltype.Ptr(S)), ('a', lltype.Array(lltype.Char))) def setup(j): p = lltype.malloc(S) p.x", "lltype.Bool)] # contains_weakptr break else: assert 0, \"oups, not found\"", "run([]) def define_llinterp_lists(cls): def malloc_a_lot(): i = 0 while i", "is a ref = g() llop.gc__collect(lltype.Void) result = result and", "not called again llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted * 10 +", "A() persistent_a3 = A() persistent_a4 = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) b.bla", "u.x = x # invoke write barrier rgc.collect() return x.meth(100)", "malloc(T6, 1) t.s[0] = 1 return t.s[0] def func(): return", "for GenerationGC, enough for a minor collection a = A()", "def define_weakref_to_object_with_finalizer(cls): import weakref, gc class A(object): count = 0", "def test_do_malloc_operations(self): run = self.runner(\"do_malloc_operations\") run([]) def define_do_malloc_operations_in_call(cls): P =", "no write barrier emitted res = rgc.can_move(annlowlevel.cast_instance_to_base_ptr(a)) rgc.collect() objectmodel.keepalive_until_here(a) return", "llgroup.HALFWORD), Constant(llmemory.sizeof(P), lltype.Signed), Constant(False, lltype.Bool), # has_finalizer Constant(False, lltype.Bool), #", "[] def f(): for i in range(10): s = lltype.malloc(S)", "res % 10000 == 2611 totsize = (res / 10000)", "return static.p.x + i def cleanup(): static.p = None return", "TestGenerationalNoFullCollectGC(GCTest): # test that nursery is doing its job and", "= [i] * i i += 1 assert ref() is", "= self.runner(\"weakref\") res = run([]) assert res def define_weakref_to_object_with_finalizer(cls): import", "needed when most allocated objects die quickly gcname = \"generation\"", "== 200 def define_write_barrier_direct(cls): from rpython.rlib import rgc S =", "range(20)] i = 0 while i < len(alist): assert idarray[i]", "define_instances(cls): class A(object): pass class B(A): def __init__(self, something): self.something", "collect all[i] = [i] * i i += 1 i", "lltype.GcStruct('S', ('x', lltype.Signed)) A = lltype.GcArray(lltype.Ptr(S)) def f(): lst =", "= self.runner(\"llinterp_dict\") run([]) def skipdefine_global_list(cls): gl = [] class Box:", "from rpython.translator.c import gc from rpython.annotator import model as annmodel", "A(object): pass def f(): # we need at least 1", "else: func = funcs2[num] res = func(args[1], args[2]) cleanup =", "from rpython.flowspace.model import Constant from rpython.rtyper.lltypesystem import rffi layoutbuilder =", "At the moment we get additional_roots_sources == 6: # *", "f.l = [UnboxedObject(10)] def fn(n): if n > 0: x", "U4 = GcArray(T4) def f4(): u = malloc(U4, 1) u[0].s.x", "+= 1 nr = i if tb[i].count > 50: d", "self.runner(\"weakref_to_object_with_finalizer\") res = run([]) assert res def define_collect_during_collect(cls): class B(object):", "x = UnboxedObject(n) f.l.append(x) rgc.collect() return f.l[-1].meth(100) def func(): return", "self.runner(\"finalizer_resurrects\") res = run([5, 42]) #XXX pure lazyness here too", "def test_adr_of_nursery(self): run = self.runner(\"adr_of_nursery\") res = run([]) class TestGenerationalNoFullCollectGC(GCTest):", "static.p = None def f(): t1 = B() t1.x =", "'small_request_threshold': 5*WORD, 'large_object': 8*WORD, 'card_page_indices': 4, 'translated_to_c': False, } root_stack_depth", "error return func def test_id(self): run = self.runner(\"id\") res =", "b * 10 + a return f def test_gc_heap_stats(self): py.test.skip(\"this", "GC_CAN_SHRINK_ARRAY = True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import", "test_instances(self): run = self.runner(\"instances\") run([]) def define_llinterp_lists(cls): def malloc_a_lot(): i", "XXX XXX mess t.config.translation.gc = gcname t.config.translation.gcremovetypeptr = True t.config.set(**extraconfigopts)", "return f, cleanup, fix_graph_of_g def test_do_malloc_operations(self): run = self.runner(\"do_malloc_operations\") run([])", "unique = {} for i in range(len(objects)): assert compute_identity_hash(objects[i]) ==", "that totsize - varsize would be dividable by 4 #", "res == 12 def define_collect_0(cls): def concat(j, dummy): lst =", "run([]) assert res == self.GC_CAN_MOVE def define_shrink_array(cls): from rpython.rtyper.lltypesystem.rstr import", "= 0 for i in range(len(tb)): if tb[i].count == 10:", "obj to allocate a nursery a = A() nf_a =", "inputtypes) if specialize: t.buildrtyper().specialize() if backendopt: from rpython.translator.backendopt.all import backend_optimizations", "== 12 def define_finalizer_resurrects(cls): class B(object): pass b = B()", "= self.name_to_func entrygraph = self.entrygraph from rpython.rtyper.llinterp import LLInterpreter llinterp", "func() == 205 return func def test_tagged_simple(self): func = self.runner(\"tagged_simple\")", "moment we get additional_roots_sources == 6: # * all[0] #", "A() return rgc.get_typeid(a) return fn def test_gettypeid(self): func = self.runner(\"gettypeid\")", "self.__ready = True def semispace_collect(self, size_changing=False): ll_assert(not self.__ready, \"no full", "res = func() else: func = funcs2[num] res = func(args[1],", "TestHybridTaggedPointerGC(TaggedPointerGCTests): gcname = \"hybrid\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation", "otherwise this test takes ages llop.gc__collect(lltype.Void) tb = rgc._heap_stats() a", "= child2 child2.field = 8 T_ALL = lltype.Ptr(lltype.GcArray(T_PARENT)) all =", "= \"incminimark\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.incminimark import IncrementalMiniMarkGC", "s0.next = lltype.nullptr(S) return f, cleanup, None def test_write_barrier_direct(self): run", "<reponame>jptomo/pypy-lang-scheme import py import inspect from rpython.rlib.objectmodel import compute_hash, compute_identity_hash", "('x', lltype.Char)) TP = lltype.GcArray(lltype.Ptr(S)) def fn(): l = lltype.malloc(TP,", "UnboxedValue class TaggedBase(object): __slots__ = () def meth(self, x): raise", "# 'lst' is set the single mark \"12-15\" lst[15].x =", "A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) aid = b.a.id b.a = None #", "* i i += 1 i = static.p.x llop.gc__collect(lltype.Void) return", "in the graph of g graph = graphof(translator, g) for", "return t.s[0] def func(): return (f1() * 100000 + f2()", "s.append(\"abcd\") s.append(\"defg\") s.append(\"rty\") s.append_multiple_char('y', 1000) gc.collect() s.append_multiple_char('y', 1000) res =", "j) # the following line generates a write_barrier call at", "res <= 165 def define_custom_trace(cls): # S = lltype.GcStruct('S', ('x',", "import weakref, gc class A(object): pass def g(): a =", "gc.collect() return ord(res) return fn def test_string_builder_over_allocation(self): fn = self.runner(\"string_builder_over_allocation\")", "arg, obj + offset_of_x) lambda_customtrace = lambda: customtrace # def", "additional_roots_sources == 6: # * all[0] # * all[1] #", "= run([100, 100]) assert res == 200 def define_write_barrier_direct(cls): from", "isinstance(func_fixup, tuple): func, cleanup, fixup = func_fixup mixlevelstuff.append(fixup) else: func", "gc._trace_callback(callback, arg, obj + offset_of_x) lambda_customtrace = lambda: customtrace #", "('items', Array(S3))) def f3(): t = malloc(T3, 1) t.items[0].x =", "run([]) assert res % 10000 == 2611 totsize = (res", "with card marking. # Check that it is turned off.", "AAA() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted return f def test_finalizer_calls_malloc(self): run", "lst[4] == lltype.nullptr(S)) return f def test_malloc_array_of_gcptr(self): run = self.runner('malloc_array_of_gcptr')", "= lltype.Struct(\"C\", ('p', lltype.Ptr(T1))) static = lltype.malloc(T2, immortal=True) def f():", "a i += 1 return 0 return f def test_many_weakrefs(self):", "b.a = None # check that __del__ is not called", "backendopt=False, **extraconfigopts): from rpython.translator.translator import TranslationContext t = TranslationContext() #", "= True class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import GenerationGC", "= parent2 def f(x, y): res = all[x] #all[x] =", "A: pass def f(): a = A() i = 0", "= run([]) assert res == 4243 def define_weakref(cls): import weakref,", "that are of type Ptr(Gc). # At the moment we", "run = self.runner(\"no_clean_setarrayitems\") res = run([]) assert res == 123", "x: i += 1 a = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return", "A(object): pass a1 = A() def func(): a2 = A()", "u[0].s.x = 1 return u[0].s.x S5 = Struct(\"S5\", ('x', Signed))", "lst.p.x return f def test_ref_from_rawmalloced_to_regular(self): run = self.runner(\"ref_from_rawmalloced_to_regular\") res =", "fn(1000) + fn(-1000) assert func() == 205 return func def", "__del__(self): b.num_deleted += 1 b.a = self def f(x, y):", "def cleanup(): s0.next = lltype.nullptr(S) return f, cleanup, None def", "= self.runner(\"immutable_to_old_promotion\", transformer=True) run([1, 4]) if not transformer.GCClass.prebuilt_gc_objects_are_static_roots: assert len(transformer.layoutbuilder.addresses_of_static_ptrs)", "0 while j < 30: j += 1 a.append(j) return", "from rpython.rtyper.llannotation import SomePtr from rpython.rtyper.lltypesystem import lltype, llmemory, rffi,", "for x in range(100)])) def define_nongc_static_root(cls): T1 = lltype.GcStruct(\"C\", ('x',", "A() i = 0 while i < 17: ref =", "self.runner(\"tagged_prebuilt\") res = func([]) assert res == -1999 def define_gettypeid(cls):", "= name_to_func cls.entrygraph = entrygraph cls.rtyper = t.rtyper cls.db =", "jit2gc['layoutbuilder'] marker = cls.marker GCClass = cls.gcpolicy.transformerclass.GCClass layoutbuilder = framework.TransformerLayoutBuilder(translator,", "+= 1 a = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) aid = b.a.id", "8*WORD, 'translated_to_c': False} root_stack_depth = 200 def define_ref_from_rawmalloced_to_regular(cls): import gc", "= {} for i in range(len(objects)): assert compute_identity_hash(objects[i]) == hashes[i]", "b = [a] * 10 j = 0 while j", "in range(50)] idarray = lltype.malloc(rffi.SIGNEDP.TO, len(alist), flavor='raw') # Compute the", "is a llop.gc__collect(lltype.Void) assert ref() is a return a.foo +", "== lltype.nullptr(S)) return f def test_malloc_array_of_gcptr(self): run = self.runner('malloc_array_of_gcptr') res", "1 b.a = self def f(x, y): a = A()", "f def test_collect_during_collect(self): run = self.runner(\"collect_during_collect\") # runs collect recursively", "None def test_static_root_minor_collect(self): run = self.runner(\"static_root_minor_collect\") res = run([]) assert", "l4.append(s) # We cheat here and only read the table", "x = 20 all = [None] * x i =", "append_to_list(i, j): box.lst.append([i] * 50) llop.gc__collect(lltype.Void) return box.lst[j][0] return append_to_list,", "assert res == 205 def define_tagged_prebuilt(cls): class F: pass f", "cleanup, None def test_write_barrier_direct(self): run = self.runner(\"write_barrier_direct\") res = run([])", "malloc(T1) t.s.x = 1 return t.s.x S2 = Struct(\"S2\", ('x',", "weakref.ref(a) assert ref() is a i += 1 return 0", "len(alist): idarray[i] = compute_unique_id(alist[i]) i += 1 j = 0", "= t.rtyper cls.db = db def runner(self, name, transformer=False): db", "1)) return func def test_can_move(self): run = self.runner(\"can_move\") res =", "cleanups.append(cleanup) def entrypoint(args): num = args[0] func = funcs0[num] if", "def cleanup(): assert marker[0] > 0 marker[0] = 0 else:", "lltype.GcStruct('S', ('x', lltype.Signed)) l1 = [] l2 = [] l3", "pass def fn(): a1 = A() a = objectmodel.instantiate(A, nonmovable=True)", "b = B() b.nextid = 0 b.num_deleted = 0 class", "* 10 + aid + 100 * (b.a is None)", "1000 + f4() * 100 + f5() * 10 +", "'incminimark': marker = cls.marker def cleanup(): assert marker[0] > 0", "= r.x return p.x def f(): i = 0 while", "a = A() i = 0 while i < x:", "B(object): def __del__(self): a.count += 1 def g(): b =", "fn def test_writebarrier_before_copy(self): run = self.runner(\"writebarrier_before_copy\") run([]) # ________________________________________________________________ class", "i = static.p.x llop.gc__collect(lltype.Void) return static.p.x + i def cleanup():", "return fn def test_nursery_hash_base(self): res = self.runner('nursery_hash_base') assert res([]) >=", "lltype.Bool), # is_finalizer_light Constant(False, lltype.Bool)] # contains_weakptr break else: assert", "nf_a.address[0] nt0 = nt_a.address[0] a0 = A() a1 = A()", "def cleanup(): static.p = lltype.nullptr(T1) return f, cleanup, None def", "p = lltype.cast_opaque_ptr(lltype.Ptr(P), p) p.x = r.x return p.x def", "AAA(object): def __init__(self): self.id = b.nextid b.nextid += 1 def", "Array(S5))) def f5(): t = malloc(T5, 1) return len(t.items) T6", "res from rpython.rlib.objectmodel import UnboxedValue class TaggedBase(object): __slots__ = ()", "cleanup = cleanups[num] if cleanup: cleanup() return res from rpython.translator.c.genc", "run([]) assert res def define_weakref_to_object_with_finalizer(cls): import weakref, gc class A(object):", "\\ GCClass GC_PARAMS = {'space_size': 512*WORD, 'nursery_size': 32*WORD, 'translated_to_c': False}", "run([]) assert res def define_malloc_struct_of_gcptr(cls): S1 = lltype.GcStruct('S', ('x', lltype.Signed))", "run([]) def define_llinterp_tuples(cls): def malloc_a_lot(): i = 0 while i", "self.runner(\"instances\") run([]) def define_llinterp_lists(cls): def malloc_a_lot(): i = 0 while", "define_can_move(cls): TP = lltype.GcArray(lltype.Float) def func(): return rgc.can_move(lltype.malloc(TP, 1)) return", "20: j += 1 b[1, j, i] = A() return", "def f(): i = 0 while i < 40: g()", "== lltype.nullptr(S) and lst[1] == lltype.nullptr(S) and lst[2] == lltype.nullptr(S)", "l[50 + i] return 0 return fn def test_writebarrier_before_copy(self): run", "+= 1 a = [1] * 10 j = 0", "# * all[0] # * all[1] # * parent.sub #", "while i < 10: i += 1 a = [1]", "s1 = lltype.malloc(S) s1.x = llmemory.cast_ptr_to_adr(tx) return s1 def f():", "t.s.x = 1 return t.s.x S2 = Struct(\"S2\", ('x', Signed))", "return layoutbuilder def define_do_malloc_operations(cls): P = lltype.GcStruct('P', ('x', lltype.Signed)) def", "'translated_to_c': False} root_stack_depth = 200 def test_gettypeid(self): py.test.skip(\"fails for obscure", "t1.x = 42 static.p = t1 x = 20 all", "* 1000 + f4() * 100 + f5() * 10", "f = F() f.l = [UnboxedObject(10)] def fn(n): if n", "in dir(cls): if not fullname.startswith('define'): continue definefunc = getattr(cls, fullname)", "+= 1 a = somea = A() a.last = first", "rgc.can_move(annlowlevel.cast_instance_to_base_ptr(a)) rgc.collect() objectmodel.keepalive_until_here(a) return res return fn def test_instantiate_nonmovable(self): res", "> 0: x = BoxedObject(n) else: x = UnboxedObject(n) u.x", "lltype.malloc(P) r.x = 1 p = llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder p", "self.runner(\"shrink_array\") if self.GC_CAN_SHRINK_ARRAY: expected = 0x62024231 else: expected = 0x62024230", "(res / 10000) size_of_int = rffi.sizeof(lltype.Signed) assert (totsize - 26", "return func def test_tagged_prebuilt(self): func = self.runner(\"tagged_prebuilt\") res = func([])", "len(''.join([str(x) for x in range(100)])) def define_nongc_static_root(cls): T1 = lltype.GcStruct(\"C\",", "[s_args], gcname=cls.gcname, taggedpointers=cls.taggedpointers) for fixup in mixlevelstuff: if fixup: fixup(t)", "number of prebuilt GC objects, but the number of locations", "j): lst = setup(j) gc.collect() return lst.p.x return f def", "f def test_gc_heap_stats(self): py.test.skip(\"this test makes the following test crash.", "run = self.runner(\"do_malloc_operations\") run([]) def define_do_malloc_operations_in_call(cls): P = lltype.GcStruct('P', ('x',", "lltype.Ptr(lltype.GcStruct('Parent', ('sub', T_CHILD))) child = lltype.malloc(T_CHILD.TO) child2 = lltype.malloc(T_CHILD.TO) parent", "3) class GCTest(object): gcpolicy = None GC_CAN_MOVE = False taggedpointers", "run = self.runner(\"many_ids\") run([]) @classmethod def ensure_layoutbuilder(cls, translator): jit2gc =", "rpython.memory.gc.generation import GenerationGC GenerationGC.setup(self) self.__ready = True def semispace_collect(self, size_changing=False):", "def define_shrink_array(cls): from rpython.rtyper.lltypesystem.rstr import STR def f(): ptr =", "* 5 class TestHybridGC(TestGenerationGC): gcname = \"hybrid\" class gcpolicy(gc.BasicFrameworkGcPolicy): class", "assert res([]) == 0 class TestIncrementalMiniMarkGC(TestMiniMarkGC): gcname = \"incminimark\" class", "/ 10000) size_of_int = rffi.sizeof(lltype.Signed) assert (totsize - 26 *", "and only read the table which we later on #", "A() nf1 = nf_a.address[0] nt1 = nt_a.address[0] assert nf1 >", "will trigger some collections itself i = 0 while i", "True t.config.set(**extraconfigopts) ann = t.buildannotator() ann.build_types(func, inputtypes) if specialize: t.buildrtyper().specialize()", "GCClass GC_PARAMS = {'nursery_size': 32*WORD, 'page_size': 16*WORD, 'arena_size': 64*WORD, 'small_request_threshold':", "pass def f(): # we need at least 1 obj", "GC objects, but the number of locations # within prebuilt", "run([100, 0]) assert res == len(''.join([str(x) for x in range(100)]))", "res = self.runner('instantiate_nonmovable') assert res([]) == 0 class TestIncrementalMiniMarkGC(TestMiniMarkGC): gcname", "for fixup in mixlevelstuff: if fixup: fixup(t) cbuild = CStandaloneBuilder(t,", "def define_static_root_minor_collect(cls): class A: pass class B: pass static =", "= A() static.p = None def f(): t1 = B()", "= GcStruct(\"T1\", ('s', S1)) def f1(): t = malloc(T1) t.s.x", "can be allocated directly # in generation 2. This can", "self.smallint + x + 3 class TestHybridTaggedPointerGC(TaggedPointerGCTests): gcname = \"hybrid\"", "def define_nursery_hash_base(cls): class A: pass def fn(): objects = []", "allocate some stuff between the two iterations [A() for i", "res from rpython.translator.c.genc import CStandaloneBuilder s_args = SomePtr(lltype.Ptr(ARGS)) t =", "= first first = a j = 0 while j", "0 class AAA(object): def __init__(self): self.id = b.nextid b.nextid +=", "we need at least 1 obj to allocate a nursery", "cls.marker GCClass = cls.gcpolicy.transformerclass.GCClass layoutbuilder = framework.TransformerLayoutBuilder(translator, GCClass) layoutbuilder.delay_encoding() def", "fullname.startswith('define'): continue definefunc = getattr(cls, fullname) _, name = fullname.split('_',", "fn def test_gettypeid(self): func = self.runner(\"gettypeid\") res = func([]) print", "run, gct else: return run class GenericGCTests(GCTest): GC_CAN_SHRINK_ARRAY = False", "a return f def test_gc_heap_stats(self): py.test.skip(\"this test makes the following", "8 T_ALL = lltype.Ptr(lltype.GcArray(T_PARENT)) all = lltype.malloc(T_ALL.TO, 2) all[0] =", "the following test crash. Investigate.\") run = self.runner(\"gc_heap_stats\") res =", "> 10 rgc.collect() sub(lst) null = lltype.nullptr(S) lst[15] = null", "def define_weakref(cls): import weakref, gc class A(object): pass def g():", "def __init__(self): self.id = b.nextid b.nextid += 1 def __del__(self):", "fit in the model, tested elsewhere too\") run = self.runner(\"global_list\")", "dividable by 4 # (and give fixedsize) def define_writebarrier_before_copy(cls): S", "error += 4 return error return func def test_id(self): run", "a = A() return weakref.ref(a) def f(): a = A()", "= 0 b = 0 c = 0 d =", "Constant(False, lltype.Bool)] # contains_weakptr break else: assert 0, \"oups, not", "b = 0 c = 0 d = 0 e", "return rgc.can_move(lltype.malloc(TP, 1)) return func def test_can_move(self): run = self.runner(\"can_move\")", "range(20): x.append((1, lltype.malloc(S))) for i in range(50): assert l2[i] ==", "need at least 1 obj to allocate a nursery a", "(ptr2.hash << 24)) return f def test_shrink_array(self): run = self.runner(\"shrink_array\")", "func() == -1999 return func def test_tagged_prebuilt(self): func = self.runner(\"tagged_prebuilt\")", "# a collection import weakref class A: pass def f():", "5) return (lst[0] == lltype.nullptr(S) and lst[1] == lltype.nullptr(S) and", "b.num_deleted += 1 b.num_deleted_c += 1 def f(x, y): persistent_a1", "else: func = func_fixup func.func_name = \"f_%s\" % name if", "def __del__(self): b.num_deleted += 1 b.a = self def f(x,", "# the following line generates a write_barrier call at the", "allocated objects die quickly gcname = \"generation\" class gcpolicy(gc.BasicFrameworkGcPolicy): class", "x i = 0 while i < x: all[i] =", "= 0 while i < len(alist): assert idarray[i] == compute_unique_id(alist[i])", "} root_stack_depth = 200 def define_malloc_array_of_gcptr(self): S = lltype.GcStruct('S', ('x',", "= lltype.GcStruct('S', ('x', lltype.Signed)) A = lltype.GcArray(lltype.Ptr(S)) def f(): lst", "0/2 arguments\") # used to let test cleanup static root", "20 def define_nongc_static_root_minor_collect(cls): T1 = lltype.GcStruct(\"C\", ('x', lltype.Signed)) T2 =", "def test_immutable_to_old_promotion(self): run, transformer = self.runner(\"immutable_to_old_promotion\", transformer=True) run([1, 4]) if", "f(): lst = lltype.malloc(A, 16) # 16 > 10 rgc.collect()", "LONG_BIT WORD = LONG_BIT // 8 def rtype(func, inputtypes, specialize=True,", "A() a = objectmodel.instantiate(A, nonmovable=True) a.next = a1 # 'a'", "assert 0, \"oups, not found\" return f, cleanup, fix_graph_of_g def", "run([]) assert res == 42 class TestMiniMarkGC(TestHybridGC): gcname = \"minimark\"", "nt_a.address[0] a0 = A() a1 = A() nf1 = nf_a.address[0]", "import TranslationContext t = TranslationContext() # XXX XXX XXX mess", "def ensure_layoutbuilder(cls, translator): jit2gc = getattr(translator, '_jit2gc', None) if jit2gc:", "by 4 # (and give fixedsize) def define_writebarrier_before_copy(cls): S =", "class GenericMovingGCTests(GenericGCTests): GC_CAN_MOVE = True GC_CAN_TEST_ID = False def define_many_ids(cls):", "parent = lltype.malloc(T_PARENT.TO) parent2 = lltype.malloc(T_PARENT.TO) parent.sub = child child.field", "t1 = lltype.malloc(T1) t1.x = 42 static.p = t1 x", "0 return malloc_a_lot def test_llinterp_tuples(self): run = self.runner(\"llinterp_tuples\") run([]) def", "== 4: b += 1 c += tb[i].links[nr] e +=", "if cleanup: cleanup() return res from rpython.translator.c.genc import CStandaloneBuilder s_args", "too assert 160 <= res <= 165 def define_custom_trace(cls): #", "B() t1.x = 42 static.p = t1 x = 20", "def f(): return (s0.filed1 == lltype.nullptr(S1) and s0.filed2 == lltype.nullptr(S1))", "= b.nextid b.nextid += 1 def __del__(self): b.num_deleted += 1", "gc class A(object): pass def g(): a = A() return", "else: assert len(transformer.layoutbuilder.addresses_of_static_ptrs) >= 4 # NB. Remember that the", "42]) #XXX pure lazyness here too assert res == 6", "t.viewcg() cls.name_to_func = name_to_func cls.entrygraph = entrygraph cls.rtyper = t.rtyper", "all[x] #all[x] = lltype.nullptr(T_PARENT.TO) return res.sub.field return f def test_immutable_to_old_promotion(self):", "b.bla = persistent_a1.id + persistent_a2.id + persistent_a3.id + persistent_a4.id #", "in range(1, 5): res = run([i, i - 1]) assert", "= True t.config.set(**extraconfigopts) ann = t.buildannotator() ann.build_types(func, inputtypes) if specialize:", "[] l2 = [] l3 = [] l4 = []", "+= 4 return error return func def test_id(self): run =", "b.num_deleted_c = 0 class A(object): def __init__(self): self.id = b.nextid", "= StringBuilder(4) s.append(\"abcd\") s.append(\"defg\") s.append(\"rty\") s.append_multiple_char('y', 1000) gc.collect() s.append_multiple_char('y', 1000)", "A: pass def fn(): a1 = A() a = objectmodel.instantiate(A,", "run = self.runner(\"ref_from_rawmalloced_to_regular\") res = run([100, 100]) assert res ==", "+= 1 b.a = self def f(x, y): a =", "the number above does not count # the number of", "len(t.items) T6 = GcStruct(\"T6\", ('s', Array(Signed))) def f6(): t =", "all = lltype.malloc(T_ALL.TO, 2) all[0] = parent all[1] = parent2", "None # check that __del__ is not called again llop.gc__collect(lltype.Void)", "== 84 def define_static_root_minor_collect(cls): class A: pass class B: pass", "test_malloc_struct_of_gcptr(self): run = self.runner(\"malloc_struct_of_gcptr\") res = run([]) assert res #", "class A(object): pass def malloc_a_lot(): i = 0 while i", "('z', lltype.Signed)) offset_of_x = llmemory.offsetof(S, 'x') def customtrace(gc, obj, callback,", "!= compute_unique_id(a1): error += 1 if id2 != compute_unique_id(a2): error", "[A() for i in range(50)] idarray = lltype.malloc(rffi.SIGNEDP.TO, len(alist), flavor='raw')", "2) all[0] = parent all[1] = parent2 def f(x, y):", "test_static_root_minor_collect(self): run = self.runner(\"static_root_minor_collect\") res = run([]) assert res ==", "run = self.runner(\"write_barrier_direct\") res = run([]) assert res == 42", "from rpython.rtyper.lltypesystem import lltype, llmemory, rffi, llgroup from rpython.memory.gctransform import", "= 0 while i < 10: i += 1 a", "s0.filed2 == lltype.nullptr(S1)) return f def test_malloc_struct_of_gcptr(self): run = self.runner(\"malloc_struct_of_gcptr\")", "def semispace_collect(self, size_changing=False): ll_assert(not self.__ready, \"no full collect should occur", "def f(): s1 = setup() llop.gc__collect(lltype.Void) return llmemory.cast_adr_to_ptr(s1.x, lltype.Ptr(T)).z return", "('x', lltype.Signed)) def g(): llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder def f(): q", "def g(): a = A() return weakref.ref(a) def f(): a", "f, cleanup, None def test_nongc_static_root(self): run = self.runner(\"nongc_static_root\") res =", "20 + 20 def define_nongc_static_root_minor_collect(cls): T1 = lltype.GcStruct(\"C\", ('x', lltype.Signed))", "remember the ids, it will trigger some collections itself i", "not fullname.startswith('define'): continue definefunc = getattr(cls, fullname) _, name =", "lltype.malloc(S) rgc.ll_arraycopy(l, l2, 50, 0, 50) # force nursery collect", "# (and give fixedsize) def define_writebarrier_before_copy(cls): S = lltype.GcStruct('S', ('x',", "cleanup(): static.p = lltype.nullptr(T1) return f, cleanup, None def test_nongc_static_root_minor_collect(self):", "0 b.num_deleted = 0 class AAA(object): def __init__(self): self.id =", "% name if cleanup: cleanup.func_name = \"clean_%s\" % name nargs", "result return concat def test_collect_0(self): run = self.runner(\"collect_0\") res =", "0: x = BoxedObject(n) else: x = UnboxedObject(n) u.x =", "= (1, 2, i) b = {a: A()} j =", "class A: pass def fn(): objects = [] hashes =", "= (res / 10000) size_of_int = rffi.sizeof(lltype.Signed) assert (totsize -", "too assert res == 12 def define_finalizer_resurrects(cls): class B(object): pass", "== -1999 return func def test_tagged_prebuilt(self): func = self.runner(\"tagged_prebuilt\") res", "self.runner(\"collect_during_collect\") # runs collect recursively 4 times res = run([4,", "if j == 1: # allocate some stuff between the", "res == 12 def define_finalizer_resurrects(cls): class B(object): pass b =", "return f def test_working_nursery(self): run = self.runner(\"working_nursery\") res = run([])", "\\ as GCClass GC_PARAMS = {'nursery_size': 32*WORD, 'page_size': 16*WORD, 'arena_size':", "lltype.Signed), ('prev', lltype.Ptr(S)), ('next', lltype.Ptr(S)))) s0 = lltype.malloc(S, immortal=True) def", "elif nargs == 0: funcs0.append(func) funcs2.append(None) else: raise NotImplementedError( \"defined", "at least 1 obj to allocate a nursery a =", "collect recursively 4 times res = run([4, 42]) #XXX pure", "expected = 0x62024231 else: expected = 0x62024230 assert run([]) ==", "res == 20 + 20 def define_nongc_static_root_minor_collect(cls): T1 = lltype.GcStruct(\"C\",", "= run([]) assert res == 84 def define_static_root_minor_collect(cls): class A:", "no full collection # is needed when most allocated objects", "0 while j < 20: j += 1 b[1, j,", "n > 0: x = BoxedObject(n) else: x = UnboxedObject(n)", "== lltype.nullptr(S1)) return f def test_malloc_struct_of_gcptr(self): run = self.runner(\"malloc_struct_of_gcptr\") res", "void('next'), s) llop.gc_writebarrier(lltype.Void, llmemory.cast_ptr_to_adr(s0)) rgc.collect(0) return s0.next.x def cleanup(): s0.next", "funcs2.append(func) funcs0.append(None) elif nargs == 0: funcs0.append(func) funcs2.append(None) else: raise", "the weakref itself triggers # a collection import weakref class", "arguments\") # used to let test cleanup static root pointing", "result = result and (ref() is None) return result return", "return a.foo + len(all) return f def test_weakref_across_minor_collection(self): run =", "if not fullname.startswith('define'): continue definefunc = getattr(cls, fullname) _, name", "b.append((1, j, i)) return 0 return malloc_a_lot def test_llinterp_tuples(self): run", "compute_unique_id(a2): error += 2 if id3 != compute_unique_id(a3): error +=", "setup(j) gc.collect() return lst.p.x return f def test_ref_from_rawmalloced_to_regular(self): run =", "def __del__(self): b.num_deleted += 1 def f(x, y): a =", "= parent all[1] = parent2 def f(x, y): res =", "while i < x: i += 1 a = A()", "constants are not considered roots def define_string_concatenation(cls): def concat(j, dummy):", "gct.frameworkgc_setup_ptr.value._obj.graph # setup => resets the gc llinterp.eval_graph(setupgraph, []) def", "(1, 2, i) b = {a: A()} j = 0", "= self.runner(\"llinterp_lists\") run([]) def define_llinterp_tuples(cls): def malloc_a_lot(): i = 0", "while i < 40: g() i += 1 return 0", "import gc S = lltype.GcStruct('S', ('x', lltype.Signed)) A = lltype.GcStruct('A',", "define_interior_ptrs(cls): from rpython.rtyper.lltypesystem.lltype import Struct, GcStruct, GcArray from rpython.rtyper.lltypesystem.lltype import", "= lltype.Ptr(lltype.GcStruct('Child', ('field', lltype.Signed))) T_PARENT = lltype.Ptr(lltype.GcStruct('Parent', ('sub', T_CHILD))) child", "parent2.sub # * the GcArray pointer from gc.wr_to_objects_with_id # *", "> nf1 assert nt1 == nt0 return 0 return f", "= GcStruct(\"T5\", ('items', Array(S5))) def f5(): t = malloc(T5, 1)", "f def test_adr_of_nursery(self): run = self.runner(\"adr_of_nursery\") res = run([]) class", "(ord(ptr2.chars[1]) << 8) + (len(ptr2.chars) << 16) + (ptr2.hash <<", "varsize would be dividable by 4 # (and give fixedsize)", "A: pass def f(): x = 20 # for GenerationGC,", "and (ref() is None) return result return f def test_weakref_to_object_with_finalizer(self):", "= 123 lst[0] = lst[15] # that would be a", "objects = [] hashes = [] for i in range(200):", "root_stack_depth = 200 def define_working_nursery(cls): def f(): total = 0", "# that would be a \"clean_setarrayitem\" def f(): lst =", "error += 2 if id3 != compute_unique_id(a3): error += 4", "len(all) return f def test_weakref_across_minor_collection(self): run = self.runner(\"weakref_across_minor_collection\") res =", "lltype.nullptr(S) and lst[2] == lltype.nullptr(S) and lst[3] == lltype.nullptr(S) and", "objects, but the number of locations # within prebuilt GC", "return f def test_custom_trace(self): run = self.runner(\"custom_trace\") res = run([])", "nargs = len(inspect.getargspec(func)[0]) name_to_func[name] = len(funcs0) if nargs == 2:", "[i] * i i += 1 i = static.p.x llop.gc__collect(lltype.Void)", "== 2: funcs2.append(func) funcs0.append(None) elif nargs == 0: funcs0.append(func) funcs2.append(None)", "0, 50) # force nursery collect x = [] for", "# * the GcArray pointer from gc.wr_to_objects_with_id # * the", "res = run([]) assert res == 42 def define_finalizer(cls): class", "parent.sub # * parent2.sub # * the GcArray pointer from", "gc S = lltype.GcStruct('S', ('x', lltype.Signed)) A = lltype.GcStruct('A', ('p',", "lltype.Ptr(S)), ('next', lltype.Ptr(S)))) s0 = lltype.malloc(S, immortal=True) def f(): s", "def func(): return fn(1000) + fn(-1000) assert func() == 205", "b.num_deleted = 0 b.num_deleted_c = 0 class A(object): def __init__(self):", "t.config.set(**extraconfigopts) ann = t.buildannotator() ann.build_types(func, inputtypes) if specialize: t.buildrtyper().specialize() if", "type Ptr(Gc). # At the moment we get additional_roots_sources ==", "+ 2 class UnboxedObject(TaggedBase, UnboxedValue): __slots__ = 'smallint' def meth(self,", "ptr.chars[1] = 'B' ptr.chars[2] = 'C' ptr2 = rgc.ll_shrink_array(ptr, 2)", "= self.runner(\"finalizer_resurrects\") res = run([5, 42]) #XXX pure lazyness here", "512*WORD, 'nursery_size': 32*WORD, 'translated_to_c': False} root_stack_depth = 200 def test_gettypeid(self):", "S = lltype.GcStruct('S', ('x', lltype.Signed)) A = lltype.GcStruct('A', ('p', lltype.Ptr(S)),", "db def runner(self, name, transformer=False): db = self.db name_to_func =", "# is_finalizer_light Constant(False, lltype.Bool)] # contains_weakptr break else: assert 0,", "static = A() static.p = None def f(): t1 =", "class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.hybrid import HybridGC as GCClass GC_PARAMS =", "the moment, # which is important because the 'lst' can", "here, so no write barrier emitted res = rgc.can_move(annlowlevel.cast_instance_to_base_ptr(a)) rgc.collect()", "def f(): lst = lltype.malloc(A, 5) return (lst[0] == lltype.nullptr(S)", "a = [1] * 10 j = 0 while j", "cls.rtyper = t.rtyper cls.db = db def runner(self, name, transformer=False):", "rgc.ll_shrink_array(ptr, 2) return ((ptr == ptr2) + ord(ptr2.chars[0]) + (ord(ptr2.chars[1])", "512*WORD, 'nursery_size': 128*WORD, 'translated_to_c': False} root_stack_depth = 200 def define_working_nursery(cls):", "= 0 while i < 17: ref = weakref.ref(a) assert", "for i in range(len(args)): ll_args[1+i] = args[i] res = llinterp.eval_graph(entrygraph,", "root pointing to runtime # allocated stuff cleanups.append(cleanup) def entrypoint(args):", "lltype.malloc(S))) for i in range(50): assert l2[i] == l[50 +", "nt0 return 0 return f def test_adr_of_nursery(self): run = self.runner(\"adr_of_nursery\")", "varsized mallocs. lst.p = p return lst def f(i, j):", "translator): jit2gc = getattr(translator, '_jit2gc', None) if jit2gc: assert 'invoke_after_minor_collection'", "def define_tagged_prebuilt(cls): class F: pass f = F() f.l =", "= lltype.nullptr(T1) return f, cleanup, None def test_nongc_static_root_minor_collect(self): run =", "= Struct(\"S2\", ('x', Signed)) T2 = GcArray(S2) def f2(): t", "B() b.nextid = 0 b.num_deleted = 0 class AAA(object): def", "s = StringBuilder(4) s.append(\"abcd\") s.append(\"defg\") s.append(\"rty\") s.append_multiple_char('y', 1000) gc.collect() s.append_multiple_char('y',", "getattr(translator, '_jit2gc', None) if jit2gc: assert 'invoke_after_minor_collection' in jit2gc return", "gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.semispace import SemiSpaceGC as GCClass GC_PARAMS", "lltype.malloc(TP, 100) l2 = lltype.malloc(TP, 100) for i in range(100):", "lltype.Signed), Constant(False, lltype.Bool), # has_finalizer Constant(False, lltype.Bool), # is_finalizer_light Constant(False,", "0 return malloc_a_lot def test_instances(self): run = self.runner(\"instances\") run([]) def", "res = s.build()[1000] gc.collect() return ord(res) return fn def test_string_builder_over_allocation(self):", "Constant from rpython.rtyper.lltypesystem import rffi layoutbuilder = cls.ensure_layoutbuilder(translator) type_id =", "ll_args = lltype.malloc(ARGS, immortal=True) ll_args[0] = name_to_func[name] for i in", "run = self.runner(\"gc_heap_stats\") res = run([]) assert res % 10000", "used to let test cleanup static root pointing to runtime", "a = A() a.foo = x ref = weakref.ref(a) all", "result = len(\"\".join(lst)) if we_are_translated(): llop.gc__collect(lltype.Void, 0) return result return", "expected = 0x62024230 assert run([]) == expected def define_string_builder_over_allocation(cls): import", "= {'nursery_size': 32*WORD, 'page_size': 16*WORD, 'arena_size': 64*WORD, 'small_request_threshold': 5*WORD, 'large_object':", "run([]) assert res == 123 def define_nursery_hash_base(cls): class A: pass", "not count # the number of prebuilt GC objects, but", "persistent_a4.id # NB print would create a static root! llop.debug_print(lltype.Void,", "= 1 return t.s[0] def func(): return (f1() * 100000", "i += 1 a = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) aid =", "lst[15].x = 123 lst[0] = lst[15] # that would be", "- 1]) assert res == i - 1 # crashes", "6 def define_finalizer_calls_malloc(cls): class B(object): pass b = B() b.nextid", "self.runner(\"do_malloc_operations\") run([]) def define_do_malloc_operations_in_call(cls): P = lltype.GcStruct('P', ('x', lltype.Signed)) def", "from rpython.rlib.debug import ll_assert from rpython.rlib import rgc from rpython.conftest", "collection a = A() a.foo = x ref = weakref.ref(a)", "-1999 def define_gettypeid(cls): class A(object): pass def fn(): a =", "if not transformer.GCClass.prebuilt_gc_objects_are_static_roots: assert len(transformer.layoutbuilder.addresses_of_static_ptrs) == 0 else: assert len(transformer.layoutbuilder.addresses_of_static_ptrs)", "= self.runner(\"string_concatenation\") res = run([100, 0]) assert res == len(''.join([str(x)", "self.runner(\"finalizer_calls_malloc\") res = run([5, 42]) #XXX pure lazyness here too", "__del__(self): a.count += 1 def g(): b = B() return", "res = run([]) assert res == 111111 def define_id(cls): class", "return len(t.items) T6 = GcStruct(\"T6\", ('s', Array(Signed))) def f6(): t", "run, transformer = self.runner(\"immutable_to_old_promotion\", transformer=True) run([1, 4]) if not transformer.GCClass.prebuilt_gc_objects_are_static_roots:", "cleanup = None if isinstance(func_fixup, tuple): func, cleanup, fixup =", "malloc_a_lot def test_instances(self): run = self.runner(\"instances\") run([]) def define_llinterp_lists(cls): def", "4 # NB. Remember that the number above does not", "here is expected GenerationGC._teardown(self) GC_PARAMS = {'space_size': 512*WORD, 'nursery_size': 128*WORD,", "+= 1 return 0 return malloc_a_lot def test_instances(self): run =", "g) for op in graph.startblock.operations: if op.opname == 'do_malloc_fixedsize': op.args", "= A() persistent_a4 = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) b.bla = persistent_a1.id", "break else: assert 0, \"oups, not found\" return f, None,", "in range(20): x.append((1, lltype.malloc(S))) for i in range(50): assert l2[i]", "= 0 first = None while i < 10: i", "define_weakref_to_object_with_finalizer(cls): import weakref, gc class A(object): count = 0 a", "define_collect_during_collect(cls): class B(object): pass b = B() b.nextid = 1", "transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.semispace import SemiSpaceGC as GCClass GC_PARAMS = {'space_size':", "def setup(): rgc.register_custom_trace_hook(S, lambda_customtrace) tx = lltype.malloc(T) tx.z = 4243", "0 first = None while i < 10: i +=", "times res = run([4, 42]) #XXX pure lazyness here too", "i in range(len(tb)): if tb[i].count == 10: a += 1", "found\" return f, cleanup, fix_graph_of_g def test_do_malloc_operations(self): run = self.runner(\"do_malloc_operations\")", "result return f def test_weakref(self): run = self.runner(\"weakref\") res =", "is None) return result return f def test_weakref_to_object_with_finalizer(self): run =", "llop.gc__collect(lltype.Void) aid = b.a.id b.a = None # check that", "return f def test_weakref(self): run = self.runner(\"weakref\") res = run([])", "return f, cleanup, None def test_write_barrier_direct(self): run = self.runner(\"write_barrier_direct\") res", "taggedpointers = False def setup_class(cls): cls.marker = lltype.malloc(rffi.CArray(lltype.Signed), 1, flavor='raw',", "if the GC needs memory to # remember the ids,", "def seeme(): marker[0] += 1 translator._jit2gc = { 'layoutbuilder': layoutbuilder,", "nf0 = nf_a.address[0] nt0 = nt_a.address[0] a0 = A() a1", "s) llop.gc_writebarrier(lltype.Void, llmemory.cast_ptr_to_adr(s0)) rgc.collect(0) return s0.next.x def cleanup(): s0.next =", "g() i += 1 return 0 if cls.gcname == 'incminimark':", "run([]) assert res == 111111 def define_id(cls): class A(object): pass", "== lltype.nullptr(S) and lst[2] == lltype.nullptr(S) and lst[3] == lltype.nullptr(S)", "lst.p = p return lst def f(i, j): lst =", "None def test_write_barrier_direct(self): run = self.runner(\"write_barrier_direct\") res = run([]) assert", "# Compute the id of all the elements of the", "itself i = 0 while i < len(alist): idarray[i] =", "+ 3 class TestHybridTaggedPointerGC(TaggedPointerGCTests): gcname = \"hybrid\" class gcpolicy(gc.BasicFrameworkGcPolicy): class", "\"oups, not found\" return f, cleanup, fix_graph_of_g def test_do_malloc_operations(self): run", "a2 = A() a3 = A() id1 = compute_unique_id(a1) id2", "S = lltype.GcStruct('S', ('x', lltype.Signed), ('filed1', lltype.Ptr(S1)), ('filed2', lltype.Ptr(S1))) s0", "False, } root_stack_depth = 200 def define_malloc_array_of_gcptr(self): S = lltype.GcStruct('S',", "most allocated objects die quickly gcname = \"generation\" class gcpolicy(gc.BasicFrameworkGcPolicy):", "lltype.Signed)) A = lltype.GcArray(lltype.Ptr(S)) def sub(lst): lst[15] = lltype.malloc(S) #", "10: i += 1 a = [1] * 10 j", "= A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted return f def test_finalizer(self):", "teardowngraph = gct.frameworkgc__teardown_ptr.value._obj.graph llinterp.eval_graph(teardowngraph, []) self.__class__._used = True # FIIIIISH", "compute_unique_id(a2) id3 = compute_unique_id(a3) llop.gc__collect(lltype.Void) error = 0 if id1", "import LONG_BIT WORD = LONG_BIT // 8 def rtype(func, inputtypes,", "S = lltype.GcStruct('S', ('x', llmemory.Address)) T = lltype.GcStruct('T', ('z', lltype.Signed))", "b.nextid += 1 def __del__(self): b.num_deleted += 1 b.a =", "= entrypointptr._obj.graph if option.view: t.viewcg() cls.name_to_func = name_to_func cls.entrygraph =", "= malloc(T2, 1) t[0].x = 1 return t[0].x S3 =", "import rffi layoutbuilder = cls.ensure_layoutbuilder(translator) type_id = layoutbuilder.get_type_id(P) # #", "def test_finalizer(self): run = self.runner(\"finalizer\") res = run([5, 42]) #XXX", "T1 = GcStruct(\"T1\", ('s', S1)) def f1(): t = malloc(T1)", "<= res <= 165 def define_custom_trace(cls): # S = lltype.GcStruct('S',", "def test_many_ids(self): if not self.GC_CAN_TEST_ID: py.test.skip(\"fails for bad reasons in", "= run([]) assert res == 111111 def define_id(cls): class A(object):", "= child child.field = 3 parent2.sub = child2 child2.field =", "p return lst def f(i, j): lst = setup(j) gc.collect()", "def define_writebarrier_before_copy(cls): S = lltype.GcStruct('S', ('x', lltype.Char)) TP = lltype.GcArray(lltype.Ptr(S))", "# NB print would create a static root! llop.debug_print(lltype.Void, b.num_deleted_c)", "Struct(\"S4\", ('x', Signed)) T4 = Struct(\"T4\", ('s', S4)) U4 =", "for i in range(10): s = lltype.malloc(S) l1.append(s) l2.append(s) if", "= run([]) assert res == 84 def define_many_weakrefs(cls): # test", "return len(unique) return fn def test_nursery_hash_base(self): res = self.runner('nursery_hash_base') assert", "def define_malloc_struct_of_gcptr(cls): S1 = lltype.GcStruct('S', ('x', lltype.Signed)) S = lltype.GcStruct('S',", "f def test_weakref_to_object_with_finalizer(self): run = self.runner(\"weakref_to_object_with_finalizer\") res = run([]) assert", "f def test_weakref_across_minor_collection(self): run = self.runner(\"weakref_across_minor_collection\") res = run([]) assert", "def test_tagged_prebuilt(self): func = self.runner(\"tagged_prebuilt\") res = func([]) assert res", "graph = graphof(translator, g) for op in graph.startblock.operations: if op.opname", "id2 = compute_unique_id(a2) id3 = compute_unique_id(a3) llop.gc__collect(lltype.Void) error = 0", "not found\" return f, None, fix_graph_of_g def test_do_malloc_operations_in_call(self): run =", "(f1() * 100000 + f2() * 10000 + f3() *", "p.x def f(): i = 0 while i < 40:", "# test that nursery is doing its job and that", "the 'lst' can be allocated directly # in generation 2.", "10: i += 1 a = somea = A() a.last", "= Struct(\"S3\", ('x', Signed)) T3 = GcStruct(\"T3\", ('items', Array(S3))) def", "+= 1 a = (1, 2, i) b = {a:", "lst = lltype.malloc(A, 5) return (lst[0] == lltype.nullptr(S) and lst[1]", "c * 100 + b * 10 + a return", "def test_collect_during_collect(self): run = self.runner(\"collect_during_collect\") # runs collect recursively 4", "= entrygraph cls.rtyper = t.rtyper cls.db = db def runner(self,", "def test_global_list(self): py.test.skip(\"doesn't fit in the model, tested elsewhere too\")", "\"defined test functions should have 0/2 arguments\") # used to", "return (lst[0] == lltype.nullptr(S) and lst[1] == lltype.nullptr(S) and lst[2]", "* 100000 + f2() * 10000 + f3() * 1000", "1 def g(): b = B() return weakref.ref(b) def f():", "import compute_hash, compute_identity_hash from rpython.translator.c import gc from rpython.annotator import", "= '0' ptr.chars[1] = 'B' ptr.chars[2] = 'C' ptr2 =", "func([]) print res from rpython.rlib.objectmodel import UnboxedValue class TaggedBase(object): __slots__", "= 42 llop.bare_setfield(lltype.Void, s0, void('next'), s) llop.gc_writebarrier(lltype.Void, llmemory.cast_ptr_to_adr(s0)) rgc.collect(0) return", "s.append_multiple_char('y', 1000) gc.collect() s.append_multiple_char('y', 1000) res = s.build()[1000] gc.collect() return", "lst[15] # that would be a \"clean_setarrayitem\" def f(): lst", "res == -1999 def define_gettypeid(cls): class A(object): pass def fn():", "return f def test_finalizer_resurrects(self): run = self.runner(\"finalizer_resurrects\") res = run([5,", "+= 1 return 0 if cls.gcname == 'incminimark': marker =", "assert res == 12 def define_collect_0(cls): def concat(j, dummy): lst", "cleanup(): static.p = None return f, cleanup, None def test_static_root_minor_collect(self):", "rpython.memory.gc.generation import GenerationGC class GCClass(GenerationGC): __ready = False def setup(self):", "assert res # ________________________________________________________________ # tagged pointers class TaggedPointerGCTests(GCTest): taggedpointers", "= something def malloc_a_lot(): i = 0 first = None", "= 66 def __init__(self, normalint): self.normalint = normalint def meth(self,", "i - 1]) assert res == i - 1 #", "= lltype.malloc(rffi.SIGNEDP.TO, len(alist), flavor='raw') # Compute the id of all", "func_fixup func.func_name = \"f_%s\" % name if cleanup: cleanup.func_name =", "40: g() i += 1 return 0 if cls.gcname ==", "0, \"oups, not found\" return f, None, fix_graph_of_g def test_do_malloc_operations_in_call(self):", "rgc from rpython.conftest import option from rpython.rlib.rstring import StringBuilder from", "placeholder def f(): q = lltype.malloc(P) q.x = 1 i", "5*WORD, 'large_object': 8*WORD, 'card_page_indices': 4, 'translated_to_c': False, } root_stack_depth =", "entrypoint, config=t.config, gcpolicy=cls.gcpolicy) db = cbuild.generate_graphs_for_llinterp() entrypointptr = cbuild.getentrypointptr() entrygraph", "we_are_translated(): llop.gc__collect(lltype.Void, 0) return result return concat def test_collect_0(self): run", "= lltype.malloc(A, 5) return (lst[0] == lltype.nullptr(S) and lst[1] ==", "class GenericGCTests(GCTest): GC_CAN_SHRINK_ARRAY = False def define_instances(cls): class A(object): pass", "* all[1] # * parent.sub # * parent2.sub # *", "0 while i < 10: i += 1 a =", "self.runner(\"writebarrier_before_copy\") run([]) # ________________________________________________________________ class TestSemiSpaceGC(GenericMovingGCTests): gcname = \"semispace\" GC_CAN_SHRINK_ARRAY", "func def test_can_move(self): run = self.runner(\"can_move\") res = run([]) assert", "1 a = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted return f", "0 while i < x: # enough to cause a", "nursery is doing its job and that no full collection", "func = func_fixup func.func_name = \"f_%s\" % name if cleanup:", "< 10: i += 1 a = [1] * 10", "lltype.GcForwardReference() S.become(lltype.GcStruct('S', ('x', lltype.Signed), ('prev', lltype.Ptr(S)), ('next', lltype.Ptr(S)))) s0 =", "transformer=True) run([1, 4]) if not transformer.GCClass.prebuilt_gc_objects_are_static_roots: assert len(transformer.layoutbuilder.addresses_of_static_ptrs) == 0", "two iterations [A() for i in range(20)] i = 0", "op in graph.startblock.operations: if op.opname == 'do_malloc_fixedsize': op.args = [Constant(type_id,", "def f1(): t = malloc(T1) t.s.x = 1 return t.s.x", "a minor collection a = A() a.foo = x ref", "malloc(T3, 1) t.items[0].x = 1 return t.items[0].x S4 = Struct(\"S4\",", "self.name_to_func entrygraph = self.entrygraph from rpython.rtyper.llinterp import LLInterpreter llinterp =", "layoutbuilder, 'invoke_after_minor_collection': seeme, } return layoutbuilder def define_do_malloc_operations(cls): P =", "malloc(T5, 1) return len(t.items) T6 = GcStruct(\"T6\", ('s', Array(Signed))) def", "import weakref class A: pass def f(): x = 20", "= self.runner(\"malloc_struct_of_gcptr\") res = run([]) assert res # ________________________________________________________________ #", "f def test_finalizer_calls_malloc(self): run = self.runner(\"finalizer_calls_malloc\") res = run([5, 42])", "def define_llinterp_dict(self): class A(object): pass def malloc_a_lot(): i = 0", "== 6: # * all[0] # * all[1] # *", "graph of g graph = graphof(translator, g) for op in", "0 e = 0 for i in range(len(tb)): if tb[i].count", "test_string_builder_over_allocation(self): fn = self.runner(\"string_builder_over_allocation\") res = fn([]) assert res ==", "== 40 * 5 class TestHybridGC(TestGenerationGC): gcname = \"hybrid\" class", "= setup(j) gc.collect() return lst.p.x return f def test_ref_from_rawmalloced_to_regular(self): run", "u.x = UnboxedObject(47) def fn(n): rgc.collect() # check that a", "('items', Array(S5))) def f5(): t = malloc(T5, 1) return len(t.items)", "model as annmodel from rpython.rtyper.llannotation import SomePtr from rpython.rtyper.lltypesystem import", "res return fn def test_instantiate_nonmovable(self): res = self.runner('instantiate_nonmovable') assert res([])", "class UnboxedObject(TaggedBase, UnboxedValue): __slots__ = 'smallint' def meth(self, x): return", "a = (1, 2, i) b = {a: A()} j", "= g() llop.gc__collect(lltype.Void) result = result and (ref() is None)", "Array, Signed, malloc S1 = Struct(\"S1\", ('x', Signed)) T1 =", "test\") def _teardown(self): self.__ready = False # collecting here is", "i in range(200): rgc.collect(0) # nursery-only collection, if possible obj", "assert ref() is a i += 1 return 0 return", "here too assert res == 12 def define_collect_0(cls): def concat(j,", "[]) self.__class__._used = True # FIIIIISH setupgraph = gct.frameworkgc_setup_ptr.value._obj.graph #", "T_CHILD))) child = lltype.malloc(T_CHILD.TO) child2 = lltype.malloc(T_CHILD.TO) parent = lltype.malloc(T_PARENT.TO)", "= self.runner(\"shrink_array\") if self.GC_CAN_SHRINK_ARRAY: expected = 0x62024231 else: expected =", "return error return func def test_id(self): run = self.runner(\"id\") res", "= self.runner(\"many_weakrefs\") run([]) def define_immutable_to_old_promotion(cls): T_CHILD = lltype.Ptr(lltype.GcStruct('Child', ('field', lltype.Signed)))", "# At the moment we get additional_roots_sources == 6: #", "__del__(self): b.num_deleted += 1 def f(x, y): a = A()", "range(50)] idarray = lltype.malloc(rffi.SIGNEDP.TO, len(alist), flavor='raw') # Compute the id", "if func: res = func() else: func = funcs2[num] res", "return f def test_no_clean_setarrayitems(self): run = self.runner(\"no_clean_setarrayitems\") res = run([])", "+ f4() * 100 + f5() * 10 + f6())", "define_write_barrier_direct(cls): from rpython.rlib import rgc S = lltype.GcForwardReference() S.become(lltype.GcStruct('S', ('x',", "funcs0[num] if func: res = func() else: func = funcs2[num]", "None def f(): t1 = B() t1.x = 42 static.p", "False taggedpointers = False def setup_class(cls): cls.marker = lltype.malloc(rffi.CArray(lltype.Signed), 1,", "= lltype.malloc(T) tx.z = 4243 s1 = lltype.malloc(S) s1.x =", "t[0].x S3 = Struct(\"S3\", ('x', Signed)) T3 = GcStruct(\"T3\", ('items',", "= name_to_func[name] for i in range(len(args)): ll_args[1+i] = args[i] res", "f(): from rpython.rtyper.lltypesystem import rffi alist = [A() for i", "= 0 class AAA(object): def __init__(self): self.id = b.nextid b.nextid", "rffi layoutbuilder = cls.ensure_layoutbuilder(translator) type_id = layoutbuilder.get_type_id(P) # # now", "e += tb[i].size return d * 1000 + c *", "The optimization find_clean_setarrayitems() in # gctransformer/framework.py does not work with", "= func([]) assert res == -1999 def define_gettypeid(cls): class A(object):", "llop.bare_setfield(lltype.Void, s0, void('next'), s) llop.gc_writebarrier(lltype.Void, llmemory.cast_ptr_to_adr(s0)) rgc.collect(0) return s0.next.x def", "generation 2. This can only occur with varsized mallocs. lst.p", "def define_nongc_static_root(cls): T1 = lltype.GcStruct(\"C\", ('x', lltype.Signed)) T2 = lltype.Struct(\"C\",", "MiniMarkGC as GCClass GC_PARAMS = {'nursery_size': 32*WORD, 'page_size': 16*WORD, 'arena_size':", "b.nextid += 1 def __del__(self): b.num_deleted += 1 def f(x,", "lltype.Ptr(lltype.GcStruct('Child', ('field', lltype.Signed))) T_PARENT = lltype.Ptr(lltype.GcStruct('Parent', ('sub', T_CHILD))) child =", "def f6(): t = malloc(T6, 1) t.s[0] = 1 return", "llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return b.num_deleted return f def test_finalizer_calls_malloc(self): run =", "import Struct, GcStruct, GcArray from rpython.rtyper.lltypesystem.lltype import Array, Signed, malloc", "1 def f(x, y): persistent_a1 = A() persistent_a2 = A()", "fix_graph_of_g def test_do_malloc_operations_in_call(self): run = self.runner(\"do_malloc_operations_in_call\") run([]) def define_gc_heap_stats(cls): S", "fn(): l = lltype.malloc(TP, 100) l2 = lltype.malloc(TP, 100) for", "only occur with varsized mallocs. lst.p = p return lst", "^ fn(-1000) assert func() == -1999 return func def test_tagged_prebuilt(self):", "= 200 class TestGenerationGC(GenericMovingGCTests): gcname = \"generation\" GC_CAN_SHRINK_ARRAY = True", "while i < x: all[i] = [i] * i i", "ref() is a llop.gc__collect(lltype.Void) assert ref() is a return a.foo", "cleanup, None def test_static_root_minor_collect(self): run = self.runner(\"static_root_minor_collect\") res = run([])", "so no write barrier emitted res = rgc.can_move(annlowlevel.cast_instance_to_base_ptr(a)) rgc.collect() objectmodel.keepalive_until_here(a)", "0 marker[0] = 0 else: cleanup = None def fix_graph_of_g(translator):", "test_many_weakrefs(self): run = self.runner(\"many_weakrefs\") run([]) def define_immutable_to_old_promotion(cls): T_CHILD = lltype.Ptr(lltype.GcStruct('Child',", "= lltype.GcStruct('S', ('x', lltype.Signed)) A = lltype.GcStruct('A', ('p', lltype.Ptr(S)), ('a',", "do_malloc_fixedsize in the graph of g graph = graphof(translator, g)", "pass static = A() static.p = None def f(): t1", "func(): return fn(1000) ^ fn(-1000) assert func() == -1999 return", "in jit2gc return jit2gc['layoutbuilder'] marker = cls.marker GCClass = cls.gcpolicy.transformerclass.GCClass", "somea = A() a.last = first first = a j", "so that if the GC needs memory to # remember", "allocate a nursery a = A() nf_a = llop.gc_adr_of_nursery_free(llmemory.Address) nt_a", "__ready = False def setup(self): from rpython.memory.gc.generation import GenerationGC GenerationGC.setup(self)", "== hashes[i] unique[hashes[i]] = None return len(unique) return fn def", "x: i += 1 a = AAA() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) return", "+ f6()) assert func() == 111111 return func def test_interior_ptrs(self):", "f(): ptr = lltype.malloc(STR, 3) ptr.hash = 0x62 ptr.chars[0] =", "g graph = graphof(translator, g) for op in graph.startblock.operations: if", "def test_malloc_struct_of_gcptr(self): run = self.runner(\"malloc_struct_of_gcptr\") res = run([]) assert res", "self.runner(\"gettypeid\") res = func([]) print res from rpython.rlib.objectmodel import UnboxedValue", "self.__ready, \"no full collect should occur in this test\") def", "= [] l2 = [] l3 = [] l4 =", "False} root_stack_depth = 200 def define_weakref_across_minor_collection(cls): import weakref class A:", "should occur in this test\") def _teardown(self): self.__ready = False", "1 return total return f def test_working_nursery(self): run = self.runner(\"working_nursery\")", "y): res = all[x] #all[x] = lltype.nullptr(T_PARENT.TO) return res.sub.field return", "and s0.filed2 == lltype.nullptr(S1)) return f def test_malloc_struct_of_gcptr(self): run =", "not work with card marking. # Check that it is", "transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import GenerationGC class GCClass(GenerationGC): __ready = False", "that no full collection # is needed when most allocated", "b.num_deleted += 1 def f(x, y): a = AAA() i", "res = run([100, 100]) assert res == 200 def define_write_barrier_direct(cls):", "fn(-1000) assert func() == 205 return func def test_tagged_simple(self): func", "gct.frameworkgc__teardown_ptr.value._obj.graph llinterp.eval_graph(teardowngraph, []) self.__class__._used = True # FIIIIISH setupgraph =", "llop.gc__collect(lltype.Void) return static.p.x + i def cleanup(): static.p = lltype.nullptr(T1)", "range(len(objects)): assert compute_identity_hash(objects[i]) == hashes[i] unique[hashes[i]] = None return len(unique)", "transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.minimark import MiniMarkGC as GCClass GC_PARAMS = {'nursery_size':", "which we later on # process ourselves, otherwise this test", "= [UnboxedObject(10)] def fn(n): if n > 0: x =", "class B(object): pass b = B() b.nextid = 1 b.num_deleted", "NB. Remember that the number above does not count #", "# enough to cause a minor collect all[i] = [i]", "= () def meth(self, x): raise NotImplementedError class BoxedObject(TaggedBase): attrvalue", "immortal=True) ll_args[0] = name_to_func[name] for i in range(len(args)): ll_args[1+i] =", "self.normalint = normalint def meth(self, x): return self.normalint + x", "rgc.get_typeid(a) return fn def test_gettypeid(self): func = self.runner(\"gettypeid\") res =", "collection # is needed when most allocated objects die quickly", "reasons in lltype.py :-(\") run = self.runner(\"many_ids\") run([]) @classmethod def", "first first = a j = 0 while j <", "def define_finalizer(cls): class B(object): pass b = B() b.nextid =", "= A() def func(): a2 = A() a3 = A()", "class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.semispace import SemiSpaceGC as GCClass", "= i if tb[i].count > 50: d += 1 for", "dummy): lst = [] for i in range(j): lst.append(str(i)) result", "error = 0 if id1 != compute_unique_id(a1): error += 1", "q = lltype.malloc(P) q.x = 1 i = 0 while", "== lltype.nullptr(S1) and s0.filed2 == lltype.nullptr(S1)) return f def test_malloc_struct_of_gcptr(self):", "lltype.nullptr(T1) return f, cleanup, None def test_nongc_static_root(self): run = self.runner(\"nongc_static_root\")", "return f def test_adr_of_nursery(self): run = self.runner(\"adr_of_nursery\") res = run([])", "< 17: ref = weakref.ref(a) assert ref() is a i", "16) # 16 > 10 rgc.collect() sub(lst) null = lltype.nullptr(S)", "lambda_customtrace = lambda: customtrace # def setup(): rgc.register_custom_trace_hook(S, lambda_customtrace) tx", "we later on # process ourselves, otherwise this test takes", "import GenerationGC class GCClass(GenerationGC): __ready = False def setup(self): from", "i += q.x return 0 def fix_graph_of_g(translator): from rpython.translator.translator import", "= 'B' ptr.chars[2] = 'C' ptr2 = rgc.ll_shrink_array(ptr, 2) return", "# clear, so that A() is only visible via lst[0]", "sub(lst) null = lltype.nullptr(S) lst[15] = null # clear, so", "A(object): pass class B(A): def __init__(self, something): self.something = something", "some stuff between the two iterations [A() for i in", "= LONG_BIT // 8 def rtype(func, inputtypes, specialize=True, gcname='ref', backendopt=False,", "class F: pass f = F() f.l = [UnboxedObject(10)] def", "= lltype.GcArray(lltype.Ptr(S)) def sub(lst): lst[15] = lltype.malloc(S) # 'lst' is", "0 for i in range(len(tb)): if tb[i].count == 10: a", "== 1: # allocate some stuff between the two iterations", "lltype.malloc(ARGS, immortal=True) ll_args[0] = name_to_func[name] for i in range(len(args)): ll_args[1+i]", "# placeholder def f(): q = lltype.malloc(P) q.x = 1", "gct = db.gctransformer if self.__class__.__dict__.get('_used', False): teardowngraph = gct.frameworkgc__teardown_ptr.value._obj.graph llinterp.eval_graph(teardowngraph,", "i) b = {a: A()} j = 0 while j", "1 lltype.free(idarray, flavor='raw') return 0 return f def test_many_ids(self): if", "= malloc(T3, 1) t.items[0].x = 1 return t.items[0].x S4 =", "return ord(res) return fn def test_string_builder_over_allocation(self): fn = self.runner(\"string_builder_over_allocation\") res", "None return f, cleanup, None def test_static_root_minor_collect(self): run = self.runner(\"static_root_minor_collect\")", "def test_finalizer_calls_malloc(self): run = self.runner(\"finalizer_calls_malloc\") res = run([5, 42]) #XXX", "= lltype.malloc(S) s1.x = llmemory.cast_ptr_to_adr(tx) return s1 def f(): s1", "define_do_malloc_operations(cls): P = lltype.GcStruct('P', ('x', lltype.Signed)) def g(): r =", "needs memory to # remember the ids, it will trigger", "triggers # a collection import weakref class A: pass def", "Constant(False, lltype.Bool), # has_finalizer Constant(False, lltype.Bool), # is_finalizer_light Constant(False, lltype.Bool)]", "# runs collect recursively 4 times res = run([4, 42])", "lltype.Signed)) def g(): llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder def f(): q =", "self.runner(\"ref_from_rawmalloced_to_regular\") res = run([100, 100]) assert res == 200 def", "= 1 return t[0].x S3 = Struct(\"S3\", ('x', Signed)) T3", "lltype.malloc(S) s.x = 42 llop.bare_setfield(lltype.Void, s0, void('next'), s) llop.gc_writebarrier(lltype.Void, llmemory.cast_ptr_to_adr(s0))", "i = 0 while i < 40: g() i +=", "lltype.malloc(S, immortal=True) def f(): s = lltype.malloc(S) s.x = 42", "= B(somea) b.last = first j += 1 return 0", "def append_to_list(i, j): box.lst.append([i] * 50) llop.gc__collect(lltype.Void) return box.lst[j][0] return", "-1999 return func def test_tagged_prebuilt(self): func = self.runner(\"tagged_prebuilt\") res =", "nursery a = A() nf_a = llop.gc_adr_of_nursery_free(llmemory.Address) nt_a = llop.gc_adr_of_nursery_top(llmemory.Address)", "that a further collection is fine llop.gc__collect(lltype.Void) result = result", "(1, 2, i) b = [a] * 10 j =", "rpython.rtyper.lltypesystem import rffi layoutbuilder = cls.ensure_layoutbuilder(translator) type_id = layoutbuilder.get_type_id(P) #", "None def test_nongc_static_root_minor_collect(self): run = self.runner(\"nongc_static_root_minor_collect\") res = run([]) assert", "CStandaloneBuilder(t, entrypoint, config=t.config, gcpolicy=cls.gcpolicy) db = cbuild.generate_graphs_for_llinterp() entrypointptr = cbuild.getentrypointptr()", "run = self.runner(\"collect_during_collect\") # runs collect recursively 4 times res", "malloc(T2, 1) t[0].x = 1 return t[0].x S3 = Struct(\"S3\",", "= 1 p = llop.do_malloc_fixedsize(llmemory.GCREF) # placeholder p = lltype.cast_opaque_ptr(lltype.Ptr(P),", "cbuild.generate_graphs_for_llinterp() entrypointptr = cbuild.getentrypointptr() entrygraph = entrypointptr._obj.graph if option.view: t.viewcg()", "model, tested elsewhere too\") run = self.runner(\"global_list\") res = run([0,", "2) return ((ptr == ptr2) + ord(ptr2.chars[0]) + (ord(ptr2.chars[1]) <<", "# * parent.sub # * parent2.sub # * the GcArray", "= 0 while i < 40: lst = [] j", "f(): a = A() i = 0 while i <", "__init__(self, normalint): self.normalint = normalint def meth(self, x): return self.normalint", "= self.runner(\"global_list\") res = run([0, 0]) assert res == 0", "1 def __del__(self): b.num_deleted += 1 def f(x, y): a", "+ a return f def test_gc_heap_stats(self): py.test.skip(\"this test makes the", "= nt_a.address[0] assert nf1 > nf0 assert nt1 > nf1", "import option from rpython.rlib.rstring import StringBuilder from rpython.rlib.rarithmetic import LONG_BIT", "False} root_stack_depth = 200 class TestGenerationGC(GenericMovingGCTests): gcname = \"generation\" GC_CAN_SHRINK_ARRAY", "run = self.runner(\"static_root_minor_collect\") res = run([]) assert res == 84", "import SemiSpaceGC as GCClass GC_PARAMS = {'space_size': 512*WORD, 'translated_to_c': False}", "GC objects that are of type Ptr(Gc). # At the", "return fn def test_gettypeid(self): func = self.runner(\"gettypeid\") res = func([])", "cleanup, fix_graph_of_g def test_do_malloc_operations(self): run = self.runner(\"do_malloc_operations\") run([]) def define_do_malloc_operations_in_call(cls):", "i < x: # enough to cause a minor collect", "of type Ptr(Gc). # At the moment we get additional_roots_sources", "= SomePtr(lltype.Ptr(ARGS)) t = rtype(entrypoint, [s_args], gcname=cls.gcname, taggedpointers=cls.taggedpointers) for fixup", "assert res == 42 def define_finalizer(cls): class B(object): pass b", "nf1 > nf0 assert nt1 > nf1 assert nt1 ==", "= lltype.GcStruct('S', ('x', lltype.Signed)) l1 = [] l2 = []", "4]) if not transformer.GCClass.prebuilt_gc_objects_are_static_roots: assert len(transformer.layoutbuilder.addresses_of_static_ptrs) == 0 else: assert", "lltype.GcStruct('T', ('z', lltype.Signed)) offset_of_x = llmemory.offsetof(S, 'x') def customtrace(gc, obj,", "== 12 def define_collect_0(cls): def concat(j, dummy): lst = []", "i in range(20)] i = 0 while i < len(alist):", "malloc_a_lot(): i = 0 while i < 10: i +=", "0 class TestIncrementalMiniMarkGC(TestMiniMarkGC): gcname = \"incminimark\" class gcpolicy(gc.BasicFrameworkGcPolicy): class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer):", "run = self.runner(\"weakref_across_minor_collection\") res = run([]) assert res == 20", "= db def runner(self, name, transformer=False): db = self.db name_to_func", "= 0 c = 0 d = 0 e =", "lltype.GcArray(lltype.Ptr(S)) def f(): lst = lltype.malloc(A, 5) return (lst[0] ==", "cls.db = db def runner(self, name, transformer=False): db = self.db", "args[2]) cleanup = cleanups[num] if cleanup: cleanup() return res from", "len(transformer.layoutbuilder.addresses_of_static_ptrs) == 0 else: assert len(transformer.layoutbuilder.addresses_of_static_ptrs) >= 4 # NB.", "def test_weakref(self): run = self.runner(\"weakref\") res = run([]) assert res", "= Struct(\"S4\", ('x', Signed)) T4 = Struct(\"T4\", ('s', S4)) U4", "f3(): t = malloc(T3, 1) t.items[0].x = 1 return t.items[0].x", "collecting here is expected GenerationGC._teardown(self) GC_PARAMS = {'space_size': 512*WORD, 'nursery_size':", "setup_class(cls): cls.marker = lltype.malloc(rffi.CArray(lltype.Signed), 1, flavor='raw', zero=True) funcs0 = []", "0: x = BoxedObject(n) else: x = UnboxedObject(n) f.l.append(x) rgc.collect()", "1 a = A() llop.gc__collect(lltype.Void) llop.gc__collect(lltype.Void) aid = b.a.id b.a", "crude assumption that totsize - varsize would be dividable by", "1 a = (1, 2, i) b = {a: A()}", "= run([100, 0]) assert res == len(''.join([str(x) for x in", "# * parent2.sub # * the GcArray pointer from gc.wr_to_objects_with_id", "0 return malloc_a_lot def test_llinterp_dict(self): run = self.runner(\"llinterp_dict\") run([]) def", "parent all[1] = parent2 def f(x, y): res = all[x]", "= lltype.GcStruct('S', ('x', lltype.Signed)) S = lltype.GcStruct('S', ('x', lltype.Signed), ('filed1',", "111111 def define_id(cls): class A(object): pass a1 = A() def", "== 0 else: assert len(transformer.layoutbuilder.addresses_of_static_ptrs) >= 4 # NB. Remember", "run([]) assert res == 0 def define_can_move(cls): TP = lltype.GcArray(lltype.Float)", "def define_string_builder_over_allocation(cls): import gc def fn(): s = StringBuilder(4) s.append(\"abcd\")", "= 0 while i < x: # enough to cause", "test crash. Investigate.\") run = self.runner(\"gc_heap_stats\") res = run([]) assert", "= 0 while i < 40: g() i += 1", "makes the following test crash. Investigate.\") run = self.runner(\"gc_heap_stats\") res", "class transformerclass(shadowstack.ShadowStackFrameworkGCTransformer): from rpython.memory.gc.generation import GenerationGC as \\ GCClass GC_PARAMS", "error += 1 if id2 != compute_unique_id(a2): error += 2", "id1 = compute_unique_id(a1) id2 = compute_unique_id(a2) id3 = compute_unique_id(a3) llop.gc__collect(lltype.Void)", "test cleanup static root pointing to runtime # allocated stuff" ]
[ "utils from . import display from . import save from", "from . import save from . import FFTW from .", ". import display from . import save from . import", "import display from . import save from . import FFTW", "save from . import FFTW from . import stackregistration __version__=\"0.2.1\"", "display from . import save from . import FFTW from", "from . import display from . import save from .", ". import save from . import FFTW from . import", ". import utils from . import display from . import", "import save from . import FFTW from . import stackregistration", "import utils from . import display from . import save", "from . import utils from . import display from ." ]
[ "considers them all) compute_on_step: Forward only calls ``update()`` and return", ">>> indexes = tensor([0, 0, 0, 1, 1, 1, 1])", "only float tensors res.append(self._metric(mini_preds, mini_target)) return B.stack([x.to(preds) for x in", "1, 1, 1]) >>> preds = tensor([0.2, 0.3, 0.5, 0.1,", "with binary target data. Accepts float predictions from a model", "2.0 (the \"License\"); # you may not use this file", "or an integer larger than 0 Example: >>> from torchmetrics", "groups = get_group_indexes(indexes) for group in groups: mini_preds = preds[group]", "predictions from a model output. Forward accepts: - ``preds`` (float", "from pangu.core.backend import Tensor, tensor from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out from", "output. Forward accepts: - ``preds`` (float tensor): ``(N, ...)`` -", "which query a prediction belongs. Predictions will be first grouped", "query (default: None, which considers them all) compute_on_step: Forward only", "skipped, ``0.0`` is returned - ``'error'``: raise a ``ValueError`` k:", "perform the allgather. default: None Raises: ValueError: If ``k`` parameter", "torchmetrics.retrieval.retrieval_metric import RetrievalMetric from torchmetrics.utilities.data import get_group_indexes class RetrievalFallOut(RetrievalMetric): \"\"\"Computes", "will be computed as the mean of the `Fall-out` over", "from: - ``'neg'``: those queries count as ``0.0`` (default) -", "if res else tensor(0.0).to(preds) def _metric(self, preds: Tensor, target: Tensor)", "preds: Tensor, target: Tensor) -> Tensor: return retrieval_fall_out(preds, target, k=self.k)", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "group on which synchronization is called. default: None (which selects", "targets is at least 1, otherwise behave as specified by", "``'pos'``: those queries count as ``1.0`` - ``'skip'``: skip those", "larger than 0 Example: >>> from torchmetrics import RetrievalFallOut >>>", "``ValueError`` k: consider only the top k elements for each", "= tensor([False, False, True, False, True, False, True]) >>> fo", "k: int = None, compute_on_step: bool = True, dist_sync_on_step: bool", "not (1 - mini_target).sum(): if self.empty_target_action == \"error\": raise ValueError(\"`compute`", "the step. default: False process_group: Specify the process group on", "and return None if this is set to False. default:", "0.5, 0.1, 0.3, 0.5, 0.2]) >>> target = tensor([False, False,", "bool = True, dist_sync_on_step: bool = False, process_group: Optional[Any] =", "language governing permissions and # limitations under the License. from", "k > 0): raise ValueError(\"`k` has to be a positive", "data. Accepts float predictions from a model output. Forward accepts:", "pangu.core.backend import Tensor, tensor from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out from torchmetrics.retrieval.retrieval_metric", ") if (k is not None) and not (isinstance(k, int)", "use this file except in compliance with the License. #", "def __init__( self, empty_target_action: str = \"pos\", k: int =", "# limitations under the License. from typing import Any, Callable,", "the allgather. default: None Raises: ValueError: If ``k`` parameter is", "binary target data. Accepts float predictions from a model output.", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "- ``'skip'``: skip those queries; if all queries are skipped,", "process_group=process_group, dist_sync_fn=dist_sync_fn, ) if (k is not None) and not", "only calls ``update()`` and return None if this is set", "return None if this is set to False. default: True", "License. # You may obtain a copy of the License", "`self.empty_target_action`. \"\"\" indexes = B.cat(self.indexes, dim=0) preds = B.cat(self.preds, dim=0)", "only the top k elements for each query (default: None,", "ensure list containt only float tensors res.append(self._metric(mini_preds, mini_target)) return B.stack([x.to(preds)", "group in groups: mini_preds = preds[group] mini_target = target[group] if", "RetrievalFallOut >>> indexes = tensor([0, 0, 0, 1, 1, 1,", "= [] groups = get_group_indexes(indexes) for group in groups: mini_preds", "groups: mini_preds = preds[group] mini_target = target[group] if not (1", "under the License is distributed on an \"AS IS\" BASIS,", "preds = B.cat(self.preds, dim=0) target = B.cat(self.target, dim=0) res =", "Forward only calls ``update()`` and return None if this is", "as ``1.0`` - ``'skip'``: skip those queries; if all queries", "each group compute the `_metric` if the number of negative", "License for the specific language governing permissions and # limitations", "groups that will help in keeping together predictions about the", "``preds`` (float tensor): ``(N, ...)`` - ``target`` (long or bool", "world) dist_sync_fn: Callback that performs the allgather operation on the", "res]).mean() if res else tensor(0.0).to(preds) def _metric(self, preds: Tensor, target:", "default: True dist_sync_on_step: Synchronize metric state across processes at each", "Optional[Any] = None, dist_sync_fn: Callable = None, ) -> None:", "a positive integer or None\") self.k = k def compute(self)", "target data. Accepts float predictions from a model output. Forward", "bool = False, process_group: Optional[Any] = None, dist_sync_fn: Callable =", "behave as specified by `self.empty_target_action`. \"\"\" indexes = B.cat(self.indexes, dim=0)", "from a model output. Forward accepts: - ``preds`` (float tensor):", "Finally, for each group compute the `_metric` if the number", "in compliance with the License. # You may obtain a", "0.1, 0.3, 0.5, 0.2]) >>> target = tensor([False, False, True,", "from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out from torchmetrics.retrieval.retrieval_metric import RetrievalMetric from torchmetrics.utilities.data", "count as ``0.0`` (default) - ``'pos'``: those queries count as", "software # distributed under the License is distributed on an", "indexes = B.cat(self.indexes, dim=0) preds = B.cat(self.preds, dim=0) target =", "- ``indexes`` (long tensor): ``(N, ...)`` ``indexes``, ``preds`` and ``target``", "get_group_indexes(indexes) for group in groups: mini_preds = preds[group] mini_target =", "is not `None` or an integer larger than 0 Example:", "provided with a query with no negative target.\") if self.empty_target_action", "has to be a positive integer or None\") self.k =", "for x in res]).mean() if res else tensor(0.0).to(preds) def _metric(self,", "dist_sync_fn: Callback that performs the allgather operation on the metric", "and not (isinstance(k, int) and k > 0): raise ValueError(\"`k`", "indexes = tensor([0, 0, 0, 1, 1, 1, 1]) >>>", "each ``forward()`` before returning the value at the step. default:", "target = tensor([False, False, True, False, True, False, True]) >>>", "import get_group_indexes class RetrievalFallOut(RetrievalMetric): \"\"\"Computes `Fall-out`_. Works with binary target", "on the metric state. When `None`, DDP will be used", "about the same query. Finally, for each group compute the", "stored as lists. After that, compute list of groups that", "-> None: super().__init__( empty_target_action=empty_target_action, compute_on_step=compute_on_step, dist_sync_on_step=dist_sync_on_step, process_group=process_group, dist_sync_fn=dist_sync_fn, ) if", "def compute(self) -> Tensor: \"\"\"First concat state `indexes`, `preds` and", "tensor([0, 0, 0, 1, 1, 1, 1]) >>> preds =", "B.cat(self.preds, dim=0) target = B.cat(self.target, dim=0) res = [] groups", "None\") self.k = k def compute(self) -> Tensor: \"\"\"First concat", "(long tensor): ``(N, ...)`` ``indexes``, ``preds`` and ``target`` must have", "otherwise behave as specified by `self.empty_target_action`. \"\"\" indexes = B.cat(self.indexes,", "the value at the step. default: False process_group: Specify the", "1, 1]) >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3,", "specified by `self.empty_target_action`. \"\"\" indexes = B.cat(self.indexes, dim=0) preds =", "= B.cat(self.preds, dim=0) target = B.cat(self.target, dim=0) res = []", "indexes=indexes) tensor(0.5000) \"\"\" higher_is_better = False def __init__( self, empty_target_action:", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "first grouped by ``indexes`` and then `Fall-out` will be computed", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "if self.empty_target_action == \"pos\": res.append(tensor(1.0)) elif self.empty_target_action == \"neg\": res.append(tensor(0.0))", "``indexes``, ``preds`` and ``target`` must have the same dimension. ``indexes``", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "performs the allgather operation on the metric state. When `None`,", "tensor): ``(N, ...)`` ``indexes``, ``preds`` and ``target`` must have the", "to in writing, software # distributed under the License is", "``0.0`` (default) - ``'pos'``: those queries count as ``1.0`` -", "# See the License for the specific language governing permissions", "process_group: Specify the process group on which synchronization is called.", "or agreed to in writing, software # distributed under the", "query. Args: empty_target_action: Specify what to do with queries that", "required by applicable law or agreed to in writing, software", "grouped by ``indexes`` and then `Fall-out` will be computed as", "same query. Finally, for each group compute the `_metric` if", "torchmetrics import RetrievalFallOut >>> indexes = tensor([0, 0, 0, 1,", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "with the License. # You may obtain a copy of", "belongs. Predictions will be first grouped by ``indexes`` and then", "skip those queries; if all queries are skipped, ``0.0`` is", "if the number of negative targets is at least 1,", "under the License. from typing import Any, Callable, Optional import", "RetrievalMetric from torchmetrics.utilities.data import get_group_indexes class RetrievalFallOut(RetrievalMetric): \"\"\"Computes `Fall-out`_. Works", "since they were stored as lists. After that, compute list", "parameter is not `None` or an integer larger than 0", "torchmetrics.utilities.data import get_group_indexes class RetrievalFallOut(RetrievalMetric): \"\"\"Computes `Fall-out`_. Works with binary", "concat state `indexes`, `preds` and `target` since they were stored", "= preds[group] mini_target = target[group] if not (1 - mini_target).sum():", "int) and k > 0): raise ValueError(\"`k` has to be", "value at the step. default: False process_group: Specify the process", "compliance with the License. # You may obtain a copy", "returned - ``'error'``: raise a ``ValueError`` k: consider only the", "`Fall-out` over each query. Args: empty_target_action: Specify what to do", "agreed to in writing, software # distributed under the License", "= False, process_group: Optional[Any] = None, dist_sync_fn: Callable = None,", "negative ``target``. Choose from: - ``'neg'``: those queries count as", "returning the value at the step. default: False process_group: Specify", "distributed under the License is distributed on an \"AS IS\"", "those queries count as ``0.0`` (default) - ``'pos'``: those queries", "False, True, False, True]) >>> fo = RetrievalFallOut(k=2) >>> fo(preds,", "import RetrievalMetric from torchmetrics.utilities.data import get_group_indexes class RetrievalFallOut(RetrievalMetric): \"\"\"Computes `Fall-out`_.", "queries count as ``0.0`` (default) - ``'pos'``: those queries count", "``'skip'``: skip those queries; if all queries are skipped, ``0.0``", "import Tensor, tensor from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out from torchmetrics.retrieval.retrieval_metric import", "mini_target)) return B.stack([x.to(preds) for x in res]).mean() if res else", "Synchronize metric state across processes at each ``forward()`` before returning", "None if this is set to False. default: True dist_sync_on_step:", "and # limitations under the License. from typing import Any,", "Copyright The PyTorch Lightning team. # # Licensed under the", "dimension. ``indexes`` indicate to which query a prediction belongs. Predictions", "express or implied. # See the License for the specific", "list containt only float tensors res.append(self._metric(mini_preds, mini_target)) return B.stack([x.to(preds) for", "tensor(0.5000) \"\"\" higher_is_better = False def __init__( self, empty_target_action: str", "except in compliance with the License. # You may obtain", "state `indexes`, `preds` and `target` since they were stored as", "True]) >>> fo = RetrievalFallOut(k=2) >>> fo(preds, target, indexes=indexes) tensor(0.5000)", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "empty_target_action=empty_target_action, compute_on_step=compute_on_step, dist_sync_on_step=dist_sync_on_step, process_group=process_group, dist_sync_fn=dist_sync_fn, ) if (k is not", "not use this file except in compliance with the License.", "``update()`` and return None if this is set to False.", "raise ValueError(\"`k` has to be a positive integer or None\")", "containt only float tensors res.append(self._metric(mini_preds, mini_target)) return B.stack([x.to(preds) for x", "all queries are skipped, ``0.0`` is returned - ``'error'``: raise", "writing, software # distributed under the License is distributed on", "(isinstance(k, int) and k > 0): raise ValueError(\"`k` has to", "License. from typing import Any, Callable, Optional import pangu.core.backend as", "you may not use this file except in compliance with", "`None` or an integer larger than 0 Example: >>> from", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "\"error\": raise ValueError(\"`compute` method was provided with a query with", "0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) >>> target = tensor([False,", "When `None`, DDP will be used to perform the allgather.", "from torchmetrics import RetrievalFallOut >>> indexes = tensor([0, 0, 0,", "True, False, True]) >>> fo = RetrievalFallOut(k=2) >>> fo(preds, target,", "== \"pos\": res.append(tensor(1.0)) elif self.empty_target_action == \"neg\": res.append(tensor(0.0)) else: #", "of negative targets is at least 1, otherwise behave as", "if not (1 - mini_target).sum(): if self.empty_target_action == \"error\": raise", "metric state across processes at each ``forward()`` before returning the", "a query with no negative target.\") if self.empty_target_action == \"pos\":", "the entire world) dist_sync_fn: Callback that performs the allgather operation", ">>> from torchmetrics import RetrievalFallOut >>> indexes = tensor([0, 0,", "the metric state. When `None`, DDP will be used to", "tensor([False, False, True, False, True, False, True]) >>> fo =", "those queries; if all queries are skipped, ``0.0`` is returned", "mini_target = target[group] if not (1 - mini_target).sum(): if self.empty_target_action", "float predictions from a model output. Forward accepts: - ``preds``", "PyTorch Lightning team. # # Licensed under the Apache License,", "of the `Fall-out` over each query. Args: empty_target_action: Specify what", "CONDITIONS OF ANY KIND, either express or implied. # See", "DDP will be used to perform the allgather. default: None", "the `_metric` if the number of negative targets is at", "[] groups = get_group_indexes(indexes) for group in groups: mini_preds =", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "operation on the metric state. When `None`, DDP will be", "- ``'pos'``: those queries count as ``1.0`` - ``'skip'``: skip", "a model output. Forward accepts: - ``preds`` (float tensor): ``(N,", "on which synchronization is called. default: None (which selects the", "be a positive integer or None\") self.k = k def", "tensor): ``(N, ...)`` - ``indexes`` (long tensor): ``(N, ...)`` ``indexes``,", "\"\"\"First concat state `indexes`, `preds` and `target` since they were", "compute_on_step: bool = True, dist_sync_on_step: bool = False, process_group: Optional[Any]", "that will help in keeping together predictions about the same", "res.append(self._metric(mini_preds, mini_target)) return B.stack([x.to(preds) for x in res]).mean() if res", "float tensors res.append(self._metric(mini_preds, mini_target)) return B.stack([x.to(preds) for x in res]).mean()", "``(N, ...)`` - ``target`` (long or bool tensor): ``(N, ...)``", "step. default: False process_group: Specify the process group on which", "not (isinstance(k, int) and k > 0): raise ValueError(\"`k` has", "def _metric(self, preds: Tensor, target: Tensor) -> Tensor: return retrieval_fall_out(preds,", "Accepts float predictions from a model output. Forward accepts: -", "accepts: - ``preds`` (float tensor): ``(N, ...)`` - ``target`` (long", "as specified by `self.empty_target_action`. \"\"\" indexes = B.cat(self.indexes, dim=0) preds", "...)`` - ``indexes`` (long tensor): ``(N, ...)`` ``indexes``, ``preds`` and", "have at least a negative ``target``. Choose from: - ``'neg'``:", "Callable = None, ) -> None: super().__init__( empty_target_action=empty_target_action, compute_on_step=compute_on_step, dist_sync_on_step=dist_sync_on_step,", "``1.0`` - ``'skip'``: skip those queries; if all queries are", "0): raise ValueError(\"`k` has to be a positive integer or", "than 0 Example: >>> from torchmetrics import RetrievalFallOut >>> indexes", "as the mean of the `Fall-out` over each query. Args:", "None, which considers them all) compute_on_step: Forward only calls ``update()``", "0.5, 0.2]) >>> target = tensor([False, False, True, False, True,", "dist_sync_fn: Callable = None, ) -> None: super().__init__( empty_target_action=empty_target_action, compute_on_step=compute_on_step,", "the License. from typing import Any, Callable, Optional import pangu.core.backend", "a ``ValueError`` k: consider only the top k elements for", "OR CONDITIONS OF ANY KIND, either express or implied. #", "the License is distributed on an \"AS IS\" BASIS, #", "is at least 1, otherwise behave as specified by `self.empty_target_action`.", "which considers them all) compute_on_step: Forward only calls ``update()`` and", "is not None) and not (isinstance(k, int) and k >", "Optional import pangu.core.backend as B from pangu.core.backend import Tensor, tensor", "k: consider only the top k elements for each query", "(default: None, which considers them all) compute_on_step: Forward only calls", "(which selects the entire world) dist_sync_fn: Callback that performs the", "as B from pangu.core.backend import Tensor, tensor from torchmetrics.functional.retrieval.fall_out import", "import RetrievalFallOut >>> indexes = tensor([0, 0, 0, 1, 1,", "import Any, Callable, Optional import pangu.core.backend as B from pangu.core.backend", "law or agreed to in writing, software # distributed under", "negative target.\") if self.empty_target_action == \"pos\": res.append(tensor(1.0)) elif self.empty_target_action ==", "will be first grouped by ``indexes`` and then `Fall-out` will", "0 Example: >>> from torchmetrics import RetrievalFallOut >>> indexes =", "is set to False. default: True dist_sync_on_step: Synchronize metric state", "the number of negative targets is at least 1, otherwise", "query with no negative target.\") if self.empty_target_action == \"pos\": res.append(tensor(1.0))", "= \"pos\", k: int = None, compute_on_step: bool = True,", "lists. After that, compute list of groups that will help", "torchmetrics.functional.retrieval.fall_out import retrieval_fall_out from torchmetrics.retrieval.retrieval_metric import RetrievalMetric from torchmetrics.utilities.data import", "__init__( self, empty_target_action: str = \"pos\", k: int = None,", "them all) compute_on_step: Forward only calls ``update()`` and return None", "\"neg\": res.append(tensor(0.0)) else: # ensure list containt only float tensors", "have the same dimension. ``indexes`` indicate to which query a", "- ``preds`` (float tensor): ``(N, ...)`` - ``target`` (long or", "integer larger than 0 Example: >>> from torchmetrics import RetrievalFallOut", "will help in keeping together predictions about the same query.", "preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) >>>", "may obtain a copy of the License at # #", "Example: >>> from torchmetrics import RetrievalFallOut >>> indexes = tensor([0,", "else tensor(0.0).to(preds) def _metric(self, preds: Tensor, target: Tensor) -> Tensor:", "-> Tensor: \"\"\"First concat state `indexes`, `preds` and `target` since", "= target[group] if not (1 - mini_target).sum(): if self.empty_target_action ==", "Args: empty_target_action: Specify what to do with queries that do", "False, True]) >>> fo = RetrievalFallOut(k=2) >>> fo(preds, target, indexes=indexes)", "for group in groups: mini_preds = preds[group] mini_target = target[group]", "compute list of groups that will help in keeping together", "str = \"pos\", k: int = None, compute_on_step: bool =", "None: super().__init__( empty_target_action=empty_target_action, compute_on_step=compute_on_step, dist_sync_on_step=dist_sync_on_step, process_group=process_group, dist_sync_fn=dist_sync_fn, ) if (k", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "typing import Any, Callable, Optional import pangu.core.backend as B from", "- ``'neg'``: those queries count as ``0.0`` (default) - ``'pos'``:", "Works with binary target data. Accepts float predictions from a", "allgather operation on the metric state. When `None`, DDP will", "may not use this file except in compliance with the", "``indexes`` and then `Fall-out` will be computed as the mean", "1, 1, 1, 1]) >>> preds = tensor([0.2, 0.3, 0.5,", "the same query. Finally, for each group compute the `_metric`", "state across processes at each ``forward()`` before returning the value", ">>> target = tensor([False, False, True, False, True, False, True])", "at least a negative ``target``. Choose from: - ``'neg'``: those", "group compute the `_metric` if the number of negative targets", "not `None` or an integer larger than 0 Example: >>>", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "= tensor([0, 0, 0, 1, 1, 1, 1]) >>> preds", "``k`` parameter is not `None` or an integer larger than", "this file except in compliance with the License. # You", "and then `Fall-out` will be computed as the mean of", "``indexes`` (long tensor): ``(N, ...)`` ``indexes``, ``preds`` and ``target`` must", "None, dist_sync_fn: Callable = None, ) -> None: super().__init__( empty_target_action=empty_target_action,", "import retrieval_fall_out from torchmetrics.retrieval.retrieval_metric import RetrievalMetric from torchmetrics.utilities.data import get_group_indexes", "then `Fall-out` will be computed as the mean of the", "fo(preds, target, indexes=indexes) tensor(0.5000) \"\"\" higher_is_better = False def __init__(", "== \"error\": raise ValueError(\"`compute` method was provided with a query", "Choose from: - ``'neg'``: those queries count as ``0.0`` (default)", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "the same dimension. ``indexes`` indicate to which query a prediction", "empty_target_action: Specify what to do with queries that do not", "the allgather operation on the metric state. When `None`, DDP", "Lightning team. # # Licensed under the Apache License, Version", "get_group_indexes class RetrievalFallOut(RetrievalMetric): \"\"\"Computes `Fall-out`_. Works with binary target data.", "= RetrievalFallOut(k=2) >>> fo(preds, target, indexes=indexes) tensor(0.5000) \"\"\" higher_is_better =", "be first grouped by ``indexes`` and then `Fall-out` will be", "# # Licensed under the Apache License, Version 2.0 (the", "= None, compute_on_step: bool = True, dist_sync_on_step: bool = False,", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "do with queries that do not have at least a", "``target`` must have the same dimension. ``indexes`` indicate to which", "None, compute_on_step: bool = True, dist_sync_on_step: bool = False, process_group:", "from torchmetrics.utilities.data import get_group_indexes class RetrievalFallOut(RetrievalMetric): \"\"\"Computes `Fall-out`_. Works with", "(long or bool tensor): ``(N, ...)`` - ``indexes`` (long tensor):", "``target`` (long or bool tensor): ``(N, ...)`` - ``indexes`` (long", "res else tensor(0.0).to(preds) def _metric(self, preds: Tensor, target: Tensor) ->", "True dist_sync_on_step: Synchronize metric state across processes at each ``forward()``", "keeping together predictions about the same query. Finally, for each", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "compute(self) -> Tensor: \"\"\"First concat state `indexes`, `preds` and `target`", "each query. Args: empty_target_action: Specify what to do with queries", "mini_target).sum(): if self.empty_target_action == \"error\": raise ValueError(\"`compute` method was provided", "\"\"\" higher_is_better = False def __init__( self, empty_target_action: str =", "res.append(tensor(0.0)) else: # ensure list containt only float tensors res.append(self._metric(mini_preds,", "in groups: mini_preds = preds[group] mini_target = target[group] if not", "team. # # Licensed under the Apache License, Version 2.0", "as ``0.0`` (default) - ``'pos'``: those queries count as ``1.0``", "Raises: ValueError: If ``k`` parameter is not `None` or an", "0, 0, 1, 1, 1, 1]) >>> preds = tensor([0.2,", "`Fall-out`_. Works with binary target data. Accepts float predictions from", "\"pos\": res.append(tensor(1.0)) elif self.empty_target_action == \"neg\": res.append(tensor(0.0)) else: # ensure", "0, 1, 1, 1, 1]) >>> preds = tensor([0.2, 0.3,", "_metric(self, preds: Tensor, target: Tensor) -> Tensor: return retrieval_fall_out(preds, target,", "if (k is not None) and not (isinstance(k, int) and", "tensor(0.0).to(preds) def _metric(self, preds: Tensor, target: Tensor) -> Tensor: return", "across processes at each ``forward()`` before returning the value at", "no negative target.\") if self.empty_target_action == \"pos\": res.append(tensor(1.0)) elif self.empty_target_action", "was provided with a query with no negative target.\") if", "...)`` ``indexes``, ``preds`` and ``target`` must have the same dimension.", "allgather. default: None Raises: ValueError: If ``k`` parameter is not", "dim=0) target = B.cat(self.target, dim=0) res = [] groups =", "governing permissions and # limitations under the License. from typing", "bool tensor): ``(N, ...)`` - ``indexes`` (long tensor): ``(N, ...)``", "as lists. After that, compute list of groups that will", "and k > 0): raise ValueError(\"`k` has to be a", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "list of groups that will help in keeping together predictions", "B.cat(self.indexes, dim=0) preds = B.cat(self.preds, dim=0) target = B.cat(self.target, dim=0)", "Predictions will be first grouped by ``indexes`` and then `Fall-out`", "or implied. # See the License for the specific language", "tensor): ``(N, ...)`` - ``target`` (long or bool tensor): ``(N,", "0.3, 0.5, 0.2]) >>> target = tensor([False, False, True, False,", "be computed as the mean of the `Fall-out` over each", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) >>> target =", "= B.cat(self.indexes, dim=0) preds = B.cat(self.preds, dim=0) target = B.cat(self.target,", "raise ValueError(\"`compute` method was provided with a query with no", "\"pos\", k: int = None, compute_on_step: bool = True, dist_sync_on_step:", "`_metric` if the number of negative targets is at least", "dim=0) preds = B.cat(self.preds, dim=0) target = B.cat(self.target, dim=0) res", "this is set to False. default: True dist_sync_on_step: Synchronize metric", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "0.2]) >>> target = tensor([False, False, True, False, True, False,", "that performs the allgather operation on the metric state. When", "with no negative target.\") if self.empty_target_action == \"pos\": res.append(tensor(1.0)) elif", "calls ``update()`` and return None if this is set to", "not have at least a negative ``target``. Choose from: -", "default: None Raises: ValueError: If ``k`` parameter is not `None`", "``forward()`` before returning the value at the step. default: False", "for each query (default: None, which considers them all) compute_on_step:", "by `self.empty_target_action`. \"\"\" indexes = B.cat(self.indexes, dim=0) preds = B.cat(self.preds,", "- ``'error'``: raise a ``ValueError`` k: consider only the top", "(the \"License\"); # you may not use this file except", "must have the same dimension. ``indexes`` indicate to which query", "self.k = k def compute(self) -> Tensor: \"\"\"First concat state", "or bool tensor): ``(N, ...)`` - ``indexes`` (long tensor): ``(N,", "> 0): raise ValueError(\"`k` has to be a positive integer", "# you may not use this file except in compliance", "self.empty_target_action == \"pos\": res.append(tensor(1.0)) elif self.empty_target_action == \"neg\": res.append(tensor(0.0)) else:", ") -> None: super().__init__( empty_target_action=empty_target_action, compute_on_step=compute_on_step, dist_sync_on_step=dist_sync_on_step, process_group=process_group, dist_sync_fn=dist_sync_fn, )", "False process_group: Specify the process group on which synchronization is", "are skipped, ``0.0`` is returned - ``'error'``: raise a ``ValueError``", "least a negative ``target``. Choose from: - ``'neg'``: those queries", "= True, dist_sync_on_step: bool = False, process_group: Optional[Any] = None,", "else: # ensure list containt only float tensors res.append(self._metric(mini_preds, mini_target))", "== \"neg\": res.append(tensor(0.0)) else: # ensure list containt only float", "permissions and # limitations under the License. from typing import", "# Copyright The PyTorch Lightning team. # # Licensed under", "same dimension. ``indexes`` indicate to which query a prediction belongs.", "together predictions about the same query. Finally, for each group", "# # Unless required by applicable law or agreed to", "False, process_group: Optional[Any] = None, dist_sync_fn: Callable = None, )", "if this is set to False. default: True dist_sync_on_step: Synchronize", "a prediction belongs. Predictions will be first grouped by ``indexes``", "positive integer or None\") self.k = k def compute(self) ->", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "they were stored as lists. After that, compute list of", "RetrievalFallOut(RetrievalMetric): \"\"\"Computes `Fall-out`_. Works with binary target data. Accepts float", "Version 2.0 (the \"License\"); # you may not use this", "synchronization is called. default: None (which selects the entire world)", "ValueError(\"`compute` method was provided with a query with no negative", "None, ) -> None: super().__init__( empty_target_action=empty_target_action, compute_on_step=compute_on_step, dist_sync_on_step=dist_sync_on_step, process_group=process_group, dist_sync_fn=dist_sync_fn,", "return B.stack([x.to(preds) for x in res]).mean() if res else tensor(0.0).to(preds)", "negative targets is at least 1, otherwise behave as specified", "``0.0`` is returned - ``'error'``: raise a ``ValueError`` k: consider", "RetrievalFallOut(k=2) >>> fo(preds, target, indexes=indexes) tensor(0.5000) \"\"\" higher_is_better = False", "the mean of the `Fall-out` over each query. Args: empty_target_action:", "target[group] if not (1 - mini_target).sum(): if self.empty_target_action == \"error\":", "implied. # See the License for the specific language governing", "tensor from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out from torchmetrics.retrieval.retrieval_metric import RetrievalMetric from", "under the Apache License, Version 2.0 (the \"License\"); # you", "= get_group_indexes(indexes) for group in groups: mini_preds = preds[group] mini_target", "queries count as ``1.0`` - ``'skip'``: skip those queries; if", "queries that do not have at least a negative ``target``.", "be used to perform the allgather. default: None Raises: ValueError:", "\"\"\" indexes = B.cat(self.indexes, dim=0) preds = B.cat(self.preds, dim=0) target", "those queries count as ``1.0`` - ``'skip'``: skip those queries;", "if self.empty_target_action == \"error\": raise ValueError(\"`compute` method was provided with", "B.cat(self.target, dim=0) res = [] groups = get_group_indexes(indexes) for group", "by applicable law or agreed to in writing, software #", "mini_preds = preds[group] mini_target = target[group] if not (1 -", "= None, dist_sync_fn: Callable = None, ) -> None: super().__init__(", "After that, compute list of groups that will help in", "least 1, otherwise behave as specified by `self.empty_target_action`. \"\"\" indexes", "before returning the value at the step. default: False process_group:", "target.\") if self.empty_target_action == \"pos\": res.append(tensor(1.0)) elif self.empty_target_action == \"neg\":", "If ``k`` parameter is not `None` or an integer larger", "...)`` - ``target`` (long or bool tensor): ``(N, ...)`` -", "state. When `None`, DDP will be used to perform the", "ValueError(\"`k` has to be a positive integer or None\") self.k", "int = None, compute_on_step: bool = True, dist_sync_on_step: bool =", "ValueError: If ``k`` parameter is not `None` or an integer", "dist_sync_fn=dist_sync_fn, ) if (k is not None) and not (isinstance(k,", "selects the entire world) dist_sync_fn: Callback that performs the allgather", "which synchronization is called. default: None (which selects the entire", "a negative ``target``. Choose from: - ``'neg'``: those queries count", "and ``target`` must have the same dimension. ``indexes`` indicate to", "mean of the `Fall-out` over each query. Args: empty_target_action: Specify", "dim=0) res = [] groups = get_group_indexes(indexes) for group in", "elements for each query (default: None, which considers them all)", "is called. default: None (which selects the entire world) dist_sync_fn:", "the `Fall-out` over each query. Args: empty_target_action: Specify what to", "= B.cat(self.target, dim=0) res = [] groups = get_group_indexes(indexes) for", "None) and not (isinstance(k, int) and k > 0): raise", "(k is not None) and not (isinstance(k, int) and k", "at least 1, otherwise behave as specified by `self.empty_target_action`. \"\"\"", "\"\"\"Computes `Fall-out`_. Works with binary target data. Accepts float predictions", "`indexes`, `preds` and `target` since they were stored as lists.", "= None, ) -> None: super().__init__( empty_target_action=empty_target_action, compute_on_step=compute_on_step, dist_sync_on_step=dist_sync_on_step, process_group=process_group,", "``(N, ...)`` ``indexes``, ``preds`` and ``target`` must have the same", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "Tensor: \"\"\"First concat state `indexes`, `preds` and `target` since they", "an integer larger than 0 Example: >>> from torchmetrics import", "k def compute(self) -> Tensor: \"\"\"First concat state `indexes`, `preds`", "Unless required by applicable law or agreed to in writing,", "class RetrievalFallOut(RetrievalMetric): \"\"\"Computes `Fall-out`_. Works with binary target data. Accepts", "compute_on_step: Forward only calls ``update()`` and return None if this", "and `target` since they were stored as lists. After that,", "Specify the process group on which synchronization is called. default:", "raise a ``ValueError`` k: consider only the top k elements", "`target` since they were stored as lists. After that, compute", "k elements for each query (default: None, which considers them", "the specific language governing permissions and # limitations under the", "1]) >>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5,", "applicable law or agreed to in writing, software # distributed", "what to do with queries that do not have at", "``'neg'``: those queries count as ``0.0`` (default) - ``'pos'``: those", ">>> fo = RetrievalFallOut(k=2) >>> fo(preds, target, indexes=indexes) tensor(0.5000) \"\"\"", "predictions about the same query. Finally, for each group compute", "(float tensor): ``(N, ...)`` - ``target`` (long or bool tensor):", "to which query a prediction belongs. Predictions will be first", "in writing, software # distributed under the License is distributed", "indicate to which query a prediction belongs. Predictions will be", "# ensure list containt only float tensors res.append(self._metric(mini_preds, mini_target)) return", "in res]).mean() if res else tensor(0.0).to(preds) def _metric(self, preds: Tensor,", "count as ``1.0`` - ``'skip'``: skip those queries; if all", "`Fall-out` will be computed as the mean of the `Fall-out`", "in keeping together predictions about the same query. Finally, for", "to do with queries that do not have at least", "at each ``forward()`` before returning the value at the step.", "at the step. default: False process_group: Specify the process group", "used to perform the allgather. default: None Raises: ValueError: If", "self, empty_target_action: str = \"pos\", k: int = None, compute_on_step:", "dist_sync_on_step: bool = False, process_group: Optional[Any] = None, dist_sync_fn: Callable", "Callable, Optional import pangu.core.backend as B from pangu.core.backend import Tensor,", "True, dist_sync_on_step: bool = False, process_group: Optional[Any] = None, dist_sync_fn:", "fo = RetrievalFallOut(k=2) >>> fo(preds, target, indexes=indexes) tensor(0.5000) \"\"\" higher_is_better", "compute_on_step=compute_on_step, dist_sync_on_step=dist_sync_on_step, process_group=process_group, dist_sync_fn=dist_sync_fn, ) if (k is not None)", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "License, Version 2.0 (the \"License\"); # you may not use", "# You may obtain a copy of the License at", "query a prediction belongs. Predictions will be first grouped by", "that, compute list of groups that will help in keeping", "is returned - ``'error'``: raise a ``ValueError`` k: consider only", "metric state. When `None`, DDP will be used to perform", "query. Finally, for each group compute the `_metric` if the", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "entire world) dist_sync_fn: Callback that performs the allgather operation on", "self.empty_target_action == \"neg\": res.append(tensor(0.0)) else: # ensure list containt only", "retrieval_fall_out from torchmetrics.retrieval.retrieval_metric import RetrievalMetric from torchmetrics.utilities.data import get_group_indexes class", "x in res]).mean() if res else tensor(0.0).to(preds) def _metric(self, preds:", "None (which selects the entire world) dist_sync_fn: Callback that performs", "``target``. Choose from: - ``'neg'``: those queries count as ``0.0``", "processes at each ``forward()`` before returning the value at the", "default: None (which selects the entire world) dist_sync_fn: Callback that", "higher_is_better = False def __init__( self, empty_target_action: str = \"pos\",", "dist_sync_on_step=dist_sync_on_step, process_group=process_group, dist_sync_fn=dist_sync_fn, ) if (k is not None) and", "will be used to perform the allgather. default: None Raises:", "1, otherwise behave as specified by `self.empty_target_action`. \"\"\" indexes =", "the License for the specific language governing permissions and #", "from typing import Any, Callable, Optional import pangu.core.backend as B", "process_group: Optional[Any] = None, dist_sync_fn: Callable = None, ) ->", "Apache License, Version 2.0 (the \"License\"); # you may not", "if all queries are skipped, ``0.0`` is returned - ``'error'``:", "model output. Forward accepts: - ``preds`` (float tensor): ``(N, ...)``", "either express or implied. # See the License for the", "that do not have at least a negative ``target``. Choose", "were stored as lists. After that, compute list of groups", "= False def __init__( self, empty_target_action: str = \"pos\", k:", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "over each query. Args: empty_target_action: Specify what to do with", "import pangu.core.backend as B from pangu.core.backend import Tensor, tensor from", "- mini_target).sum(): if self.empty_target_action == \"error\": raise ValueError(\"`compute` method was", "compute the `_metric` if the number of negative targets is", "of groups that will help in keeping together predictions about", "False. default: True dist_sync_on_step: Synchronize metric state across processes at", "elif self.empty_target_action == \"neg\": res.append(tensor(0.0)) else: # ensure list containt", "to False. default: True dist_sync_on_step: Synchronize metric state across processes", "or None\") self.k = k def compute(self) -> Tensor: \"\"\"First", "Tensor, tensor from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out from torchmetrics.retrieval.retrieval_metric import RetrievalMetric", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "for each group compute the `_metric` if the number of", "(default) - ``'pos'``: those queries count as ``1.0`` - ``'skip'``:", "`preds` and `target` since they were stored as lists. After", "`None`, DDP will be used to perform the allgather. default:", "integer or None\") self.k = k def compute(self) -> Tensor:", "limitations under the License. from typing import Any, Callable, Optional", "= k def compute(self) -> Tensor: \"\"\"First concat state `indexes`,", "not None) and not (isinstance(k, int) and k > 0):", "pangu.core.backend as B from pangu.core.backend import Tensor, tensor from torchmetrics.functional.retrieval.fall_out", "Forward accepts: - ``preds`` (float tensor): ``(N, ...)`` - ``target``", "set to False. default: True dist_sync_on_step: Synchronize metric state across", "called. default: None (which selects the entire world) dist_sync_fn: Callback", "Callback that performs the allgather operation on the metric state.", "\"License\"); # you may not use this file except in", "tensors res.append(self._metric(mini_preds, mini_target)) return B.stack([x.to(preds) for x in res]).mean() if", "each query (default: None, which considers them all) compute_on_step: Forward", "queries are skipped, ``0.0`` is returned - ``'error'``: raise a", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "The PyTorch Lightning team. # # Licensed under the Apache", "``indexes`` indicate to which query a prediction belongs. Predictions will", "Any, Callable, Optional import pangu.core.backend as B from pangu.core.backend import", "# distributed under the License is distributed on an \"AS", "``'error'``: raise a ``ValueError`` k: consider only the top k", "target = B.cat(self.target, dim=0) res = [] groups = get_group_indexes(indexes)", ">>> fo(preds, target, indexes=indexes) tensor(0.5000) \"\"\" higher_is_better = False def", "# Unless required by applicable law or agreed to in", "prediction belongs. Predictions will be first grouped by ``indexes`` and", "from torchmetrics.retrieval.retrieval_metric import RetrievalMetric from torchmetrics.utilities.data import get_group_indexes class RetrievalFallOut(RetrievalMetric):", "res = [] groups = get_group_indexes(indexes) for group in groups:", "Specify what to do with queries that do not have", "top k elements for each query (default: None, which considers", "= tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2]) >>> target", "all) compute_on_step: Forward only calls ``update()`` and return None if", "to perform the allgather. default: None Raises: ValueError: If ``k``", "process group on which synchronization is called. default: None (which", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "the top k elements for each query (default: None, which", "(1 - mini_target).sum(): if self.empty_target_action == \"error\": raise ValueError(\"`compute` method", "self.empty_target_action == \"error\": raise ValueError(\"`compute` method was provided with a", "consider only the top k elements for each query (default:", "queries; if all queries are skipped, ``0.0`` is returned -", "False, True, False, True, False, True]) >>> fo = RetrievalFallOut(k=2)", "the process group on which synchronization is called. default: None", "target, indexes=indexes) tensor(0.5000) \"\"\" higher_is_better = False def __init__( self,", "``preds`` and ``target`` must have the same dimension. ``indexes`` indicate", "do not have at least a negative ``target``. Choose from:", "B from pangu.core.backend import Tensor, tensor from torchmetrics.functional.retrieval.fall_out import retrieval_fall_out", "res.append(tensor(1.0)) elif self.empty_target_action == \"neg\": res.append(tensor(0.0)) else: # ensure list", "default: False process_group: Specify the process group on which synchronization", "B.stack([x.to(preds) for x in res]).mean() if res else tensor(0.0).to(preds) def", "You may obtain a copy of the License at #", "False def __init__( self, empty_target_action: str = \"pos\", k: int", "to be a positive integer or None\") self.k = k", "None Raises: ValueError: If ``k`` parameter is not `None` or", ">>> preds = tensor([0.2, 0.3, 0.5, 0.1, 0.3, 0.5, 0.2])", "- ``target`` (long or bool tensor): ``(N, ...)`` - ``indexes``", "method was provided with a query with no negative target.\")", "by ``indexes`` and then `Fall-out` will be computed as the", "number of negative targets is at least 1, otherwise behave", "the Apache License, Version 2.0 (the \"License\"); # you may", "dist_sync_on_step: Synchronize metric state across processes at each ``forward()`` before", "help in keeping together predictions about the same query. Finally,", "True, False, True, False, True]) >>> fo = RetrievalFallOut(k=2) >>>", "empty_target_action: str = \"pos\", k: int = None, compute_on_step: bool", "``(N, ...)`` - ``indexes`` (long tensor): ``(N, ...)`` ``indexes``, ``preds``", "computed as the mean of the `Fall-out` over each query.", "with queries that do not have at least a negative", "super().__init__( empty_target_action=empty_target_action, compute_on_step=compute_on_step, dist_sync_on_step=dist_sync_on_step, process_group=process_group, dist_sync_fn=dist_sync_fn, ) if (k is", "preds[group] mini_target = target[group] if not (1 - mini_target).sum(): if", "with a query with no negative target.\") if self.empty_target_action ==" ]
[ "= builder() dlm.add(seasonality(period=2, discount=1, w=1.0)) dlm.initialize() self.kf11.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.state[0][0, 0],", "dlm = builder() dlm.add(self.trend0) dlm.initialize() self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs, 0) # the", "self.kf11.forwardFilter(dlm.model, -1) self.assertAlmostEqual(dlm.model.state[0][0, 0], -0.5) self.assertAlmostEqual(dlm.model.state[1][0, 0], 0.5) def testBackwardSmoother(self):", "builder from pydlm.base.kalmanFilter import kalmanFilter class testKalmanFilter(unittest.TestCase): def setUp(self): self.kf1", "self.assertAlmostEqual(dlm.model.state[0][0, 0], -0.5) self.assertAlmostEqual(dlm.model.state[1][0, 0], 0.5) def testBackwardSmoother(self): dlm =", "should expect the filterd mean to be 0.5 self.kf1.forwardFilter(dlm.model, 1)", "0]/1e10, 0.5) self.kf0.forwardFilter(dlm.model, None) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5)", "filtered mean close to 1 self.kf0.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs[0, 0], 1)", "= builder() dlm.add(self.trend0) dlm.initialize() self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs, 0) # the prior", "direct fit on the three data points, 0, 1, -1.", "discount=0.98, w=1.0, name='a') self.trend1 = trend(degree=1, discount=1, w=1.0) def testForwardFilter(self):", "second order trend with discount = 1. The smoothed result", "np.matrix([[0.5]]), \\ np.matrix([[0.375]])) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0/3) self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.18518519) #", "from pydlm.modeler.seasonality import seasonality from pydlm.modeler.builder import builder from pydlm.base.kalmanFilter", "be 0.0 def testBackwardSmootherMultiDim(self): dlm = builder() dlm.add(self.trend1) dlm.initialize() self.kf11.forwardFilter(dlm.model,", "the prior on the mean is zero, but observe 1,", "self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.5) self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs[0, 0], 1) self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 1)", "self.assertAlmostEqual(dlm.model.sysVar, 0.375) self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs, 0.5) self.assertAlmostEqual(dlm.model.prediction.obs, 0.5) dlm.initialize() self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs,", "-0.5) self.assertAlmostEqual(dlm.model.state[1][0, 0], 0.5) def testBackwardSmoother(self): dlm = builder() dlm.add(self.trend0)", "equal to a direct fit on the three data points,", "dlm.add(self.trend1) dlm.initialize() self.kf11.forwardFilter(dlm.model, 1) state1 = dlm.model.state cov1 = dlm.model.sysVar", "self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5) self.kf0.forwardFilter(dlm.model, 0) self.assertAlmostEqual(dlm.model.obs[0, 0],", "def testEvolveMode(self): dlm = builder() dlm.add(self.trend0_90) dlm.add(self.trend0_98) dlm.initialize() kf2 =", "0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0], 1.0) self.kf0.forwardFilter(dlm.model, None) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0)", "discount=0.9, w=1.0) self.trend0_98 = trend(degree=0, discount=0.98, w=1.0, name='a') self.trend1 =", "is zero, but observe 1, with discount = 0 #", "dlm.initialize() self.kf0.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0], 1.0) self.kf0.forwardFilter(dlm.model,", "at 1 will be 1/3, for discount = 1 self.kf1.forwardFilter(dlm.model,", "1) self.assertAlmostEqual(dlm.model.obs, 0.5) self.assertAlmostEqual(dlm.model.prediction.obs, 0) self.assertAlmostEqual(dlm.model.sysVar, 0.375) self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs, 0.5)", "self.assertAlmostEqual(dlm.model.prediction.obs, 0) self.assertAlmostEqual(dlm.model.sysVar, 0.375) self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs, 0.5) self.assertAlmostEqual(dlm.model.prediction.obs, 0.5) dlm.initialize()", "self.kf1.forwardFilter(dlm.model, 1) self.kf1.forwardFilter(dlm.model, 0) self.kf1.backwardSmoother(dlm.model, \\ np.matrix([[0.5]]), \\ np.matrix([[0.375]])) self.assertAlmostEqual(dlm.model.obs[0,", "0.5) self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs[0, 0], 1) self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 1) def testForwardFilterMultiDim(self):", "self.assertAlmostEqual(dlm.model.transition, 1.0) def testEvolveMode(self): dlm = builder() dlm.add(self.trend0_90) dlm.add(self.trend0_98) dlm.initialize()", "self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5) self.kf0.forwardFilter(dlm.model, None) self.assertAlmostEqual(dlm.model.obs[0, 0],", "builder() dlm.add(self.trend0) dlm.initialize() dlm.model.evaluation = np.matrix([[None]]) self.kf1.forwardFilter(dlm.model, 1.0, dealWithMissingEvaluation =", "dlm.add(self.trend0) dlm.initialize() # with mean being 0 and observe 1", "self.assertAlmostEqual(dlm.model.state[1][0, 0], 0.5) def testBackwardSmoother(self): dlm = builder() dlm.add(self.trend0) dlm.initialize()", "0.5) def testBackwardSmoother(self): dlm = builder() dlm.add(self.trend0) dlm.initialize() # with", "-1) self.kf11.backwardSmoother(dlm.model, \\ rawState = state1, \\ rawSysVar = cov1)", "shall # expect the smoothed mean at 1 will be", "0], 1) self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 1) def testForwardFilterMultiDim(self): dlm = builder()", "index=dlm.componentIndex) kf2.forwardFilter(dlm.model, 1.0) self.assertAlmostEqual(dlm.model.innovation[0, 1], 0.0) self.assertAlmostEqual(dlm.model.innovation[1, 0], 0.0) if", "builder() dlm.add(self.trend0) dlm.initialize() self.kf0.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0],", "self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs[0, 0], 1) self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 1) def testForwardFilterMultiDim(self): dlm", "= dlm.model.state cov1 = dlm.model.sysVar self.kf11.forwardFilter(dlm.model, -1) self.kf11.backwardSmoother(dlm.model, \\ rawState", "testForwardFilterMultiDim(self): dlm = builder() dlm.add(seasonality(period=2, discount=1, w=1.0)) dlm.initialize() self.kf11.forwardFilter(dlm.model, 1)", "def testForwardFilterMultiDim(self): dlm = builder() dlm.add(seasonality(period=2, discount=1, w=1.0)) dlm.initialize() self.kf11.forwardFilter(dlm.model,", "0], -0.5) self.assertAlmostEqual(dlm.model.state[1][0, 0], 0.5) def testBackwardSmoother(self): dlm = builder()", "# expect the smoothed mean at 1 will be 1/3,", "builder() dlm.add(self.trend1) dlm.initialize() self.kf11.forwardFilter(dlm.model, 1) state1 = dlm.model.state cov1 =", "0) self.assertAlmostEqual(dlm.model.sysVar, 0.375) self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs, 0.5) self.assertAlmostEqual(dlm.model.prediction.obs, 0.5) dlm.initialize() self.kf0.predict(dlm.model)", "1) self.assertAlmostEqual(dlm.model.obs[0, 0], 1) self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 0) self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.5)", "cov1 = dlm.model.sysVar self.kf11.forwardFilter(dlm.model, -1) self.kf11.backwardSmoother(dlm.model, \\ rawState = state1,", "1.0/3) self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.18518519) # second order trend with discount", "dealWithMissingEvaluation = True) self.assertAlmostEqual(dlm.model.obs, 0.0) self.assertAlmostEqual(dlm.model.transition, 1.0) def testEvolveMode(self): dlm", "= kalmanFilter(discount=[1e-10]) self.kf11 = kalmanFilter(discount=[1, 1]) self.trend0 = trend(degree=0, discount=1,", "self.kf0.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs[0, 0], 1) self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 0) self.assertAlmostEqual(dlm.model.sysVar[0, 0],", "pydlm.modeler.seasonality import seasonality from pydlm.modeler.builder import builder from pydlm.base.kalmanFilter import", "mean at 1 will be 1/3, for discount = 1", "dlm.initialize() self.kf11.forwardFilter(dlm.model, 1) state1 = dlm.model.state cov1 = dlm.model.sysVar self.kf11.forwardFilter(dlm.model,", "self.kf11.forwardFilter(dlm.model, 1) state1 = dlm.model.state cov1 = dlm.model.sysVar self.kf11.forwardFilter(dlm.model, -1)", "from pydlm.base.kalmanFilter import kalmanFilter class testKalmanFilter(unittest.TestCase): def setUp(self): self.kf1 =", "self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0) def testMissingEvaluation(self): dlm = builder() dlm.add(self.trend0) dlm.initialize()", "the # smoothed observation should be 0.0 def testBackwardSmootherMultiDim(self): dlm", "= state1, \\ rawSysVar = cov1) self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0) def", "seasonality from pydlm.modeler.builder import builder from pydlm.base.kalmanFilter import kalmanFilter class", "mean to be 0.5 self.kf1.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs, 0.5) self.assertAlmostEqual(dlm.model.prediction.obs, 0)", "but observe 1, with # discount = 1, one should", "np import unittest from pydlm.modeler.trends import trend from pydlm.modeler.seasonality import", "\\ np.matrix([[0.375]])) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0/3) self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.18518519) # second", "\\ np.matrix([[0.5]]), \\ np.matrix([[0.375]])) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0/3) self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.18518519)", "self.kf0.forwardFilter(dlm.model, 0) self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0) def testMissingEvaluation(self): dlm = builder()", "dlm.model.state cov1 = dlm.model.sysVar self.kf11.forwardFilter(dlm.model, -1) self.kf11.backwardSmoother(dlm.model, \\ rawState =", "0.5 self.kf1.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs, 0.5) self.assertAlmostEqual(dlm.model.prediction.obs, 0) self.assertAlmostEqual(dlm.model.sysVar, 0.375) self.kf1.predict(dlm.model)", "self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5) self.kf0.forwardFilter(dlm.model, None) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10,", "# discount = 1, one should expect the filterd mean", "dlm.model.evaluation = np.matrix([[None]]) self.kf1.forwardFilter(dlm.model, 1.0, dealWithMissingEvaluation = True) self.assertAlmostEqual(dlm.model.obs, 0.0)", "# with mean being 0 and observe 1 and 0", "to be 0.5 self.kf1.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs, 0.5) self.assertAlmostEqual(dlm.model.prediction.obs, 0) self.assertAlmostEqual(dlm.model.sysVar,", "self.assertAlmostEqual(dlm.model.obs, 0.5) self.assertAlmostEqual(dlm.model.prediction.obs, 0.5) dlm.initialize() self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs, 0) # the", "0.33333333333) self.assertAlmostEqual(dlm.model.state[1][0, 0], -0.33333333333) self.kf11.forwardFilter(dlm.model, -1) self.assertAlmostEqual(dlm.model.state[0][0, 0], -0.5) self.assertAlmostEqual(dlm.model.state[1][0,", "dlm.initialize() # with mean being 0 and observe 1 and", "state1 = dlm.model.state cov1 = dlm.model.sysVar self.kf11.forwardFilter(dlm.model, -1) self.kf11.backwardSmoother(dlm.model, \\", "= kalmanFilter(discount=[1]) self.kf0 = kalmanFilter(discount=[1e-10]) self.kf11 = kalmanFilter(discount=[1, 1]) self.trend0", "def testMissingData(self): dlm = builder() dlm.add(self.trend0) dlm.initialize() self.kf0.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs[0,", "zero, but observe 1, with discount = 0 # one", "0, 1, -1. Thus, the # smoothed observation should be", "1, with discount = 0 # one should expect the", "rawSysVar = cov1) self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0) def testMissingData(self): dlm =", "trend(degree=0, discount=0.98, w=1.0, name='a') self.trend1 = trend(degree=1, discount=1, w=1.0) def", "self.kf1.forwardFilter(dlm.model, 1.0, dealWithMissingEvaluation = True) self.assertAlmostEqual(dlm.model.obs, 0.0) self.assertAlmostEqual(dlm.model.transition, 1.0) def", "self.assertAlmostEqual(dlm.model.prediction.obs, 0.5) dlm.initialize() self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs, 0) # the prior on", "dlm.model.sysVar self.kf11.forwardFilter(dlm.model, -1) self.kf11.backwardSmoother(dlm.model, \\ rawState = state1, \\ rawSysVar", "0], 0) self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.5) self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs[0, 0], 1) self.assertAlmostEqual(dlm.model.prediction.obs[0,", "None) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5) self.kf0.forwardFilter(dlm.model, None) self.assertAlmostEqual(dlm.model.obs[0,", "dlm.add(self.trend0) dlm.initialize() self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs, 0) # the prior on the", "discount=1, w=1.0) self.trend0_90 = trend(degree=0, discount=0.9, w=1.0) self.trend0_98 = trend(degree=0,", "kf2.forwardFilter(dlm.model, 1.0) self.assertAlmostEqual(dlm.model.innovation[0, 1], 0.0) self.assertAlmostEqual(dlm.model.innovation[1, 0], 0.0) if __name__", "0 and observe 1 and 0 consectively, one shall #", "builder() dlm.add(self.trend0_90) dlm.add(self.trend0_98) dlm.initialize() kf2 = kalmanFilter(discount=[0.9, 0.98], updateInnovation='component', index=dlm.componentIndex)", "def testForwardFilter(self): dlm = builder() dlm.add(self.trend0) dlm.initialize() self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs, 0)", "mean is zero, but observe 1, with # discount =", "trend from pydlm.modeler.seasonality import seasonality from pydlm.modeler.builder import builder from", "= builder() dlm.add(self.trend0) dlm.initialize() self.kf0.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0,", "= builder() dlm.add(self.trend0) dlm.initialize() dlm.model.evaluation = np.matrix([[None]]) self.kf1.forwardFilter(dlm.model, 1.0, dealWithMissingEvaluation", "1, with # discount = 1, one should expect the", "kalmanFilter(discount=[1e-10]) self.kf11 = kalmanFilter(discount=[1, 1]) self.trend0 = trend(degree=0, discount=1, w=1.0)", "0.0) self.assertAlmostEqual(dlm.model.transition, 1.0) def testEvolveMode(self): dlm = builder() dlm.add(self.trend0_90) dlm.add(self.trend0_98)", "discount = 0 # one should expect the filtered mean", "0.5) self.assertAlmostEqual(dlm.model.prediction.obs, 0) self.assertAlmostEqual(dlm.model.sysVar, 0.375) self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs, 0.5) self.assertAlmostEqual(dlm.model.prediction.obs, 0.5)", "1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0], 1.0) self.kf0.forwardFilter(dlm.model, None) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0,", "1, one should expect the filterd mean to be 0.5", "kalmanFilter(discount=[1]) self.kf0 = kalmanFilter(discount=[1e-10]) self.kf11 = kalmanFilter(discount=[1, 1]) self.trend0 =", "\\ rawState = state1, \\ rawSysVar = cov1) self.assertAlmostEqual(dlm.model.obs[0, 0],", "0.5) dlm.initialize() self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs, 0) # the prior on the", "0 # one should expect the filtered mean close to", "1) self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 1) def testForwardFilterMultiDim(self): dlm = builder() dlm.add(seasonality(period=2,", "discount = 1, one should expect the filterd mean to", "self.kf11.backwardSmoother(dlm.model, \\ rawState = state1, \\ rawSysVar = cov1) self.assertAlmostEqual(dlm.model.obs[0,", "expect the smoothed mean at 1 will be 1/3, for", "0], 1) def testForwardFilterMultiDim(self): dlm = builder() dlm.add(seasonality(period=2, discount=1, w=1.0))", "should be 0.0 def testBackwardSmootherMultiDim(self): dlm = builder() dlm.add(self.trend1) dlm.initialize()", "= cov1) self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0) def testMissingData(self): dlm = builder()", "self.assertAlmostEqual(dlm.model.obs, 0.0) self.assertAlmostEqual(dlm.model.transition, 1.0) def testEvolveMode(self): dlm = builder() dlm.add(self.trend0_90)", "as np import unittest from pydlm.modeler.trends import trend from pydlm.modeler.seasonality", "0.0) def testMissingEvaluation(self): dlm = builder() dlm.add(self.trend0) dlm.initialize() dlm.model.evaluation =", "1.0) self.kf0.forwardFilter(dlm.model, None) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5) self.kf0.forwardFilter(dlm.model,", "= kalmanFilter(discount=[1, 1]) self.trend0 = trend(degree=0, discount=1, w=1.0) self.trend0_90 =", "dlm.add(seasonality(period=2, discount=1, w=1.0)) dlm.initialize() self.kf11.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.state[0][0, 0], 0.33333333333) self.assertAlmostEqual(dlm.model.state[1][0,", "self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs, 0.5) self.assertAlmostEqual(dlm.model.prediction.obs, 0.5) dlm.initialize() self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs, 0) #", "= builder() dlm.add(self.trend1) dlm.initialize() self.kf11.forwardFilter(dlm.model, 1) state1 = dlm.model.state cov1", "self.trend1 = trend(degree=1, discount=1, w=1.0) def testForwardFilter(self): dlm = builder()", "<gh_stars>100-1000 import numpy as np import unittest from pydlm.modeler.trends import", "being 0 and observe 1 and 0 consectively, one shall", "updateInnovation='component', index=dlm.componentIndex) kf2.forwardFilter(dlm.model, 1.0) self.assertAlmostEqual(dlm.model.innovation[0, 1], 0.0) self.assertAlmostEqual(dlm.model.innovation[1, 0], 0.0)", "self.assertAlmostEqual(dlm.model.innovation[0, 1], 0.0) self.assertAlmostEqual(dlm.model.innovation[1, 0], 0.0) if __name__ == '__main__':", "one should expect the filtered mean close to 1 self.kf0.forwardFilter(dlm.model,", "self.assertAlmostEqual(dlm.model.prediction.obs, 0) # the prior on the mean is zero,", "import unittest from pydlm.modeler.trends import trend from pydlm.modeler.seasonality import seasonality", "1 and 0 consectively, one shall # expect the smoothed", "testMissingEvaluation(self): dlm = builder() dlm.add(self.trend0) dlm.initialize() dlm.model.evaluation = np.matrix([[None]]) self.kf1.forwardFilter(dlm.model,", "self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.18518519) # second order trend with discount =", "observation should be 0.0 def testBackwardSmootherMultiDim(self): dlm = builder() dlm.add(self.trend1)", "1) self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 0) self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.5) self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs[0, 0],", "w=1.0) def testForwardFilter(self): dlm = builder() dlm.add(self.trend0) dlm.initialize() self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs,", "with mean being 0 and observe 1 and 0 consectively,", "The smoothed result should be # equal to a direct", "0], 1.0) self.kf0.forwardFilter(dlm.model, None) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5)", "three data points, 0, 1, -1. Thus, the # smoothed", "1], 0.0) self.assertAlmostEqual(dlm.model.innovation[1, 0], 0.0) if __name__ == '__main__': unittest.main()", "mean is zero, but observe 1, with discount = 0", "1 will be 1/3, for discount = 1 self.kf1.forwardFilter(dlm.model, 1)", "self.kf0.forwardFilter(dlm.model, None) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5) self.kf0.forwardFilter(dlm.model, 0)", "# second order trend with discount = 1. The smoothed", "pydlm.base.kalmanFilter import kalmanFilter class testKalmanFilter(unittest.TestCase): def setUp(self): self.kf1 = kalmanFilter(discount=[1])", "= 1, one should expect the filterd mean to be", "order trend with discount = 1. The smoothed result should", "dlm = builder() dlm.add(self.trend0) dlm.initialize() # with mean being 0", "kalmanFilter class testKalmanFilter(unittest.TestCase): def setUp(self): self.kf1 = kalmanFilter(discount=[1]) self.kf0 =", "= kalmanFilter(discount=[0.9, 0.98], updateInnovation='component', index=dlm.componentIndex) kf2.forwardFilter(dlm.model, 1.0) self.assertAlmostEqual(dlm.model.innovation[0, 1], 0.0)", "0.98], updateInnovation='component', index=dlm.componentIndex) kf2.forwardFilter(dlm.model, 1.0) self.assertAlmostEqual(dlm.model.innovation[0, 1], 0.0) self.assertAlmostEqual(dlm.model.innovation[1, 0],", "with discount = 1. The smoothed result should be #", "testMissingData(self): dlm = builder() dlm.add(self.trend0) dlm.initialize() self.kf0.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs[0, 0],", "testForwardFilter(self): dlm = builder() dlm.add(self.trend0) dlm.initialize() self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs, 0) #", "dlm = builder() dlm.add(self.trend0) dlm.initialize() self.kf0.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0)", "testKalmanFilter(unittest.TestCase): def setUp(self): self.kf1 = kalmanFilter(discount=[1]) self.kf0 = kalmanFilter(discount=[1e-10]) self.kf11", "state1, \\ rawSysVar = cov1) self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0) def testMissingData(self):", "kalmanFilter(discount=[1, 1]) self.trend0 = trend(degree=0, discount=1, w=1.0) self.trend0_90 = trend(degree=0,", "0.375) self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs, 0.5) self.assertAlmostEqual(dlm.model.prediction.obs, 0.5) dlm.initialize() self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs, 0)", "dlm.add(self.trend0) dlm.initialize() dlm.model.evaluation = np.matrix([[None]]) self.kf1.forwardFilter(dlm.model, 1.0, dealWithMissingEvaluation = True)", "0], 0.5) def testBackwardSmoother(self): dlm = builder() dlm.add(self.trend0) dlm.initialize() #", "# one should expect the filtered mean close to 1", "self.assertAlmostEqual(dlm.model.state[0][0, 0], 0.33333333333) self.assertAlmostEqual(dlm.model.state[1][0, 0], -0.33333333333) self.kf11.forwardFilter(dlm.model, -1) self.assertAlmostEqual(dlm.model.state[0][0, 0],", "on the mean is zero, but observe 1, with #", "0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5) self.kf0.forwardFilter(dlm.model, 0) self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0)", "True) self.assertAlmostEqual(dlm.model.obs, 0.0) self.assertAlmostEqual(dlm.model.transition, 1.0) def testEvolveMode(self): dlm = builder()", "self.assertAlmostEqual(dlm.model.obs, 0.5) self.assertAlmostEqual(dlm.model.prediction.obs, 0) self.assertAlmostEqual(dlm.model.sysVar, 0.375) self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs, 0.5) self.assertAlmostEqual(dlm.model.prediction.obs,", "0.0 def testBackwardSmootherMultiDim(self): dlm = builder() dlm.add(self.trend1) dlm.initialize() self.kf11.forwardFilter(dlm.model, 1)", "0], 0.0) def testMissingEvaluation(self): dlm = builder() dlm.add(self.trend0) dlm.initialize() dlm.model.evaluation", "dlm.add(self.trend0_98) dlm.initialize() kf2 = kalmanFilter(discount=[0.9, 0.98], updateInnovation='component', index=dlm.componentIndex) kf2.forwardFilter(dlm.model, 1.0)", "to 1 self.kf0.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs[0, 0], 1) self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 0)", "self.kf1 = kalmanFilter(discount=[1]) self.kf0 = kalmanFilter(discount=[1e-10]) self.kf11 = kalmanFilter(discount=[1, 1])", "\\ rawSysVar = cov1) self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0) def testMissingData(self): dlm", "dlm.initialize() dlm.model.evaluation = np.matrix([[None]]) self.kf1.forwardFilter(dlm.model, 1.0, dealWithMissingEvaluation = True) self.assertAlmostEqual(dlm.model.obs,", "self.assertAlmostEqual(dlm.model.obs[0, 0], 1) self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 0) self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.5) self.kf0.predict(dlm.model)", "with discount = 0 # one should expect the filtered", "be # equal to a direct fit on the three", "= np.matrix([[None]]) self.kf1.forwardFilter(dlm.model, 1.0, dealWithMissingEvaluation = True) self.assertAlmostEqual(dlm.model.obs, 0.0) self.assertAlmostEqual(dlm.model.transition,", "dlm.initialize() self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs, 0) # the prior on the mean", "self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs, 0) # the prior on the mean is", "a direct fit on the three data points, 0, 1,", "be 1/3, for discount = 1 self.kf1.forwardFilter(dlm.model, 1) self.kf1.forwardFilter(dlm.model, 0)", "-1. Thus, the # smoothed observation should be 0.0 def", "import numpy as np import unittest from pydlm.modeler.trends import trend", "observe 1, with discount = 0 # one should expect", "discount=1, w=1.0)) dlm.initialize() self.kf11.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.state[0][0, 0], 0.33333333333) self.assertAlmostEqual(dlm.model.state[1][0, 0],", "self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0) def testMissingData(self): dlm = builder() dlm.add(self.trend0) dlm.initialize()", "w=1.0) self.trend0_90 = trend(degree=0, discount=0.9, w=1.0) self.trend0_98 = trend(degree=0, discount=0.98,", "import kalmanFilter class testKalmanFilter(unittest.TestCase): def setUp(self): self.kf1 = kalmanFilter(discount=[1]) self.kf0", "expect the filtered mean close to 1 self.kf0.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs[0,", "mean close to 1 self.kf0.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs[0, 0], 1) self.assertAlmostEqual(dlm.model.prediction.obs[0,", "= True) self.assertAlmostEqual(dlm.model.obs, 0.0) self.assertAlmostEqual(dlm.model.transition, 1.0) def testEvolveMode(self): dlm =", "self.kf1.backwardSmoother(dlm.model, \\ np.matrix([[0.5]]), \\ np.matrix([[0.375]])) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0/3) self.assertAlmostEqual(dlm.model.sysVar[0, 0],", "self.trend0_90 = trend(degree=0, discount=0.9, w=1.0) self.trend0_98 = trend(degree=0, discount=0.98, w=1.0,", "self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5) self.kf0.forwardFilter(dlm.model, 0) self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0) def testMissingEvaluation(self):", "name='a') self.trend1 = trend(degree=1, discount=1, w=1.0) def testForwardFilter(self): dlm =", "= trend(degree=0, discount=0.9, w=1.0) self.trend0_98 = trend(degree=0, discount=0.98, w=1.0, name='a')", "testBackwardSmoother(self): dlm = builder() dlm.add(self.trend0) dlm.initialize() # with mean being", "0], -0.33333333333) self.kf11.forwardFilter(dlm.model, -1) self.assertAlmostEqual(dlm.model.state[0][0, 0], -0.5) self.assertAlmostEqual(dlm.model.state[1][0, 0], 0.5)", "kalmanFilter(discount=[0.9, 0.98], updateInnovation='component', index=dlm.componentIndex) kf2.forwardFilter(dlm.model, 1.0) self.assertAlmostEqual(dlm.model.innovation[0, 1], 0.0) self.assertAlmostEqual(dlm.model.innovation[1,", "on the three data points, 0, 1, -1. Thus, the", "discount = 1 self.kf1.forwardFilter(dlm.model, 1) self.kf1.forwardFilter(dlm.model, 0) self.kf1.backwardSmoother(dlm.model, \\ np.matrix([[0.5]]),", "result should be # equal to a direct fit on", "cov1) self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0) def testMissingData(self): dlm = builder() dlm.add(self.trend0)", "import seasonality from pydlm.modeler.builder import builder from pydlm.base.kalmanFilter import kalmanFilter", "on the mean is zero, but observe 1, with discount", "0], 0.33333333333) self.assertAlmostEqual(dlm.model.state[1][0, 0], -0.33333333333) self.kf11.forwardFilter(dlm.model, -1) self.assertAlmostEqual(dlm.model.state[0][0, 0], -0.5)", "0.5) self.kf0.forwardFilter(dlm.model, 0) self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0) def testMissingEvaluation(self): dlm =", "the filtered mean close to 1 self.kf0.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs[0, 0],", "self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0], 1.0) self.kf0.forwardFilter(dlm.model, None) self.assertAlmostEqual(dlm.model.obs[0, 0],", "self.trend0 = trend(degree=0, discount=1, w=1.0) self.trend0_90 = trend(degree=0, discount=0.9, w=1.0)", "numpy as np import unittest from pydlm.modeler.trends import trend from", "should expect the filtered mean close to 1 self.kf0.forwardFilter(dlm.model, 1)", "0.5) self.kf0.forwardFilter(dlm.model, None) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5) self.kf0.forwardFilter(dlm.model,", "0]/1e10, 0.5) self.kf0.forwardFilter(dlm.model, 0) self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0) def testMissingEvaluation(self): dlm", "self.kf11 = kalmanFilter(discount=[1, 1]) self.trend0 = trend(degree=0, discount=1, w=1.0) self.trend0_90", "1) self.kf1.forwardFilter(dlm.model, 0) self.kf1.backwardSmoother(dlm.model, \\ np.matrix([[0.5]]), \\ np.matrix([[0.375]])) self.assertAlmostEqual(dlm.model.obs[0, 0],", "close to 1 self.kf0.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs[0, 0], 1) self.assertAlmostEqual(dlm.model.prediction.obs[0, 0],", "dlm = builder() dlm.add(seasonality(period=2, discount=1, w=1.0)) dlm.initialize() self.kf11.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.state[0][0,", "0 consectively, one shall # expect the smoothed mean at", "mean being 0 and observe 1 and 0 consectively, one", "self.assertAlmostEqual(dlm.model.obs[0, 0], 1) self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 1) def testForwardFilterMultiDim(self): dlm =", "kf2 = kalmanFilter(discount=[0.9, 0.98], updateInnovation='component', index=dlm.componentIndex) kf2.forwardFilter(dlm.model, 1.0) self.assertAlmostEqual(dlm.model.innovation[0, 1],", "1.0) self.assertAlmostEqual(dlm.model.innovation[0, 1], 0.0) self.assertAlmostEqual(dlm.model.innovation[1, 0], 0.0) if __name__ ==", "the smoothed mean at 1 will be 1/3, for discount", "0], 0.0) def testMissingData(self): dlm = builder() dlm.add(self.trend0) dlm.initialize() self.kf0.forwardFilter(dlm.model,", "and 0 consectively, one shall # expect the smoothed mean", "# the prior on the mean is zero, but observe", "-1) self.assertAlmostEqual(dlm.model.state[0][0, 0], -0.5) self.assertAlmostEqual(dlm.model.state[1][0, 0], 0.5) def testBackwardSmoother(self): dlm", "1]) self.trend0 = trend(degree=0, discount=1, w=1.0) self.trend0_90 = trend(degree=0, discount=0.9,", "w=1.0, name='a') self.trend1 = trend(degree=1, discount=1, w=1.0) def testForwardFilter(self): dlm", "= trend(degree=0, discount=0.98, w=1.0, name='a') self.trend1 = trend(degree=1, discount=1, w=1.0)", "np.matrix([[0.375]])) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0/3) self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.18518519) # second order", "fit on the three data points, 0, 1, -1. Thus,", "and observe 1 and 0 consectively, one shall # expect", "0) self.kf1.backwardSmoother(dlm.model, \\ np.matrix([[0.5]]), \\ np.matrix([[0.375]])) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0/3) self.assertAlmostEqual(dlm.model.sysVar[0,", "w=1.0) self.trend0_98 = trend(degree=0, discount=0.98, w=1.0, name='a') self.trend1 = trend(degree=1,", "points, 0, 1, -1. Thus, the # smoothed observation should", "the three data points, 0, 1, -1. Thus, the #", "builder() dlm.add(self.trend0) dlm.initialize() self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs, 0) # the prior on", "the mean is zero, but observe 1, with # discount", "self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs, 0) # the prior on the mean is", "trend(degree=1, discount=1, w=1.0) def testForwardFilter(self): dlm = builder() dlm.add(self.trend0) dlm.initialize()", "pydlm.modeler.trends import trend from pydlm.modeler.seasonality import seasonality from pydlm.modeler.builder import", "# smoothed observation should be 0.0 def testBackwardSmootherMultiDim(self): dlm =", "= trend(degree=0, discount=1, w=1.0) self.trend0_90 = trend(degree=0, discount=0.9, w=1.0) self.trend0_98", "= 0 # one should expect the filtered mean close", "discount = 1. The smoothed result should be # equal", "import builder from pydlm.base.kalmanFilter import kalmanFilter class testKalmanFilter(unittest.TestCase): def setUp(self):", "self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0/3) self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.18518519) # second order trend", "1) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0], 1.0) self.kf0.forwardFilter(dlm.model, None) self.assertAlmostEqual(dlm.model.obs[0,", "one should expect the filterd mean to be 0.5 self.kf1.forwardFilter(dlm.model,", "be 0.5 self.kf1.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs, 0.5) self.assertAlmostEqual(dlm.model.prediction.obs, 0) self.assertAlmostEqual(dlm.model.sysVar, 0.375)", "1. The smoothed result should be # equal to a", "self.kf1.forwardFilter(dlm.model, 0) self.kf1.backwardSmoother(dlm.model, \\ np.matrix([[0.5]]), \\ np.matrix([[0.375]])) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0/3)", "self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 1) def testForwardFilterMultiDim(self): dlm = builder() dlm.add(seasonality(period=2, discount=1,", "with # discount = 1, one should expect the filterd", "Thus, the # smoothed observation should be 0.0 def testBackwardSmootherMultiDim(self):", "smoothed mean at 1 will be 1/3, for discount =", "0.5) self.assertAlmostEqual(dlm.model.prediction.obs, 0.5) dlm.initialize() self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs, 0) # the prior", "1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5) self.kf0.forwardFilter(dlm.model, None) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0,", "1.0) def testEvolveMode(self): dlm = builder() dlm.add(self.trend0_90) dlm.add(self.trend0_98) dlm.initialize() kf2", "0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5) self.kf0.forwardFilter(dlm.model, None) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0)", "observe 1, with # discount = 1, one should expect", "1) self.assertAlmostEqual(dlm.model.state[0][0, 0], 0.33333333333) self.assertAlmostEqual(dlm.model.state[1][0, 0], -0.33333333333) self.kf11.forwardFilter(dlm.model, -1) self.assertAlmostEqual(dlm.model.state[0][0,", "dlm.initialize() self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.prediction.obs, 0) # the prior on the mean", "zero, but observe 1, with # discount = 1, one", "1.0, dealWithMissingEvaluation = True) self.assertAlmostEqual(dlm.model.obs, 0.0) self.assertAlmostEqual(dlm.model.transition, 1.0) def testEvolveMode(self):", "0) # the prior on the mean is zero, but", "self.kf11.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.state[0][0, 0], 0.33333333333) self.assertAlmostEqual(dlm.model.state[1][0, 0], -0.33333333333) self.kf11.forwardFilter(dlm.model, -1)", "0) self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0) def testMissingEvaluation(self): dlm = builder() dlm.add(self.trend0)", "trend(degree=0, discount=1, w=1.0) self.trend0_90 = trend(degree=0, discount=0.9, w=1.0) self.trend0_98 =", "= trend(degree=1, discount=1, w=1.0) def testForwardFilter(self): dlm = builder() dlm.add(self.trend0)", "observe 1 and 0 consectively, one shall # expect the", "= 1 self.kf1.forwardFilter(dlm.model, 1) self.kf1.forwardFilter(dlm.model, 0) self.kf1.backwardSmoother(dlm.model, \\ np.matrix([[0.5]]), \\", "dlm = builder() dlm.add(self.trend0) dlm.initialize() dlm.model.evaluation = np.matrix([[None]]) self.kf1.forwardFilter(dlm.model, 1.0,", "dlm = builder() dlm.add(self.trend0_90) dlm.add(self.trend0_98) dlm.initialize() kf2 = kalmanFilter(discount=[0.9, 0.98],", "to a direct fit on the three data points, 0,", "dlm.add(self.trend0) dlm.initialize() self.kf0.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0], 1.0)", "= builder() dlm.add(self.trend0_90) dlm.add(self.trend0_98) dlm.initialize() kf2 = kalmanFilter(discount=[0.9, 0.98], updateInnovation='component',", "discount=1, w=1.0) def testForwardFilter(self): dlm = builder() dlm.add(self.trend0) dlm.initialize() self.kf1.predict(dlm.model)", "but observe 1, with discount = 0 # one should", "is zero, but observe 1, with # discount = 1,", "self.kf0 = kalmanFilter(discount=[1e-10]) self.kf11 = kalmanFilter(discount=[1, 1]) self.trend0 = trend(degree=0,", "the mean is zero, but observe 1, with discount =", "1 self.kf1.forwardFilter(dlm.model, 1) self.kf1.forwardFilter(dlm.model, 0) self.kf1.backwardSmoother(dlm.model, \\ np.matrix([[0.5]]), \\ np.matrix([[0.375]]))", "self.kf0.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0], 1.0) self.kf0.forwardFilter(dlm.model, None)", "= 1. The smoothed result should be # equal to", "testBackwardSmootherMultiDim(self): dlm = builder() dlm.add(self.trend1) dlm.initialize() self.kf11.forwardFilter(dlm.model, 1) state1 =", "def testBackwardSmootherMultiDim(self): dlm = builder() dlm.add(self.trend1) dlm.initialize() self.kf11.forwardFilter(dlm.model, 1) state1", "1) def testForwardFilterMultiDim(self): dlm = builder() dlm.add(seasonality(period=2, discount=1, w=1.0)) dlm.initialize()", "trend(degree=0, discount=0.9, w=1.0) self.trend0_98 = trend(degree=0, discount=0.98, w=1.0, name='a') self.trend1", "one shall # expect the smoothed mean at 1 will", "smoothed observation should be 0.0 def testBackwardSmootherMultiDim(self): dlm = builder()", "1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5) self.kf0.forwardFilter(dlm.model, 0) self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0) def", "0) self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.5) self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs[0, 0], 1) self.assertAlmostEqual(dlm.model.prediction.obs[0, 0],", "0.18518519) # second order trend with discount = 1. The", "None) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5) self.kf0.forwardFilter(dlm.model, 0) self.assertAlmostEqual(dlm.model.obs[0,", "for discount = 1 self.kf1.forwardFilter(dlm.model, 1) self.kf1.forwardFilter(dlm.model, 0) self.kf1.backwardSmoother(dlm.model, \\", "0], 0.5) self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs[0, 0], 1) self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 1) def", "expect the filterd mean to be 0.5 self.kf1.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs,", "dlm.add(self.trend0_90) dlm.add(self.trend0_98) dlm.initialize() kf2 = kalmanFilter(discount=[0.9, 0.98], updateInnovation='component', index=dlm.componentIndex) kf2.forwardFilter(dlm.model,", "from pydlm.modeler.builder import builder from pydlm.base.kalmanFilter import kalmanFilter class testKalmanFilter(unittest.TestCase):", "-0.33333333333) self.kf11.forwardFilter(dlm.model, -1) self.assertAlmostEqual(dlm.model.state[0][0, 0], -0.5) self.assertAlmostEqual(dlm.model.state[1][0, 0], 0.5) def", "1) state1 = dlm.model.state cov1 = dlm.model.sysVar self.kf11.forwardFilter(dlm.model, -1) self.kf11.backwardSmoother(dlm.model,", "from pydlm.modeler.trends import trend from pydlm.modeler.seasonality import seasonality from pydlm.modeler.builder", "pydlm.modeler.builder import builder from pydlm.base.kalmanFilter import kalmanFilter class testKalmanFilter(unittest.TestCase): def", "builder() dlm.add(self.trend0) dlm.initialize() # with mean being 0 and observe", "self.trend0_98 = trend(degree=0, discount=0.98, w=1.0, name='a') self.trend1 = trend(degree=1, discount=1,", "unittest from pydlm.modeler.trends import trend from pydlm.modeler.seasonality import seasonality from", "def setUp(self): self.kf1 = kalmanFilter(discount=[1]) self.kf0 = kalmanFilter(discount=[1e-10]) self.kf11 =", "def testMissingEvaluation(self): dlm = builder() dlm.add(self.trend0) dlm.initialize() dlm.model.evaluation = np.matrix([[None]])", "import trend from pydlm.modeler.seasonality import seasonality from pydlm.modeler.builder import builder", "builder() dlm.add(seasonality(period=2, discount=1, w=1.0)) dlm.initialize() self.kf11.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.state[0][0, 0], 0.33333333333)", "0], 1) self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 0) self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.5) self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs[0,", "dlm.initialize() self.kf11.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.state[0][0, 0], 0.33333333333) self.assertAlmostEqual(dlm.model.state[1][0, 0], -0.33333333333) self.kf11.forwardFilter(dlm.model,", "self.kf1.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs, 0.5) self.assertAlmostEqual(dlm.model.prediction.obs, 0) self.assertAlmostEqual(dlm.model.sysVar, 0.375) self.kf1.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs,", "consectively, one shall # expect the smoothed mean at 1", "prior on the mean is zero, but observe 1, with", "testEvolveMode(self): dlm = builder() dlm.add(self.trend0_90) dlm.add(self.trend0_98) dlm.initialize() kf2 = kalmanFilter(discount=[0.9,", "self.kf11.forwardFilter(dlm.model, -1) self.kf11.backwardSmoother(dlm.model, \\ rawState = state1, \\ rawSysVar =", "= dlm.model.sysVar self.kf11.forwardFilter(dlm.model, -1) self.kf11.backwardSmoother(dlm.model, \\ rawState = state1, \\", "1, -1. Thus, the # smoothed observation should be 0.0", "# equal to a direct fit on the three data", "smoothed result should be # equal to a direct fit", "self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 0) self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.5) self.kf0.predict(dlm.model) self.assertAlmostEqual(dlm.model.obs[0, 0], 1)", "1/3, for discount = 1 self.kf1.forwardFilter(dlm.model, 1) self.kf1.forwardFilter(dlm.model, 0) self.kf1.backwardSmoother(dlm.model,", "class testKalmanFilter(unittest.TestCase): def setUp(self): self.kf1 = kalmanFilter(discount=[1]) self.kf0 = kalmanFilter(discount=[1e-10])", "self.assertAlmostEqual(dlm.model.state[1][0, 0], -0.33333333333) self.kf11.forwardFilter(dlm.model, -1) self.assertAlmostEqual(dlm.model.state[0][0, 0], -0.5) self.assertAlmostEqual(dlm.model.state[1][0, 0],", "dlm.initialize() kf2 = kalmanFilter(discount=[0.9, 0.98], updateInnovation='component', index=dlm.componentIndex) kf2.forwardFilter(dlm.model, 1.0) self.assertAlmostEqual(dlm.model.innovation[0,", "the filterd mean to be 0.5 self.kf1.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs, 0.5)", "filterd mean to be 0.5 self.kf1.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs, 0.5) self.assertAlmostEqual(dlm.model.prediction.obs,", "data points, 0, 1, -1. Thus, the # smoothed observation", "w=1.0)) dlm.initialize() self.kf11.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.state[0][0, 0], 0.33333333333) self.assertAlmostEqual(dlm.model.state[1][0, 0], -0.33333333333)", "trend with discount = 1. The smoothed result should be", "self.assertAlmostEqual(dlm.model.obsVar[0, 0], 1.0) self.kf0.forwardFilter(dlm.model, None) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10,", "rawState = state1, \\ rawSysVar = cov1) self.assertAlmostEqual(dlm.model.obs[0, 0], 0.0)", "0.0) def testMissingData(self): dlm = builder() dlm.add(self.trend0) dlm.initialize() self.kf0.forwardFilter(dlm.model, 1)", "np.matrix([[None]]) self.kf1.forwardFilter(dlm.model, 1.0, dealWithMissingEvaluation = True) self.assertAlmostEqual(dlm.model.obs, 0.0) self.assertAlmostEqual(dlm.model.transition, 1.0)", "def testBackwardSmoother(self): dlm = builder() dlm.add(self.trend0) dlm.initialize() # with mean", "setUp(self): self.kf1 = kalmanFilter(discount=[1]) self.kf0 = kalmanFilter(discount=[1e-10]) self.kf11 = kalmanFilter(discount=[1,", "= builder() dlm.add(self.trend0) dlm.initialize() # with mean being 0 and", "0], 1.0/3) self.assertAlmostEqual(dlm.model.sysVar[0, 0], 0.18518519) # second order trend with", "0], 0.18518519) # second order trend with discount = 1.", "should be # equal to a direct fit on the", "will be 1/3, for discount = 1 self.kf1.forwardFilter(dlm.model, 1) self.kf1.forwardFilter(dlm.model,", "self.kf0.forwardFilter(dlm.model, None) self.assertAlmostEqual(dlm.model.obs[0, 0], 1.0) self.assertAlmostEqual(dlm.model.obsVar[0, 0]/1e10, 0.5) self.kf0.forwardFilter(dlm.model, None)", "dlm = builder() dlm.add(self.trend1) dlm.initialize() self.kf11.forwardFilter(dlm.model, 1) state1 = dlm.model.state", "1 self.kf0.forwardFilter(dlm.model, 1) self.assertAlmostEqual(dlm.model.obs[0, 0], 1) self.assertAlmostEqual(dlm.model.prediction.obs[0, 0], 0) self.assertAlmostEqual(dlm.model.sysVar[0," ]
[ "migrate rule for 'sata1' r = MigrateRule(source='sata1', threshold=(90, 50)) #", "to start of the policy policy.rules.insert(r, 0) # save changes", "arcapix.fs.gpfs.policy import PlacementPolicy from arcapix.fs.gpfs.rule import MigrateRule # load placement", "placement policy for mmfs1 policy = PlacementPolicy('mmfs1') # create a", "MigrateRule(source='sata1', threshold=(90, 50)) # add rule to start of the", "mmfs1 policy = PlacementPolicy('mmfs1') # create a new migrate rule", "PlacementPolicy('mmfs1') # create a new migrate rule for 'sata1' r", "import MigrateRule # load placement policy for mmfs1 policy =", "r = MigrateRule(source='sata1', threshold=(90, 50)) # add rule to start", "policy = PlacementPolicy('mmfs1') # create a new migrate rule for", "from arcapix.fs.gpfs.policy import PlacementPolicy from arcapix.fs.gpfs.rule import MigrateRule # load", "load placement policy for mmfs1 policy = PlacementPolicy('mmfs1') # create", "# add rule to start of the policy policy.rules.insert(r, 0)", "# create a new migrate rule for 'sata1' r =", "50)) # add rule to start of the policy policy.rules.insert(r,", "= MigrateRule(source='sata1', threshold=(90, 50)) # add rule to start of", "add rule to start of the policy policy.rules.insert(r, 0) #", "MigrateRule # load placement policy for mmfs1 policy = PlacementPolicy('mmfs1')", "create a new migrate rule for 'sata1' r = MigrateRule(source='sata1',", "rule to start of the policy policy.rules.insert(r, 0) # save", "rule for 'sata1' r = MigrateRule(source='sata1', threshold=(90, 50)) # add", "'sata1' r = MigrateRule(source='sata1', threshold=(90, 50)) # add rule to", "import PlacementPolicy from arcapix.fs.gpfs.rule import MigrateRule # load placement policy", "for mmfs1 policy = PlacementPolicy('mmfs1') # create a new migrate", "# load placement policy for mmfs1 policy = PlacementPolicy('mmfs1') #", "PlacementPolicy from arcapix.fs.gpfs.rule import MigrateRule # load placement policy for", "policy for mmfs1 policy = PlacementPolicy('mmfs1') # create a new", "arcapix.fs.gpfs.rule import MigrateRule # load placement policy for mmfs1 policy", "= PlacementPolicy('mmfs1') # create a new migrate rule for 'sata1'", "from arcapix.fs.gpfs.rule import MigrateRule # load placement policy for mmfs1", "new migrate rule for 'sata1' r = MigrateRule(source='sata1', threshold=(90, 50))", "a new migrate rule for 'sata1' r = MigrateRule(source='sata1', threshold=(90,", "for 'sata1' r = MigrateRule(source='sata1', threshold=(90, 50)) # add rule", "start of the policy policy.rules.insert(r, 0) # save changes policy.save()", "threshold=(90, 50)) # add rule to start of the policy" ]
[ "= [a > b for (a, b) in zip(depths[1:], depths[:-1])]", "= list(map(int, sys.stdin)) increased = [a > b for (a,", "#!/usr/bin/env python3 import sys depths = list(map(int, sys.stdin)) increased =", "<reponame>tjol/advent-of-code-2021<gh_stars>1-10 #!/usr/bin/env python3 import sys depths = list(map(int, sys.stdin)) increased", "sys depths = list(map(int, sys.stdin)) increased = [a > b", "list(map(int, sys.stdin)) increased = [a > b for (a, b)", "import sys depths = list(map(int, sys.stdin)) increased = [a >", "python3 import sys depths = list(map(int, sys.stdin)) increased = [a", "depths = list(map(int, sys.stdin)) increased = [a > b for", "increased = [a > b for (a, b) in zip(depths[1:],", "[a > b for (a, b) in zip(depths[1:], depths[:-1])] print(sum(increased))", "sys.stdin)) increased = [a > b for (a, b) in" ]
[ "== url).first() if Paste.query.filter(Paste.url == url).first() != None: if is_active(paste):", "== url).first() user = User.query.filter(paste.user_id == User.id).first() if is_active(paste): return", "methods=['POST']) @requires_auth def get_all_pastes_object(): user_id = session['user_id'] user = User.query.filter(user_id", "user_id).all() active = [] for paste in pastes: if is_active(paste):", "userid_to_red = paste.user_id user_to_red = User.query.filter(userid_to_red == User.id) user_to_red.paste_count =", "session['user_id'] # pastes = paste.query.filter(paste.user_id == user_id).all() if 'user_id' in", "# def edit_paste(id): # user_id = session['user_id'] # paste =", "userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return jsonify({'paste_list':", "user_id = session['user_id'] # paste = Paste.query.filter( # Paste.id ==", "== url).first() != None: if is_active(paste): if 'user_id' in session:", "1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/paste', methods=['GET']) #", "Paste.query.filter(Paste.url == url).first() # style = HtmlFormatter().get_style_defs('.highlight') # lexer =", "@mod_paste.route('/paste/<id>', methods=['POST']) # @requires_auth # def edit_paste(id): # user_id =", "= highlight(paste.text, lexer, formatter) # return render_template(\"view_paste.html\", paste_title=paste.title, # paste_lang=paste.lang,", "\"/\" # for paste in paste_list: # paste.url = url_pre", "render_template(\"index.html\"),4044 # else: # return jsonify(success=True, paste=paste.to_dict()) # @mod_paste.route('/paste/<id>', methods=['POST'])", "lang = request.form['lang'] time_form = request.form['time'] paste_type = request.form['type'] expire_time", "1 db.session.delete(paste) db.session.commit() return jsonify({'paste_list': active, 'username': user.username}), 200 @mod_paste.route('/<url>/embed',", "else: return render_template(\"index.html\"), 404 @mod_paste.route('/api/<url>', methods=['POST']) def ret_paste(url): paste =", "5: # db.session.delete(paste_to_delete) # else: # paste_to_delete.report_count = paste_to_delete.report_count +", "time_form = request.form['time'] paste_type = request.form['type'] expire_time = str(time_form) paste.title", "reply=\"Please Login\") @mod_paste.route('/admin/pastes', methods=['GET']) @requires_admin def all_pastes(): paste_list = db.session.all()", "wraps from datetime import datetime from dateutil import parser def", "404 if is_active(paste): if paste.user_id == user_id or user.user_type ==", "request.form['time'] expire_time = str(time_form) add_time = str(datetime.now()) url = str(uuid.uuid4())", "# url_pre = \"/\" # for paste in paste_list: #", "lang, add_time, expire_time, user_id, url, report_count, paste_type) user = User.query.filter(User.id", "user_id or user.user_type == 2: userid_to_red = paste.user_id user_to_red =", "import uuid from datetime import datetime from app.user.models import User", "db.session.delete(paste) db.session.commit() return render_template('allpaste.html', paste_list=paste_list) @mod_paste.route('/<username>/paste', methods=['GET']) @requires_admin def get_user_pastes(username):", "paste_to_delete = Paste.query.filter(Paste.url == url).first() # if paste_to_delete.report_count > 5:", "# return jsonify({'paste_list':active,'username':user.username}),200 # @mod_paste.route('/paste/<id>', methods=['GET']) # @requires_auth # def", "return jsonify(success=True, pastes=[paste.to_dict() for paste in # pastes]) @mod_paste.route('/<username>/api/paste', methods=['POST'])", "== user_id).first() if user.user_type == 1: return render_template('view_paste.html') if user.user_type", "session: curr_id = session['user_id'] user = User.query.filter(curr_id == User.id).first() if", "jsonify(message=\"Unauthorized\", success=False), 401 user_id = session['user_id'] user = User.query.filter(User.id ==", "User.id).first() pastes = Paste.query.filter(Paste.user_id == user_id).all() active = [] for", "Login\"), 400 @mod_paste.route('/<url>/edit', methods=['POST']) @requires_auth def edit_paste(url): if 'user_id' in", "request.form['title'] # paste.text = request.form['text'] # paste.color = request.form['color'] #", "= session['user_id'] # print(user_id) paste = Paste.query.filter(Paste.url == url).first() user", "user.user_type == 2: return render_template('view_paste_admin.html') return render_template(\"view_paste_guest.html\") else: userid_to_red =", "pastes=[paste.to_dict() for paste in # pastes]) @mod_paste.route('/<username>/api/paste', methods=['POST']) #@requires_admin def", "url).first() if is_active(paste): return render_template('embed.html', paste_text=paste.text, paste_link=\"http://127.0.0.1:8080/\" + url) else:", "= url) @mod_paste.route('/<url>/embed/output', methods=['GET']) def embed_code_disp(url): paste = Paste.query.filter(Paste.url ==", "= user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 return", "paste_list=paste_list) @mod_paste.route('/<url>/edit', methods=['GET']) @requires_auth def edit_form(url): if 'user_id' in session:", "user_id = session['user_id'] paste = Paste.query.filter(Paste.url == url).first() if is_active(paste):", "= paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count", "@requires_auth def get_all_pastes_object(): user_id = session['user_id'] user = User.query.filter(user_id ==", "= Paste.query.filter(Paste.url == url).first() # return jsonify(paste_text = paste.text,paste_link =", "in paste_list: # paste.url = url_pre + paste.url # if", "paste = paste.query.filter( # Paste.id == id, Paste.user_id == user_id).first()", "session: if(paste.paste_type == \"1\" and session['user_id'] != paste.user_id): return render_template(\"index.html\"),", "from dateutil import parser def requires_admin(f): @wraps(f) def decorated(*args, **kwargs):", "return f(*args, **kwargs) return decorated mod_paste = Blueprint('paste', __name__) CORS(mod_paste)", "@mod_paste.route('/<url>/delete', methods=['POST']) @requires_auth def delete_paste(url): user_id = session['user_id'] # print(user_id)", "if paste is None: # return render_template(\"index.html\"),4044 # else: #", "= paste.query.filter(paste.user_id == user_id).all() # curr_id = session['user_id'] # user", "# if user.user_type == 1: # return render_template('mypaste.html', paste_list=paste_list) #", "paste.user_id == user_id or user.user_type == 2: userid_to_red = paste.user_id", "= Paste.query.filter( # Paste.id == id, Paste.user_id == user_id).first() #", "if 'user_id' not in session: return jsonify(message=\"Unauthorized\", success=False), 401 user_id", "Paste.query.filter(Paste.user_id == user_id).all() active = [] for paste in pastes:", "jsonify({'paste_list': active, 'username': user.username}), 200 @mod_paste.route('/<url>/embed', methods=['GET']) def embed_code_form(url): paste", "@mod_paste.route('/paste/<id>', methods=['GET']) # @requires_auth # def get_paste(id): # user_id =", "else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count", "user_id = session['user_id'] user = User.query.filter(User.id == user_id).first() if(user.user_type !=", "# temp_paste['title'] = paste.title # temp_paste['add_time']=paste.add_time # temp_paste['expire_time']=paste.expire_time # temp_paste['lang']=paste.lang", "is_active(paste): return render_template('embed_output.html') else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id", "= [] # for paste in pastes: # temp_paste =", "# else: # paste_to_delete.report_count = paste_to_delete.report_count + 1 # db.session.commit()", "if paste_to_delete.report_count > 5: # db.session.delete(paste_to_delete) # else: # paste_to_delete.report_count", "200 else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first()", "if paste.user_id == user_id or user.user_type == 2: userid_to_red =", "def is_active(paste): return parser.parse(paste.expire_time) > datetime.now() @mod_paste.route('/create_paste', methods=['GET']) @requires_auth def", "pastes]) @mod_paste.route('/<username>/api/paste', methods=['POST']) #@requires_admin def get_user_pastes_object(username): # admin_id = session['user_id']", "paste_list: if is_active(paste): paste.url = url_pre + paste.url else: userid_to_red", "Paste.query.filter(Paste.url == url).first() # if paste_to_delete.report_count > 5: # db.session.delete(paste_to_delete)", "= User.query.filter(User.username == username).first() pastes = Paste.query.filter(Paste.user_id == user.id).all() active", "# style = HtmlFormatter().get_style_defs('.highlight') # lexer = get_lexer_by_name(paste.lang) # formatter", "'paste_lang': paste.lang, 'paste_add': paste.add_time, 'paste_expire': paste.expire_time}), 200 else: userid_to_red =", "user_id = session['user_id'] else: user = User.query.filter(User.username == 'Guest').first() user_id", "db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>/embed', methods=['POST']) # def embed_code(url):", "# paste = Paste.query.filter(Paste.url == url).first() # return jsonify(paste_text =", "return render_template(\"index.html\"),4044 # else: # return jsonify(success=True, paste=paste.to_dict()) # @mod_paste.route('/paste/<id>',", "admin = User.query.filter(admin_id == User.id).first() user = User.query.filter(User.username == username).first()", "dateutil import parser def requires_admin(f): @wraps(f) def decorated(*args, **kwargs): if", "'user_id' in session: curr_id = session['user_id'] user = User.query.filter(curr_id ==", "is_active(paste): return render_template('embed.html', paste_text=paste.text, paste_link=\"http://127.0.0.1:8080/\" + url) else: userid_to_red =", "# if paste.is_active(): # temp_paste['title'] = paste.title # temp_paste['add_time']=paste.add_time #", "= session['user_id'] user = User.query.filter(user_id == User.id).first() pastes = Paste.query.filter(Paste.user_id", "db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>/add_report', methods=['POST']) # @requires_auth", "session['user_id'] # paste_list = Paste.query.filter(Paste.user_id == curr_id).all() # url_pre =", "== User.id) user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return", "= User.query.filter(curr_id == User.id).first() if user.user_type == 2: return render_template('admin_mypaste.html')", "# paste.lang = request.form['lang'] # db.session.commit() # return jsonify(success=True) @mod_paste.route('/<url>/delete',", "user.paste_count user.paste_count = x + 1 db.session.add(paste) db.session.commit() # jsonify(success=True,", "user = User.query.filter(User.id == user_id).first() if paste is None: return", "methods=['POST']) def ret_paste(url): paste = Paste.query.filter(Paste.url == url).first() user =", "user.id lang = request.form['lang'] time_form = request.form['time'] expire_time = str(time_form)", "jsonify(success=True, user_type=user.user_type), 200 else: return jsonify(success=False), 400 else: userid_to_red =", "= paste.title # temp_paste['add_time']=paste.add_time # temp_paste['expire_time']=paste.expire_time # temp_paste['lang']=paste.lang # temp_paste['url']=paste.url", "'paste_text': paste.text, 'paste_title': paste.title, 'paste_lang': paste.lang, 'paste_add': paste.add_time, 'paste_expire': paste.expire_time}),", "return render_template('index.html'), 404 if paste.user_id != user_id: return jsonify(success=False, reply=\"Not", "# if paste is None: # return render_template(\"index.html\"),4044 # else:", "request.form['title'] text = request.form['text'] lang = request.form['lang'] time_form = request.form['time']", "methods=['POST']) # @requires_auth # def get_all_pastes_object(): # user_id = session['user_id']", "paste.url else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first()", "return render_template(\"mypaste.html\") else: return jsonify({'error': 'Please Login to Continue'}), 400", "= db.session.all() url_pre = \"/\" for paste in paste_list: if", "paste.query.filter(paste.user_id == user_id).all() if 'user_id' in session: return render_template('user_paste.html') else:", "paste_list=paste_list) @mod_paste.route('/<username>/paste', methods=['GET']) @requires_admin def get_user_pastes(username): # user_id = session['user_id']", "add_time = str(datetime.now()) url = str(uuid.uuid4()) report_count = 0 try:", "methods=['POST']) @requires_auth def edit_paste(url): if 'user_id' in session: user_id =", "is_active(paste): active.append(paste.to_dict()) else: userid_to_red = paste.user_id user_to_red = User.query.filter(userid_to_red ==", "user_id = session['user_id'] paste = Paste.query.filter(Paste.url == url).first() if not", "Paste.query.filter(Paste.url == url).first() if not is_active(paste): userid_to_red = paste.user_id user_to_red", "200 user_id = session['user_id'] user = User.query.filter(User.id == user_id).first() if", "return jsonify(success=False, reply=\"Please Login\"), 400 @mod_paste.route('/<url>/edit', methods=['POST']) @requires_auth def edit_paste(url):", "== url).first() if is_active(paste): return render_template('embed.html', paste_text=paste.text, paste_link=\"http://127.0.0.1:8080/\" + url)", "# # @mod_paste.route('/api/paste', methods=['POST']) # @requires_auth # def get_all_pastes_object(): #", "get_paste(id): # user_id = session['user_id'] # paste = paste.query.filter( #", "404 # @mod_paste.route('/<url>/embed', methods=['POST']) # def embed_code(url): # paste =", "None: return render_template(\"index.html\"), 404 if is_active(paste): if paste.user_id == user_id", "return render_template('mypaste.html', paste_list=paste_list) @mod_paste.route('/<url>/edit', methods=['GET']) @requires_auth def edit_form(url): if 'user_id'", "create_form(): curr_id = session['user_id'] user = User.query.filter(User.id == curr_id).first() return", "return jsonify({'paste_list': active, 'username': user.username}), 200 @mod_paste.route('/<url>/embed', methods=['GET']) def embed_code_form(url):", "None: # return render_template(\"index.html\"),4044 # else: # paste.title = request.form['title']", "__name__) CORS(mod_paste) def is_active(paste): return parser.parse(paste.expire_time) > datetime.now() @mod_paste.route('/create_paste', methods=['GET'])", "from flask_cors import CORS from .models import Paste import uuid", "# result = highlight(paste.text, lexer, formatter) # return render_template(\"view_paste.html\", paste_title=paste.title,", "user_id: return render_template('editpaste.html') return jsonify(success=False, reply=\"Not Authorized\"), 400 else: userid_to_red", "username).first() pastes = Paste.query.filter(Paste.user_id == user.id).all() active = [] for", "'user_id' in session: user_id = session['user_id'] else: user = User.query.filter(User.username", "url = str(uuid.uuid4()) report_count = 0 try: paste = Paste(title,", "user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return jsonify(success=True, user_type=user.user_type), 200 else:", "= paste.text) def display_paste(url): paste = Paste.query.filter(Paste.url == url).first() if", "= User.query.filter(admin_id == User.id).first() user = User.query.filter(User.username == username).first() pastes", "== curr_id).first() # paste_list = Paste.query.filter(curr_id == Paste.user_id).all() # url_pre", "decorated(*args, **kwargs): if 'user_id' not in session: return jsonify(message=\"Unauthorized\", success=False),", "get_all_pastes_object(): user_id = session['user_id'] user = User.query.filter(user_id == User.id).first() pastes", "request.form['color'] # paste.lang = request.form['lang'] # db.session.commit() # return jsonify(success=True)", "str(time_form) paste.title = title paste.text = text paste.lang = lang", "return jsonify(success=False, reply=\"Please Login\") @mod_paste.route('/admin/pastes', methods=['GET']) @requires_admin def all_pastes(): paste_list", "not in session: return jsonify(message=\"Unauthorized\", success=False), 401 user_id = session['user_id']", "app import db, requires_auth from flask_cors import CORS from .models", "render_template('embed_output.html') else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first()", "# paste_to_delete = Paste.query.filter(Paste.url == url).first() # if paste_to_delete.report_count >", "user_id).first() if(user.user_type != 2): return jsonify(message=\"Unauthorized\", success=False), 401 return f(*args,", "return jsonify(success=False, reply=\"Not Authorized\"), 400 else: userid_to_red = paste.user_id user_to_red", "jsonify(success=True, pastes=[paste.to_dict() for paste in # pastes]) @mod_paste.route('/<username>/api/paste', methods=['POST']) #@requires_admin", "return jsonify({'url': url}), 200 except: return jsonify({'error': 'Error while creating", "redirect, url_for, jsonify from app import db, requires_auth from flask_cors", "pastes]) # # # @mod_paste.route('/api/paste', methods=['POST']) # @requires_auth # def", "reply=\"Please Login\"), 400 @mod_paste.route('/<url>/edit', methods=['POST']) @requires_auth def edit_paste(url): if 'user_id'", "= Paste.query.filter(Paste.url == url).first() if is_active(paste): return render_template('embed_output.html') else: userid_to_red", "ret_paste(url): paste = Paste.query.filter(Paste.url == url).first() user = User.query.filter(paste.user_id ==", "if is_active(paste): return render_template('embed.html', paste_text=paste.text, paste_link=\"http://127.0.0.1:8080/\" + url) else: userid_to_red", "404 # @mod_paste.route('/paste', methods=['GET']) # @requires_auth # def get_all_pastes(): #", "# db.session.delete(paste_to_delete) # else: # paste_to_delete.report_count = paste_to_delete.report_count + 1", "methods=['GET']) @requires_auth def edit_form(url): if 'user_id' in session: user_id =", "is None: # return render_template(\"index.html\"),4044 # else: # paste.title =", "request.form['text'] paste_type = request.form['type'] if 'user_id' in session: user_id =", "from functools import wraps from datetime import datetime from dateutil", "url_pre + paste.url # if user.user_type == 1: # return", "in session: if(paste.paste_type == \"1\" and session['user_id'] != paste.user_id): return", "add_time, expire_time, user_id, url, report_count, paste_type) user = User.query.filter(User.id ==", "= User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste)", "user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template('allpaste.html', paste_list=paste_list)", "+ url) else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id ==", "paste in paste_list: # paste.url = url_pre + paste.url #", "paste.text) def display_paste(url): paste = Paste.query.filter(Paste.url == url).first() if Paste.query.filter(Paste.url", "# if paste_to_delete.report_count > 5: # db.session.delete(paste_to_delete) # else: #", "user_id).first() if paste is None: return render_template(\"index.html\"), 404 if is_active(paste):", "@mod_paste.route('/<url>/embed/output', methods=['GET']) def embed_code_disp(url): paste = Paste.query.filter(Paste.url == url).first() if", "paste.add_time, 'paste_expire': paste.expire_time}), 200 else: userid_to_red = paste.user_id user_to_red =", "== User.id).first() if is_active(paste): return jsonify({'paste_owner': user.username, 'paste_text': paste.text, 'paste_title':", "user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template('allpaste.html', paste_list=paste_list) @mod_paste.route('/<username>/paste', methods=['GET'])", "# pastes = paste.query.filter(paste.user_id == user_id).all() if 'user_id' in session:", "url, report_count, paste_type) user = User.query.filter(User.id == user_id).first() x =", "creating Paste, Please check if all fields are filled'}), 400", "= User.query.filter(paste.user_id == User.id).first() if is_active(paste): return jsonify({'paste_owner': user.username, 'paste_text':", "render_template('view_paste.html') if user.user_type == 2: return render_template('view_paste_admin.html') return render_template(\"view_paste_guest.html\") else:", "# temp_paste['expire_time']=paste.expire_time # temp_paste['lang']=paste.lang # temp_paste['url']=paste.url # active.append(temp_paste) # #", "request.form['time'] paste_type = request.form['type'] expire_time = str(time_form) paste.title = title", "paste.query.filter(paste.user_id == user_id).all() # curr_id = session['user_id'] # user =", "= User.query.filter(userid_to_red == User.id) user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste)", "render_template(\"index.html\"), 404 # @mod_paste.route('/<url>/add_report', methods=['POST']) # @requires_auth # def to_delete(url):", "paste=paste.to_dict()) # @mod_paste.route('/paste/<id>', methods=['POST']) # @requires_auth # def edit_paste(id): #", "render_template('editpaste.html') return jsonify(success=False, reply=\"Not Authorized\"), 400 else: userid_to_red = paste.user_id", "get_lexer_by_name, guess_lexer from pygments.formatters import HtmlFormatter from functools import wraps", "== user_id: return render_template('editpaste.html') return jsonify(success=False, reply=\"Not Authorized\"), 400 else:", "# paste_to_delete.report_count = paste_to_delete.report_count + 1 # db.session.commit() # curr_id", "return jsonify(message=\"Unauthorized\", success=False), 401 user_id = session['user_id'] user = User.query.filter(User.id", "return render_template('view_paste.html') if user.user_type == 2: return render_template('view_paste_admin.html') return render_template(\"view_paste_guest.html\")", "user.paste_count = x + 1 db.session.add(paste) db.session.commit() # jsonify(success=True, paste=paste.to_dict())", "== 1: # return render_template('mypaste.html', paste_list=paste_list) # return render_template('admin_mypaste.html',paste_list =", "= Paste.query.filter(Paste.url == url).first() if Paste.query.filter(Paste.url == url).first() != None:", "user_id = session['user_id'] user = User.query.filter(User.id == user_id).first() if user.user_type", "import datetime from dateutil import parser def requires_admin(f): @wraps(f) def", "def create_paste(): title = request.form['title'] text = request.form['text'] paste_type =", "def get_all_pastes(): # user_id = session['user_id'] # pastes = paste.query.filter(paste.user_id", "user = User.query.filter(User.id == user_id).first() if user.user_type == 1: return", "pastes=[paste.to_dict() for paste in # pastes]) @mod_paste.route('/api/paste', methods=['POST']) @requires_auth def", "def get_all_pastes_object(): user_id = session['user_id'] user = User.query.filter(user_id == User.id).first()", "paste_type) user = User.query.filter(User.id == user_id).first() x = user.paste_count user.paste_count", "# user_id = session['user_id'] # paste = Paste.query.filter( # Paste.id", "1: return render_template('view_paste.html') if user.user_type == 2: return render_template('view_paste_admin.html') return", "if is_active(paste): paste.url = url_pre + paste.url else: userid_to_red =", "@mod_paste.route('/<username>/paste', methods=['GET']) @requires_admin def get_user_pastes(username): # user_id = session['user_id'] #", "# def get_paste(id): # user_id = session['user_id'] # paste =", "1 db.session.add(paste) db.session.commit() # jsonify(success=True, paste=paste.to_dict()) return jsonify({'url': url}), 200", "= Paste.query.filter(Paste.url == url).first() if is_active(paste): return render_template('embed.html', paste_text=paste.text, paste_link=\"http://127.0.0.1:8080/\"", "userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count =", "import Paste import uuid from datetime import datetime from app.user.models", "= session['user_id'] # pastes = paste.query.filter(paste.user_id == user_id).all() if 'user_id'", "[] for paste in pastes: if is_active(paste): active.append(paste.to_dict()) else: userid_to_red", "userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return jsonify(success=True,", "user = User.query.filter(user_id == User.id).first() pastes = Paste.query.filter(Paste.user_id == user_id).all()", "def get_all_pastes_object(): # user_id = session['user_id'] # user = User.query.filter(user_id", "url_pre = \"/\" # for paste in paste_list: # paste.url", "# paste_lang=paste.lang, highlight_style=style, @mod_paste.route('/<url>', methods=['GET']) # paste_text=result,paste_rawdata = paste.text) def", "db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 else: return render_template(\"index.html\"), 404 @mod_paste.route('/api/<url>',", "paste_to_delete.report_count + 1 # db.session.commit() # curr_id = session['user_id'] #", "return jsonify(success=True, pastes=[paste.to_dict() for paste in # # pastes]) #", "= session['user_id'] # paste_list = Paste.query.filter(Paste.user_id == curr_id).all() # url_pre", "Blueprint, request, render_template, \\ flash, g, session, redirect, url_for, jsonify", "request.form['type'] if 'user_id' in session: user_id = session['user_id'] else: user", "return render_template('embed.html', paste_text=paste.text, paste_link=\"http://127.0.0.1:8080/\" + url) else: userid_to_red = paste.user_id", "Paste import uuid from datetime import datetime from app.user.models import", "# user_id = session['user_id'] # paste = paste.query.filter( # Paste.id", "pygments.formatters import HtmlFormatter from functools import wraps from datetime import", "'user_id' in session: return render_template('user_paste.html') else: return jsonify({'error': 'Please Login", "paste_list) # # return jsonify(success=True, pastes=[paste.to_dict() for paste in #", "check if all fields are filled'}), 400 @mod_paste.route('/paste', methods=['GET']) @requires_auth", "datetime import datetime from dateutil import parser def requires_admin(f): @wraps(f)", "Paste.query.filter(Paste.url == url).first() != None: if is_active(paste): if 'user_id' in", "user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template('index.html'), 404", "= paste.query.filter(paste.user_id == user_id).all() if 'user_id' in session: return render_template('user_paste.html')", "paste.lang = request.form['lang'] # db.session.commit() # return jsonify(success=True) @mod_paste.route('/<url>/delete', methods=['POST'])", "is_active(paste): return jsonify({'paste_owner': user.username, 'paste_text': paste.text, 'paste_title': paste.title, 'paste_lang': paste.lang,", "user_id).first() x = user.paste_count user.paste_count = x + 1 db.session.add(paste)", "render_template(\"view_paste_guest.html\") else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first()", "session['user_id'] # paste = paste.query.filter( # Paste.id == id, Paste.user_id", "= request.form['time'] paste_type = request.form['type'] expire_time = str(time_form) paste.title =", "@wraps(f) def decorated(*args, **kwargs): if 'user_id' not in session: return", "- 1 db.session.delete(paste) db.session.commit() return render_template('allpaste.html', paste_list=paste_list) @mod_paste.route('/<username>/paste', methods=['GET']) @requires_admin", "return render_template('user.html', username=user.username) @mod_paste.route('/create_paste', methods=['POST']) def create_paste(): title = request.form['title']", "# return render_template(\"index.html\"),4044 # else: # paste.title = request.form['title'] #", "session: return render_template('user_paste.html') else: return jsonify({'error': 'Please Login to Continue'}),", "# return jsonify(success=True, pastes=[paste.to_dict() for paste in # # pastes])", "== user_id).all() # active = [] # for paste in", "import get_lexer_by_name, guess_lexer from pygments.formatters import HtmlFormatter from functools import", "db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/paste', methods=['GET']) # @requires_auth", "# # pastes]) # # # @mod_paste.route('/api/paste', methods=['POST']) # @requires_auth", "= get_lexer_by_name(paste.lang) # formatter = HtmlFormatter(linenos=True, cssclass=\"highlight\") # result =", "- 1 db.session.delete(paste) db.session.commit() return render_template('index.html'), 404 if paste.user_id !=", "User.query.filter(User.username == 'Guest').first() user_id = user.id lang = request.form['lang'] time_form", "paste=paste.to_dict()) return jsonify({'url': url}), 200 except: return jsonify({'error': 'Error while", "@mod_paste.route('/<url>', methods=['GET']) # paste_text=result,paste_rawdata = paste.text) def display_paste(url): paste =", "return jsonify(success=True, url=url) return jsonify(success=False, reply=\"Please Login\") @mod_paste.route('/admin/pastes', methods=['GET']) @requires_admin", "url).first() if is_active(paste): return render_template('embed_output.html') else: userid_to_red = paste.user_id user_to_red", "return decorated mod_paste = Blueprint('paste', __name__) CORS(mod_paste) def is_active(paste): return", "# active = [] # for paste in pastes: #", "if paste is None: return render_template(\"index.html\"), 404 if is_active(paste): if", "session, redirect, url_for, jsonify from app import db, requires_auth from", "@requires_auth # def get_all_pastes(): # # user_id = session['user_id'] #", "highlight from pygments.lexers import get_lexer_by_name, guess_lexer from pygments.formatters import HtmlFormatter", "db.session.commit() return jsonify(success=True, user_type=user.user_type), 200 else: return jsonify(success=False), 400 else:", "def decorated(*args, **kwargs): if 'user_id' not in session: return jsonify(message=\"Unauthorized\",", "is_active(paste): return parser.parse(paste.expire_time) > datetime.now() @mod_paste.route('/create_paste', methods=['GET']) @requires_auth def create_form():", "# lexer = get_lexer_by_name(paste.lang) # formatter = HtmlFormatter(linenos=True, cssclass=\"highlight\") #", "return render_template('embed_output.html') else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id ==", "lexer, formatter) # return render_template(\"view_paste.html\", paste_title=paste.title, # paste_lang=paste.lang, highlight_style=style, @mod_paste.route('/<url>',", "active.append(paste.to_dict()) else: userid_to_red = paste.user_id user_to_red = User.query.filter(userid_to_red == User.id)", "# return render_template('mypaste.html', paste_list=paste_list) @mod_paste.route('/<url>/edit', methods=['GET']) @requires_auth def edit_form(url): if", "request.form['lang'] # db.session.commit() # return jsonify(success=True) @mod_paste.route('/<url>/delete', methods=['POST']) @requires_auth def", "jsonify(success=False), 400 else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id ==", "return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>/embed', methods=['POST']) # def embed_code(url): #", "f(*args, **kwargs) return decorated mod_paste = Blueprint('paste', __name__) CORS(mod_paste) def", "# admin = User.query.filter(admin_id == User.id).first() user = User.query.filter(User.username ==", "1 db.session.delete(paste) db.session.commit() return render_template('allpaste.html', paste_list=paste_list) @mod_paste.route('/<username>/paste', methods=['GET']) @requires_admin def", "== 1: return render_template('view_paste.html') if user.user_type == 2: return render_template('view_paste_admin.html')", "if user.user_type == 1: # return render_template('mypaste.html', paste_list=paste_list) # return", "return jsonify({'paste_owner': user.username, 'paste_text': paste.text, 'paste_title': paste.title, 'paste_lang': paste.lang, 'paste_add':", "return render_template(\"view_paste.html\", paste_title=paste.title, # paste_lang=paste.lang, highlight_style=style, @mod_paste.route('/<url>', methods=['GET']) # paste_text=result,paste_rawdata", "- 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 return jsonify(success=False, reply=\"Please", "# @mod_paste.route('/paste/<id>', methods=['POST']) # @requires_auth # def edit_paste(id): # user_id", "= session['user_id'] user = User.query.filter(User.id == user_id).first() if user.user_type ==", "== curr_id).all() # url_pre = \"/\" # for paste in", "if is_active(paste): active.append(paste.to_dict()) else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id", "id, Paste.user_id == user_id).first() # if paste is None: #", "curr_id = session['user_id'] # paste_list = Paste.query.filter(Paste.user_id == curr_id).all() #", "\\ flash, g, session, redirect, url_for, jsonify from app import", "# def to_delete(url): # paste_to_delete = Paste.query.filter(Paste.url == url).first() #", "# temp_paste = {} # if paste.is_active(): # temp_paste['title'] =", "report_count, paste_type) user = User.query.filter(User.id == user_id).first() x = user.paste_count", "temp_paste['add_time']=paste.add_time # temp_paste['expire_time']=paste.expire_time # temp_paste['lang']=paste.lang # temp_paste['url']=paste.url # active.append(temp_paste) #", "return jsonify(success=True, user_type=user.user_type), 200 else: return jsonify(success=False), 400 else: userid_to_red", "url).first() if Paste.query.filter(Paste.url == url).first() != None: if is_active(paste): if", "== url).first() # return jsonify(paste_text = paste.text,paste_link = url) @mod_paste.route('/<url>/embed/output',", "return render_template(\"index.html\"),4044 # else: # paste.title = request.form['title'] # paste.text", "paste = Paste.query.filter(Paste.url == url).first() if is_active(paste): return render_template('embed_output.html') else:", "paste.query.filter( # Paste.id == id, Paste.user_id == user_id).first() # if", "report_count = 0 try: paste = Paste(title, text, lang, add_time,", "user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1", "= User.query.filter(User.id == user_id).first() if paste is None: return render_template(\"index.html\"),", "curr_id).first() return render_template('user.html', username=user.username) @mod_paste.route('/create_paste', methods=['POST']) def create_paste(): title =", "user = User.query.filter(User.id == user_id).first() if(user.user_type != 2): return jsonify(message=\"Unauthorized\",", "x + 1 db.session.add(paste) db.session.commit() # jsonify(success=True, paste=paste.to_dict()) return jsonify({'url':", "return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>/add_report', methods=['POST']) # @requires_auth # def", "1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>', methods=['GET']) #", "import HtmlFormatter from functools import wraps from datetime import datetime", "session['user_id'] user = User.query.filter(User.id == user_id).first() if(user.user_type != 2): return", "= session['user_id'] # user = User.query.filter(user_id == User.id).first() # pastes", "in session: user_id = session['user_id'] paste = Paste.query.filter(Paste.url == url).first()", "in paste_list: # paste.url = url_pre + paste.url # return", "@mod_paste.route('/<url>/edit', methods=['POST']) @requires_auth def edit_paste(url): if 'user_id' in session: user_id", "@mod_paste.route('/create_paste', methods=['POST']) def create_paste(): title = request.form['title'] text = request.form['text']", "try: paste = Paste(title, text, lang, add_time, expire_time, user_id, url,", "def get_paste(id): # user_id = session['user_id'] # paste = paste.query.filter(", "paste = Paste.query.filter(Paste.url == url).first() user = User.query.filter(User.id == user_id).first()", "# return render_template('mypaste.html', paste_list=paste_list) # return render_template('admin_mypaste.html',paste_list = paste_list) #", "import datetime from app.user.models import User from pygments import highlight", "== url).first() if is_active(paste): return render_template('embed_output.html') else: userid_to_red = paste.user_id", "# db.session.commit() # return jsonify(success=True) @mod_paste.route('/<url>/delete', methods=['POST']) @requires_auth def delete_paste(url):", "paste.url = url_pre + paste.url # if user.user_type == 1:", "parser.parse(paste.expire_time) > datetime.now() @mod_paste.route('/create_paste', methods=['GET']) @requires_auth def create_form(): curr_id =", "== id, Paste.user_id == user_id).first() # if paste is None:", "paste.text = request.form['text'] # paste.color = request.form['color'] # paste.lang =", "paste.expire_time}), 200 else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id ==", "get_lexer_by_name(paste.lang) # formatter = HtmlFormatter(linenos=True, cssclass=\"highlight\") # result = highlight(paste.text,", "400 # return jsonify(success=True, pastes=[paste.to_dict() for paste in # pastes])", "user_to_red = User.query.filter(userid_to_red == User.id) user_to_red.paste_count = user_to_red.paste_count - 1", "paste_text=paste.text, paste_link=\"http://127.0.0.1:8080/\" + url) else: userid_to_red = paste.user_id user_to_red =", "2: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count", "'user_id' in session: if(paste.paste_type == \"1\" and session['user_id'] != paste.user_id):", "= Paste.query.filter(Paste.user_id == user_id).all() # active = [] # for", "paste = Paste.query.filter( # Paste.id == id, Paste.user_id == user_id).first()", "user = User.query.filter(user_id == User.id).first() # pastes = Paste.query.filter(Paste.user_id ==", "paste.lang = lang paste.expire_time = expire_time paste.paste_type = paste_type db.session.commit()", "200 @mod_paste.route('/<url>/embed', methods=['GET']) def embed_code_form(url): paste = Paste.query.filter(Paste.url == url).first()", "= user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template('index.html'), 404 if", "= session['user_id'] user = User.query.filter(User.id == curr_id).first() return render_template('user.html', username=user.username)", "== url).first() # style = HtmlFormatter().get_style_defs('.highlight') # lexer = get_lexer_by_name(paste.lang)", "db.session.delete(paste_to_delete) # else: # paste_to_delete.report_count = paste_to_delete.report_count + 1 #", "Paste.user_id == user_id).first() # if paste is None: # return", "if 'user_id' in session: if(paste.paste_type == \"1\" and session['user_id'] !=", "2: return render_template('view_paste_admin.html') return render_template(\"view_paste_guest.html\") else: userid_to_red = paste.user_id user_to_red", "= session['user_id'] # paste = Paste.query.filter( # Paste.id == id,", "jsonify({'error': 'Error while creating Paste, Please check if all fields", "Paste.query.filter(Paste.url == url).first() user = User.query.filter(paste.user_id == User.id).first() if is_active(paste):", "paste.text,paste_link = url) @mod_paste.route('/<url>/embed/output', methods=['GET']) def embed_code_disp(url): paste = Paste.query.filter(Paste.url", "def requires_admin(f): @wraps(f) def decorated(*args, **kwargs): if 'user_id' not in", ".models import Paste import uuid from datetime import datetime from", "expire_time = str(time_form) add_time = str(datetime.now()) url = str(uuid.uuid4()) report_count", "= Paste(title, text, lang, add_time, expire_time, user_id, url, report_count, paste_type)", "render_template('mypaste.html', paste_list=paste_list) # return render_template('admin_mypaste.html',paste_list = paste_list) # # return", "# temp_paste['url']=paste.url # active.append(temp_paste) # # return jsonify({'paste_list':active,'username':user.username}),200 # @mod_paste.route('/paste/<id>',", "Paste.query.filter( # Paste.id == id, Paste.user_id == user_id).first() # if", "user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return jsonify(success=True, user_type=user.user_type),", "# paste = Paste.query.filter(Paste.url == url).first() # style = HtmlFormatter().get_style_defs('.highlight')", "User.query.filter(User.id == user_id).first() if user.user_type == 1: return render_template('view_paste.html') if", "= User.query.filter(user_id == User.id).first() pastes = Paste.query.filter(Paste.user_id == user_id).all() active", "if(paste.paste_type == \"1\" and session['user_id'] != paste.user_id): return render_template(\"index.html\"), 200", "= str(time_form) paste.title = title paste.text = text paste.lang =", "from .models import Paste import uuid from datetime import datetime", "paste_type db.session.commit() return jsonify(success=True, url=url) return jsonify(success=False, reply=\"Please Login\") @mod_paste.route('/admin/pastes',", "in paste_list: if is_active(paste): paste.url = url_pre + paste.url else:", "# # return jsonify({'paste_list':active,'username':user.username}),200 # @mod_paste.route('/paste/<id>', methods=['GET']) # @requires_auth #", "# paste.url = url_pre + paste.url # return render_template('mypaste.html', paste_list=paste_list)", "paste = Paste.query.filter(Paste.url == url).first() if not is_active(paste): userid_to_red =", "jsonify(message=\"Unauthorized\", success=False), 401 return f(*args, **kwargs) return decorated mod_paste =", "request.form['title'] text = request.form['text'] paste_type = request.form['type'] if 'user_id' in", "- 1 db.session.delete(paste) db.session.commit() return jsonify(success=True, user_type=user.user_type), 200 else: return", "'Error while creating Paste, Please check if all fields are", "User.query.filter(user_id == User.id).first() # pastes = Paste.query.filter(Paste.user_id == user_id).all() #", "def display_paste(url): # paste = Paste.query.filter(Paste.url == url).first() # style", "def to_delete(url): # paste_to_delete = Paste.query.filter(Paste.url == url).first() # if", "print(user_id) paste = Paste.query.filter(Paste.url == url).first() user = User.query.filter(User.id ==", "if paste.user_id == user_id: return render_template('editpaste.html') return jsonify(success=False, reply=\"Not Authorized\"),", "paste_list: # paste.url = url_pre + paste.url # if user.user_type", "return render_template('user_paste.html') else: return jsonify({'error': 'Please Login to Continue'}), 400", "return render_template('admin_mypaste.html',paste_list = paste_list) # # return jsonify(success=True, pastes=[paste.to_dict() for", "== User.id).first() # pastes = Paste.query.filter(Paste.user_id == user_id).all() # active", "curr_id = session['user_id'] # user = User.query.filter(User.id == curr_id).first() #", "if is_active(paste): if paste.user_id == user_id or user.user_type == 2:", "active = [] for paste in pastes: if is_active(paste): active.append(paste.to_dict())", "HtmlFormatter from functools import wraps from datetime import datetime from", "def edit_paste(id): # user_id = session['user_id'] # paste = Paste.query.filter(", "for paste in # # pastes]) # # # @mod_paste.route('/api/paste',", "Paste.query.filter(Paste.user_id == user_id).all() # active = [] # for paste", "# print(user_id) paste = Paste.query.filter(Paste.url == url).first() user = User.query.filter(User.id", "session['user_id'] else: user = User.query.filter(User.username == 'Guest').first() user_id = user.id", "404 # @mod_paste.route('/<url>', methods=['GET']) # def display_paste(url): # paste =", "= user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return jsonify({'paste_list': active, 'username':", "highlight(paste.text, lexer, formatter) # return render_template(\"view_paste.html\", paste_title=paste.title, # paste_lang=paste.lang, highlight_style=style,", "methods=['GET']) def embed_code_disp(url): paste = Paste.query.filter(Paste.url == url).first() if is_active(paste):", "temp_paste['url']=paste.url # active.append(temp_paste) # # return jsonify({'paste_list':active,'username':user.username}),200 # @mod_paste.route('/paste/<id>', methods=['GET'])", "session['user_id'] paste = Paste.query.filter(Paste.url == url).first() if is_active(paste): if paste.user_id", "session['user_id'] user = User.query.filter(user_id == User.id).first() pastes = Paste.query.filter(Paste.user_id ==", "return render_template(\"index.html\"), 404 else: return render_template(\"index.html\"), 404 @mod_paste.route('/api/<url>', methods=['POST']) def", "db.session.add(paste) db.session.commit() # jsonify(success=True, paste=paste.to_dict()) return jsonify({'url': url}), 200 except:", "request.form['lang'] time_form = request.form['time'] paste_type = request.form['type'] expire_time = str(time_form)", "@mod_paste.route('/<username>/api/paste', methods=['POST']) #@requires_admin def get_user_pastes_object(username): # admin_id = session['user_id'] #", "= Blueprint('paste', __name__) CORS(mod_paste) def is_active(paste): return parser.parse(paste.expire_time) > datetime.now()", "reply=\"Not Authorized\"), 400 title = request.form['title'] text = request.form['text'] lang", "x = user.paste_count user.paste_count = x + 1 db.session.add(paste) db.session.commit()", "return jsonify(success=True, pastes=[paste.to_dict() for paste in # pastes]) @mod_paste.route('/api/paste', methods=['POST'])", "= Paste.query.filter(curr_id == Paste.user_id).all() # url_pre = \"/\" # for", "user_id = session['user_id'] # user = User.query.filter(user_id == User.id).first() #", "db.session.commit() return render_template(\"index.html\"), 404 return jsonify(success=False, reply=\"Please Login\"), 400 @mod_paste.route('/<url>/edit',", "= request.form['time'] expire_time = str(time_form) add_time = str(datetime.now()) url =", "methods=['POST']) @requires_auth def delete_paste(url): user_id = session['user_id'] # print(user_id) paste", "paste = Paste.query.filter(Paste.url == url).first() user = User.query.filter(paste.user_id == User.id).first()", "user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return jsonify({'paste_list': active,", "temp_paste = {} # if paste.is_active(): # temp_paste['title'] = paste.title", "pygments import highlight from pygments.lexers import get_lexer_by_name, guess_lexer from pygments.formatters", "user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template('index.html'), 404 if paste.user_id", "return jsonify(paste_text = paste.text,paste_link = url) @mod_paste.route('/<url>/embed/output', methods=['GET']) def embed_code_disp(url):", "pastes = Paste.query.filter(Paste.user_id == user_id).all() # active = [] #", "db.session.commit() return render_template('index.html'), 404 if paste.user_id != user_id: return jsonify(success=False,", "userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template('allpaste.html',", "if is_active(paste): if paste.user_id == user_id: return render_template('editpaste.html') return jsonify(success=False,", "paste = Paste.query.filter(Paste.url == url).first() if Paste.query.filter(Paste.url == url).first() !=", "= Paste.query.filter(Paste.user_id == user.id).all() active = [] for paste in", "paste_type = request.form['type'] if 'user_id' in session: user_id = session['user_id']", "import User from pygments import highlight from pygments.lexers import get_lexer_by_name,", "'Guest').first() user_id = user.id lang = request.form['lang'] time_form = request.form['time']", "paste.url # return render_template('mypaste.html', paste_list=paste_list) @mod_paste.route('/<url>/edit', methods=['GET']) @requires_auth def edit_form(url):", "404 # @mod_paste.route('/<url>/add_report', methods=['POST']) # @requires_auth # def to_delete(url): #", "= session['user_id'] user = User.query.filter(User.id == user_id).first() if(user.user_type != 2):", "= session['user_id'] # paste = paste.query.filter( # Paste.id == id,", "if is_active(paste): if 'user_id' in session: if(paste.paste_type == \"1\" and", "@mod_paste.route('/<url>', methods=['GET']) # def display_paste(url): # paste = Paste.query.filter(Paste.url ==", "str(datetime.now()) url = str(uuid.uuid4()) report_count = 0 try: paste =", "paste = Paste.query.filter(Paste.url == url).first() # style = HtmlFormatter().get_style_defs('.highlight') #", "\"/\" for paste in paste_list: if is_active(paste): paste.url = url_pre", "pygments.lexers import get_lexer_by_name, guess_lexer from pygments.formatters import HtmlFormatter from functools", "user = User.query.filter(paste.user_id == User.id).first() if is_active(paste): return jsonify({'paste_owner': user.username,", "in session: return render_template('user_paste.html') else: return jsonify({'error': 'Please Login to", "Paste.query.filter(Paste.url == url).first() # return jsonify(paste_text = paste.text,paste_link = url)", "from pygments.formatters import HtmlFormatter from functools import wraps from datetime", "import CORS from .models import Paste import uuid from datetime", "# return render_template(\"view_paste.html\", paste_title=paste.title, # paste_lang=paste.lang, highlight_style=style, @mod_paste.route('/<url>', methods=['GET']) #", "paste_to_delete.report_count = paste_to_delete.report_count + 1 # db.session.commit() # curr_id =", "== user_id).all() if 'user_id' in session: return render_template('user_paste.html') else: return", "highlight_style=style, @mod_paste.route('/<url>', methods=['GET']) # paste_text=result,paste_rawdata = paste.text) def display_paste(url): paste", "Authorized\"), 400 else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id ==", "fields are filled'}), 400 @mod_paste.route('/paste', methods=['GET']) @requires_auth def get_all_pastes(): #", "== user_id).all() # curr_id = session['user_id'] # user = User.query.filter(User.id", "render_template(\"index.html\"), 404 if is_active(paste): if paste.user_id == user_id or user.user_type", "- 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>', methods=['GET'])", "lexer = get_lexer_by_name(paste.lang) # formatter = HtmlFormatter(linenos=True, cssclass=\"highlight\") # result", "import Blueprint, request, render_template, \\ flash, g, session, redirect, url_for,", "= request.form['title'] text = request.form['text'] lang = request.form['lang'] time_form =", "paste.expire_time = expire_time paste.paste_type = paste_type db.session.commit() return jsonify(success=True, url=url)", "User.query.filter(paste.user_id == User.id).first() if is_active(paste): return jsonify({'paste_owner': user.username, 'paste_text': paste.text,", "user = User.query.filter(User.username == 'Guest').first() user_id = user.id lang =", "user_id).all() if 'user_id' in session: curr_id = session['user_id'] user =", "# @mod_paste.route('/api/paste', methods=['POST']) # @requires_auth # def get_all_pastes_object(): # user_id", "= user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return jsonify(success=True, user_type=user.user_type), 200", "+ 1 db.session.add(paste) db.session.commit() # jsonify(success=True, paste=paste.to_dict()) return jsonify({'url': url}),", "# return jsonify(paste_text = paste.text,paste_link = url) @mod_paste.route('/<url>/embed/output', methods=['GET']) def", "render_template(\"index.html\"), 404 # @mod_paste.route('/paste', methods=['GET']) # @requires_auth # def get_all_pastes():", "# paste = paste.query.filter( # Paste.id == id, Paste.user_id ==", "def edit_form(url): if 'user_id' in session: user_id = session['user_id'] paste", "return render_template('admin_mypaste.html') return render_template(\"mypaste.html\") else: return jsonify({'error': 'Please Login to", "jsonify(success=True, url=url) return jsonify(success=False, reply=\"Please Login\") @mod_paste.route('/admin/pastes', methods=['GET']) @requires_admin def", "== user_id).first() if paste is None: return render_template(\"index.html\"), 404 if", "User.query.filter(User.id == user_id).first() if(user.user_type != 2): return jsonify(message=\"Unauthorized\", success=False), 401", "parser def requires_admin(f): @wraps(f) def decorated(*args, **kwargs): if 'user_id' not", "from app.user.models import User from pygments import highlight from pygments.lexers", "def embed_code_disp(url): paste = Paste.query.filter(Paste.url == url).first() if is_active(paste): return", "return render_template('view_paste_admin.html') return render_template(\"view_paste_guest.html\") else: userid_to_red = paste.user_id user_to_red =", "expire_time = str(time_form) paste.title = title paste.text = text paste.lang", "@requires_auth def edit_paste(url): if 'user_id' in session: user_id = session['user_id']", "active, 'username': user.username}), 200 @mod_paste.route('/<url>/embed', methods=['GET']) def embed_code_form(url): paste =", "return render_template(\"index.html\"), 404 @mod_paste.route('/api/<url>', methods=['POST']) def ret_paste(url): paste = Paste.query.filter(Paste.url", "+ paste.url # if user.user_type == 1: # return render_template('mypaste.html',", "requires_auth from flask_cors import CORS from .models import Paste import", "jsonify({'paste_list':active,'username':user.username}),200 # @mod_paste.route('/paste/<id>', methods=['GET']) # @requires_auth # def get_paste(id): #", "datetime.now() @mod_paste.route('/create_paste', methods=['GET']) @requires_auth def create_form(): curr_id = session['user_id'] user", "render_template, \\ flash, g, session, redirect, url_for, jsonify from app", "render_template(\"index.html\"), 404 # @mod_paste.route('/<url>/embed', methods=['POST']) # def embed_code(url): # paste", "jsonify({'url': url}), 200 except: return jsonify({'error': 'Error while creating Paste,", "return jsonify({'error': 'Please Login to Continue'}), 400 # return jsonify(success=True,", "if user.user_type == 1: return render_template('view_paste.html') if user.user_type == 2:", "= Paste.query.filter(Paste.user_id == curr_id).all() # url_pre = \"/\" # for", "session['user_id'] user = User.query.filter(User.id == curr_id).first() return render_template('user.html', username=user.username) @mod_paste.route('/create_paste',", "from datetime import datetime from app.user.models import User from pygments", "@requires_auth def get_all_pastes(): # user_id = session['user_id'] # pastes =", "- 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/paste', methods=['GET'])", "db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/paste', methods=['GET']) # @requires_auth #", "None: # return render_template(\"index.html\"),4044 # else: # return jsonify(success=True, paste=paste.to_dict())", "db.session.delete(paste) db.session.commit() return jsonify(success=True, user_type=user.user_type), 200 else: return jsonify(success=False), 400", "@requires_auth # def to_delete(url): # paste_to_delete = Paste.query.filter(Paste.url == url).first()", "# curr_id = session['user_id'] # paste_list = Paste.query.filter(Paste.user_id == curr_id).all()", "paste.query.filter(paste.user_id == user_id).all() if 'user_id' in session: curr_id = session['user_id']", "# # user_id = session['user_id'] # # pastes = paste.query.filter(paste.user_id", "embed_code_disp(url): paste = Paste.query.filter(Paste.url == url).first() if is_active(paste): return render_template('embed_output.html')", "'Please Login to Continue'}), 400 # return jsonify(success=True, pastes=[paste.to_dict() for", "else: # paste_to_delete.report_count = paste_to_delete.report_count + 1 # db.session.commit() #", "== userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return", "# paste = Paste.query.filter( # Paste.id == id, Paste.user_id ==", "db.session.delete(paste) db.session.commit() return render_template('index.html'), 404 if paste.user_id != user_id: return", "request.form['text'] # paste.color = request.form['color'] # paste.lang = request.form['lang'] #", "user.id).all() active = [] for paste in pastes: if is_active(paste):", "db.session.commit() # return jsonify(success=True) @mod_paste.route('/<url>/delete', methods=['POST']) @requires_auth def delete_paste(url): user_id", "user_id).all() # curr_id = session['user_id'] # user = User.query.filter(User.id ==", "CORS(mod_paste) def is_active(paste): return parser.parse(paste.expire_time) > datetime.now() @mod_paste.route('/create_paste', methods=['GET']) @requires_auth", "+ 1 # db.session.commit() # curr_id = session['user_id'] # paste_list", "User.id).first() # pastes = Paste.query.filter(Paste.user_id == user_id).all() # active =", "== 2: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first()", "in # pastes]) @mod_paste.route('/<username>/api/paste', methods=['POST']) #@requires_admin def get_user_pastes_object(username): # admin_id", "for paste in # pastes]) @mod_paste.route('/<username>/api/paste', methods=['POST']) #@requires_admin def get_user_pastes_object(username):", "jsonify({'paste_owner': user.username, 'paste_text': paste.text, 'paste_title': paste.title, 'paste_lang': paste.lang, 'paste_add': paste.add_time,", "paste_list: # paste.url = url_pre + paste.url # return render_template('mypaste.html',", "embed_code_form(url): paste = Paste.query.filter(Paste.url == url).first() if is_active(paste): return render_template('embed.html',", "# @requires_auth # def edit_paste(id): # user_id = session['user_id'] #", "expire_time, user_id, url, report_count, paste_type) user = User.query.filter(User.id == user_id).first()", "def create_form(): curr_id = session['user_id'] user = User.query.filter(User.id == curr_id).first()", "Login\") @mod_paste.route('/admin/pastes', methods=['GET']) @requires_admin def all_pastes(): paste_list = db.session.all() url_pre", "# jsonify(success=True, paste=paste.to_dict()) return jsonify({'url': url}), 200 except: return jsonify({'error':", "is_active(paste): paste.url = url_pre + paste.url else: userid_to_red = paste.user_id", "user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>',", "url).first() != None: if is_active(paste): if 'user_id' in session: if(paste.paste_type", "Authorized\"), 400 title = request.form['title'] text = request.form['text'] lang =", "paste in paste_list: if is_active(paste): paste.url = url_pre + paste.url", "user_id, url, report_count, paste_type) user = User.query.filter(User.id == user_id).first() x", "= User.query.filter(User.id == user_id).first() if user.user_type == 1: return render_template('view_paste.html')", "else: return jsonify(success=False), 400 else: userid_to_red = paste.user_id user_to_red =", "jsonify(success=True) @mod_paste.route('/<url>/delete', methods=['POST']) @requires_auth def delete_paste(url): user_id = session['user_id'] #", "paste_link=\"http://127.0.0.1:8080/\" + url) else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id", "HtmlFormatter().get_style_defs('.highlight') # lexer = get_lexer_by_name(paste.lang) # formatter = HtmlFormatter(linenos=True, cssclass=\"highlight\")", "jsonify(success=True, paste=paste.to_dict()) # @mod_paste.route('/paste/<id>', methods=['POST']) # @requires_auth # def edit_paste(id):", "1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>/embed', methods=['POST']) #", "user = User.query.filter(User.id == curr_id).first() # paste_list = Paste.query.filter(curr_id ==", "get_all_pastes(): # user_id = session['user_id'] # pastes = paste.query.filter(paste.user_id ==", "@mod_paste.route('/create_paste', methods=['GET']) @requires_auth def create_form(): curr_id = session['user_id'] user =", "= paste.query.filter(paste.user_id == user_id).all() if 'user_id' in session: curr_id =", "Paste.user_id).all() # url_pre = \"/\" # for paste in paste_list:", "user.username}), 200 @mod_paste.route('/<url>/embed', methods=['GET']) def embed_code_form(url): paste = Paste.query.filter(Paste.url ==", "+ paste.url else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id ==", "datetime from app.user.models import User from pygments import highlight from", "return jsonify({'error': 'Error while creating Paste, Please check if all", "return parser.parse(paste.expire_time) > datetime.now() @mod_paste.route('/create_paste', methods=['GET']) @requires_auth def create_form(): curr_id", "def embed_code(url): # paste = Paste.query.filter(Paste.url == url).first() # return", "def ret_paste(url): paste = Paste.query.filter(Paste.url == url).first() user = User.query.filter(paste.user_id", "Paste.id == id, Paste.user_id == user_id).first() # if paste is", "render_template('index.html'), 404 if paste.user_id != user_id: return jsonify(success=False, reply=\"Not Authorized\"),", "db.session.commit() return jsonify(success=True, url=url) return jsonify(success=False, reply=\"Please Login\") @mod_paste.route('/admin/pastes', methods=['GET'])", "methods=['GET']) def embed_code_form(url): paste = Paste.query.filter(Paste.url == url).first() if is_active(paste):", "User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit()", "for paste in paste_list: # paste.url = url_pre + paste.url", "db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>/embed', methods=['POST']) # def", "== url).first() user = User.query.filter(User.id == user_id).first() if paste is", "@requires_auth def delete_paste(url): user_id = session['user_id'] # print(user_id) paste =", "edit_paste(id): # user_id = session['user_id'] # paste = Paste.query.filter( #", "- 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 else: return render_template(\"index.html\"),", "in session: user_id = session['user_id'] else: user = User.query.filter(User.username ==", "@mod_paste.route('/api/<url>', methods=['POST']) def ret_paste(url): paste = Paste.query.filter(Paste.url == url).first() user", "in pastes: # temp_paste = {} # if paste.is_active(): #", "1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>/add_report', methods=['POST']) #", "= session['user_id'] # # pastes = paste.query.filter(paste.user_id == user_id).all() #", "# for paste in pastes: # temp_paste = {} #", "session['user_id'] # print(user_id) paste = Paste.query.filter(Paste.url == url).first() user =", "session['user_id'] user = User.query.filter(curr_id == User.id).first() if user.user_type == 2:", "uuid from datetime import datetime from app.user.models import User from", "None: if is_active(paste): if 'user_id' in session: if(paste.paste_type == \"1\"", "in pastes: if is_active(paste): active.append(paste.to_dict()) else: userid_to_red = paste.user_id user_to_red", "401 user_id = session['user_id'] user = User.query.filter(User.id == user_id).first() if(user.user_type", "Continue'}), 400 # return jsonify(success=True, pastes=[paste.to_dict() for paste in #", "@mod_paste.route('/<url>/embed', methods=['GET']) def embed_code_form(url): paste = Paste.query.filter(Paste.url == url).first() if", "# pastes]) @mod_paste.route('/<username>/api/paste', methods=['POST']) #@requires_admin def get_user_pastes_object(username): # admin_id =", "session['user_id'] # user = User.query.filter(User.id == curr_id).first() # paste_list =", "if user.user_type == 2: return render_template('view_paste_admin.html') return render_template(\"view_paste_guest.html\") else: userid_to_red", "# curr_id = session['user_id'] # user = User.query.filter(User.id == curr_id).first()", "def all_pastes(): paste_list = db.session.all() url_pre = \"/\" for paste", "= user.paste_count user.paste_count = x + 1 db.session.add(paste) db.session.commit() #", "pastes=[paste.to_dict() for paste in # # pastes]) # # #", "== username).first() pastes = Paste.query.filter(Paste.user_id == user.id).all() active = []", "temp_paste['expire_time']=paste.expire_time # temp_paste['lang']=paste.lang # temp_paste['url']=paste.url # active.append(temp_paste) # # return", "jsonify from app import db, requires_auth from flask_cors import CORS", "paste in pastes: if is_active(paste): active.append(paste.to_dict()) else: userid_to_red = paste.user_id", "app.user.models import User from pygments import highlight from pygments.lexers import", "User.query.filter(admin_id == User.id).first() user = User.query.filter(User.username == username).first() pastes =", "Paste.query.filter(curr_id == Paste.user_id).all() # url_pre = \"/\" # for paste", "= url_pre + paste.url # if user.user_type == 1: #", "= Paste.query.filter(Paste.url == url).first() if is_active(paste): if paste.user_id == user_id:", "user_id = user.id lang = request.form['lang'] time_form = request.form['time'] expire_time", "# for paste in paste_list: # paste.url = url_pre +", "not is_active(paste): userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first()", "import parser def requires_admin(f): @wraps(f) def decorated(*args, **kwargs): if 'user_id'", "user.user_type == 1: # return render_template('mypaste.html', paste_list=paste_list) # return render_template('admin_mypaste.html',paste_list", "# user = User.query.filter(User.id == curr_id).first() # paste_list = Paste.query.filter(curr_id", "cssclass=\"highlight\") # result = highlight(paste.text, lexer, formatter) # return render_template(\"view_paste.html\",", "paste.url = url_pre + paste.url # return render_template('mypaste.html', paste_list=paste_list) @mod_paste.route('/<url>/edit',", "!= user_id: return jsonify(success=False, reply=\"Not Authorized\"), 400 title = request.form['title']", "db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>/add_report', methods=['POST']) # @requires_auth #", "return render_template('mypaste.html', paste_list=paste_list) # return render_template('admin_mypaste.html',paste_list = paste_list) # #", "= \"/\" # for paste in paste_list: # paste.url =", "0 try: paste = Paste(title, text, lang, add_time, expire_time, user_id,", "user.user_type == 2: return render_template('admin_mypaste.html') return render_template(\"mypaste.html\") else: return jsonify({'error':", "# return render_template(\"index.html\"),4044 # else: # return jsonify(success=True, paste=paste.to_dict()) #", "get_user_pastes_object(username): # admin_id = session['user_id'] # admin = User.query.filter(admin_id ==", "paste is None: return render_template(\"index.html\"), 404 if is_active(paste): if paste.user_id", "from pygments import highlight from pygments.lexers import get_lexer_by_name, guess_lexer from", "CORS from .models import Paste import uuid from datetime import", "if 'user_id' in session: curr_id = session['user_id'] user = User.query.filter(curr_id", "render_template(\"index.html\"), 404 # @mod_paste.route('/<url>', methods=['GET']) # def display_paste(url): # paste", "1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 return jsonify(success=False, reply=\"Please Login\"),", "**kwargs): if 'user_id' not in session: return jsonify(message=\"Unauthorized\", success=False), 401", "db.session.commit() return render_template('allpaste.html', paste_list=paste_list) @mod_paste.route('/<username>/paste', methods=['GET']) @requires_admin def get_user_pastes(username): #", "# # return jsonify(success=True, pastes=[paste.to_dict() for paste in # #", "# paste.color = request.form['color'] # paste.lang = request.form['lang'] # db.session.commit()", "# @mod_paste.route('/<url>', methods=['GET']) # def display_paste(url): # paste = Paste.query.filter(Paste.url", "def edit_paste(url): if 'user_id' in session: user_id = session['user_id'] paste", "from app import db, requires_auth from flask_cors import CORS from", "#@requires_admin def get_user_pastes_object(username): # admin_id = session['user_id'] # admin =", "# db.session.commit() # curr_id = session['user_id'] # paste_list = Paste.query.filter(Paste.user_id", "methods=['GET']) # paste_text=result,paste_rawdata = paste.text) def display_paste(url): paste = Paste.query.filter(Paste.url", "db.session.commit() return jsonify({'paste_list': active, 'username': user.username}), 200 @mod_paste.route('/<url>/embed', methods=['GET']) def", "# @mod_paste.route('/paste/<id>', methods=['GET']) # @requires_auth # def get_paste(id): # user_id", "curr_id = session['user_id'] user = User.query.filter(User.id == curr_id).first() return render_template('user.html',", "Paste(title, text, lang, add_time, expire_time, user_id, url, report_count, paste_type) user", "# else: # paste.title = request.form['title'] # paste.text = request.form['text']", "Please check if all fields are filled'}), 400 @mod_paste.route('/paste', methods=['GET'])", "methods=['GET']) @requires_auth def get_all_pastes(): # user_id = session['user_id'] # pastes", "= paste_list) # # return jsonify(success=True, pastes=[paste.to_dict() for paste in", "paste in # pastes]) @mod_paste.route('/<username>/api/paste', methods=['POST']) #@requires_admin def get_user_pastes_object(username): #", "= request.form['text'] # paste.color = request.form['color'] # paste.lang = request.form['lang']", "title = request.form['title'] text = request.form['text'] lang = request.form['lang'] time_form", "paste.title # temp_paste['add_time']=paste.add_time # temp_paste['expire_time']=paste.expire_time # temp_paste['lang']=paste.lang # temp_paste['url']=paste.url #", "'paste_title': paste.title, 'paste_lang': paste.lang, 'paste_add': paste.add_time, 'paste_expire': paste.expire_time}), 200 else:", "paste.color = request.form['color'] # paste.lang = request.form['lang'] # db.session.commit() #", "400 title = request.form['title'] text = request.form['text'] lang = request.form['lang']", "user_id).first() if user.user_type == 1: return render_template('view_paste.html') if user.user_type ==", "url_for, jsonify from app import db, requires_auth from flask_cors import", "paste in # # pastes]) # # # @mod_paste.route('/api/paste', methods=['POST'])", "paste.paste_type = paste_type db.session.commit() return jsonify(success=True, url=url) return jsonify(success=False, reply=\"Please", "= User.query.filter(User.username == 'Guest').first() user_id = user.id lang = request.form['lang']", "user.user_type == 2: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id ==", "User.query.filter(curr_id == User.id).first() if user.user_type == 2: return render_template('admin_mypaste.html') return", "# user = User.query.filter(user_id == User.id).first() # pastes = Paste.query.filter(Paste.user_id", "if paste.is_active(): # temp_paste['title'] = paste.title # temp_paste['add_time']=paste.add_time # temp_paste['expire_time']=paste.expire_time", "if not is_active(paste): userid_to_red = paste.user_id user_to_red = User.query.filter(User.id ==", "jsonify(paste_text = paste.text,paste_link = url) @mod_paste.route('/<url>/embed/output', methods=['GET']) def embed_code_disp(url): paste", "url).first() # if paste_to_delete.report_count > 5: # db.session.delete(paste_to_delete) # else:", "== url).first() if is_active(paste): if paste.user_id == user_id: return render_template('editpaste.html')", "request.form['lang'] time_form = request.form['time'] expire_time = str(time_form) add_time = str(datetime.now())", "userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"),", "paste.user_id != user_id: return jsonify(success=False, reply=\"Not Authorized\"), 400 title =", "@mod_paste.route('/api/paste', methods=['POST']) # @requires_auth # def get_all_pastes_object(): # user_id =", "if Paste.query.filter(Paste.url == url).first() != None: if is_active(paste): if 'user_id'", "Paste.query.filter(Paste.user_id == user.id).all() active = [] for paste in pastes:", "# return render_template('admin_mypaste.html',paste_list = paste_list) # # return jsonify(success=True, pastes=[paste.to_dict()", "# paste.text = request.form['text'] # paste.color = request.form['color'] # paste.lang", "user_type=user.user_type), 200 else: return jsonify(success=False), 400 else: userid_to_red = paste.user_id", "401 return f(*args, **kwargs) return decorated mod_paste = Blueprint('paste', __name__)", "paste_list = Paste.query.filter(curr_id == Paste.user_id).all() # url_pre = \"/\" #", "datetime import datetime from app.user.models import User from pygments import", "render_template('user.html', username=user.username) @mod_paste.route('/create_paste', methods=['POST']) def create_paste(): title = request.form['title'] text", "for paste in paste_list: if is_active(paste): paste.url = url_pre +", "return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>', methods=['GET']) # def display_paste(url): #", "= User.query.filter(User.id == user_id).first() if(user.user_type != 2): return jsonify(message=\"Unauthorized\", success=False),", "= Paste.query.filter(Paste.url == url).first() # if paste_to_delete.report_count > 5: #", "== user_id).all() if 'user_id' in session: curr_id = session['user_id'] user", "import highlight from pygments.lexers import get_lexer_by_name, guess_lexer from pygments.formatters import", "for paste in # pastes]) @mod_paste.route('/api/paste', methods=['POST']) @requires_auth def get_all_pastes_object():", "== user_id or user.user_type == 2: userid_to_red = paste.user_id user_to_red", "guess_lexer from pygments.formatters import HtmlFormatter from functools import wraps from", "Paste.query.filter(Paste.url == url).first() if is_active(paste): return render_template('embed_output.html') else: userid_to_red =", "url).first() user = User.query.filter(User.id == user_id).first() if paste is None:", "in # # pastes]) # # # @mod_paste.route('/api/paste', methods=['POST']) #", "methods=['POST']) # @requires_auth # def to_delete(url): # paste_to_delete = Paste.query.filter(Paste.url", "render_template(\"mypaste.html\") else: return jsonify({'error': 'Please Login to Continue'}), 400 #", "= 0 try: paste = Paste(title, text, lang, add_time, expire_time,", "# pastes]) @mod_paste.route('/api/paste', methods=['POST']) @requires_auth def get_all_pastes_object(): user_id = session['user_id']", "== user.id).all() active = [] for paste in pastes: if", "in session: curr_id = session['user_id'] user = User.query.filter(curr_id == User.id).first()", "session['user_id'] != paste.user_id): return render_template(\"index.html\"), 200 user_id = session['user_id'] user", "Paste.query.filter(Paste.url == url).first() if is_active(paste): return render_template('embed.html', paste_text=paste.text, paste_link=\"http://127.0.0.1:8080/\" +", "else: # return jsonify(success=True, paste=paste.to_dict()) # @mod_paste.route('/paste/<id>', methods=['POST']) # @requires_auth", "= Paste.query.filter(Paste.url == url).first() # style = HtmlFormatter().get_style_defs('.highlight') # lexer", "methods=['GET']) # def display_paste(url): # paste = Paste.query.filter(Paste.url == url).first()", "= paste_type db.session.commit() return jsonify(success=True, url=url) return jsonify(success=False, reply=\"Please Login\")", "= request.form['lang'] time_form = request.form['time'] paste_type = request.form['type'] expire_time =", "if(user.user_type != 2): return jsonify(message=\"Unauthorized\", success=False), 401 return f(*args, **kwargs)", "db.session.all() url_pre = \"/\" for paste in paste_list: if is_active(paste):", "jsonify(success=False, reply=\"Please Login\") @mod_paste.route('/admin/pastes', methods=['GET']) @requires_admin def all_pastes(): paste_list =", "# temp_paste['lang']=paste.lang # temp_paste['url']=paste.url # active.append(temp_paste) # # return jsonify({'paste_list':active,'username':user.username}),200", "@requires_admin def get_user_pastes(username): # user_id = session['user_id'] # pastes =", "url).first() if is_active(paste): if paste.user_id == user_id: return render_template('editpaste.html') return", "# paste_list = Paste.query.filter(curr_id == Paste.user_id).all() # url_pre = \"/\"", "== Paste.user_id).all() # url_pre = \"/\" # for paste in", "active.append(temp_paste) # # return jsonify({'paste_list':active,'username':user.username}),200 # @mod_paste.route('/paste/<id>', methods=['GET']) # @requires_auth", "= paste_to_delete.report_count + 1 # db.session.commit() # curr_id = session['user_id']", "# return jsonify(success=True, paste=paste.to_dict()) # @mod_paste.route('/paste/<id>', methods=['POST']) # @requires_auth #", "delete_paste(url): user_id = session['user_id'] # print(user_id) paste = Paste.query.filter(Paste.url ==", "= request.form['type'] if 'user_id' in session: user_id = session['user_id'] else:", "is None: # return render_template(\"index.html\"),4044 # else: # return jsonify(success=True,", "request, render_template, \\ flash, g, session, redirect, url_for, jsonify from", "pastes = Paste.query.filter(Paste.user_id == user_id).all() active = [] for paste", "render_template(\"index.html\"),4044 # else: # paste.title = request.form['title'] # paste.text =", "jsonify({'error': 'Please Login to Continue'}), 400 # return jsonify(success=True, pastes=[paste.to_dict()", "> datetime.now() @mod_paste.route('/create_paste', methods=['GET']) @requires_auth def create_form(): curr_id = session['user_id']", "user_id = session['user_id'] # print(user_id) paste = Paste.query.filter(Paste.url == url).first()", "paste.user_id): return render_template(\"index.html\"), 200 user_id = session['user_id'] user = User.query.filter(User.id", "Blueprint('paste', __name__) CORS(mod_paste) def is_active(paste): return parser.parse(paste.expire_time) > datetime.now() @mod_paste.route('/create_paste',", "= session['user_id'] paste = Paste.query.filter(Paste.url == url).first() if not is_active(paste):", "# # # @mod_paste.route('/api/paste', methods=['POST']) # @requires_auth # def get_all_pastes_object():", "- 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>/embed', methods=['POST'])", "def embed_code_form(url): paste = Paste.query.filter(Paste.url == url).first() if is_active(paste): return", "get_all_pastes(): # # user_id = session['user_id'] # # pastes =", "is_active(paste): userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count", "render_template('user_paste.html') else: return jsonify({'error': 'Please Login to Continue'}), 400 #", "paste = Paste.query.filter(Paste.url == url).first() if is_active(paste): return render_template('embed.html', paste_text=paste.text,", "request.form['text'] lang = request.form['lang'] time_form = request.form['time'] paste_type = request.form['type']", "User.query.filter(User.username == username).first() pastes = Paste.query.filter(Paste.user_id == user.id).all() active =", "# Paste.id == id, Paste.user_id == user_id).first() # if paste", "- 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>/add_report', methods=['POST'])", "= title paste.text = text paste.lang = lang paste.expire_time =", "in session: return jsonify(message=\"Unauthorized\", success=False), 401 user_id = session['user_id'] user", "curr_id = session['user_id'] user = User.query.filter(curr_id == User.id).first() if user.user_type", "# paste.title = request.form['title'] # paste.text = request.form['text'] # paste.color", "db.session.delete(paste) db.session.commit() return jsonify({'paste_list': active, 'username': user.username}), 200 @mod_paste.route('/<url>/embed', methods=['GET'])", "return render_template(\"index.html\"), 404 if is_active(paste): if paste.user_id == user_id or", "paste.lang, 'paste_add': paste.add_time, 'paste_expire': paste.expire_time}), 200 else: userid_to_red = paste.user_id", "paste is None: # return render_template(\"index.html\"),4044 # else: # return", "if all fields are filled'}), 400 @mod_paste.route('/paste', methods=['GET']) @requires_auth def", "session['user_id'] user = User.query.filter(User.id == user_id).first() if user.user_type == 1:", "lang = request.form['lang'] time_form = request.form['time'] expire_time = str(time_form) add_time", "= HtmlFormatter(linenos=True, cssclass=\"highlight\") # result = highlight(paste.text, lexer, formatter) #", "400 @mod_paste.route('/<url>/edit', methods=['POST']) @requires_auth def edit_paste(url): if 'user_id' in session:", "is_active(paste): active.append(paste.to_dict()) else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id ==", "= session['user_id'] # admin = User.query.filter(admin_id == User.id).first() user =", "paste.title, 'paste_lang': paste.lang, 'paste_add': paste.add_time, 'paste_expire': paste.expire_time}), 200 else: userid_to_red", "to_delete(url): # paste_to_delete = Paste.query.filter(Paste.url == url).first() # if paste_to_delete.report_count", "= text paste.lang = lang paste.expire_time = expire_time paste.paste_type =", "jsonify(success=False, reply=\"Please Login\"), 400 @mod_paste.route('/<url>/edit', methods=['POST']) @requires_auth def edit_paste(url): if", "**kwargs) return decorated mod_paste = Blueprint('paste', __name__) CORS(mod_paste) def is_active(paste):", "to Continue'}), 400 # return jsonify(success=True, pastes=[paste.to_dict() for paste in", "paste_list=paste_list) # return render_template('admin_mypaste.html',paste_list = paste_list) # # return jsonify(success=True,", "db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>', methods=['GET']) # def", "return render_template(\"view_paste_guest.html\") else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id ==", "@mod_paste.route('/admin/pastes', methods=['GET']) @requires_admin def all_pastes(): paste_list = db.session.all() url_pre =", "User.query.filter(userid_to_red == User.id) user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit()", "pastes]) @mod_paste.route('/api/paste', methods=['POST']) @requires_auth def get_all_pastes_object(): user_id = session['user_id'] user", "methods=['GET']) # @requires_auth # def get_all_pastes(): # # user_id =", "db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 return jsonify(success=False, reply=\"Please Login\"), 400", "username=user.username) @mod_paste.route('/create_paste', methods=['POST']) def create_paste(): title = request.form['title'] text =", "== 2: return render_template('admin_mypaste.html') return render_template(\"mypaste.html\") else: return jsonify({'error': 'Please", "= paste.query.filter( # Paste.id == id, Paste.user_id == user_id).first() #", "paste in # pastes]) @mod_paste.route('/api/paste', methods=['POST']) @requires_auth def get_all_pastes_object(): user_id", "@requires_auth def create_form(): curr_id = session['user_id'] user = User.query.filter(User.id ==", "flask_cors import CORS from .models import Paste import uuid from", "# # pastes = paste.query.filter(paste.user_id == user_id).all() # curr_id =", "1: # return render_template('mypaste.html', paste_list=paste_list) # return render_template('admin_mypaste.html',paste_list = paste_list)", "text = request.form['text'] lang = request.form['lang'] time_form = request.form['time'] paste_type", "= session['user_id'] paste = Paste.query.filter(Paste.url == url).first() if is_active(paste): if", "# return jsonify(success=True) @mod_paste.route('/<url>/delete', methods=['POST']) @requires_auth def delete_paste(url): user_id =", "def display_paste(url): paste = Paste.query.filter(Paste.url == url).first() if Paste.query.filter(Paste.url ==", "[] # for paste in pastes: # temp_paste = {}", "User.query.filter(User.id == user_id).first() if paste is None: return render_template(\"index.html\"), 404", "from flask import Blueprint, request, render_template, \\ flash, g, session,", "404 if paste.user_id != user_id: return jsonify(success=False, reply=\"Not Authorized\"), 400", "400 @mod_paste.route('/paste', methods=['GET']) @requires_auth def get_all_pastes(): # user_id = session['user_id']", "@mod_paste.route('/paste', methods=['GET']) @requires_auth def get_all_pastes(): # user_id = session['user_id'] #", "else: return jsonify({'error': 'Please Login to Continue'}), 400 # return", "# @requires_auth # def get_all_pastes(): # # user_id = session['user_id']", "paste = Paste.query.filter(Paste.url == url).first() if is_active(paste): if paste.user_id ==", "Paste.query.filter(Paste.url == url).first() if Paste.query.filter(Paste.url == url).first() != None: if", "paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count -", "paste.title = title paste.text = text paste.lang = lang paste.expire_time", "user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>/embed',", "= paste.user_id user_to_red = User.query.filter(userid_to_red == User.id) user_to_red.paste_count = user_to_red.paste_count", "all fields are filled'}), 400 @mod_paste.route('/paste', methods=['GET']) @requires_auth def get_all_pastes():", "jsonify(success=True, pastes=[paste.to_dict() for paste in # pastes]) @mod_paste.route('/api/paste', methods=['POST']) @requires_auth", "time_form = request.form['time'] expire_time = str(time_form) add_time = str(datetime.now()) url", "@mod_paste.route('/paste', methods=['GET']) # @requires_auth # def get_all_pastes(): # # user_id", "user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 else: return", "HtmlFormatter(linenos=True, cssclass=\"highlight\") # result = highlight(paste.text, lexer, formatter) # return", "db.session.commit() return render_template(\"index.html\"), 404 else: return render_template(\"index.html\"), 404 @mod_paste.route('/api/<url>', methods=['POST'])", "if is_active(paste): return render_template('embed_output.html') else: userid_to_red = paste.user_id user_to_red =", "Login to Continue'}), 400 # return jsonify(success=True, pastes=[paste.to_dict() for paste", "user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>/add_report',", "= lang paste.expire_time = expire_time paste.paste_type = paste_type db.session.commit() return", "pastes = paste.query.filter(paste.user_id == user_id).all() if 'user_id' in session: return", "session['user_id'] # user = User.query.filter(user_id == User.id).first() # pastes =", "= User.query.filter(user_id == User.id).first() # pastes = Paste.query.filter(Paste.user_id == user_id).all()", "== User.id).first() user = User.query.filter(User.username == username).first() pastes = Paste.query.filter(Paste.user_id", "pastes = Paste.query.filter(Paste.user_id == user.id).all() active = [] for paste", "== curr_id).first() return render_template('user.html', username=user.username) @mod_paste.route('/create_paste', methods=['POST']) def create_paste(): title", "@mod_paste.route('/api/paste', methods=['POST']) @requires_auth def get_all_pastes_object(): user_id = session['user_id'] user =", "!= None: if is_active(paste): if 'user_id' in session: if(paste.paste_type ==", "if is_active(paste): active.append(paste.to_dict()) else: userid_to_red = paste.user_id user_to_red = User.query.filter(userid_to_red", "== 2: return render_template('view_paste_admin.html') return render_template(\"view_paste_guest.html\") else: userid_to_red = paste.user_id", "from pygments.lexers import get_lexer_by_name, guess_lexer from pygments.formatters import HtmlFormatter from", "= session['user_id'] # user = User.query.filter(User.id == curr_id).first() # paste_list", "jsonify(success=True, pastes=[paste.to_dict() for paste in # # pastes]) # #", "# pastes = Paste.query.filter(Paste.user_id == user_id).all() # active = []", "if user.user_type == 2: return render_template('admin_mypaste.html') return render_template(\"mypaste.html\") else: return", "return render_template(\"index.html\"), 404 # @mod_paste.route('/paste', methods=['GET']) # @requires_auth # def", "except: return jsonify({'error': 'Error while creating Paste, Please check if", "user_id).all() if 'user_id' in session: return render_template('user_paste.html') else: return jsonify({'error':", "methods=['GET']) @requires_admin def all_pastes(): paste_list = db.session.all() url_pre = \"/\"", "= request.form['lang'] # db.session.commit() # return jsonify(success=True) @mod_paste.route('/<url>/delete', methods=['POST']) @requires_auth", "== user_id).all() active = [] for paste in pastes: if", "is_active(paste): if 'user_id' in session: if(paste.paste_type == \"1\" and session['user_id']", "curr_id).first() # paste_list = Paste.query.filter(curr_id == Paste.user_id).all() # url_pre =", "flash, g, session, redirect, url_for, jsonify from app import db,", "else: userid_to_red = paste.user_id user_to_red = User.query.filter(userid_to_red == User.id) user_to_red.paste_count", "# def get_all_pastes_object(): # user_id = session['user_id'] # user =", "jsonify(success=True, paste=paste.to_dict()) return jsonify({'url': url}), 200 except: return jsonify({'error': 'Error", "are filled'}), 400 @mod_paste.route('/paste', methods=['GET']) @requires_auth def get_all_pastes(): # user_id", "paste.is_active(): # temp_paste['title'] = paste.title # temp_paste['add_time']=paste.add_time # temp_paste['expire_time']=paste.expire_time #", "is None: return render_template(\"index.html\"), 404 if is_active(paste): if paste.user_id ==", "result = highlight(paste.text, lexer, formatter) # return render_template(\"view_paste.html\", paste_title=paste.title, #", "= user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 #", "return render_template(\"index.html\"), 200 user_id = session['user_id'] user = User.query.filter(User.id ==", "= x + 1 db.session.add(paste) db.session.commit() # jsonify(success=True, paste=paste.to_dict()) return", "paste in pastes: # temp_paste = {} # if paste.is_active():", "for paste in pastes: # temp_paste = {} # if", "@mod_paste.route('/<url>/add_report', methods=['POST']) # @requires_auth # def to_delete(url): # paste_to_delete =", "url).first() if not is_active(paste): userid_to_red = paste.user_id user_to_red = User.query.filter(User.id", "# user_id = session['user_id'] # pastes = paste.query.filter(paste.user_id == user_id).all()", "'username': user.username}), 200 @mod_paste.route('/<url>/embed', methods=['GET']) def embed_code_form(url): paste = Paste.query.filter(Paste.url", "methods=['GET']) # @requires_auth # def get_paste(id): # user_id = session['user_id']", "= [] for paste in pastes: if is_active(paste): active.append(paste.to_dict()) else:", "def get_user_pastes(username): # user_id = session['user_id'] # pastes = paste.query.filter(paste.user_id", "render_template('admin_mypaste.html') return render_template(\"mypaste.html\") else: return jsonify({'error': 'Please Login to Continue'}),", "is_active(paste): if paste.user_id == user_id or user.user_type == 2: userid_to_red", "if 'user_id' in session: return render_template('user_paste.html') else: return jsonify({'error': 'Please", "1 db.session.delete(paste) db.session.commit() return jsonify(success=True, user_type=user.user_type), 200 else: return jsonify(success=False),", "# pastes = paste.query.filter(paste.user_id == user_id).all() # curr_id = session['user_id']", "return render_template('editpaste.html') return jsonify(success=False, reply=\"Not Authorized\"), 400 else: userid_to_red =", "400 else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first()", "= str(time_form) add_time = str(datetime.now()) url = str(uuid.uuid4()) report_count =", "= user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template('allpaste.html', paste_list=paste_list) @mod_paste.route('/<username>/paste',", "str(uuid.uuid4()) report_count = 0 try: paste = Paste(title, text, lang,", "= request.form['lang'] time_form = request.form['time'] expire_time = str(time_form) add_time =", "from datetime import datetime from dateutil import parser def requires_admin(f):", "user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return jsonify({'paste_list': active, 'username': user.username}),", "# temp_paste['add_time']=paste.add_time # temp_paste['expire_time']=paste.expire_time # temp_paste['lang']=paste.lang # temp_paste['url']=paste.url # active.append(temp_paste)", "= user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 else:", "render_template('mypaste.html', paste_list=paste_list) @mod_paste.route('/<url>/edit', methods=['GET']) @requires_auth def edit_form(url): if 'user_id' in", "# formatter = HtmlFormatter(linenos=True, cssclass=\"highlight\") # result = highlight(paste.text, lexer,", "== url).first() if not is_active(paste): userid_to_red = paste.user_id user_to_red =", "methods=['POST']) #@requires_admin def get_user_pastes_object(username): # admin_id = session['user_id'] # admin", "url) @mod_paste.route('/<url>/embed/output', methods=['GET']) def embed_code_disp(url): paste = Paste.query.filter(Paste.url == url).first()", "filled'}), 400 @mod_paste.route('/paste', methods=['GET']) @requires_auth def get_all_pastes(): # user_id =", "= User.query.filter(User.id == curr_id).first() # paste_list = Paste.query.filter(curr_id == Paste.user_id).all()", "# @requires_auth # def get_all_pastes_object(): # user_id = session['user_id'] #", "url).first() # style = HtmlFormatter().get_style_defs('.highlight') # lexer = get_lexer_by_name(paste.lang) #", "session: user_id = session['user_id'] paste = Paste.query.filter(Paste.url == url).first() if", "request.form['type'] expire_time = str(time_form) paste.title = title paste.text = text", "success=False), 401 return f(*args, **kwargs) return decorated mod_paste = Blueprint('paste',", "return jsonify(success=True) @mod_paste.route('/<url>/delete', methods=['POST']) @requires_auth def delete_paste(url): user_id = session['user_id']", "paste.title = request.form['title'] # paste.text = request.form['text'] # paste.color =", "render_template('embed.html', paste_text=paste.text, paste_link=\"http://127.0.0.1:8080/\" + url) else: userid_to_red = paste.user_id user_to_red", "Paste.query.filter(Paste.user_id == curr_id).all() # url_pre = \"/\" # for paste", "# paste.url = url_pre + paste.url # if user.user_type ==", "404 @mod_paste.route('/api/<url>', methods=['POST']) def ret_paste(url): paste = Paste.query.filter(Paste.url == url).first()", "= Paste.query.filter(Paste.url == url).first() user = User.query.filter(paste.user_id == User.id).first() if", "if 'user_id' in session: user_id = session['user_id'] else: user =", "db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/<url>', methods=['GET']) # def display_paste(url):", "'user_id' not in session: return jsonify(message=\"Unauthorized\", success=False), 401 user_id =", "for paste in pastes: if is_active(paste): active.append(paste.to_dict()) else: userid_to_red =", "get_all_pastes_object(): # user_id = session['user_id'] # user = User.query.filter(user_id ==", "paste = Paste.query.filter(Paste.url == url).first() # return jsonify(paste_text = paste.text,paste_link", "paste.url # if user.user_type == 1: # return render_template('mypaste.html', paste_list=paste_list)", "# admin_id = session['user_id'] # admin = User.query.filter(admin_id == User.id).first()", "= request.form['title'] # paste.text = request.form['text'] # paste.color = request.form['color']", "jsonify(success=False, reply=\"Not Authorized\"), 400 title = request.form['title'] text = request.form['text']", "@requires_auth # def get_paste(id): # user_id = session['user_id'] # paste", "# @mod_paste.route('/<url>/add_report', methods=['POST']) # @requires_auth # def to_delete(url): # paste_to_delete", "pastes: # temp_paste = {} # if paste.is_active(): # temp_paste['title']", "return jsonify(success=False, reply=\"Not Authorized\"), 400 title = request.form['title'] text =", "= request.form['type'] expire_time = str(time_form) paste.title = title paste.text =", "== url).first() # if paste_to_delete.report_count > 5: # db.session.delete(paste_to_delete) #", "paste_lang=paste.lang, highlight_style=style, @mod_paste.route('/<url>', methods=['GET']) # paste_text=result,paste_rawdata = paste.text) def display_paste(url):", "user = User.query.filter(User.username == username).first() pastes = Paste.query.filter(Paste.user_id == user.id).all()", "== user_id).first() x = user.paste_count user.paste_count = x + 1", "@requires_admin def all_pastes(): paste_list = db.session.all() url_pre = \"/\" for", "active.append(paste.to_dict()) else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first()", "is_active(paste): if paste.user_id == user_id: return render_template('editpaste.html') return jsonify(success=False, reply=\"Not", "pastes: if is_active(paste): active.append(paste.to_dict()) else: userid_to_red = paste.user_id user_to_red =", "paste = Paste(title, text, lang, add_time, expire_time, user_id, url, report_count,", "2): return jsonify(message=\"Unauthorized\", success=False), 401 return f(*args, **kwargs) return decorated", "methods=['POST']) # @requires_auth # def edit_paste(id): # user_id = session['user_id']", "Paste.query.filter(Paste.url == url).first() if is_active(paste): if paste.user_id == user_id: return", "session['user_id'] # admin = User.query.filter(admin_id == User.id).first() user = User.query.filter(User.username", "user = User.query.filter(User.id == curr_id).first() return render_template('user.html', username=user.username) @mod_paste.route('/create_paste', methods=['POST'])", "\"1\" and session['user_id'] != paste.user_id): return render_template(\"index.html\"), 200 user_id =", "= url_pre + paste.url # return render_template('mypaste.html', paste_list=paste_list) @mod_paste.route('/<url>/edit', methods=['GET'])", "user = User.query.filter(User.id == user_id).first() x = user.paste_count user.paste_count =", "200 else: return jsonify(success=False), 400 else: userid_to_red = paste.user_id user_to_red", "== user_id).first() if(user.user_type != 2): return jsonify(message=\"Unauthorized\", success=False), 401 return", "# paste_text=result,paste_rawdata = paste.text) def display_paste(url): paste = Paste.query.filter(Paste.url ==", "= request.form['text'] paste_type = request.form['type'] if 'user_id' in session: user_id", "== 'Guest').first() user_id = user.id lang = request.form['lang'] time_form =", "= User.query.filter(User.id == user_id).first() x = user.paste_count user.paste_count = x", "url=url) return jsonify(success=False, reply=\"Please Login\") @mod_paste.route('/admin/pastes', methods=['GET']) @requires_admin def all_pastes():", "url) else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id == userid_to_red).first()", "while creating Paste, Please check if all fields are filled'}),", "db.session.commit() # curr_id = session['user_id'] # paste_list = Paste.query.filter(Paste.user_id ==", "user_id).first() # if paste is None: # return render_template(\"index.html\"),4044 #", "paste_list = db.session.all() url_pre = \"/\" for paste in paste_list:", "@requires_auth # def edit_paste(id): # user_id = session['user_id'] # paste", "session['user_id'] # paste = Paste.query.filter( # Paste.id == id, Paste.user_id", "!= paste.user_id): return render_template(\"index.html\"), 200 user_id = session['user_id'] user =", "jsonify(success=False, reply=\"Not Authorized\"), 400 else: userid_to_red = paste.user_id user_to_red =", "= expire_time paste.paste_type = paste_type db.session.commit() return jsonify(success=True, url=url) return", "flask import Blueprint, request, render_template, \\ flash, g, session, redirect,", "user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404", "formatter = HtmlFormatter(linenos=True, cssclass=\"highlight\") # result = highlight(paste.text, lexer, formatter)", "'user_id' in session: user_id = session['user_id'] paste = Paste.query.filter(Paste.url ==", "success=False), 401 user_id = session['user_id'] user = User.query.filter(User.id == user_id).first()", "embed_code(url): # paste = Paste.query.filter(Paste.url == url).first() # return jsonify(paste_text", "style = HtmlFormatter().get_style_defs('.highlight') # lexer = get_lexer_by_name(paste.lang) # formatter =", "# @requires_auth # def to_delete(url): # paste_to_delete = Paste.query.filter(Paste.url ==", "# active.append(temp_paste) # # return jsonify({'paste_list':active,'username':user.username}),200 # @mod_paste.route('/paste/<id>', methods=['GET']) #", "expire_time paste.paste_type = paste_type db.session.commit() return jsonify(success=True, url=url) return jsonify(success=False,", "+ paste.url # return render_template('mypaste.html', paste_list=paste_list) @mod_paste.route('/<url>/edit', methods=['GET']) @requires_auth def", "> 5: # db.session.delete(paste_to_delete) # else: # paste_to_delete.report_count = paste_to_delete.report_count", "datetime from dateutil import parser def requires_admin(f): @wraps(f) def decorated(*args,", "else: user = User.query.filter(User.username == 'Guest').first() user_id = user.id lang", "curr_id).all() # url_pre = \"/\" # for paste in paste_list:", "User.id).first() user = User.query.filter(User.username == username).first() pastes = Paste.query.filter(Paste.user_id ==", "title = request.form['title'] text = request.form['text'] paste_type = request.form['type'] if", "1 # db.session.commit() # curr_id = session['user_id'] # paste_list =", "formatter) # return render_template(\"view_paste.html\", paste_title=paste.title, # paste_lang=paste.lang, highlight_style=style, @mod_paste.route('/<url>', methods=['GET'])", "paste.text = text paste.lang = lang paste.expire_time = expire_time paste.paste_type", "@requires_auth # def get_all_pastes_object(): # user_id = session['user_id'] # user", "paste_title=paste.title, # paste_lang=paste.lang, highlight_style=style, @mod_paste.route('/<url>', methods=['GET']) # paste_text=result,paste_rawdata = paste.text)", "user_id = session['user_id'] # pastes = paste.query.filter(paste.user_id == user_id).all() if", "session: return jsonify(message=\"Unauthorized\", success=False), 401 user_id = session['user_id'] user =", "= \"/\" for paste in paste_list: if is_active(paste): paste.url =", "# def embed_code(url): # paste = Paste.query.filter(Paste.url == url).first() #", "session: user_id = session['user_id'] else: user = User.query.filter(User.username == 'Guest').first()", "url}), 200 except: return jsonify({'error': 'Error while creating Paste, Please", "# def display_paste(url): # paste = Paste.query.filter(Paste.url == url).first() #", "1 db.session.delete(paste) db.session.commit() return render_template('index.html'), 404 if paste.user_id != user_id:", "user_id = session['user_id'] user = User.query.filter(user_id == User.id).first() pastes =", "decorated mod_paste = Blueprint('paste', __name__) CORS(mod_paste) def is_active(paste): return parser.parse(paste.expire_time)", "import wraps from datetime import datetime from dateutil import parser", "return jsonify(success=True, paste=paste.to_dict()) # @mod_paste.route('/paste/<id>', methods=['POST']) # @requires_auth # def", "if paste.user_id != user_id: return jsonify(success=False, reply=\"Not Authorized\"), 400 title", "methods=['GET']) @requires_auth def create_form(): curr_id = session['user_id'] user = User.query.filter(User.id", "# pastes]) # # # @mod_paste.route('/api/paste', methods=['POST']) # @requires_auth #", "methods=['POST']) # def embed_code(url): # paste = Paste.query.filter(Paste.url == url).first()", "render_template('view_paste_admin.html') return render_template(\"view_paste_guest.html\") else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id", "= user.id lang = request.form['lang'] time_form = request.form['time'] expire_time =", "Paste, Please check if all fields are filled'}), 400 @mod_paste.route('/paste',", "User.query.filter(User.id == curr_id).first() return render_template('user.html', username=user.username) @mod_paste.route('/create_paste', methods=['POST']) def create_paste():", "temp_paste['title'] = paste.title # temp_paste['add_time']=paste.add_time # temp_paste['expire_time']=paste.expire_time # temp_paste['lang']=paste.lang #", "str(time_form) add_time = str(datetime.now()) url = str(uuid.uuid4()) report_count = 0", "2: return render_template('admin_mypaste.html') return render_template(\"mypaste.html\") else: return jsonify({'error': 'Please Login", "edit_paste(url): if 'user_id' in session: user_id = session['user_id'] paste =", "render_template(\"index.html\"), 404 return jsonify(success=False, reply=\"Please Login\"), 400 @mod_paste.route('/<url>/edit', methods=['POST']) @requires_auth", "def get_all_pastes(): # # user_id = session['user_id'] # # pastes", "Paste.query.filter(Paste.url == url).first() user = User.query.filter(User.id == user_id).first() if paste", "create_paste(): title = request.form['title'] text = request.form['text'] paste_type = request.form['type']", "url).first() user = User.query.filter(paste.user_id == User.id).first() if is_active(paste): return jsonify({'paste_owner':", "paste_text=result,paste_rawdata = paste.text) def display_paste(url): paste = Paste.query.filter(Paste.url == url).first()", "paste.text, 'paste_title': paste.title, 'paste_lang': paste.lang, 'paste_add': paste.add_time, 'paste_expire': paste.expire_time}), 200", "paste_type = request.form['type'] expire_time = str(time_form) paste.title = title paste.text", "def get_user_pastes_object(username): # admin_id = session['user_id'] # admin = User.query.filter(admin_id", "= str(uuid.uuid4()) report_count = 0 try: paste = Paste(title, text,", "# else: # return jsonify(success=True, paste=paste.to_dict()) # @mod_paste.route('/paste/<id>', methods=['POST']) #", "User.query.filter(User.id == curr_id).first() # paste_list = Paste.query.filter(curr_id == Paste.user_id).all() #", "= HtmlFormatter().get_style_defs('.highlight') # lexer = get_lexer_by_name(paste.lang) # formatter = HtmlFormatter(linenos=True,", "active = [] # for paste in pastes: # temp_paste", "== User.id).first() pastes = Paste.query.filter(Paste.user_id == user_id).all() active = []", "paste.url = url_pre + paste.url else: userid_to_red = paste.user_id user_to_red", "requires_admin(f): @wraps(f) def decorated(*args, **kwargs): if 'user_id' not in session:", "User.query.filter(user_id == User.id).first() pastes = Paste.query.filter(Paste.user_id == user_id).all() active =", "or user.user_type == 2: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id", "url).first() # return jsonify(paste_text = paste.text,paste_link = url) @mod_paste.route('/<url>/embed/output', methods=['GET'])", "methods=['GET']) @requires_admin def get_user_pastes(username): # user_id = session['user_id'] # pastes", "== User.id).first() if user.user_type == 2: return render_template('admin_mypaste.html') return render_template(\"mypaste.html\")", "User.query.filter(User.id == user_id).first() x = user.paste_count user.paste_count = x +", "user_id = session['user_id'] # paste = paste.query.filter( # Paste.id ==", "== \"1\" and session['user_id'] != paste.user_id): return render_template(\"index.html\"), 200 user_id", "admin_id = session['user_id'] # admin = User.query.filter(admin_id == User.id).first() user", "pastes = paste.query.filter(paste.user_id == user_id).all() if 'user_id' in session: curr_id", "paste.user_id user_to_red = User.query.filter(userid_to_red == User.id) user_to_red.paste_count = user_to_red.paste_count -", "# @mod_paste.route('/<url>/embed', methods=['POST']) # def embed_code(url): # paste = Paste.query.filter(Paste.url", "paste.user_id == user_id: return render_template('editpaste.html') return jsonify(success=False, reply=\"Not Authorized\"), 400", "and session['user_id'] != paste.user_id): return render_template(\"index.html\"), 200 user_id = session['user_id']", "import db, requires_auth from flask_cors import CORS from .models import", "if is_active(paste): return jsonify({'paste_owner': user.username, 'paste_text': paste.text, 'paste_title': paste.title, 'paste_lang':", "user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 return jsonify(success=False,", "= User.query.filter(User.id == curr_id).first() return render_template('user.html', username=user.username) @mod_paste.route('/create_paste', methods=['POST']) def", "!= 2): return jsonify(message=\"Unauthorized\", success=False), 401 return f(*args, **kwargs) return", "# def get_all_pastes(): # # user_id = session['user_id'] # #", "render_template(\"index.html\"), 200 user_id = session['user_id'] user = User.query.filter(User.id == user_id).first()", "title paste.text = text paste.lang = lang paste.expire_time = expire_time", "temp_paste['lang']=paste.lang # temp_paste['url']=paste.url # active.append(temp_paste) # # return jsonify({'paste_list':active,'username':user.username}),200 #", "@mod_paste.route('/<url>/embed', methods=['POST']) # def embed_code(url): # paste = Paste.query.filter(Paste.url ==", "def delete_paste(url): user_id = session['user_id'] # print(user_id) paste = Paste.query.filter(Paste.url", "edit_form(url): if 'user_id' in session: user_id = session['user_id'] paste =", "404 return jsonify(success=False, reply=\"Please Login\"), 400 @mod_paste.route('/<url>/edit', methods=['POST']) @requires_auth def", "@mod_paste.route('/<url>/edit', methods=['GET']) @requires_auth def edit_form(url): if 'user_id' in session: user_id", "user.username, 'paste_text': paste.text, 'paste_title': paste.title, 'paste_lang': paste.lang, 'paste_add': paste.add_time, 'paste_expire':", "user.user_type == 1: return render_template('view_paste.html') if user.user_type == 2: return", "userid_to_red).first() user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template('index.html'),", "text paste.lang = lang paste.expire_time = expire_time paste.paste_type = paste_type", "lang paste.expire_time = expire_time paste.paste_type = paste_type db.session.commit() return jsonify(success=True,", "= session['user_id'] else: user = User.query.filter(User.username == 'Guest').first() user_id =", "db, requires_auth from flask_cors import CORS from .models import Paste", "User from pygments import highlight from pygments.lexers import get_lexer_by_name, guess_lexer", "return jsonify(message=\"Unauthorized\", success=False), 401 return f(*args, **kwargs) return decorated mod_paste", "# user_id = session['user_id'] # # pastes = paste.query.filter(paste.user_id ==", "paste is None: # return render_template(\"index.html\"),4044 # else: # paste.title", "User.id).first() if user.user_type == 2: return render_template('admin_mypaste.html') return render_template(\"mypaste.html\") else:", "all_pastes(): paste_list = db.session.all() url_pre = \"/\" for paste in", "= request.form['color'] # paste.lang = request.form['lang'] # db.session.commit() # return", "# return jsonify(success=True, pastes=[paste.to_dict() for paste in # pastes]) @mod_paste.route('/api/paste',", "url_pre + paste.url else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id", "# @mod_paste.route('/paste', methods=['GET']) # @requires_auth # def get_all_pastes(): # #", "g, session, redirect, url_for, jsonify from app import db, requires_auth", "# return jsonify(success=True, pastes=[paste.to_dict() for paste in # pastes]) @mod_paste.route('/<username>/api/paste',", "= request.form['text'] lang = request.form['lang'] time_form = request.form['time'] paste_type =", "= request.form['title'] text = request.form['text'] paste_type = request.form['type'] if 'user_id'", "mod_paste = Blueprint('paste', __name__) CORS(mod_paste) def is_active(paste): return parser.parse(paste.expire_time) >", "user = User.query.filter(curr_id == User.id).first() if user.user_type == 2: return", "= paste.text,paste_link = url) @mod_paste.route('/<url>/embed/output', methods=['GET']) def embed_code_disp(url): paste =", "= Paste.query.filter(Paste.url == url).first() user = User.query.filter(User.id == user_id).first() if", "return jsonify(success=False), 400 else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id", "display_paste(url): # paste = Paste.query.filter(Paste.url == url).first() # style =", "url_pre = \"/\" for paste in paste_list: if is_active(paste): paste.url", "= url_pre + paste.url else: userid_to_red = paste.user_id user_to_red =", "render_template('allpaste.html', paste_list=paste_list) @mod_paste.route('/<username>/paste', methods=['GET']) @requires_admin def get_user_pastes(username): # user_id =", "user_id = session['user_id'] # # pastes = paste.query.filter(paste.user_id == user_id).all()", "'paste_expire': paste.expire_time}), 200 else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id", "= {} # if paste.is_active(): # temp_paste['title'] = paste.title #", "render_template(\"index.html\"), 404 @mod_paste.route('/api/<url>', methods=['POST']) def ret_paste(url): paste = Paste.query.filter(Paste.url ==", "functools import wraps from datetime import datetime from dateutil import", "if 'user_id' in session: user_id = session['user_id'] paste = Paste.query.filter(Paste.url", "# @requires_auth # def get_paste(id): # user_id = session['user_id'] #", "200 except: return jsonify({'error': 'Error while creating Paste, Please check", "= session['user_id'] user = User.query.filter(curr_id == User.id).first() if user.user_type ==", "# user_id = session['user_id'] # user = User.query.filter(user_id == User.id).first()", "== user_id).first() # if paste is None: # return render_template(\"index.html\"),4044", "1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 else: return render_template(\"index.html\"), 404", "# paste_list = Paste.query.filter(Paste.user_id == curr_id).all() # url_pre = \"/\"", "- 1 db.session.delete(paste) db.session.commit() return jsonify({'paste_list': active, 'username': user.username}), 200", "url_pre + paste.url # return render_template('mypaste.html', paste_list=paste_list) @mod_paste.route('/<url>/edit', methods=['GET']) @requires_auth", "pastes = paste.query.filter(paste.user_id == user_id).all() # curr_id = session['user_id'] #", "session['user_id'] paste = Paste.query.filter(Paste.url == url).first() if not is_active(paste): userid_to_red", "methods=['POST']) def create_paste(): title = request.form['title'] text = request.form['text'] paste_type", "return render_template(\"index.html\"), 404 return jsonify(success=False, reply=\"Please Login\"), 400 @mod_paste.route('/<url>/edit', methods=['POST'])", "user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return render_template(\"index.html\"), 404 # @mod_paste.route('/paste',", "paste_to_delete.report_count > 5: # db.session.delete(paste_to_delete) # else: # paste_to_delete.report_count =", "user_id: return jsonify(success=False, reply=\"Not Authorized\"), 400 title = request.form['title'] text", "user_id).all() # active = [] # for paste in pastes:", "text, lang, add_time, expire_time, user_id, url, report_count, paste_type) user =", "= Paste.query.filter(Paste.url == url).first() if not is_active(paste): userid_to_red = paste.user_id", "db.session.commit() # jsonify(success=True, paste=paste.to_dict()) return jsonify({'url': url}), 200 except: return", "display_paste(url): paste = Paste.query.filter(Paste.url == url).first() if Paste.query.filter(Paste.url == url).first()", "text = request.form['text'] paste_type = request.form['type'] if 'user_id' in session:", "in # pastes]) @mod_paste.route('/api/paste', methods=['POST']) @requires_auth def get_all_pastes_object(): user_id =", "404 else: return render_template(\"index.html\"), 404 @mod_paste.route('/api/<url>', methods=['POST']) def ret_paste(url): paste", "return render_template('allpaste.html', paste_list=paste_list) @mod_paste.route('/<username>/paste', methods=['GET']) @requires_admin def get_user_pastes(username): # user_id", "paste_list = Paste.query.filter(Paste.user_id == curr_id).all() # url_pre = \"/\" #", "else: # paste.title = request.form['title'] # paste.text = request.form['text'] #", "User.id).first() if is_active(paste): return jsonify({'paste_owner': user.username, 'paste_text': paste.text, 'paste_title': paste.title,", "reply=\"Not Authorized\"), 400 else: userid_to_red = paste.user_id user_to_red = User.query.filter(User.id", "User.id) user_to_red.paste_count = user_to_red.paste_count - 1 db.session.delete(paste) db.session.commit() return jsonify({'paste_list':", "'paste_add': paste.add_time, 'paste_expire': paste.expire_time}), 200 else: userid_to_red = paste.user_id user_to_red", "= str(datetime.now()) url = str(uuid.uuid4()) report_count = 0 try: paste", "= Paste.query.filter(Paste.user_id == user_id).all() active = [] for paste in", "render_template(\"view_paste.html\", paste_title=paste.title, # paste_lang=paste.lang, highlight_style=style, @mod_paste.route('/<url>', methods=['GET']) # paste_text=result,paste_rawdata =", "@requires_auth def edit_form(url): if 'user_id' in session: user_id = session['user_id']", "render_template(\"index.html\"), 404 else: return render_template(\"index.html\"), 404 @mod_paste.route('/api/<url>', methods=['POST']) def ret_paste(url):", "return jsonify({'paste_list':active,'username':user.username}),200 # @mod_paste.route('/paste/<id>', methods=['GET']) # @requires_auth # def get_paste(id):", "render_template('admin_mypaste.html',paste_list = paste_list) # # return jsonify(success=True, pastes=[paste.to_dict() for paste", "session['user_id'] # # pastes = paste.query.filter(paste.user_id == user_id).all() # curr_id", "{} # if paste.is_active(): # temp_paste['title'] = paste.title # temp_paste['add_time']=paste.add_time", "get_user_pastes(username): # user_id = session['user_id'] # pastes = paste.query.filter(paste.user_id ==" ]
[ "if COMMANDS[command_id] == \"move_forward\": anafi.move_relative(dx=1, dy=0, dz=0, dradians=0) if COMMANDS[command_id]", "image, format: MinWidth,MaxWidth,MinHeight,MaxHeight.\\ Set -1 for the unchanged ones\" )", "imgs = [] while True: ret, frame = cam.read() if", "required=False, default=7, type=int, help=\"Number of classes.\" ) parser.add_argument( \"-c\", \"--crop\",", "kernel = np.ones((k_size, k_size), np.uint8) frame = cv2.dilate(frame, kernel, iterations=int(iteration))", "help=\"Camera ID, default is 0\" ) parser.add_argument( \"-t\", \"--tensorflow\", required=False,", "frame.shape[0] min_width, max_width = 0, frame.shape[1] print(\"Cam resolution: {}x{}\".format(max_width, max_height))", "import numpy as np import os import time import sys", "weights for the model.\" ) parser.add_argument( \"-a\", \"--pyparrot_path\", required=True, type=str,", "max_width = res[1] if res[2] != -1: min_height = res[2]", "\"move_forward\", 1: \"go_down\", 2: \"rot_10_deg\", 3: \"go_up\", 4: \"take_off\", 5:", "== \"move_forward\": anafi.move_relative(dx=1, dy=0, dz=0, dradians=0) if COMMANDS[command_id] == \"go_down\":", "is not None: frame = frame[min_height:max_height, min_width:max_width] cv2.imshow(\"Original image\", frame)", "pause: pause = False else: pause = True if not", "type=str, help=\"Path to pyparrot module downloaded from amymcgovern on github.\"", "following command will be sent: \", COMMANDS[command_id]) if COMMANDS[command_id] ==", "-1 for the unchanged ones\" ) parser.add_argument( \"-r\", \"--resize\", required=False,", "NN.Linear(hidden_size, num_class), NN.Softmax()], NN.LossMSE()) model.load(args.weight_path) \"\"\" Webcam process \"\"\" print(\"Start", "NN.BatchNorm(), NN.Linear(hidden_size, num_class), NN.Softmax()], NN.LossMSE()) model.load(args.weight_path) \"\"\" Webcam process \"\"\"", "required=False, default=28, type=int, help=\"Image width.\" ) parser.add_argument( \"-n\", \"--num_classes\", required=False,", "f\"Command id not in COMMANDS choices: {command_id}\" print(\"The following command", "\"/../\") from homemade_framework import framework as NN model = NN.Sequential([NN.Linear(input_size,", "print(\"Start webcam...\") cam = cv2.VideoCapture(args.camid) ret, frame = cam.read() min_height,", "print(\"Connecting to drone...\") anafi = Anafi(drone_type=\"Anafi\", ip_address=\"192.168.42.1\") success = anafi.connect(10)", "image = np.asarray(frame)/255. cv2.imshow(\"Input image for the model\", frame) image", "print(\"Model's output on buffer: \", results) if np.unique(results).size == 1", "function of the command id \"\"\" if command_id not in", "cv2.VideoCapture(args.camid) ret, frame = cam.read() min_height, max_height = 0, frame.shape[0]", "not None: frame = frame[min_height:max_height, min_width:max_width] cv2.imshow(\"Original image\", frame) k", "print(\"Sleeping few seconds...\") anafi.smart_sleep(3) \"\"\" Load model \"\"\" print(\"Loading model...\")", "model = tf.keras.models.load_model(args.weight_path) else: script_path = os.path.realpath(__file__) sys.path.append(os.path.dirname(script_path) + \"/../\")", "\"--img_width\", required=False, default=28, type=int, help=\"Image width.\" ) parser.add_argument( \"-n\", \"--num_classes\",", "print(\"Loading model...\") input_size = args.img_width**2 num_class = args.num_classes hidden_size =", "seconds...\") anafi.smart_sleep(3) \"\"\" Load model \"\"\" print(\"Loading model...\") input_size =", "cam.read() if not ret: print(\"failed to grab frame\") break if", "Load model \"\"\" print(\"Loading model...\") input_size = args.img_width**2 num_class =", "args.erode is not None: k_size, iteration = [int(x) for x", "command id \"\"\" if command_id not in COMMANDS: raise f\"Command", "anafi.connect(10) print(success) print(\"Sleeping few seconds...\") anafi.smart_sleep(3) \"\"\" Load model \"\"\"", "cam = cv2.VideoCapture(args.camid) ret, frame = cam.read() min_height, max_height =", "input_size = args.img_width**2 num_class = args.num_classes hidden_size = 128 if", "not pause: if args.gray: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if args.binarize:", "\"-g\", \"--gray\", required=False, action=\"store_true\", help=\"To save 1-channel images\" ) parser.add_argument(", "anafi = Anafi(drone_type=\"Anafi\", ip_address=\"192.168.42.1\") success = anafi.connect(10) print(success) print(\"Sleeping few", "type=int, help=\"Number of classes.\" ) parser.add_argument( \"-c\", \"--crop\", required=False, default=None,", "= cam.read() if not ret: print(\"failed to grab frame\") break", "[int(x) for x in args.crop.split(',')] if res[0] != -1: min_width", "cam.read() min_height, max_height = 0, frame.shape[0] min_width, max_width = 0,", "print(\"Image cropped to minWidth:maxWidth, minHeight:maxHeight: {}:{}\\ , {},{}\".format(min_width, max_width, min_height,", "kernel_size,iteration\" ) parser.add_argument( \"-m\", \"--camid\", required=False, default=0, type=int, help=\"Camera ID,", "parser.add_argument( \"-n\", \"--num_classes\", required=False, default=7, type=int, help=\"Number of classes.\" )", "type=str, help=\"Path to load weights for the model.\" ) parser.add_argument(", "= cv2.resize(frame, (height, width), interpolation=cv2.INTER_AREA) image = np.asarray(frame)/255. cv2.imshow(\"Input image", "args.resize: height, width = [int(size) for size in args.resize.split(',')] frame", "else: results = NN.get_inferences(model, np.asarray(imgs)) print(\"Model's output on buffer: \",", "required=False, action=\"store_true\", help=\"To specify if Tensorflow model is used.\" )", "on buffer: \", results) if np.unique(results).size == 1 and\\ COMMANDS[results[0]]", "format: kernel_size,iteration\" ) parser.add_argument( \"-d\", \"--dilate\", required=False, default=None, type=str, help=\"Dilate", ") parser.add_argument( \"-e\", \"--erode\", required=False, default=None, type=str, help=\"Erode option, format:", "if args.gray: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if args.binarize: frame =", ") parser.add_argument( \"-n\", \"--num_classes\", required=False, default=7, type=int, help=\"Number of classes.\"", "hidden_size), NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size, hidden_size), NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size, num_class), NN.Softmax()],", "required=False, default=None, type=str, help=\"Erode option, format: kernel_size,iteration\" ) parser.add_argument( \"-d\",", "number of identical commands before sending to drone.\" ) args", "else: if args.tensorflow: results = np.argmax(model(np.asarray(imgs)), axis=1) else: results =", "frame = cv2.threshold(frame, min_thresh, max_thresh, cv2.THRESH_BINARY) if args.erode is not", "if len(imgs) < args.number_of_confimation: imgs.append(image) else: if args.tensorflow: results =", "\"-t\", \"--tensorflow\", required=False, action=\"store_true\", help=\"To specify if Tensorflow model is", "run neural network model on a camera live stream \"\"\"", "default is 0\" ) parser.add_argument( \"-t\", \"--tensorflow\", required=False, action=\"store_true\", help=\"To", "for size in args.resize.split(',')] frame = cv2.resize(frame, (height, width), interpolation=cv2.INTER_AREA)", "for thresholding: min,max\" ) parser.add_argument( \"-g\", \"--gray\", required=False, action=\"store_true\", help=\"To", "send_command(anafi, command_id): \"\"\" Function to send commands to an Anafi", "default=None, type=str, help=\"To binarize images, format for thresholding: min,max\" )", "on a camera live stream \"\"\" import argparse import cv2", "= {0: \"move_forward\", 1: \"go_down\", 2: \"rot_10_deg\", 3: \"go_up\", 4:", "= cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if args.binarize: frame = cv2.medianBlur(frame, 5) min_thresh,", "COMMANDS[command_id] == \"go_up\": anafi.move_relative(dx=0, dy=0, dz=0.5, dradians=0) if COMMANDS[command_id] ==", "option, format: kernel_size,iteration\" ) parser.add_argument( \"-m\", \"--camid\", required=False, default=0, type=int,", "print(\"The following command will be sent: \", COMMANDS[command_id]) if COMMANDS[command_id]", "default=None, type=str, help=\"Erode option, format: kernel_size,iteration\" ) parser.add_argument( \"-d\", \"--dilate\",", "hidden_size), NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size, num_class), NN.Softmax()], NN.LossMSE()) model.load(args.weight_path) \"\"\" Webcam", "\"move_forward\": anafi.move_relative(dx=1, dy=0, dz=0, dradians=0) if COMMANDS[command_id] == \"go_down\": anafi.move_relative(dx=0,", "\"\"\" Drone connection \"\"\" sys.path.append(args.pyparrot_path) from pyparrot.Anafi import Anafi print(\"Connecting", "results[0]) imgs = [] imgs = imgs[1:] imgs.append(image) time.sleep(0.3) cam.release()", "= cv2.waitKey(1) if k % 256 == 27: # ESC", "required=True, type=str, help=\"Path to load weights for the model.\" )", "github.\" ) parser.add_argument( \"-w\", \"--img_width\", required=False, default=28, type=int, help=\"Image width.\"", "frame = frame[min_height:max_height, min_width:max_width] cv2.imshow(\"Original image\", frame) k = cv2.waitKey(1)", "model.\" ) parser.add_argument( \"-a\", \"--pyparrot_path\", required=True, type=str, help=\"Path to pyparrot", "= [] while True: ret, frame = cam.read() if not", "closing...\") break elif k % 256 == ord('p'): # p", "= [int(x) for x in args.dilate.split(',')] kernel = np.ones((k_size, k_size),", "k % 256 == ord('p'): # p pressed if pause:", "not in COMMANDS choices: {command_id}\" print(\"The following command will be", "0\" ) parser.add_argument( \"-t\", \"--tensorflow\", required=False, action=\"store_true\", help=\"To specify if", "pyparrot.Anafi import Anafi print(\"Connecting to drone...\") anafi = Anafi(drone_type=\"Anafi\", ip_address=\"192.168.42.1\")", "min_height = res[2] if res[3] != -1: max_height = res[3]", "few seconds...\") anafi.smart_sleep(3) \"\"\" Load model \"\"\" print(\"Loading model...\") input_size", "cv2.imshow(\"Input image for the model\", frame) image = image.reshape([np.prod(image.shape)]) if", "in function of the command id \"\"\" if command_id not", "!= -1: min_width = res[0] if res[1] != -1: max_width", "== ord('p'): # p pressed if pause: pause = False", "choices: {command_id}\" print(\"The following command will be sent: \", COMMANDS[command_id])", "if not pause: if args.gray: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if", "cv2.resize(frame, (height, width), interpolation=cv2.INTER_AREA) image = np.asarray(frame)/255. cv2.imshow(\"Input image for", "frame = cv2.medianBlur(frame, 5) min_thresh, max_thresh = [int(x) for x", "= np.ones((k_size, k_size), np.uint8) frame = cv2.erode(frame, kernel, iterations=int(iteration)) if", "= res[3] print(\"Image cropped to minWidth:maxWidth, minHeight:maxHeight: {}:{}\\ , {},{}\".format(min_width,", "import Anafi print(\"Connecting to drone...\") anafi = Anafi(drone_type=\"Anafi\", ip_address=\"192.168.42.1\") success", "numpy as np import os import time import sys COMMANDS", "== \"rot_10_deg\": anafi.move_relative(dx=0, dy=0, dz=0, dradians=0.785) if COMMANDS[command_id] == \"go_up\":", "\"-e\", \"--erode\", required=False, default=None, type=str, help=\"Erode option, format: kernel_size,iteration\" )", "k_size), np.uint8) frame = cv2.erode(frame, kernel, iterations=int(iteration)) if args.dilate is", "This script run neural network model on a camera live", "for the unchanged ones\" ) parser.add_argument( \"-r\", \"--resize\", required=False, default=None,", "type=str, help=\"Resize shape, format: height,width\" ) parser.add_argument( \"-b\", \"--binarize\", required=False,", "thresholding: min,max\" ) parser.add_argument( \"-g\", \"--gray\", required=False, action=\"store_true\", help=\"To save", "Anafi(drone_type=\"Anafi\", ip_address=\"192.168.42.1\") success = anafi.connect(10) print(success) print(\"Sleeping few seconds...\") anafi.smart_sleep(3)", "height,width\" ) parser.add_argument( \"-b\", \"--binarize\", required=False, default=None, type=str, help=\"To binarize", "hit, closing...\") break elif k % 256 == ord('p'): #", "cv2.dilate(frame, kernel, iterations=int(iteration)) if args.resize: height, width = [int(size) for", "\"land\", 6: \"idle\"} def send_command(anafi, command_id): \"\"\" Function to send", "print(\"Escape hit, closing...\") break elif k % 256 == ord('p'):", ") args = parser.parse_args() \"\"\" Drone connection \"\"\" sys.path.append(args.pyparrot_path) from", ") parser.add_argument( \"-w\", \"--img_width\", required=False, default=28, type=int, help=\"Image width.\" )", "import cv2 import numpy as np import os import time", "= argparse.ArgumentParser() parser.add_argument( \"-p\", \"--weight_path\", required=True, type=str, help=\"Path to load", "to drone...\") anafi = Anafi(drone_type=\"Anafi\", ip_address=\"192.168.42.1\") success = anafi.connect(10) print(success)", "min_height, max_height = 0, frame.shape[0] min_width, max_width = 0, frame.shape[1]", "dz=0, dradians=0.785) if COMMANDS[command_id] == \"go_up\": anafi.move_relative(dx=0, dy=0, dz=0.5, dradians=0)", "classes.\" ) parser.add_argument( \"-c\", \"--crop\", required=False, default=None, type=str, help=\"Crop image,", "= image.reshape([np.prod(image.shape)]) if len(imgs) < args.number_of_confimation: imgs.append(image) else: if args.tensorflow:", "-*- coding: utf-8 -*- \"\"\" This script run neural network", "else: script_path = os.path.realpath(__file__) sys.path.append(os.path.dirname(script_path) + \"/../\") from homemade_framework import", "[] imgs = imgs[1:] imgs.append(image) time.sleep(0.3) cam.release() cv2.destroyAllWindows() if __name__", "from amymcgovern on github.\" ) parser.add_argument( \"-w\", \"--img_width\", required=False, default=28,", "\"--camid\", required=False, default=0, type=int, help=\"Camera ID, default is 0\" )", "[int(x) for x in args.dilate.split(',')] kernel = np.ones((k_size, k_size), np.uint8)", "required=True, type=str, help=\"Path to pyparrot module downloaded from amymcgovern on", "\"-b\", \"--binarize\", required=False, default=None, type=str, help=\"To binarize images, format for", "max_width, min_height, max_height)) pause = False imgs = [] while", "max_thresh = [int(x) for x in args.binarize.split(',')] ret, frame =", "4: \"take_off\", 5: \"land\", 6: \"idle\"} def send_command(anafi, command_id): \"\"\"", "cv2.waitKey(1) if k % 256 == 27: # ESC pressed", "format: kernel_size,iteration\" ) parser.add_argument( \"-m\", \"--camid\", required=False, default=0, type=int, help=\"Camera", "#!/usr/bin/env python # -*- coding: utf-8 -*- \"\"\" This script", "format for thresholding: min,max\" ) parser.add_argument( \"-g\", \"--gray\", required=False, action=\"store_true\",", "help=\"Path to load weights for the model.\" ) parser.add_argument( \"-a\",", "parser.add_argument( \"-w\", \"--img_width\", required=False, default=28, type=int, help=\"Image width.\" ) parser.add_argument(", "frame = cam.read() min_height, max_height = 0, frame.shape[0] min_width, max_width", "np.ones((k_size, k_size), np.uint8) frame = cv2.dilate(frame, kernel, iterations=int(iteration)) if args.resize:", "NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size, hidden_size), NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size, num_class), NN.Softmax()], NN.LossMSE())", "= parser.parse_args() \"\"\" Drone connection \"\"\" sys.path.append(args.pyparrot_path) from pyparrot.Anafi import", "pause = False else: pause = True if not pause:", "= NN.get_inferences(model, np.asarray(imgs)) print(\"Model's output on buffer: \", results) if", "= args.img_width**2 num_class = args.num_classes hidden_size = 128 if args.tensorflow:", "framework as NN model = NN.Sequential([NN.Linear(input_size, hidden_size), NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size,", ") parser.add_argument( \"-r\", \"--resize\", required=False, default=None, type=str, help=\"Resize shape, format:", "= NN.Sequential([NN.Linear(input_size, hidden_size), NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size, hidden_size), NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size,", "args.dilate is not None: k_size, iteration = [int(x) for x", "results = NN.get_inferences(model, np.asarray(imgs)) print(\"Model's output on buffer: \", results)", "args.dilate.split(',')] kernel = np.ones((k_size, k_size), np.uint8) frame = cv2.dilate(frame, kernel,", "to grab frame\") break if args.crop is not None: frame", "args.erode.split(',')] kernel = np.ones((k_size, k_size), np.uint8) frame = cv2.erode(frame, kernel,", "kernel_size,iteration\" ) parser.add_argument( \"-d\", \"--dilate\", required=False, default=None, type=str, help=\"Dilate option,", "= res[1] if res[2] != -1: min_height = res[2] if", "res[1] if res[2] != -1: min_height = res[2] if res[3]", "kernel = np.ones((k_size, k_size), np.uint8) frame = cv2.erode(frame, kernel, iterations=int(iteration))", "in args.binarize.split(',')] ret, frame = cv2.threshold(frame, min_thresh, max_thresh, cv2.THRESH_BINARY) if", "results) if np.unique(results).size == 1 and\\ COMMANDS[results[0]] != \"idle\": send_command(anafi,", "in args.crop.split(',')] if res[0] != -1: min_width = res[0] if", "python # -*- coding: utf-8 -*- \"\"\" This script run", "= 128 if args.tensorflow: import tensorflow as tf model =", "if command_id not in COMMANDS: raise f\"Command id not in", "sys.path.append(os.path.dirname(script_path) + \"/../\") from homemade_framework import framework as NN model", "0, frame.shape[1] print(\"Cam resolution: {}x{}\".format(max_width, max_height)) if args.crop is not", "print(\"failed to grab frame\") break if args.crop is not None:", "help=\"To binarize images, format for thresholding: min,max\" ) parser.add_argument( \"-g\",", "elif k % 256 == ord('p'): # p pressed if", "os import time import sys COMMANDS = {0: \"move_forward\", 1:", "for x in args.erode.split(',')] kernel = np.ones((k_size, k_size), np.uint8) frame", "min_height, max_height)) pause = False imgs = [] while True:", "anafi.smart_sleep(3) \"\"\" Load model \"\"\" print(\"Loading model...\") input_size = args.img_width**2", "cv2.medianBlur(frame, 5) min_thresh, max_thresh = [int(x) for x in args.binarize.split(',')]", "imgs = [] imgs = imgs[1:] imgs.append(image) time.sleep(0.3) cam.release() cv2.destroyAllWindows()", "args.num_classes hidden_size = 128 if args.tensorflow: import tensorflow as tf", "args.crop is not None: frame = frame[min_height:max_height, min_width:max_width] cv2.imshow(\"Original image\",", "COMMANDS[command_id] == \"land\": anafi.safe_land(5) return def main(): parser = argparse.ArgumentParser()", "\"-p\", \"--weight_path\", required=True, type=str, help=\"Path to load weights for the", "= anafi.connect(10) print(success) print(\"Sleeping few seconds...\") anafi.smart_sleep(3) \"\"\" Load model", "import sys COMMANDS = {0: \"move_forward\", 1: \"go_down\", 2: \"rot_10_deg\",", "a camera live stream \"\"\" import argparse import cv2 import", "script run neural network model on a camera live stream", "an Anafi drone in function of the command id \"\"\"", "as NN model = NN.Sequential([NN.Linear(input_size, hidden_size), NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size, hidden_size),", "import framework as NN model = NN.Sequential([NN.Linear(input_size, hidden_size), NN.LeakyReLU(), NN.BatchNorm(),", "of identical commands before sending to drone.\" ) args =", "res[0] if res[1] != -1: max_width = res[1] if res[2]", "help=\"Dilate option, format: kernel_size,iteration\" ) parser.add_argument( \"-m\", \"--camid\", required=False, default=0,", "min_thresh, max_thresh, cv2.THRESH_BINARY) if args.erode is not None: k_size, iteration", "help=\"Number of classes.\" ) parser.add_argument( \"-c\", \"--crop\", required=False, default=None, type=str,", "if args.tensorflow: results = np.argmax(model(np.asarray(imgs)), axis=1) else: results = NN.get_inferences(model,", "if k % 256 == 27: # ESC pressed print(\"Escape", "\"\"\" import argparse import cv2 import numpy as np import", "to send commands to an Anafi drone in function of", "dy=0, dz=-0.5, dradians=0) if COMMANDS[command_id] == \"rot_10_deg\": anafi.move_relative(dx=0, dy=0, dz=0,", "ID, default is 0\" ) parser.add_argument( \"-t\", \"--tensorflow\", required=False, action=\"store_true\",", "if COMMANDS[command_id] == \"go_up\": anafi.move_relative(dx=0, dy=0, dz=0.5, dradians=0) if COMMANDS[command_id]", "tf.keras.models.load_model(args.weight_path) else: script_path = os.path.realpath(__file__) sys.path.append(os.path.dirname(script_path) + \"/../\") from homemade_framework", "cv2.imshow(\"Original image\", frame) k = cv2.waitKey(1) if k % 256", "== \"take_off\": anafi.safe_takeoff(5) if COMMANDS[command_id] == \"land\": anafi.safe_land(5) return def", "res[0] != -1: min_width = res[0] if res[1] != -1:", "if args.crop is not None: res = [int(x) for x", "np.asarray(frame)/255. cv2.imshow(\"Input image for the model\", frame) image = image.reshape([np.prod(image.shape)])", "0, frame.shape[0] min_width, max_width = 0, frame.shape[1] print(\"Cam resolution: {}x{}\".format(max_width,", ") parser.add_argument( \"-b\", \"--binarize\", required=False, default=None, type=str, help=\"To binarize images,", "max_height)) if args.crop is not None: res = [int(x) for", "image.reshape([np.prod(image.shape)]) if len(imgs) < args.number_of_confimation: imgs.append(image) else: if args.tensorflow: results", "model\", frame) image = image.reshape([np.prod(image.shape)]) if len(imgs) < args.number_of_confimation: imgs.append(image)", "parser.add_argument( \"-b\", \"--binarize\", required=False, default=None, type=str, help=\"To binarize images, format", "time import sys COMMANDS = {0: \"move_forward\", 1: \"go_down\", 2:", "parser.add_argument( \"-t\", \"--tensorflow\", required=False, action=\"store_true\", help=\"To specify if Tensorflow model", "not None: k_size, iteration = [int(x) for x in args.erode.split(',')]", "for x in args.crop.split(',')] if res[0] != -1: min_width =", "width.\" ) parser.add_argument( \"-n\", \"--num_classes\", required=False, default=7, type=int, help=\"Number of", "= cv2.VideoCapture(args.camid) ret, frame = cam.read() min_height, max_height = 0,", "if not ret: print(\"failed to grab frame\") break if args.crop", "Function to send commands to an Anafi drone in function", "width), interpolation=cv2.INTER_AREA) image = np.asarray(frame)/255. cv2.imshow(\"Input image for the model\",", "from homemade_framework import framework as NN model = NN.Sequential([NN.Linear(input_size, hidden_size),", "== 27: # ESC pressed print(\"Escape hit, closing...\") break elif", "pyparrot module downloaded from amymcgovern on github.\" ) parser.add_argument( \"-w\",", "of classes.\" ) parser.add_argument( \"-c\", \"--crop\", required=False, default=None, type=str, help=\"Crop", "minHeight:maxHeight: {}:{}\\ , {},{}\".format(min_width, max_width, min_height, max_height)) pause = False", "id not in COMMANDS choices: {command_id}\" print(\"The following command will", "= frame[min_height:max_height, min_width:max_width] cv2.imshow(\"Original image\", frame) k = cv2.waitKey(1) if", "\"go_up\", 4: \"take_off\", 5: \"land\", 6: \"idle\"} def send_command(anafi, command_id):", "args.gray: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if args.binarize: frame = cv2.medianBlur(frame,", "coding: utf-8 -*- \"\"\" This script run neural network model", "dradians=0) if COMMANDS[command_id] == \"go_down\": anafi.move_relative(dx=0, dy=0, dz=-0.5, dradians=0) if", "!= -1: max_height = res[3] print(\"Image cropped to minWidth:maxWidth, minHeight:maxHeight:", "if res[0] != -1: min_width = res[0] if res[1] !=", "np.unique(results).size == 1 and\\ COMMANDS[results[0]] != \"idle\": send_command(anafi, results[0]) imgs", "the unchanged ones\" ) parser.add_argument( \"-r\", \"--resize\", required=False, default=None, type=str,", "NN.get_inferences(model, np.asarray(imgs)) print(\"Model's output on buffer: \", results) if np.unique(results).size", "frame.shape[1] print(\"Cam resolution: {}x{}\".format(max_width, max_height)) if args.crop is not None:", "args.img_width**2 num_class = args.num_classes hidden_size = 128 if args.tensorflow: import", "if Tensorflow model is used.\" ) parser.add_argument( \"-z\", \"--number_of_confimation\", required=False,", "pause: if args.gray: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if args.binarize: frame", "np.ones((k_size, k_size), np.uint8) frame = cv2.erode(frame, kernel, iterations=int(iteration)) if args.dilate", "== 1 and\\ COMMANDS[results[0]] != \"idle\": send_command(anafi, results[0]) imgs =", "p pressed if pause: pause = False else: pause =", "= [] imgs = imgs[1:] imgs.append(image) time.sleep(0.3) cam.release() cv2.destroyAllWindows() if", "default=28, type=int, help=\"Image width.\" ) parser.add_argument( \"-n\", \"--num_classes\", required=False, default=7,", "dy=0, dz=0, dradians=0) if COMMANDS[command_id] == \"go_down\": anafi.move_relative(dx=0, dy=0, dz=-0.5,", "argparse import cv2 import numpy as np import os import", "\"-a\", \"--pyparrot_path\", required=True, type=str, help=\"Path to pyparrot module downloaded from", "send commands to an Anafi drone in function of the", "drone...\") anafi = Anafi(drone_type=\"Anafi\", ip_address=\"192.168.42.1\") success = anafi.connect(10) print(success) print(\"Sleeping", "COMMANDS: raise f\"Command id not in COMMANDS choices: {command_id}\" print(\"The", "command_id not in COMMANDS: raise f\"Command id not in COMMANDS", "is not None: res = [int(x) for x in args.crop.split(',')]", "import time import sys COMMANDS = {0: \"move_forward\", 1: \"go_down\",", "min_width, max_width = 0, frame.shape[1] print(\"Cam resolution: {}x{}\".format(max_width, max_height)) if", "parser.add_argument( \"-p\", \"--weight_path\", required=True, type=str, help=\"Path to load weights for", "help=\"Crop image, format: MinWidth,MaxWidth,MinHeight,MaxHeight.\\ Set -1 for the unchanged ones\"", "frame = cam.read() if not ret: print(\"failed to grab frame\")", "6: \"idle\"} def send_command(anafi, command_id): \"\"\" Function to send commands", "main(): parser = argparse.ArgumentParser() parser.add_argument( \"-p\", \"--weight_path\", required=True, type=str, help=\"Path", "amymcgovern on github.\" ) parser.add_argument( \"-w\", \"--img_width\", required=False, default=28, type=int,", "image\", frame) k = cv2.waitKey(1) if k % 256 ==", "cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if args.binarize: frame = cv2.medianBlur(frame, 5) min_thresh, max_thresh", "frame = cv2.dilate(frame, kernel, iterations=int(iteration)) if args.resize: height, width =", "MinWidth,MaxWidth,MinHeight,MaxHeight.\\ Set -1 for the unchanged ones\" ) parser.add_argument( \"-r\",", "(height, width), interpolation=cv2.INTER_AREA) image = np.asarray(frame)/255. cv2.imshow(\"Input image for the", "% 256 == 27: # ESC pressed print(\"Escape hit, closing...\")", "!= -1: max_width = res[1] if res[2] != -1: min_height", "256 == ord('p'): # p pressed if pause: pause =", "args.number_of_confimation: imgs.append(image) else: if args.tensorflow: results = np.argmax(model(np.asarray(imgs)), axis=1) else:", "if args.resize: height, width = [int(size) for size in args.resize.split(',')]", "action=\"store_true\", help=\"To specify if Tensorflow model is used.\" ) parser.add_argument(", "not ret: print(\"failed to grab frame\") break if args.crop is", "x in args.crop.split(',')] if res[0] != -1: min_width = res[0]", "utf-8 -*- \"\"\" This script run neural network model on", "+ \"/../\") from homemade_framework import framework as NN model =", "NN.Softmax()], NN.LossMSE()) model.load(args.weight_path) \"\"\" Webcam process \"\"\" print(\"Start webcam...\") cam", "\"-m\", \"--camid\", required=False, default=0, type=int, help=\"Camera ID, default is 0\"", "= np.argmax(model(np.asarray(imgs)), axis=1) else: results = NN.get_inferences(model, np.asarray(imgs)) print(\"Model's output", "required=False, default=None, type=str, help=\"Resize shape, format: height,width\" ) parser.add_argument( \"-b\",", "# p pressed if pause: pause = False else: pause", "Set -1 for the unchanged ones\" ) parser.add_argument( \"-r\", \"--resize\",", "\"--pyparrot_path\", required=True, type=str, help=\"Path to pyparrot module downloaded from amymcgovern", "Tensorflow model is used.\" ) parser.add_argument( \"-z\", \"--number_of_confimation\", required=False, default=3,", "is not None: k_size, iteration = [int(x) for x in", "\"take_off\", 5: \"land\", 6: \"idle\"} def send_command(anafi, command_id): \"\"\" Function", "model \"\"\" print(\"Loading model...\") input_size = args.img_width**2 num_class = args.num_classes", "if args.tensorflow: import tensorflow as tf model = tf.keras.models.load_model(args.weight_path) else:", "COMMANDS[command_id] == \"rot_10_deg\": anafi.move_relative(dx=0, dy=0, dz=0, dradians=0.785) if COMMANDS[command_id] ==", "NN.Sequential([NN.Linear(input_size, hidden_size), NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size, hidden_size), NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size, num_class),", "27: # ESC pressed print(\"Escape hit, closing...\") break elif k", "imgs.append(image) else: if args.tensorflow: results = np.argmax(model(np.asarray(imgs)), axis=1) else: results", "required=False, default=0, type=int, help=\"Camera ID, default is 0\" ) parser.add_argument(", "pause = True if not pause: if args.gray: frame =", "send_command(anafi, results[0]) imgs = [] imgs = imgs[1:] imgs.append(image) time.sleep(0.3)", ") parser.add_argument( \"-z\", \"--number_of_confimation\", required=False, default=3, type=int, help=\"Minimum number of", "max_height)) pause = False imgs = [] while True: ret,", "args.binarize.split(',')] ret, frame = cv2.threshold(frame, min_thresh, max_thresh, cv2.THRESH_BINARY) if args.erode", "min_width:max_width] cv2.imshow(\"Original image\", frame) k = cv2.waitKey(1) if k %", "stream \"\"\" import argparse import cv2 import numpy as np", "\", COMMANDS[command_id]) if COMMANDS[command_id] == \"move_forward\": anafi.move_relative(dx=1, dy=0, dz=0, dradians=0)", "if res[2] != -1: min_height = res[2] if res[3] !=", "while True: ret, frame = cam.read() if not ret: print(\"failed", "required=False, default=None, type=str, help=\"To binarize images, format for thresholding: min,max\"", "model on a camera live stream \"\"\" import argparse import", "-1: max_height = res[3] print(\"Image cropped to minWidth:maxWidth, minHeight:maxHeight: {}:{}\\", "drone in function of the command id \"\"\" if command_id", "argparse.ArgumentParser() parser.add_argument( \"-p\", \"--weight_path\", required=True, type=str, help=\"Path to load weights", "frame[min_height:max_height, min_width:max_width] cv2.imshow(\"Original image\", frame) k = cv2.waitKey(1) if k", "break elif k % 256 == ord('p'): # p pressed", "unchanged ones\" ) parser.add_argument( \"-r\", \"--resize\", required=False, default=None, type=str, help=\"Resize", "parser.add_argument( \"-m\", \"--camid\", required=False, default=0, type=int, help=\"Camera ID, default is", "in args.resize.split(',')] frame = cv2.resize(frame, (height, width), interpolation=cv2.INTER_AREA) image =", "{0: \"move_forward\", 1: \"go_down\", 2: \"rot_10_deg\", 3: \"go_up\", 4: \"take_off\",", "id \"\"\" if command_id not in COMMANDS: raise f\"Command id", "from pyparrot.Anafi import Anafi print(\"Connecting to drone...\") anafi = Anafi(drone_type=\"Anafi\",", "images\" ) parser.add_argument( \"-e\", \"--erode\", required=False, default=None, type=str, help=\"Erode option,", "help=\"Erode option, format: kernel_size,iteration\" ) parser.add_argument( \"-d\", \"--dilate\", required=False, default=None,", "= cv2.dilate(frame, kernel, iterations=int(iteration)) if args.resize: height, width = [int(size)", "commands before sending to drone.\" ) args = parser.parse_args() \"\"\"", "model = NN.Sequential([NN.Linear(input_size, hidden_size), NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size, hidden_size), NN.LeakyReLU(), NN.BatchNorm(),", "output on buffer: \", results) if np.unique(results).size == 1 and\\", "np.argmax(model(np.asarray(imgs)), axis=1) else: results = NN.get_inferences(model, np.asarray(imgs)) print(\"Model's output on", "dradians=0) if COMMANDS[command_id] == \"take_off\": anafi.safe_takeoff(5) if COMMANDS[command_id] == \"land\":", "\"\"\" Function to send commands to an Anafi drone in", "frame) image = image.reshape([np.prod(image.shape)]) if len(imgs) < args.number_of_confimation: imgs.append(image) else:", "min,max\" ) parser.add_argument( \"-g\", \"--gray\", required=False, action=\"store_true\", help=\"To save 1-channel", "= [int(x) for x in args.erode.split(',')] kernel = np.ones((k_size, k_size),", "\"-r\", \"--resize\", required=False, default=None, type=str, help=\"Resize shape, format: height,width\" )", "drone.\" ) args = parser.parse_args() \"\"\" Drone connection \"\"\" sys.path.append(args.pyparrot_path)", "= np.asarray(frame)/255. cv2.imshow(\"Input image for the model\", frame) image =", "ones\" ) parser.add_argument( \"-r\", \"--resize\", required=False, default=None, type=str, help=\"Resize shape,", "for the model.\" ) parser.add_argument( \"-a\", \"--pyparrot_path\", required=True, type=str, help=\"Path", "COMMANDS[command_id] == \"move_forward\": anafi.move_relative(dx=1, dy=0, dz=0, dradians=0) if COMMANDS[command_id] ==", "\"--binarize\", required=False, default=None, type=str, help=\"To binarize images, format for thresholding:", "= cam.read() min_height, max_height = 0, frame.shape[0] min_width, max_width =", "COMMANDS[command_id] == \"take_off\": anafi.safe_takeoff(5) if COMMANDS[command_id] == \"land\": anafi.safe_land(5) return", "save 1-channel images\" ) parser.add_argument( \"-e\", \"--erode\", required=False, default=None, type=str,", "# ESC pressed print(\"Escape hit, closing...\") break elif k %", "of the command id \"\"\" if command_id not in COMMANDS:", ") parser.add_argument( \"-m\", \"--camid\", required=False, default=0, type=int, help=\"Camera ID, default", "help=\"Minimum number of identical commands before sending to drone.\" )", "{}x{}\".format(max_width, max_height)) if args.crop is not None: res = [int(x)", "COMMANDS[results[0]] != \"idle\": send_command(anafi, results[0]) imgs = [] imgs =", "ret, frame = cam.read() min_height, max_height = 0, frame.shape[0] min_width,", "< args.number_of_confimation: imgs.append(image) else: if args.tensorflow: results = np.argmax(model(np.asarray(imgs)), axis=1)", "default=None, type=str, help=\"Crop image, format: MinWidth,MaxWidth,MinHeight,MaxHeight.\\ Set -1 for the", "print(success) print(\"Sleeping few seconds...\") anafi.smart_sleep(3) \"\"\" Load model \"\"\" print(\"Loading", "num_class), NN.Softmax()], NN.LossMSE()) model.load(args.weight_path) \"\"\" Webcam process \"\"\" print(\"Start webcam...\")", "\"-n\", \"--num_classes\", required=False, default=7, type=int, help=\"Number of classes.\" ) parser.add_argument(", "required=False, default=None, type=str, help=\"Dilate option, format: kernel_size,iteration\" ) parser.add_argument( \"-m\",", "if res[1] != -1: max_width = res[1] if res[2] !=", "5: \"land\", 6: \"idle\"} def send_command(anafi, command_id): \"\"\" Function to", "dz=-0.5, dradians=0) if COMMANDS[command_id] == \"rot_10_deg\": anafi.move_relative(dx=0, dy=0, dz=0, dradians=0.785)", "specify if Tensorflow model is used.\" ) parser.add_argument( \"-z\", \"--number_of_confimation\",", "sys.path.append(args.pyparrot_path) from pyparrot.Anafi import Anafi print(\"Connecting to drone...\") anafi =", "webcam...\") cam = cv2.VideoCapture(args.camid) ret, frame = cam.read() min_height, max_height", "resolution: {}x{}\".format(max_width, max_height)) if args.crop is not None: res =", "{command_id}\" print(\"The following command will be sent: \", COMMANDS[command_id]) if", "max_thresh, cv2.THRESH_BINARY) if args.erode is not None: k_size, iteration =", "[int(x) for x in args.erode.split(',')] kernel = np.ones((k_size, k_size), np.uint8)", "live stream \"\"\" import argparse import cv2 import numpy as", "-1: min_width = res[0] if res[1] != -1: max_width =", "1 and\\ COMMANDS[results[0]] != \"idle\": send_command(anafi, results[0]) imgs = []", "ip_address=\"192.168.42.1\") success = anafi.connect(10) print(success) print(\"Sleeping few seconds...\") anafi.smart_sleep(3) \"\"\"", "iterations=int(iteration)) if args.dilate is not None: k_size, iteration = [int(x)", "in args.erode.split(',')] kernel = np.ones((k_size, k_size), np.uint8) frame = cv2.erode(frame,", "required=False, default=3, type=int, help=\"Minimum number of identical commands before sending", "size in args.resize.split(',')] frame = cv2.resize(frame, (height, width), interpolation=cv2.INTER_AREA) image", "if np.unique(results).size == 1 and\\ COMMANDS[results[0]] != \"idle\": send_command(anafi, results[0])", "% 256 == ord('p'): # p pressed if pause: pause", "COMMANDS choices: {command_id}\" print(\"The following command will be sent: \",", "kernel, iterations=int(iteration)) if args.resize: height, width = [int(size) for size", "res[3] print(\"Image cropped to minWidth:maxWidth, minHeight:maxHeight: {}:{}\\ , {},{}\".format(min_width, max_width,", "None: res = [int(x) for x in args.crop.split(',')] if res[0]", "NN model = NN.Sequential([NN.Linear(input_size, hidden_size), NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size, hidden_size), NN.LeakyReLU(),", "command_id): \"\"\" Function to send commands to an Anafi drone", "res = [int(x) for x in args.crop.split(',')] if res[0] !=", "homemade_framework import framework as NN model = NN.Sequential([NN.Linear(input_size, hidden_size), NN.LeakyReLU(),", ") parser.add_argument( \"-a\", \"--pyparrot_path\", required=True, type=str, help=\"Path to pyparrot module", "= np.ones((k_size, k_size), np.uint8) frame = cv2.dilate(frame, kernel, iterations=int(iteration)) if", "== \"go_up\": anafi.move_relative(dx=0, dy=0, dz=0.5, dradians=0) if COMMANDS[command_id] == \"take_off\":", "= imgs[1:] imgs.append(image) time.sleep(0.3) cam.release() cv2.destroyAllWindows() if __name__ == '__main__':", "= cv2.erode(frame, kernel, iterations=int(iteration)) if args.dilate is not None: k_size,", "\"--num_classes\", required=False, default=7, type=int, help=\"Number of classes.\" ) parser.add_argument( \"-c\",", "in COMMANDS: raise f\"Command id not in COMMANDS choices: {command_id}\"", "Drone connection \"\"\" sys.path.append(args.pyparrot_path) from pyparrot.Anafi import Anafi print(\"Connecting to", "model...\") input_size = args.img_width**2 num_class = args.num_classes hidden_size = 128", "ESC pressed print(\"Escape hit, closing...\") break elif k % 256", "network model on a camera live stream \"\"\" import argparse", "{}:{}\\ , {},{}\".format(min_width, max_width, min_height, max_height)) pause = False imgs", "False imgs = [] while True: ret, frame = cam.read()", "default=None, type=str, help=\"Resize shape, format: height,width\" ) parser.add_argument( \"-b\", \"--binarize\",", "== \"land\": anafi.safe_land(5) return def main(): parser = argparse.ArgumentParser() parser.add_argument(", "tensorflow as tf model = tf.keras.models.load_model(args.weight_path) else: script_path = os.path.realpath(__file__)", "Anafi print(\"Connecting to drone...\") anafi = Anafi(drone_type=\"Anafi\", ip_address=\"192.168.42.1\") success =", "= Anafi(drone_type=\"Anafi\", ip_address=\"192.168.42.1\") success = anafi.connect(10) print(success) print(\"Sleeping few seconds...\")", "module downloaded from amymcgovern on github.\" ) parser.add_argument( \"-w\", \"--img_width\",", "= True if not pause: if args.gray: frame = cv2.cvtColor(frame,", "help=\"To save 1-channel images\" ) parser.add_argument( \"-e\", \"--erode\", required=False, default=None,", "be sent: \", COMMANDS[command_id]) if COMMANDS[command_id] == \"move_forward\": anafi.move_relative(dx=1, dy=0,", "cv2.COLOR_BGR2GRAY) if args.binarize: frame = cv2.medianBlur(frame, 5) min_thresh, max_thresh =", "frame\") break if args.crop is not None: frame = frame[min_height:max_height,", "dy=0, dz=0.5, dradians=0) if COMMANDS[command_id] == \"take_off\": anafi.safe_takeoff(5) if COMMANDS[command_id]", "shape, format: height,width\" ) parser.add_argument( \"-b\", \"--binarize\", required=False, default=None, type=str,", "= [int(x) for x in args.binarize.split(',')] ret, frame = cv2.threshold(frame,", "args.resize.split(',')] frame = cv2.resize(frame, (height, width), interpolation=cv2.INTER_AREA) image = np.asarray(frame)/255.", "to load weights for the model.\" ) parser.add_argument( \"-a\", \"--pyparrot_path\",", "anafi.safe_land(5) return def main(): parser = argparse.ArgumentParser() parser.add_argument( \"-p\", \"--weight_path\",", "help=\"Resize shape, format: height,width\" ) parser.add_argument( \"-b\", \"--binarize\", required=False, default=None,", "in COMMANDS choices: {command_id}\" print(\"The following command will be sent:", "COMMANDS[command_id] == \"go_down\": anafi.move_relative(dx=0, dy=0, dz=-0.5, dradians=0) if COMMANDS[command_id] ==", "-1: min_height = res[2] if res[3] != -1: max_height =", "frame) k = cv2.waitKey(1) if k % 256 == 27:", "images, format for thresholding: min,max\" ) parser.add_argument( \"-g\", \"--gray\", required=False,", "k % 256 == 27: # ESC pressed print(\"Escape hit,", "np.uint8) frame = cv2.dilate(frame, kernel, iterations=int(iteration)) if args.resize: height, width", "else: pause = True if not pause: if args.gray: frame", "interpolation=cv2.INTER_AREA) image = np.asarray(frame)/255. cv2.imshow(\"Input image for the model\", frame)", "args = parser.parse_args() \"\"\" Drone connection \"\"\" sys.path.append(args.pyparrot_path) from pyparrot.Anafi", "k = cv2.waitKey(1) if k % 256 == 27: #", "type=int, help=\"Camera ID, default is 0\" ) parser.add_argument( \"-t\", \"--tensorflow\",", "NN.Linear(hidden_size, hidden_size), NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size, num_class), NN.Softmax()], NN.LossMSE()) model.load(args.weight_path) \"\"\"", "minWidth:maxWidth, minHeight:maxHeight: {}:{}\\ , {},{}\".format(min_width, max_width, min_height, max_height)) pause =", "dradians=0.785) if COMMANDS[command_id] == \"go_up\": anafi.move_relative(dx=0, dy=0, dz=0.5, dradians=0) if", "if COMMANDS[command_id] == \"rot_10_deg\": anafi.move_relative(dx=0, dy=0, dz=0, dradians=0.785) if COMMANDS[command_id]", "height, width = [int(size) for size in args.resize.split(',')] frame =", "\"\"\" Webcam process \"\"\" print(\"Start webcam...\") cam = cv2.VideoCapture(args.camid) ret,", "help=\"Path to pyparrot module downloaded from amymcgovern on github.\" )", "is used.\" ) parser.add_argument( \"-z\", \"--number_of_confimation\", required=False, default=3, type=int, help=\"Minimum", "sys COMMANDS = {0: \"move_forward\", 1: \"go_down\", 2: \"rot_10_deg\", 3:", "if args.binarize: frame = cv2.medianBlur(frame, 5) min_thresh, max_thresh = [int(x)", "default=0, type=int, help=\"Camera ID, default is 0\" ) parser.add_argument( \"-t\",", "!= -1: min_height = res[2] if res[3] != -1: max_height", "break if args.crop is not None: frame = frame[min_height:max_height, min_width:max_width]", "if COMMANDS[command_id] == \"go_down\": anafi.move_relative(dx=0, dy=0, dz=-0.5, dradians=0) if COMMANDS[command_id]", "k_size, iteration = [int(x) for x in args.erode.split(',')] kernel =", "def main(): parser = argparse.ArgumentParser() parser.add_argument( \"-p\", \"--weight_path\", required=True, type=str,", "\"\"\" Load model \"\"\" print(\"Loading model...\") input_size = args.img_width**2 num_class", "= False imgs = [] while True: ret, frame =", "np.asarray(imgs)) print(\"Model's output on buffer: \", results) if np.unique(results).size ==", "anafi.move_relative(dx=0, dy=0, dz=-0.5, dradians=0) if COMMANDS[command_id] == \"rot_10_deg\": anafi.move_relative(dx=0, dy=0,", "np.uint8) frame = cv2.erode(frame, kernel, iterations=int(iteration)) if args.dilate is not", "dy=0, dz=0, dradians=0.785) if COMMANDS[command_id] == \"go_up\": anafi.move_relative(dx=0, dy=0, dz=0.5,", "-*- \"\"\" This script run neural network model on a", "cv2.erode(frame, kernel, iterations=int(iteration)) if args.dilate is not None: k_size, iteration", "as np import os import time import sys COMMANDS =", "on github.\" ) parser.add_argument( \"-w\", \"--img_width\", required=False, default=28, type=int, help=\"Image", "parser.add_argument( \"-c\", \"--crop\", required=False, default=None, type=str, help=\"Crop image, format: MinWidth,MaxWidth,MinHeight,MaxHeight.\\", "default=None, type=str, help=\"Dilate option, format: kernel_size,iteration\" ) parser.add_argument( \"-m\", \"--camid\",", "\"go_down\", 2: \"rot_10_deg\", 3: \"go_up\", 4: \"take_off\", 5: \"land\", 6:", "if pause: pause = False else: pause = True if", "used.\" ) parser.add_argument( \"-z\", \"--number_of_confimation\", required=False, default=3, type=int, help=\"Minimum number", "= [int(size) for size in args.resize.split(',')] frame = cv2.resize(frame, (height,", "parser.add_argument( \"-r\", \"--resize\", required=False, default=None, type=str, help=\"Resize shape, format: height,width\"", "args.binarize: frame = cv2.medianBlur(frame, 5) min_thresh, max_thresh = [int(x) for", "connection \"\"\" sys.path.append(args.pyparrot_path) from pyparrot.Anafi import Anafi print(\"Connecting to drone...\")", "raise f\"Command id not in COMMANDS choices: {command_id}\" print(\"The following", "COMMANDS = {0: \"move_forward\", 1: \"go_down\", 2: \"rot_10_deg\", 3: \"go_up\",", "to minWidth:maxWidth, minHeight:maxHeight: {}:{}\\ , {},{}\".format(min_width, max_width, min_height, max_height)) pause", "load weights for the model.\" ) parser.add_argument( \"-a\", \"--pyparrot_path\", required=True,", "if args.erode is not None: k_size, iteration = [int(x) for", "required=False, action=\"store_true\", help=\"To save 1-channel images\" ) parser.add_argument( \"-e\", \"--erode\",", "\"-d\", \"--dilate\", required=False, default=None, type=str, help=\"Dilate option, format: kernel_size,iteration\" )", "import argparse import cv2 import numpy as np import os", ") parser.add_argument( \"-c\", \"--crop\", required=False, default=None, type=str, help=\"Crop image, format:", "model.load(args.weight_path) \"\"\" Webcam process \"\"\" print(\"Start webcam...\") cam = cv2.VideoCapture(args.camid)", "parser.add_argument( \"-d\", \"--dilate\", required=False, default=None, type=str, help=\"Dilate option, format: kernel_size,iteration\"", "the model.\" ) parser.add_argument( \"-a\", \"--pyparrot_path\", required=True, type=str, help=\"Path to", "iteration = [int(x) for x in args.erode.split(',')] kernel = np.ones((k_size,", "help=\"Image width.\" ) parser.add_argument( \"-n\", \"--num_classes\", required=False, default=7, type=int, help=\"Number", "x in args.binarize.split(',')] ret, frame = cv2.threshold(frame, min_thresh, max_thresh, cv2.THRESH_BINARY)", "process \"\"\" print(\"Start webcam...\") cam = cv2.VideoCapture(args.camid) ret, frame =", "import os import time import sys COMMANDS = {0: \"move_forward\",", "False else: pause = True if not pause: if args.gray:", "if COMMANDS[command_id] == \"take_off\": anafi.safe_takeoff(5) if COMMANDS[command_id] == \"land\": anafi.safe_land(5)", "= 0, frame.shape[0] min_width, max_width = 0, frame.shape[1] print(\"Cam resolution:", "128 if args.tensorflow: import tensorflow as tf model = tf.keras.models.load_model(args.weight_path)", "results = np.argmax(model(np.asarray(imgs)), axis=1) else: results = NN.get_inferences(model, np.asarray(imgs)) print(\"Model's", "grab frame\") break if args.crop is not None: frame =", "dz=0.5, dradians=0) if COMMANDS[command_id] == \"take_off\": anafi.safe_takeoff(5) if COMMANDS[command_id] ==", "NN.LossMSE()) model.load(args.weight_path) \"\"\" Webcam process \"\"\" print(\"Start webcam...\") cam =", "COMMANDS[command_id]) if COMMANDS[command_id] == \"move_forward\": anafi.move_relative(dx=1, dy=0, dz=0, dradians=0) if", "Webcam process \"\"\" print(\"Start webcam...\") cam = cv2.VideoCapture(args.camid) ret, frame", "\", results) if np.unique(results).size == 1 and\\ COMMANDS[results[0]] != \"idle\":", "format: MinWidth,MaxWidth,MinHeight,MaxHeight.\\ Set -1 for the unchanged ones\" ) parser.add_argument(", "len(imgs) < args.number_of_confimation: imgs.append(image) else: if args.tensorflow: results = np.argmax(model(np.asarray(imgs)),", "[int(x) for x in args.binarize.split(',')] ret, frame = cv2.threshold(frame, min_thresh,", "= res[2] if res[3] != -1: max_height = res[3] print(\"Image", "True: ret, frame = cam.read() if not ret: print(\"failed to", "identical commands before sending to drone.\" ) args = parser.parse_args()", "the model\", frame) image = image.reshape([np.prod(image.shape)]) if len(imgs) < args.number_of_confimation:", "not None: res = [int(x) for x in args.crop.split(',')] if", "res[3] != -1: max_height = res[3] print(\"Image cropped to minWidth:maxWidth,", "min_thresh, max_thresh = [int(x) for x in args.binarize.split(',')] ret, frame", "# -*- coding: utf-8 -*- \"\"\" This script run neural", "cv2 import numpy as np import os import time import", "\"\"\" sys.path.append(args.pyparrot_path) from pyparrot.Anafi import Anafi print(\"Connecting to drone...\") anafi", "256 == 27: # ESC pressed print(\"Escape hit, closing...\") break", "to pyparrot module downloaded from amymcgovern on github.\" ) parser.add_argument(", "= tf.keras.models.load_model(args.weight_path) else: script_path = os.path.realpath(__file__) sys.path.append(os.path.dirname(script_path) + \"/../\") from", "cropped to minWidth:maxWidth, minHeight:maxHeight: {}:{}\\ , {},{}\".format(min_width, max_width, min_height, max_height))", "image = image.reshape([np.prod(image.shape)]) if len(imgs) < args.number_of_confimation: imgs.append(image) else: if", "\"--gray\", required=False, action=\"store_true\", help=\"To save 1-channel images\" ) parser.add_argument( \"-e\",", "anafi.safe_takeoff(5) if COMMANDS[command_id] == \"land\": anafi.safe_land(5) return def main(): parser", "1-channel images\" ) parser.add_argument( \"-e\", \"--erode\", required=False, default=None, type=str, help=\"Erode", "type=str, help=\"Dilate option, format: kernel_size,iteration\" ) parser.add_argument( \"-m\", \"--camid\", required=False,", "before sending to drone.\" ) args = parser.parse_args() \"\"\" Drone", "anafi.move_relative(dx=0, dy=0, dz=0, dradians=0.785) if COMMANDS[command_id] == \"go_up\": anafi.move_relative(dx=0, dy=0,", "in args.dilate.split(',')] kernel = np.ones((k_size, k_size), np.uint8) frame = cv2.dilate(frame,", "if args.dilate is not None: k_size, iteration = [int(x) for", "type=int, help=\"Minimum number of identical commands before sending to drone.\"", "res[2] if res[3] != -1: max_height = res[3] print(\"Image cropped", "to an Anafi drone in function of the command id", "\"--crop\", required=False, default=None, type=str, help=\"Crop image, format: MinWidth,MaxWidth,MinHeight,MaxHeight.\\ Set -1", "parser.parse_args() \"\"\" Drone connection \"\"\" sys.path.append(args.pyparrot_path) from pyparrot.Anafi import Anafi", "\"--dilate\", required=False, default=None, type=str, help=\"Dilate option, format: kernel_size,iteration\" ) parser.add_argument(", ") parser.add_argument( \"-d\", \"--dilate\", required=False, default=None, type=str, help=\"Dilate option, format:", ") parser.add_argument( \"-t\", \"--tensorflow\", required=False, action=\"store_true\", help=\"To specify if Tensorflow", "\"\"\" print(\"Loading model...\") input_size = args.img_width**2 num_class = args.num_classes hidden_size", "\"idle\": send_command(anafi, results[0]) imgs = [] imgs = imgs[1:] imgs.append(image)", "iterations=int(iteration)) if args.resize: height, width = [int(size) for size in", "type=str, help=\"Crop image, format: MinWidth,MaxWidth,MinHeight,MaxHeight.\\ Set -1 for the unchanged", "x in args.erode.split(',')] kernel = np.ones((k_size, k_size), np.uint8) frame =", "cv2.threshold(frame, min_thresh, max_thresh, cv2.THRESH_BINARY) if args.erode is not None: k_size,", "buffer: \", results) if np.unique(results).size == 1 and\\ COMMANDS[results[0]] !=", "ret, frame = cam.read() if not ret: print(\"failed to grab", "frame = cv2.erode(frame, kernel, iterations=int(iteration)) if args.dilate is not None:", "cv2.THRESH_BINARY) if args.erode is not None: k_size, iteration = [int(x)", "return def main(): parser = argparse.ArgumentParser() parser.add_argument( \"-p\", \"--weight_path\", required=True,", "num_class = args.num_classes hidden_size = 128 if args.tensorflow: import tensorflow", "imgs = imgs[1:] imgs.append(image) time.sleep(0.3) cam.release() cv2.destroyAllWindows() if __name__ ==", "binarize images, format for thresholding: min,max\" ) parser.add_argument( \"-g\", \"--gray\",", "help=\"To specify if Tensorflow model is used.\" ) parser.add_argument( \"-z\",", "os.path.realpath(__file__) sys.path.append(os.path.dirname(script_path) + \"/../\") from homemade_framework import framework as NN", "\"take_off\": anafi.safe_takeoff(5) if COMMANDS[command_id] == \"land\": anafi.safe_land(5) return def main():", "action=\"store_true\", help=\"To save 1-channel images\" ) parser.add_argument( \"-e\", \"--erode\", required=False,", "iteration = [int(x) for x in args.dilate.split(',')] kernel = np.ones((k_size,", "and\\ COMMANDS[results[0]] != \"idle\": send_command(anafi, results[0]) imgs = [] imgs", "\"\"\" This script run neural network model on a camera", "print(\"Cam resolution: {}x{}\".format(max_width, max_height)) if args.crop is not None: res", "if res[3] != -1: max_height = res[3] print(\"Image cropped to", "sending to drone.\" ) args = parser.parse_args() \"\"\" Drone connection", "hidden_size = 128 if args.tensorflow: import tensorflow as tf model", "not None: k_size, iteration = [int(x) for x in args.dilate.split(',')]", "\"idle\"} def send_command(anafi, command_id): \"\"\" Function to send commands to", "\"--number_of_confimation\", required=False, default=3, type=int, help=\"Minimum number of identical commands before", "args.crop.split(',')] if res[0] != -1: min_width = res[0] if res[1]", "k_size, iteration = [int(x) for x in args.dilate.split(',')] kernel =", "args.tensorflow: results = np.argmax(model(np.asarray(imgs)), axis=1) else: results = NN.get_inferences(model, np.asarray(imgs))", "\"--weight_path\", required=True, type=str, help=\"Path to load weights for the model.\"", "parser.add_argument( \"-g\", \"--gray\", required=False, action=\"store_true\", help=\"To save 1-channel images\" )", "camera live stream \"\"\" import argparse import cv2 import numpy", "\"-w\", \"--img_width\", required=False, default=28, type=int, help=\"Image width.\" ) parser.add_argument( \"-n\",", "is 0\" ) parser.add_argument( \"-t\", \"--tensorflow\", required=False, action=\"store_true\", help=\"To specify", ", {},{}\".format(min_width, max_width, min_height, max_height)) pause = False imgs =", "for x in args.dilate.split(',')] kernel = np.ones((k_size, k_size), np.uint8) frame", "\"\"\" if command_id not in COMMANDS: raise f\"Command id not", "\"--resize\", required=False, default=None, type=str, help=\"Resize shape, format: height,width\" ) parser.add_argument(", "import tensorflow as tf model = tf.keras.models.load_model(args.weight_path) else: script_path =", "-1: max_width = res[1] if res[2] != -1: min_height =", "None: k_size, iteration = [int(x) for x in args.erode.split(',')] kernel", "kernel, iterations=int(iteration)) if args.dilate is not None: k_size, iteration =", "to drone.\" ) args = parser.parse_args() \"\"\" Drone connection \"\"\"", "\"-z\", \"--number_of_confimation\", required=False, default=3, type=int, help=\"Minimum number of identical commands", "frame = cv2.resize(frame, (height, width), interpolation=cv2.INTER_AREA) image = np.asarray(frame)/255. cv2.imshow(\"Input", "np import os import time import sys COMMANDS = {0:", "for the model\", frame) image = image.reshape([np.prod(image.shape)]) if len(imgs) <", "!= \"idle\": send_command(anafi, results[0]) imgs = [] imgs = imgs[1:]", "= cv2.threshold(frame, min_thresh, max_thresh, cv2.THRESH_BINARY) if args.erode is not None:", "2: \"rot_10_deg\", 3: \"go_up\", 4: \"take_off\", 5: \"land\", 6: \"idle\"}", "== \"go_down\": anafi.move_relative(dx=0, dy=0, dz=-0.5, dradians=0) if COMMANDS[command_id] == \"rot_10_deg\":", "downloaded from amymcgovern on github.\" ) parser.add_argument( \"-w\", \"--img_width\", required=False,", "dz=0, dradians=0) if COMMANDS[command_id] == \"go_down\": anafi.move_relative(dx=0, dy=0, dz=-0.5, dradians=0)", "neural network model on a camera live stream \"\"\" import", "type=str, help=\"To binarize images, format for thresholding: min,max\" ) parser.add_argument(", "res[1] != -1: max_width = res[1] if res[2] != -1:", "sent: \", COMMANDS[command_id]) if COMMANDS[command_id] == \"move_forward\": anafi.move_relative(dx=1, dy=0, dz=0,", "\"rot_10_deg\": anafi.move_relative(dx=0, dy=0, dz=0, dradians=0.785) if COMMANDS[command_id] == \"go_up\": anafi.move_relative(dx=0,", "axis=1) else: results = NN.get_inferences(model, np.asarray(imgs)) print(\"Model's output on buffer:", "args.tensorflow: import tensorflow as tf model = tf.keras.models.load_model(args.weight_path) else: script_path", "[int(size) for size in args.resize.split(',')] frame = cv2.resize(frame, (height, width),", "not in COMMANDS: raise f\"Command id not in COMMANDS choices:", "max_height = res[3] print(\"Image cropped to minWidth:maxWidth, minHeight:maxHeight: {}:{}\\ ,", "parser.add_argument( \"-a\", \"--pyparrot_path\", required=True, type=str, help=\"Path to pyparrot module downloaded", "pressed print(\"Escape hit, closing...\") break elif k % 256 ==", "format: height,width\" ) parser.add_argument( \"-b\", \"--binarize\", required=False, default=None, type=str, help=\"To", "True if not pause: if args.gray: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)", "min_width = res[0] if res[1] != -1: max_width = res[1]", "NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size, num_class), NN.Softmax()], NN.LossMSE()) model.load(args.weight_path) \"\"\" Webcam process", "= os.path.realpath(__file__) sys.path.append(os.path.dirname(script_path) + \"/../\") from homemade_framework import framework as", "5) min_thresh, max_thresh = [int(x) for x in args.binarize.split(',')] ret,", "frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) if args.binarize: frame = cv2.medianBlur(frame, 5)", "x in args.dilate.split(',')] kernel = np.ones((k_size, k_size), np.uint8) frame =", "as tf model = tf.keras.models.load_model(args.weight_path) else: script_path = os.path.realpath(__file__) sys.path.append(os.path.dirname(script_path)", "tf model = tf.keras.models.load_model(args.weight_path) else: script_path = os.path.realpath(__file__) sys.path.append(os.path.dirname(script_path) +", "command will be sent: \", COMMANDS[command_id]) if COMMANDS[command_id] == \"move_forward\":", "dradians=0) if COMMANDS[command_id] == \"rot_10_deg\": anafi.move_relative(dx=0, dy=0, dz=0, dradians=0.785) if", "script_path = os.path.realpath(__file__) sys.path.append(os.path.dirname(script_path) + \"/../\") from homemade_framework import framework", "parser.add_argument( \"-e\", \"--erode\", required=False, default=None, type=str, help=\"Erode option, format: kernel_size,iteration\"", "will be sent: \", COMMANDS[command_id]) if COMMANDS[command_id] == \"move_forward\": anafi.move_relative(dx=1,", "the command id \"\"\" if command_id not in COMMANDS: raise", "3: \"go_up\", 4: \"take_off\", 5: \"land\", 6: \"idle\"} def send_command(anafi,", "= res[0] if res[1] != -1: max_width = res[1] if", "= False else: pause = True if not pause: if", "ret: print(\"failed to grab frame\") break if args.crop is not", "1: \"go_down\", 2: \"rot_10_deg\", 3: \"go_up\", 4: \"take_off\", 5: \"land\",", "ret, frame = cv2.threshold(frame, min_thresh, max_thresh, cv2.THRESH_BINARY) if args.erode is", "\"go_up\": anafi.move_relative(dx=0, dy=0, dz=0.5, dradians=0) if COMMANDS[command_id] == \"take_off\": anafi.safe_takeoff(5)", "if COMMANDS[command_id] == \"land\": anafi.safe_land(5) return def main(): parser =", "for x in args.binarize.split(',')] ret, frame = cv2.threshold(frame, min_thresh, max_thresh,", "None: k_size, iteration = [int(x) for x in args.dilate.split(',')] kernel", "Anafi drone in function of the command id \"\"\" if", "= 0, frame.shape[1] print(\"Cam resolution: {}x{}\".format(max_width, max_height)) if args.crop is", "option, format: kernel_size,iteration\" ) parser.add_argument( \"-d\", \"--dilate\", required=False, default=None, type=str,", ") parser.add_argument( \"-g\", \"--gray\", required=False, action=\"store_true\", help=\"To save 1-channel images\"", "args.crop is not None: res = [int(x) for x in", "None: frame = frame[min_height:max_height, min_width:max_width] cv2.imshow(\"Original image\", frame) k =", "if args.crop is not None: frame = frame[min_height:max_height, min_width:max_width] cv2.imshow(\"Original", "pressed if pause: pause = False else: pause = True", "image for the model\", frame) image = image.reshape([np.prod(image.shape)]) if len(imgs)", "default=7, type=int, help=\"Number of classes.\" ) parser.add_argument( \"-c\", \"--crop\", required=False,", "\"--tensorflow\", required=False, action=\"store_true\", help=\"To specify if Tensorflow model is used.\"", "anafi.move_relative(dx=1, dy=0, dz=0, dradians=0) if COMMANDS[command_id] == \"go_down\": anafi.move_relative(dx=0, dy=0,", "imgs[1:] imgs.append(image) time.sleep(0.3) cam.release() cv2.destroyAllWindows() if __name__ == '__main__': main()", "\"land\": anafi.safe_land(5) return def main(): parser = argparse.ArgumentParser() parser.add_argument( \"-p\",", "\"--erode\", required=False, default=None, type=str, help=\"Erode option, format: kernel_size,iteration\" ) parser.add_argument(", "type=str, help=\"Erode option, format: kernel_size,iteration\" ) parser.add_argument( \"-d\", \"--dilate\", required=False,", "\"\"\" print(\"Start webcam...\") cam = cv2.VideoCapture(args.camid) ret, frame = cam.read()", "success = anafi.connect(10) print(success) print(\"Sleeping few seconds...\") anafi.smart_sleep(3) \"\"\" Load", "model is used.\" ) parser.add_argument( \"-z\", \"--number_of_confimation\", required=False, default=3, type=int,", "commands to an Anafi drone in function of the command", "NN.BatchNorm(), NN.Linear(hidden_size, hidden_size), NN.LeakyReLU(), NN.BatchNorm(), NN.Linear(hidden_size, num_class), NN.Softmax()], NN.LossMSE()) model.load(args.weight_path)", "\"rot_10_deg\", 3: \"go_up\", 4: \"take_off\", 5: \"land\", 6: \"idle\"} def", "anafi.move_relative(dx=0, dy=0, dz=0.5, dradians=0) if COMMANDS[command_id] == \"take_off\": anafi.safe_takeoff(5) if", "type=int, help=\"Image width.\" ) parser.add_argument( \"-n\", \"--num_classes\", required=False, default=7, type=int,", "[] while True: ret, frame = cam.read() if not ret:", "parser = argparse.ArgumentParser() parser.add_argument( \"-p\", \"--weight_path\", required=True, type=str, help=\"Path to", "max_height = 0, frame.shape[0] min_width, max_width = 0, frame.shape[1] print(\"Cam", "pause = False imgs = [] while True: ret, frame", "required=False, default=None, type=str, help=\"Crop image, format: MinWidth,MaxWidth,MinHeight,MaxHeight.\\ Set -1 for", "ord('p'): # p pressed if pause: pause = False else:", "\"go_down\": anafi.move_relative(dx=0, dy=0, dz=-0.5, dradians=0) if COMMANDS[command_id] == \"rot_10_deg\": anafi.move_relative(dx=0,", "= cv2.medianBlur(frame, 5) min_thresh, max_thresh = [int(x) for x in", "def send_command(anafi, command_id): \"\"\" Function to send commands to an", "parser.add_argument( \"-z\", \"--number_of_confimation\", required=False, default=3, type=int, help=\"Minimum number of identical", "width = [int(size) for size in args.resize.split(',')] frame = cv2.resize(frame,", "{},{}\".format(min_width, max_width, min_height, max_height)) pause = False imgs = []", "res[2] != -1: min_height = res[2] if res[3] != -1:", "= args.num_classes hidden_size = 128 if args.tensorflow: import tensorflow as", "max_width = 0, frame.shape[1] print(\"Cam resolution: {}x{}\".format(max_width, max_height)) if args.crop", "\"-c\", \"--crop\", required=False, default=None, type=str, help=\"Crop image, format: MinWidth,MaxWidth,MinHeight,MaxHeight.\\ Set", "= [int(x) for x in args.crop.split(',')] if res[0] != -1:", "k_size), np.uint8) frame = cv2.dilate(frame, kernel, iterations=int(iteration)) if args.resize: height,", "default=3, type=int, help=\"Minimum number of identical commands before sending to" ]
[ "image and labels from previous labelling session \"\"\" fname =", "mode='thick')) plt.title('segmented image') plt.subplot(1,2,2) plt.imshow(image) plt.imshow(labels, alpha=0.75) cb = plt.colorbar(orientation='horizontal',", "== -1] = 0 truth[truth == 0] = 5 truth[truth", "or directory (classify_directory()) 5. Apply classification to 3D points and", "train_labels = load_training_data(train_dir) # Train classifier clf = SVC() clf.fit(train_data,", "directory (classify_directory()) 5. Apply classification to 3D points and estimate", "= SVC() clf.fit(train_data, train_labels) # Predict labels for test images", "Display image with segments and class label overlay \"\"\" plt.figure()", "'_image.npy' image = np.load(fname) fname = 'labelled/' + name +", "train_labels = np.append(train_labels, labels.reshape(wid*ht, 1).ravel()) train_data, train_labels = shuffle(train_data, train_labels,", "'test/' train_data, train_labels = load_training_data(train_dir) # Train classifier clf =", "= np.load(fname) fname = 'labelled/' + name + '_labels.npy' labels", "using an arbitrary sklearn classifier. Saves results to results/ directory.", "an arbitrary sklearn classifier. Saves results to results/ directory. \"\"\"", "or training image array and redefine labelling for nice default", "np.hstack([X.reshape((height*width, 1)), Y.reshape((height*width, 1))]) colorxy = np.hstack([xy, colors]) colorxy /=", "in files: name = parse_filename(f) image, labels = load_image_labels(name) ht,", "This is here if the classifier needs to be trained", "= np.load(filename) # Change labels for nice default colorscale when", "training data results/ - contains results of classification I store", "scratch #print(\"Preparing training data...\") #n_samples = 1000 #train_data, train_labels =", "clf = SVC() clf.fit(train_data, train_labels) # Predict labels for test", "2017 \"\"\" import numpy as np import matplotlib.pyplot as plt", "arbitrary sklearn classifier. Saves results to results/ directory. \"\"\" #", "train_dir = 'train/' test_dir = 'test/' train_data, train_labels = load_training_data(train_dir)", "usage: 1. Load and segment images (img_utils.py) 2. Prepare training", "n_samples=n_samples) return train_data, train_labels def save_prediction(name, pred_labels): \"\"\" Save predicted", "all images in a directory using an arbitrary sklearn classifier.", "train_labels, random_state=0, n_samples=n_samples) return train_data, train_labels def save_prediction(name, pred_labels): \"\"\"", "== 0] = 5 truth[truth == 2] = 0 truth[truth", "train_labels = np.empty(0) files = os.listdir(train_dir) for f in files:", "matplotlib.pyplot as plt import skimage.color, skimage.io from skimage.segmentation import mark_boundaries", "f.strip('.JPG') + '_svm_pred.png') plt.close() np.save('results/' + f.strip('.JPG') + 'svm.npy', pred_labels.reshape((height,width)))", "= plt.colorbar(orientation='horizontal', shrink=0.5) plt.title('predicted class labels') plt.show(block=False) def load_training_images(train_dir, n_samples=1000,", "SVC from sklearn.cluster import KMeans, MeanShift from sklearn.metrics import confusion_matrix", "images in a directory using an arbitrary sklearn classifier. Saves", "colors \"\"\" truth = np.load(filename) # Change labels for nice", "images using color and other features. General pipeline usage: 1.", "n_samples=1000, n_features=3): \"\"\" Load training images from directory and subsample", "files: name = parse_filename(f) image, labels = load_image_labels(name) ht, wid,", "+ name + '_pred', pred_labels) if __name__ == \"__main__\": #", "f.strip('.JPG') + \".jpg\") plt.figure() plt.imshow(image) plt.imshow(pred_labels.reshape((height, width)), alpha=0.5, vmin=0, vmax=2)", "clf.fit(train_data, train_labels) # Predict labels for test images classify_directory(clf, test_dir)", "print(\"Saving predictions for \" + f.strip('.JPG') + \".jpg\") plt.figure() plt.imshow(image)", "in a directory using an arbitrary sklearn classifier. Saves results", "(img_utils.py) 2. Prepare training data (label_image.py) 3. Train classifier or", "Classification of pixels in images using color and other features.", "sklearn classifier. Saves results to results/ directory. \"\"\" # XXX:", "+ '_image.npy' image = np.load(fname) fname = 'labelled/' + name", "and other features. General pipeline usage: 1. Load and segment", "= load_training_images(train_dir, n_samples) # #print(\"Training classifier...\") #classifier = ImageSVC() #classifier.fit(train_data,", "Classify all images in a directory using an arbitrary sklearn", "#classifier.fit(train_data, train_labels) files = os.listdir(test_dir) for f in files: image", "return train_data, train_labels def save_prediction(name, pred_labels): \"\"\" Save predicted class", "\"\"\" Load image and labels from previous labelling session \"\"\"", "from sklearn.cluster import KMeans, MeanShift from sklearn.metrics import confusion_matrix from", "f in files: image = skimage.io.imread(f) height, width, depth =", "n_features=3): \"\"\" Load training images from directory and subsample for", "import SVC from sklearn.cluster import KMeans, MeanShift from sklearn.metrics import", "skimage.io.imread(f) height, width, depth = image.shape print(\"Predicting labels for \"", "segments, color=(1,0,0), mode='thick')) plt.title('segmented image') plt.subplot(1,2,2) plt.imshow(image) plt.imshow(labels, alpha=0.75) cb", "randomly split training and testing images in test/ and train/", "location features from image data \"\"\" height, width, depth =", "\" + f.strip('.JPG') + \".jpg\") features = compute_colorxy_features(image) features /=", "\"\"\" truth = np.load(filename) # Change labels for nice default", "'train/' test_dir = 'test/' train_data, train_labels = load_training_data(train_dir) # Train", "images/ - contains binary files of numpy arrays corresponding to", "as plt import skimage.color, skimage.io from skimage.segmentation import mark_boundaries from", "training data train_dir = 'train/' test_dir = 'test/' train_data, train_labels", "image array and redefine labelling for nice default colors \"\"\"", "classify_directory(classifier, test_dir, train_dir='train/'): \"\"\" Classify all images in a directory", "color and other features. General pipeline usage: 1. Load and", "- contains binary files of numpy arrays corresponding to survey", "\"\"\" # XXX: This is here if the classifier needs", "to be trained from scratch #print(\"Preparing training data...\") #n_samples =", "load_training_data(train_dir) # Train classifier clf = SVC() clf.fit(train_data, train_labels) #", "\"\"\" Save predicted class labels \"\"\" np.save('results/' + name +", "estimate ground plane orientation (process_pointcloud.py) Project uses the following directory", "import os, fnmatch def classify_directory(classifier, test_dir, train_dir='train/'): \"\"\" Classify all", "labels') plt.show(block=False) def load_training_images(train_dir, n_samples=1000, n_features=3): \"\"\" Load training images", "+ f.strip('.JPG') + \".jpg\") features = compute_colorxy_features(image) features /= features.max(axis=0)", "name = parse_filename(f) image, labels = load_image_labels(name) ht, wid, depth", "plt.imshow(pred_labels.reshape((height, width)), alpha=0.5, vmin=0, vmax=2) plt.show(block=False) plt.savefig('results/' + f.strip('.JPG') +", "image data \"\"\" height, width, depth = image.shape colors =", "testing images in test/ and train/ directories. Author: <NAME> E-mail:", "np.load(fname) fname = 'labelled/' + name + '_labels.npy' labels =", "features from image data \"\"\" height, width, depth = image.shape", "np.hstack([xy, colors]) colorxy /= colorxy.max(axis=0) return colorxy def load_ground_truth(filename): \"\"\"", "load_ground_truth(filename): \"\"\" Load ground truth or training image array and", "classification to 3D points and estimate ground plane orientation (process_pointcloud.py)", "data (label_image.py) 3. Train classifier or cluster data (sklearn KMeans,", "other features. General pipeline usage: 1. Load and segment images", "width, depth = image.shape print(\"Predicting labels for \" + f.strip('.JPG')", "from sklearn.metrics import confusion_matrix from sklearn.utils import shuffle import os,", "- 1 truth[truth == -1] = 0 truth[truth == 0]", "5. Apply classification to 3D points and estimate ground plane", "return colorxy def load_ground_truth(filename): \"\"\" Load ground truth or training", "images from directory and subsample for training or validation \"\"\"", "from scratch #print(\"Preparing training data...\") #n_samples = 1000 #train_data, train_labels", "shuffle(train_data, train_labels, random_state=0, n_samples=n_samples) return train_data, train_labels def save_prediction(name, pred_labels):", "colorxy = np.hstack([xy, colors]) colorxy /= colorxy.max(axis=0) return colorxy def", "classification I store randomly split training and testing images in", "test/ and train/ directories. Author: <NAME> E-mail: <EMAIL> Date: 8", "labels from previous labelling session \"\"\" fname = 'images/' +", "def save_prediction(name, pred_labels): \"\"\" Save predicted class labels \"\"\" np.save('results/'", "= load_image_labels(name) ht, wid, depth = image.shape train_data = np.append(train_data,", "truth[truth == 0] = 5 truth[truth == 2] = 0", "\"\"\" train_data = np.empty((0, n_features)) train_labels = np.empty(0) files =", "in test/ and train/ directories. Author: <NAME> E-mail: <EMAIL> Date:", "ground truth images or training data results/ - contains results", "'images/' + name + '_image.npy' image = np.load(fname) fname =", "or training data results/ - contains results of classification I", "color=(1,0,0), mode='thick')) plt.title('segmented image') plt.subplot(1,2,2) plt.imshow(image) plt.imshow(labels, alpha=0.75) cb =", "#train_data, train_labels = load_training_images(train_dir, n_samples) # #print(\"Training classifier...\") #classifier =", "f.strip('.JPG') + \".jpg\") features = compute_colorxy_features(image) features /= features.max(axis=0) pred_labels", "sklearn.svm import SVC from sklearn.cluster import KMeans, MeanShift from sklearn.metrics", "image, labels def plot_class_image(image, segments, labels): \"\"\" Display image with", "following directory structure: images/ - contains binary files of numpy", "labels = load_image_labels(name) ht, wid, depth = image.shape train_data =", "== 5] = 2 return truth def load_image_labels(name): \"\"\" Load", "labels = np.load(fname) return image, labels def plot_class_image(image, segments, labels):", "survey images and segmentations labelled/ - contains labelled ground truth", "Apply classification to 3D points and estimate ground plane orientation", "'_pred', pred_labels) if __name__ == \"__main__\": # Load training data", "is here if the classifier needs to be trained from", "data (sklearn KMeans, MeanShift, SVC, etc.) 4. Predict labels on", "data results/ - contains results of classification I store randomly", "images and segmentations labelled/ - contains labelled ground truth images", "pixel location features from image data \"\"\" height, width, depth", "\"\"\" Classification of pixels in images using color and other", "\"\"\" plt.figure() plt.subplot(1,2,1) plt.imshow(mark_boundaries(image, segments, color=(1,0,0), mode='thick')) plt.title('segmented image') plt.subplot(1,2,2)", "training data...\") #n_samples = 1000 #train_data, train_labels = load_training_images(train_dir, n_samples)", "features. General pipeline usage: 1. Load and segment images (img_utils.py)", "(process_pointcloud.py) Project uses the following directory structure: images/ - contains", "import KMeans, MeanShift from sklearn.metrics import confusion_matrix from sklearn.utils import", "= shuffle(train_data, train_labels, random_state=0, n_samples=n_samples) return train_data, train_labels def save_prediction(name,", "name + '_labels.npy' labels = np.load(fname) return image, labels def", "parse_filename(f) image, labels = load_image_labels(name) ht, wid, depth = image.shape", "colorxy /= colorxy.max(axis=0) return colorxy def load_ground_truth(filename): \"\"\" Load ground", "train_data = np.empty((0, n_features)) train_labels = np.empty(0) files = os.listdir(train_dir)", "Load training data train_dir = 'train/' test_dir = 'test/' train_data,", "name + '_image.npy' image = np.load(fname) fname = 'labelled/' +", "mark_boundaries from sklearn.svm import SVC from sklearn.cluster import KMeans, MeanShift", "features.max(axis=0) pred_labels = classifier.predict(features) print(\"Saving predictions for \" + f.strip('.JPG')", "pred_labels): \"\"\" Save predicted class labels \"\"\" np.save('results/' + name", "2. Prepare training data (label_image.py) 3. Train classifier or cluster", "directory structure: images/ - contains binary files of numpy arrays", "-1] = 0 truth[truth == 0] = 5 truth[truth ==", "ht, wid, depth = image.shape train_data = np.append(train_data, compute_color_features(image), axis=0)", "= np.append(train_data, compute_color_features(image), axis=0) train_labels = np.append(train_labels, labels.reshape(wid*ht, 1).ravel()) train_data,", "height, width, depth = image.shape colors = skimage.color.rgb2lab(image.reshape((height*width, depth)) X,", "f.strip('.JPG') + 'svm.npy', pred_labels.reshape((height,width))) def compute_colorxy_features(image): \"\"\" Extract and normalize", "np.arange(width)) xy = np.hstack([X.reshape((height*width, 1)), Y.reshape((height*width, 1))]) colorxy = np.hstack([xy,", "for f in files: image = skimage.io.imread(f) height, width, depth", "corresponding to survey images and segmentations labelled/ - contains labelled", "= 0 truth[truth == 0] = 5 truth[truth == 2]", "segments, labels): \"\"\" Display image with segments and class label", "training and testing images in test/ and train/ directories. Author:", "np.empty((0, n_features)) train_labels = np.empty(0) files = os.listdir(train_dir) for f", "= np.append(train_labels, labels.reshape(wid*ht, 1).ravel()) train_data, train_labels = shuffle(train_data, train_labels, random_state=0,", "1000 #train_data, train_labels = load_training_images(train_dir, n_samples) # #print(\"Training classifier...\") #classifier", "= compute_colorxy_features(image) features /= features.max(axis=0) pred_labels = classifier.predict(features) print(\"Saving predictions", "def compute_colorxy_features(image): \"\"\" Extract and normalize color and pixel location", "1).ravel()) train_data, train_labels = shuffle(train_data, train_labels, random_state=0, n_samples=n_samples) return train_data,", "1 truth[truth == -1] = 0 truth[truth == 0] =", "if the classifier needs to be trained from scratch #print(\"Preparing", "train_dir='train/'): \"\"\" Classify all images in a directory using an", "depth = image.shape train_data = np.append(train_data, compute_color_features(image), axis=0) train_labels =", "random_state=0, n_samples=n_samples) return train_data, train_labels def save_prediction(name, pred_labels): \"\"\" Save", "and normalize color and pixel location features from image data", "compute_colorxy_features(image): \"\"\" Extract and normalize color and pixel location features", "confusion_matrix from sklearn.utils import shuffle import os, fnmatch def classify_directory(classifier,", "as np import matplotlib.pyplot as plt import skimage.color, skimage.io from", "directory using an arbitrary sklearn classifier. Saves results to results/", "uses the following directory structure: images/ - contains binary files", "depth = image.shape print(\"Predicting labels for \" + f.strip('.JPG') +", "skimage.color, skimage.io from skimage.segmentation import mark_boundaries from sklearn.svm import SVC", "truth or training image array and redefine labelling for nice", "class labels') plt.show(block=False) def load_training_images(train_dir, n_samples=1000, n_features=3): \"\"\" Load training", "class labels \"\"\" np.save('results/' + name + '_pred', pred_labels) if", "plt.show(block=False) plt.savefig('results/' + f.strip('.JPG') + '_svm_pred.png') plt.close() np.save('results/' + f.strip('.JPG')", "= os.listdir(train_dir) for f in files: name = parse_filename(f) image,", "0] = 5 truth[truth == 2] = 0 truth[truth ==", "colorscale when plotted truth = truth - 1 truth[truth ==", "store randomly split training and testing images in test/ and", "be trained from scratch #print(\"Preparing training data...\") #n_samples = 1000", "segments and class label overlay \"\"\" plt.figure() plt.subplot(1,2,1) plt.imshow(mark_boundaries(image, segments,", "to results/ directory. \"\"\" # XXX: This is here if", "labels def plot_class_image(image, segments, labels): \"\"\" Display image with segments", "plane orientation (process_pointcloud.py) Project uses the following directory structure: images/", "array and redefine labelling for nice default colors \"\"\" truth", "training data (label_image.py) 3. Train classifier or cluster data (sklearn", "# Change labels for nice default colorscale when plotted truth", "<NAME> E-mail: <EMAIL> Date: 8 June 2017 \"\"\" import numpy", "from previous labelling session \"\"\" fname = 'images/' + name", "directory. \"\"\" # XXX: This is here if the classifier", "Extract and normalize color and pixel location features from image", "labelling for nice default colors \"\"\" truth = np.load(filename) #", "ground truth or training image array and redefine labelling for", "(classify_directory()) 5. Apply classification to 3D points and estimate ground", "default colors \"\"\" truth = np.load(filename) # Change labels for", "train_labels = load_training_images(train_dir, n_samples) # #print(\"Training classifier...\") #classifier = ImageSVC()", "needs to be trained from scratch #print(\"Preparing training data...\") #n_samples", "here if the classifier needs to be trained from scratch", "Load ground truth or training image array and redefine labelling", "XXX: This is here if the classifier needs to be", "\"\"\" fname = 'images/' + name + '_image.npy' image =", "+ f.strip('.JPG') + 'svm.npy', pred_labels.reshape((height,width))) def compute_colorxy_features(image): \"\"\" Extract and", "for training or validation \"\"\" train_data = np.empty((0, n_features)) train_labels", "label overlay \"\"\" plt.figure() plt.subplot(1,2,1) plt.imshow(mark_boundaries(image, segments, color=(1,0,0), mode='thick')) plt.title('segmented", "in images using color and other features. General pipeline usage:", "image or directory (classify_directory()) 5. Apply classification to 3D points", "previous labelling session \"\"\" fname = 'images/' + name +", "+ \".jpg\") features = compute_colorxy_features(image) features /= features.max(axis=0) pred_labels =", "os, fnmatch def classify_directory(classifier, test_dir, train_dir='train/'): \"\"\" Classify all images", "from directory and subsample for training or validation \"\"\" train_data", "pred_labels = classifier.predict(features) print(\"Saving predictions for \" + f.strip('.JPG') +", "= 0 truth[truth == 5] = 2 return truth def", "I store randomly split training and testing images in test/", "Change labels for nice default colorscale when plotted truth =", "truth - 1 truth[truth == -1] = 0 truth[truth ==", "Load image and labels from previous labelling session \"\"\" fname", "cb = plt.colorbar(orientation='horizontal', shrink=0.5) plt.title('predicted class labels') plt.show(block=False) def load_training_images(train_dir,", "classifier needs to be trained from scratch #print(\"Preparing training data...\")", "on new image or directory (classify_directory()) 5. Apply classification to", "train_data = np.append(train_data, compute_color_features(image), axis=0) train_labels = np.append(train_labels, labels.reshape(wid*ht, 1).ravel())", "2 return truth def load_image_labels(name): \"\"\" Load image and labels", "#classifier = ImageSVC() #classifier.fit(train_data, train_labels) files = os.listdir(test_dir) for f", "= image.shape colors = skimage.color.rgb2lab(image.reshape((height*width, depth)) X, Y = np.meshgrid(np.arange(height),", "and redefine labelling for nice default colors \"\"\" truth =", "1))]) colorxy = np.hstack([xy, colors]) colorxy /= colorxy.max(axis=0) return colorxy", "pred_labels) if __name__ == \"__main__\": # Load training data train_dir", "# #print(\"Training classifier...\") #classifier = ImageSVC() #classifier.fit(train_data, train_labels) files =", "alpha=0.75) cb = plt.colorbar(orientation='horizontal', shrink=0.5) plt.title('predicted class labels') plt.show(block=False) def", "\"\"\" height, width, depth = image.shape colors = skimage.color.rgb2lab(image.reshape((height*width, depth))", "labels): \"\"\" Display image with segments and class label overlay", "MeanShift from sklearn.metrics import confusion_matrix from sklearn.utils import shuffle import", "class label overlay \"\"\" plt.figure() plt.subplot(1,2,1) plt.imshow(mark_boundaries(image, segments, color=(1,0,0), mode='thick'))", "image') plt.subplot(1,2,2) plt.imshow(image) plt.imshow(labels, alpha=0.75) cb = plt.colorbar(orientation='horizontal', shrink=0.5) plt.title('predicted", "and testing images in test/ and train/ directories. Author: <NAME>", "= np.meshgrid(np.arange(height), np.arange(width)) xy = np.hstack([X.reshape((height*width, 1)), Y.reshape((height*width, 1))]) colorxy", "skimage.io from skimage.segmentation import mark_boundaries from sklearn.svm import SVC from", "4. Predict labels on new image or directory (classify_directory()) 5.", "\"\"\" Classify all images in a directory using an arbitrary", "from sklearn.utils import shuffle import os, fnmatch def classify_directory(classifier, test_dir,", "if __name__ == \"__main__\": # Load training data train_dir =", "\"\"\" import numpy as np import matplotlib.pyplot as plt import", "and train/ directories. Author: <NAME> E-mail: <EMAIL> Date: 8 June", "# Load training data train_dir = 'train/' test_dir = 'test/'", "<EMAIL> Date: 8 June 2017 \"\"\" import numpy as np", "shrink=0.5) plt.title('predicted class labels') plt.show(block=False) def load_training_images(train_dir, n_samples=1000, n_features=3): \"\"\"", "compute_color_features(image), axis=0) train_labels = np.append(train_labels, labels.reshape(wid*ht, 1).ravel()) train_data, train_labels =", "a directory using an arbitrary sklearn classifier. Saves results to", "and segment images (img_utils.py) 2. Prepare training data (label_image.py) 3.", "orientation (process_pointcloud.py) Project uses the following directory structure: images/ -", "numpy arrays corresponding to survey images and segmentations labelled/ -", "plt import skimage.color, skimage.io from skimage.segmentation import mark_boundaries from sklearn.svm", "- contains labelled ground truth images or training data results/", "train_data, train_labels = load_training_data(train_dir) # Train classifier clf = SVC()", "files = os.listdir(train_dir) for f in files: name = parse_filename(f)", "files of numpy arrays corresponding to survey images and segmentations", "train/ directories. Author: <NAME> E-mail: <EMAIL> Date: 8 June 2017", "def load_image_labels(name): \"\"\" Load image and labels from previous labelling", "image, labels = load_image_labels(name) ht, wid, depth = image.shape train_data", "MeanShift, SVC, etc.) 4. Predict labels on new image or", "skimage.color.rgb2lab(image.reshape((height*width, depth)) X, Y = np.meshgrid(np.arange(height), np.arange(width)) xy = np.hstack([X.reshape((height*width,", "image.shape train_data = np.append(train_data, compute_color_features(image), axis=0) train_labels = np.append(train_labels, labels.reshape(wid*ht,", "(label_image.py) 3. Train classifier or cluster data (sklearn KMeans, MeanShift,", "Load and segment images (img_utils.py) 2. Prepare training data (label_image.py)", "and subsample for training or validation \"\"\" train_data = np.empty((0,", "vmax=2) plt.show(block=False) plt.savefig('results/' + f.strip('.JPG') + '_svm_pred.png') plt.close() np.save('results/' +", "and estimate ground plane orientation (process_pointcloud.py) Project uses the following", "np.empty(0) files = os.listdir(train_dir) for f in files: name =", "= np.empty((0, n_features)) train_labels = np.empty(0) files = os.listdir(train_dir) for", "from image data \"\"\" height, width, depth = image.shape colors", "Project uses the following directory structure: images/ - contains binary", "width)), alpha=0.5, vmin=0, vmax=2) plt.show(block=False) plt.savefig('results/' + f.strip('.JPG') + '_svm_pred.png')", "data \"\"\" height, width, depth = image.shape colors = skimage.color.rgb2lab(image.reshape((height*width,", "with segments and class label overlay \"\"\" plt.figure() plt.subplot(1,2,1) plt.imshow(mark_boundaries(image,", "labelled/ - contains labelled ground truth images or training data", "images or training data results/ - contains results of classification", "labels for \" + f.strip('.JPG') + \".jpg\") features = compute_colorxy_features(image)", "contains results of classification I store randomly split training and", "fname = 'images/' + name + '_image.npy' image = np.load(fname)", "session \"\"\" fname = 'images/' + name + '_image.npy' image", "image = np.load(fname) fname = 'labelled/' + name + '_labels.npy'", "from sklearn.svm import SVC from sklearn.cluster import KMeans, MeanShift from", "\"\"\" Load ground truth or training image array and redefine", "plt.title('segmented image') plt.subplot(1,2,2) plt.imshow(image) plt.imshow(labels, alpha=0.75) cb = plt.colorbar(orientation='horizontal', shrink=0.5)", "colors]) colorxy /= colorxy.max(axis=0) return colorxy def load_ground_truth(filename): \"\"\" Load", "#print(\"Training classifier...\") #classifier = ImageSVC() #classifier.fit(train_data, train_labels) files = os.listdir(test_dir)", "SVC() clf.fit(train_data, train_labels) # Predict labels for test images classify_directory(clf,", "plt.colorbar(orientation='horizontal', shrink=0.5) plt.title('predicted class labels') plt.show(block=False) def load_training_images(train_dir, n_samples=1000, n_features=3):", "arrays corresponding to survey images and segmentations labelled/ - contains", "trained from scratch #print(\"Preparing training data...\") #n_samples = 1000 #train_data,", "import shuffle import os, fnmatch def classify_directory(classifier, test_dir, train_dir='train/'): \"\"\"", "+ 'svm.npy', pred_labels.reshape((height,width))) def compute_colorxy_features(image): \"\"\" Extract and normalize color", "import matplotlib.pyplot as plt import skimage.color, skimage.io from skimage.segmentation import", "#n_samples = 1000 #train_data, train_labels = load_training_images(train_dir, n_samples) # #print(\"Training", "classifier...\") #classifier = ImageSVC() #classifier.fit(train_data, train_labels) files = os.listdir(test_dir) for", "plotted truth = truth - 1 truth[truth == -1] =", "plt.subplot(1,2,1) plt.imshow(mark_boundaries(image, segments, color=(1,0,0), mode='thick')) plt.title('segmented image') plt.subplot(1,2,2) plt.imshow(image) plt.imshow(labels,", "f in files: name = parse_filename(f) image, labels = load_image_labels(name)", "labels.reshape(wid*ht, 1).ravel()) train_data, train_labels = shuffle(train_data, train_labels, random_state=0, n_samples=n_samples) return", "of pixels in images using color and other features. General", "load_training_images(train_dir, n_samples) # #print(\"Training classifier...\") #classifier = ImageSVC() #classifier.fit(train_data, train_labels)", "test_dir = 'test/' train_data, train_labels = load_training_data(train_dir) # Train classifier", "results/ directory. \"\"\" # XXX: This is here if the", "truth = truth - 1 truth[truth == -1] = 0", "the classifier needs to be trained from scratch #print(\"Preparing training", "classifier or cluster data (sklearn KMeans, MeanShift, SVC, etc.) 4.", "np.load(fname) return image, labels def plot_class_image(image, segments, labels): \"\"\" Display", "\"__main__\": # Load training data train_dir = 'train/' test_dir =", "np.append(train_labels, labels.reshape(wid*ht, 1).ravel()) train_data, train_labels = shuffle(train_data, train_labels, random_state=0, n_samples=n_samples)", "fname = 'labelled/' + name + '_labels.npy' labels = np.load(fname)", "= 5 truth[truth == 2] = 0 truth[truth == 5]", "5] = 2 return truth def load_image_labels(name): \"\"\" Load image", "plt.imshow(image) plt.imshow(pred_labels.reshape((height, width)), alpha=0.5, vmin=0, vmax=2) plt.show(block=False) plt.savefig('results/' + f.strip('.JPG')", "truth = np.load(filename) # Change labels for nice default colorscale", "predicted class labels \"\"\" np.save('results/' + name + '_pred', pred_labels)", "= 'labelled/' + name + '_labels.npy' labels = np.load(fname) return", "sklearn.utils import shuffle import os, fnmatch def classify_directory(classifier, test_dir, train_dir='train/'):", "color and pixel location features from image data \"\"\" height,", "= truth - 1 truth[truth == -1] = 0 truth[truth", "return image, labels def plot_class_image(image, segments, labels): \"\"\" Display image", "numpy as np import matplotlib.pyplot as plt import skimage.color, skimage.io", "\"\"\" Extract and normalize color and pixel location features from", "plt.title('predicted class labels') plt.show(block=False) def load_training_images(train_dir, n_samples=1000, n_features=3): \"\"\" Load", "ImageSVC() #classifier.fit(train_data, train_labels) files = os.listdir(test_dir) for f in files:", "+ \".jpg\") plt.figure() plt.imshow(image) plt.imshow(pred_labels.reshape((height, width)), alpha=0.5, vmin=0, vmax=2) plt.show(block=False)", "Train classifier or cluster data (sklearn KMeans, MeanShift, SVC, etc.)", "def plot_class_image(image, segments, labels): \"\"\" Display image with segments and", "= np.empty(0) files = os.listdir(train_dir) for f in files: name", "truth images or training data results/ - contains results of", "\".jpg\") features = compute_colorxy_features(image) features /= features.max(axis=0) pred_labels = classifier.predict(features)", "= np.load(fname) return image, labels def plot_class_image(image, segments, labels): \"\"\"", "features = compute_colorxy_features(image) features /= features.max(axis=0) pred_labels = classifier.predict(features) print(\"Saving", "using color and other features. General pipeline usage: 1. Load", "to 3D points and estimate ground plane orientation (process_pointcloud.py) Project", "plt.imshow(mark_boundaries(image, segments, color=(1,0,0), mode='thick')) plt.title('segmented image') plt.subplot(1,2,2) plt.imshow(image) plt.imshow(labels, alpha=0.75)", "validation \"\"\" train_data = np.empty((0, n_features)) train_labels = np.empty(0) files", "0 truth[truth == 5] = 2 return truth def load_image_labels(name):", "= 'test/' train_data, train_labels = load_training_data(train_dir) # Train classifier clf", "import skimage.color, skimage.io from skimage.segmentation import mark_boundaries from sklearn.svm import", "plt.figure() plt.imshow(image) plt.imshow(pred_labels.reshape((height, width)), alpha=0.5, vmin=0, vmax=2) plt.show(block=False) plt.savefig('results/' +", "alpha=0.5, vmin=0, vmax=2) plt.show(block=False) plt.savefig('results/' + f.strip('.JPG') + '_svm_pred.png') plt.close()", "= load_training_data(train_dir) # Train classifier clf = SVC() clf.fit(train_data, train_labels)", "height, width, depth = image.shape print(\"Predicting labels for \" +", "ground plane orientation (process_pointcloud.py) Project uses the following directory structure:", "train_data, train_labels def save_prediction(name, pred_labels): \"\"\" Save predicted class labels", "colorxy.max(axis=0) return colorxy def load_ground_truth(filename): \"\"\" Load ground truth or", "np.load(filename) # Change labels for nice default colorscale when plotted", "= 1000 #train_data, train_labels = load_training_images(train_dir, n_samples) # #print(\"Training classifier...\")", "in files: image = skimage.io.imread(f) height, width, depth = image.shape", "for \" + f.strip('.JPG') + \".jpg\") features = compute_colorxy_features(image) features", "truth[truth == -1] = 0 truth[truth == 0] = 5", "images in test/ and train/ directories. Author: <NAME> E-mail: <EMAIL>", "compute_colorxy_features(image) features /= features.max(axis=0) pred_labels = classifier.predict(features) print(\"Saving predictions for", "3. Train classifier or cluster data (sklearn KMeans, MeanShift, SVC,", "#print(\"Preparing training data...\") #n_samples = 1000 #train_data, train_labels = load_training_images(train_dir,", "image.shape colors = skimage.color.rgb2lab(image.reshape((height*width, depth)) X, Y = np.meshgrid(np.arange(height), np.arange(width))", "subsample for training or validation \"\"\" train_data = np.empty((0, n_features))", "== \"__main__\": # Load training data train_dir = 'train/' test_dir", "plot_class_image(image, segments, labels): \"\"\" Display image with segments and class", "or validation \"\"\" train_data = np.empty((0, n_features)) train_labels = np.empty(0)", "= skimage.color.rgb2lab(image.reshape((height*width, depth)) X, Y = np.meshgrid(np.arange(height), np.arange(width)) xy =", "- contains results of classification I store randomly split training", "= parse_filename(f) image, labels = load_image_labels(name) ht, wid, depth =", "truth[truth == 2] = 0 truth[truth == 5] = 2", "and labels from previous labelling session \"\"\" fname = 'images/'", "colorxy def load_ground_truth(filename): \"\"\" Load ground truth or training image", "__name__ == \"__main__\": # Load training data train_dir = 'train/'", "sklearn.cluster import KMeans, MeanShift from sklearn.metrics import confusion_matrix from sklearn.utils", "classifier clf = SVC() clf.fit(train_data, train_labels) # Predict labels for", "new image or directory (classify_directory()) 5. Apply classification to 3D", "images (img_utils.py) 2. Prepare training data (label_image.py) 3. Train classifier", "shuffle import os, fnmatch def classify_directory(classifier, test_dir, train_dir='train/'): \"\"\" Classify", "= 2 return truth def load_image_labels(name): \"\"\" Load image and", "def classify_directory(classifier, test_dir, train_dir='train/'): \"\"\" Classify all images in a", "segment images (img_utils.py) 2. Prepare training data (label_image.py) 3. Train", "os.listdir(test_dir) for f in files: image = skimage.io.imread(f) height, width,", "\" + f.strip('.JPG') + \".jpg\") plt.figure() plt.imshow(image) plt.imshow(pred_labels.reshape((height, width)), alpha=0.5,", "default colorscale when plotted truth = truth - 1 truth[truth", "def load_training_images(train_dir, n_samples=1000, n_features=3): \"\"\" Load training images from directory", "name + '_pred', pred_labels) if __name__ == \"__main__\": # Load", "pipeline usage: 1. Load and segment images (img_utils.py) 2. Prepare", "overlay \"\"\" plt.figure() plt.subplot(1,2,1) plt.imshow(mark_boundaries(image, segments, color=(1,0,0), mode='thick')) plt.title('segmented image')", "Y = np.meshgrid(np.arange(height), np.arange(width)) xy = np.hstack([X.reshape((height*width, 1)), Y.reshape((height*width, 1))])", "pred_labels.reshape((height,width))) def compute_colorxy_features(image): \"\"\" Extract and normalize color and pixel", "results of classification I store randomly split training and testing", "= 'images/' + name + '_image.npy' image = np.load(fname) fname", "8 June 2017 \"\"\" import numpy as np import matplotlib.pyplot", "truth def load_image_labels(name): \"\"\" Load image and labels from previous", "(sklearn KMeans, MeanShift, SVC, etc.) 4. Predict labels on new", "Date: 8 June 2017 \"\"\" import numpy as np import", "2] = 0 truth[truth == 5] = 2 return truth", "labels for nice default colorscale when plotted truth = truth", "+ f.strip('.JPG') + \".jpg\") plt.figure() plt.imshow(image) plt.imshow(pred_labels.reshape((height, width)), alpha=0.5, vmin=0,", "'svm.npy', pred_labels.reshape((height,width))) def compute_colorxy_features(image): \"\"\" Extract and normalize color and", "plt.close() np.save('results/' + f.strip('.JPG') + 'svm.npy', pred_labels.reshape((height,width))) def compute_colorxy_features(image): \"\"\"", "vmin=0, vmax=2) plt.show(block=False) plt.savefig('results/' + f.strip('.JPG') + '_svm_pred.png') plt.close() np.save('results/'", "classifier.predict(features) print(\"Saving predictions for \" + f.strip('.JPG') + \".jpg\") plt.figure()", "'_labels.npy' labels = np.load(fname) return image, labels def plot_class_image(image, segments,", "contains binary files of numpy arrays corresponding to survey images", "points and estimate ground plane orientation (process_pointcloud.py) Project uses the", "= classifier.predict(features) print(\"Saving predictions for \" + f.strip('.JPG') + \".jpg\")", "load_image_labels(name): \"\"\" Load image and labels from previous labelling session", "+ '_pred', pred_labels) if __name__ == \"__main__\": # Load training", "binary files of numpy arrays corresponding to survey images and", "np.meshgrid(np.arange(height), np.arange(width)) xy = np.hstack([X.reshape((height*width, 1)), Y.reshape((height*width, 1))]) colorxy =", "sklearn.metrics import confusion_matrix from sklearn.utils import shuffle import os, fnmatch", "test_dir, train_dir='train/'): \"\"\" Classify all images in a directory using", "Saves results to results/ directory. \"\"\" # XXX: This is", "np.append(train_data, compute_color_features(image), axis=0) train_labels = np.append(train_labels, labels.reshape(wid*ht, 1).ravel()) train_data, train_labels", "X, Y = np.meshgrid(np.arange(height), np.arange(width)) xy = np.hstack([X.reshape((height*width, 1)), Y.reshape((height*width,", "plt.imshow(labels, alpha=0.75) cb = plt.colorbar(orientation='horizontal', shrink=0.5) plt.title('predicted class labels') plt.show(block=False)", "= np.hstack([X.reshape((height*width, 1)), Y.reshape((height*width, 1))]) colorxy = np.hstack([xy, colors]) colorxy", "np.save('results/' + name + '_pred', pred_labels) if __name__ == \"__main__\":", "0 truth[truth == 0] = 5 truth[truth == 2] =", "== 2] = 0 truth[truth == 5] = 2 return", "of classification I store randomly split training and testing images", "Save predicted class labels \"\"\" np.save('results/' + name + '_pred',", "from skimage.segmentation import mark_boundaries from sklearn.svm import SVC from sklearn.cluster", "+ '_svm_pred.png') plt.close() np.save('results/' + f.strip('.JPG') + 'svm.npy', pred_labels.reshape((height,width))) def", "load_image_labels(name) ht, wid, depth = image.shape train_data = np.append(train_data, compute_color_features(image),", "= skimage.io.imread(f) height, width, depth = image.shape print(\"Predicting labels for", "Predict labels on new image or directory (classify_directory()) 5. Apply", "+ '_labels.npy' labels = np.load(fname) return image, labels def plot_class_image(image,", "= 'train/' test_dir = 'test/' train_data, train_labels = load_training_data(train_dir) #", "np import matplotlib.pyplot as plt import skimage.color, skimage.io from skimage.segmentation", "= image.shape print(\"Predicting labels for \" + f.strip('.JPG') + \".jpg\")", "'labelled/' + name + '_labels.npy' labels = np.load(fname) return image,", "= np.hstack([xy, colors]) colorxy /= colorxy.max(axis=0) return colorxy def load_ground_truth(filename):", "import mark_boundaries from sklearn.svm import SVC from sklearn.cluster import KMeans,", "<filename>classify_images.py<gh_stars>1-10 \"\"\" Classification of pixels in images using color and", "plt.imshow(image) plt.imshow(labels, alpha=0.75) cb = plt.colorbar(orientation='horizontal', shrink=0.5) plt.title('predicted class labels')", "load_training_images(train_dir, n_samples=1000, n_features=3): \"\"\" Load training images from directory and", "+ name + '_image.npy' image = np.load(fname) fname = 'labelled/'", "nice default colors \"\"\" truth = np.load(filename) # Change labels", "normalize color and pixel location features from image data \"\"\"", "or cluster data (sklearn KMeans, MeanShift, SVC, etc.) 4. Predict", "and segmentations labelled/ - contains labelled ground truth images or", "\"\"\" Load training images from directory and subsample for training", "import confusion_matrix from sklearn.utils import shuffle import os, fnmatch def", "plt.show(block=False) def load_training_images(train_dir, n_samples=1000, n_features=3): \"\"\" Load training images from", "June 2017 \"\"\" import numpy as np import matplotlib.pyplot as", "axis=0) train_labels = np.append(train_labels, labels.reshape(wid*ht, 1).ravel()) train_data, train_labels = shuffle(train_data,", "files = os.listdir(test_dir) for f in files: image = skimage.io.imread(f)", "for nice default colorscale when plotted truth = truth -", "= image.shape train_data = np.append(train_data, compute_color_features(image), axis=0) train_labels = np.append(train_labels,", "for \" + f.strip('.JPG') + \".jpg\") plt.figure() plt.imshow(image) plt.imshow(pred_labels.reshape((height, width)),", "for f in files: name = parse_filename(f) image, labels =", "n_samples) # #print(\"Training classifier...\") #classifier = ImageSVC() #classifier.fit(train_data, train_labels) files", "plt.savefig('results/' + f.strip('.JPG') + '_svm_pred.png') plt.close() np.save('results/' + f.strip('.JPG') +", "results to results/ directory. \"\"\" # XXX: This is here", "Prepare training data (label_image.py) 3. Train classifier or cluster data", "def load_ground_truth(filename): \"\"\" Load ground truth or training image array", "1)), Y.reshape((height*width, 1))]) colorxy = np.hstack([xy, colors]) colorxy /= colorxy.max(axis=0)", "results/ - contains results of classification I store randomly split", "cluster data (sklearn KMeans, MeanShift, SVC, etc.) 4. Predict labels", "np.save('results/' + f.strip('.JPG') + 'svm.npy', pred_labels.reshape((height,width))) def compute_colorxy_features(image): \"\"\" Extract", "'_svm_pred.png') plt.close() np.save('results/' + f.strip('.JPG') + 'svm.npy', pred_labels.reshape((height,width))) def compute_colorxy_features(image):", "SVC, etc.) 4. Predict labels on new image or directory", "/= features.max(axis=0) pred_labels = classifier.predict(features) print(\"Saving predictions for \" +", "\"\"\" Display image with segments and class label overlay \"\"\"", "training image array and redefine labelling for nice default colors", "KMeans, MeanShift, SVC, etc.) 4. Predict labels on new image", "Y.reshape((height*width, 1))]) colorxy = np.hstack([xy, colors]) colorxy /= colorxy.max(axis=0) return", "import numpy as np import matplotlib.pyplot as plt import skimage.color,", "nice default colorscale when plotted truth = truth - 1", "structure: images/ - contains binary files of numpy arrays corresponding", "when plotted truth = truth - 1 truth[truth == -1]", "contains labelled ground truth images or training data results/ -", "wid, depth = image.shape train_data = np.append(train_data, compute_color_features(image), axis=0) train_labels", "data train_dir = 'train/' test_dir = 'test/' train_data, train_labels =", "labels on new image or directory (classify_directory()) 5. Apply classification", "print(\"Predicting labels for \" + f.strip('.JPG') + \".jpg\") features =", "Author: <NAME> E-mail: <EMAIL> Date: 8 June 2017 \"\"\" import", "os.listdir(train_dir) for f in files: name = parse_filename(f) image, labels", "labelled ground truth images or training data results/ - contains", "data...\") #n_samples = 1000 #train_data, train_labels = load_training_images(train_dir, n_samples) #", "skimage.segmentation import mark_boundaries from sklearn.svm import SVC from sklearn.cluster import", "save_prediction(name, pred_labels): \"\"\" Save predicted class labels \"\"\" np.save('results/' +", "files: image = skimage.io.imread(f) height, width, depth = image.shape print(\"Predicting", "etc.) 4. Predict labels on new image or directory (classify_directory())", "# XXX: This is here if the classifier needs to", "E-mail: <EMAIL> Date: 8 June 2017 \"\"\" import numpy as", "1. Load and segment images (img_utils.py) 2. Prepare training data", "width, depth = image.shape colors = skimage.color.rgb2lab(image.reshape((height*width, depth)) X, Y", "features /= features.max(axis=0) pred_labels = classifier.predict(features) print(\"Saving predictions for \"", "of numpy arrays corresponding to survey images and segmentations labelled/", "image = skimage.io.imread(f) height, width, depth = image.shape print(\"Predicting labels", "classifier. Saves results to results/ directory. \"\"\" # XXX: This", "fnmatch def classify_directory(classifier, test_dir, train_dir='train/'): \"\"\" Classify all images in", "directory and subsample for training or validation \"\"\" train_data =", "# Train classifier clf = SVC() clf.fit(train_data, train_labels) # Predict", "redefine labelling for nice default colors \"\"\" truth = np.load(filename)", "Load training images from directory and subsample for training or", "train_data, train_labels = shuffle(train_data, train_labels, random_state=0, n_samples=n_samples) return train_data, train_labels", "image with segments and class label overlay \"\"\" plt.figure() plt.subplot(1,2,1)", "directories. Author: <NAME> E-mail: <EMAIL> Date: 8 June 2017 \"\"\"", "+ name + '_labels.npy' labels = np.load(fname) return image, labels", "3D points and estimate ground plane orientation (process_pointcloud.py) Project uses", "General pipeline usage: 1. Load and segment images (img_utils.py) 2.", "training images from directory and subsample for training or validation", "train_labels) files = os.listdir(test_dir) for f in files: image =", "return truth def load_image_labels(name): \"\"\" Load image and labels from", "xy = np.hstack([X.reshape((height*width, 1)), Y.reshape((height*width, 1))]) colorxy = np.hstack([xy, colors])", "split training and testing images in test/ and train/ directories.", "plt.figure() plt.subplot(1,2,1) plt.imshow(mark_boundaries(image, segments, color=(1,0,0), mode='thick')) plt.title('segmented image') plt.subplot(1,2,2) plt.imshow(image)", "for nice default colors \"\"\" truth = np.load(filename) # Change", "to survey images and segmentations labelled/ - contains labelled ground", "predictions for \" + f.strip('.JPG') + \".jpg\") plt.figure() plt.imshow(image) plt.imshow(pred_labels.reshape((height,", "depth = image.shape colors = skimage.color.rgb2lab(image.reshape((height*width, depth)) X, Y =", "labels \"\"\" np.save('results/' + name + '_pred', pred_labels) if __name__", "segmentations labelled/ - contains labelled ground truth images or training", "n_features)) train_labels = np.empty(0) files = os.listdir(train_dir) for f in", "Train classifier clf = SVC() clf.fit(train_data, train_labels) # Predict labels", "truth[truth == 5] = 2 return truth def load_image_labels(name): \"\"\"", "= ImageSVC() #classifier.fit(train_data, train_labels) files = os.listdir(test_dir) for f in", "image.shape print(\"Predicting labels for \" + f.strip('.JPG') + \".jpg\") features", "/= colorxy.max(axis=0) return colorxy def load_ground_truth(filename): \"\"\" Load ground truth", "the following directory structure: images/ - contains binary files of", "= os.listdir(test_dir) for f in files: image = skimage.io.imread(f) height,", "5 truth[truth == 2] = 0 truth[truth == 5] =", "colors = skimage.color.rgb2lab(image.reshape((height*width, depth)) X, Y = np.meshgrid(np.arange(height), np.arange(width)) xy", "KMeans, MeanShift from sklearn.metrics import confusion_matrix from sklearn.utils import shuffle", "\"\"\" np.save('results/' + name + '_pred', pred_labels) if __name__ ==", "and pixel location features from image data \"\"\" height, width,", "depth)) X, Y = np.meshgrid(np.arange(height), np.arange(width)) xy = np.hstack([X.reshape((height*width, 1)),", "training or validation \"\"\" train_data = np.empty((0, n_features)) train_labels =", "plt.subplot(1,2,2) plt.imshow(image) plt.imshow(labels, alpha=0.75) cb = plt.colorbar(orientation='horizontal', shrink=0.5) plt.title('predicted class", "+ f.strip('.JPG') + '_svm_pred.png') plt.close() np.save('results/' + f.strip('.JPG') + 'svm.npy',", "train_labels = shuffle(train_data, train_labels, random_state=0, n_samples=n_samples) return train_data, train_labels def", "and class label overlay \"\"\" plt.figure() plt.subplot(1,2,1) plt.imshow(mark_boundaries(image, segments, color=(1,0,0),", "train_labels def save_prediction(name, pred_labels): \"\"\" Save predicted class labels \"\"\"", "\".jpg\") plt.figure() plt.imshow(image) plt.imshow(pred_labels.reshape((height, width)), alpha=0.5, vmin=0, vmax=2) plt.show(block=False) plt.savefig('results/'", "labelling session \"\"\" fname = 'images/' + name + '_image.npy'", "pixels in images using color and other features. General pipeline" ]
[ "str) -> JsonDict: return self.predict_json({\"sentence\": sentence}) @overrides def _json_to_instance(self, json_dict:", "import overrides @Predictor.register(\"sentence_classifier\") class SentenceClassifierPredictor(Predictor): def predict(self, sentence: str) ->", "JsonDict from allennlp.data import DatasetReader, Instance from allennlp.models import Model", "allennlp.data import DatasetReader, Instance from allennlp.models import Model from allennlp.predictors", "allennlp.common import JsonDict from allennlp.data import DatasetReader, Instance from allennlp.models", "def predict(self, sentence: str) -> JsonDict: return self.predict_json({\"sentence\": sentence}) @overrides", "sentence: str) -> JsonDict: return self.predict_json({\"sentence\": sentence}) @overrides def _json_to_instance(self,", "@overrides def _json_to_instance(self, json_dict: JsonDict) -> Instance: sentence = json_dict[\"sentence\"]", "sentence}) @overrides def _json_to_instance(self, json_dict: JsonDict) -> Instance: sentence =", "Model from allennlp.predictors import Predictor from overrides import overrides @Predictor.register(\"sentence_classifier\")", "self.predict_json({\"sentence\": sentence}) @overrides def _json_to_instance(self, json_dict: JsonDict) -> Instance: sentence", "Instance from allennlp.models import Model from allennlp.predictors import Predictor from", "allennlp.predictors import Predictor from overrides import overrides @Predictor.register(\"sentence_classifier\") class SentenceClassifierPredictor(Predictor):", "overrides import overrides @Predictor.register(\"sentence_classifier\") class SentenceClassifierPredictor(Predictor): def predict(self, sentence: str)", "SentenceClassifierPredictor(Predictor): def predict(self, sentence: str) -> JsonDict: return self.predict_json({\"sentence\": sentence})", "from allennlp.models import Model from allennlp.predictors import Predictor from overrides", "DatasetReader, Instance from allennlp.models import Model from allennlp.predictors import Predictor", "class SentenceClassifierPredictor(Predictor): def predict(self, sentence: str) -> JsonDict: return self.predict_json({\"sentence\":", "from allennlp.common import JsonDict from allennlp.data import DatasetReader, Instance from", "-> JsonDict: return self.predict_json({\"sentence\": sentence}) @overrides def _json_to_instance(self, json_dict: JsonDict)", "import DatasetReader, Instance from allennlp.models import Model from allennlp.predictors import", "from allennlp.data import DatasetReader, Instance from allennlp.models import Model from", "Predictor from overrides import overrides @Predictor.register(\"sentence_classifier\") class SentenceClassifierPredictor(Predictor): def predict(self,", "@Predictor.register(\"sentence_classifier\") class SentenceClassifierPredictor(Predictor): def predict(self, sentence: str) -> JsonDict: return", "import Model from allennlp.predictors import Predictor from overrides import overrides", "import JsonDict from allennlp.data import DatasetReader, Instance from allennlp.models import", "from allennlp.predictors import Predictor from overrides import overrides @Predictor.register(\"sentence_classifier\") class", "from overrides import overrides @Predictor.register(\"sentence_classifier\") class SentenceClassifierPredictor(Predictor): def predict(self, sentence:", "def _json_to_instance(self, json_dict: JsonDict) -> Instance: sentence = json_dict[\"sentence\"] return", "predict(self, sentence: str) -> JsonDict: return self.predict_json({\"sentence\": sentence}) @overrides def", "return self.predict_json({\"sentence\": sentence}) @overrides def _json_to_instance(self, json_dict: JsonDict) -> Instance:", "import Predictor from overrides import overrides @Predictor.register(\"sentence_classifier\") class SentenceClassifierPredictor(Predictor): def", "overrides @Predictor.register(\"sentence_classifier\") class SentenceClassifierPredictor(Predictor): def predict(self, sentence: str) -> JsonDict:", "allennlp.models import Model from allennlp.predictors import Predictor from overrides import", "_json_to_instance(self, json_dict: JsonDict) -> Instance: sentence = json_dict[\"sentence\"] return self._dataset_reader.text_to_instance(sentence)", "JsonDict: return self.predict_json({\"sentence\": sentence}) @overrides def _json_to_instance(self, json_dict: JsonDict) ->" ]
[ "[y[P[i]] for i in range(16)] # Generate MixColumn relations for", "5, 6, 10, 11, 8, 9, 13, 14, 15, 12]", "eqs = '#%s %d Rounds\\n' % (cipher_name, R) eqs +=", "# 2 rounds # recommended_mg = 16 # recommended_ms =", "Tweakey temp1 = tk1.copy() temp2 = tk2.copy() tk1 = [temp1[TKP[i]]", "i in range(16)] y = ['y_%d_%d' % (r, i) for", "AC | x_0 ===> x_0 ===> x_0 ===> + ===>", "%s\\n' % (py[j], xout[j + 1*4]) eqs += '%s, %s,", "# recommended_mg = 31 # recommended_ms = 100 eqs =", "['x_%d_%d' % (r, i) for i in range(16)] xout =", "+ 4*i], tk[j + 4*i], y[j + 4*i]) else: eqs", "10 rounds recommended_mg = 30 recommended_ms = 100 # 11", "3*4]) # Update Tweakey temp1 = tk1.copy() temp2 = tk2.copy()", "%s\\n' % (xin[j + 4*i], tk[j + 4*i], y[j +", "['x_%d_%d' % (R, i) for i in range(16)] eqs +=", "2*4]) eqs += '%s, %s, %s\\n' % (py[j + 0*4],", "% (py[j + 1*4], py[j + 2*4], xout[j + 2*4])", "40 # 7 rounds # recommended_mg = 26 # recommended_ms", "i for i in range(16)] # 1 round # recommended_mg", "ciphertext = ['x_%d_%d' % (R, i) for i in range(16)]", "===> + ===> y_0 ===> P(y_0) ===> x_1 ===> x_1", "in range(16)] # Generate MixColumn relations for j in range(4):", "# recommended_mg = 28 # recommended_ms = 100 # 10", "range(16)] tk = ['tk_%d_%d' % (r, i) for i in", "% (tk1[j + 4*i], tk2[j + 4*i], tk[j + 4*i])", "MC SB AC | x_0 ===> x_0 ===> x_0 ===>", "'%s, %s\\n' % (xin[j + 4*i], y[j + 4*i]) #", "in range(16)] eqs += 'known\\n' + '\\n'.join(plaintext + ciphertext) eqs", "+ 4*i], y[j + 4*i]) else: eqs += '%s, %s\\n'", "in range(16)] tk2 = [temp2[TKP[i]] for i in range(16)] plaintext", "11, 0, 1, 2, 3, 4, 5, 6, 7] tk1", "of Skinny-n-n for R rounds. tk ================================================> TWEAKEY_P(tk) ===> ---", "i for i in range(16)] tk2 = ['tk2_%d' % i", "i < 2: eqs += '%s, %s, %s\\n' % (tk1[j", "# Generate MixColumn relations for j in range(4): eqs +=", "range(16)] eqs += 'known\\n' + '\\n'.join(plaintext + ciphertext) eqs +=", "range(16)] # 1 round # recommended_mg = 8 # recommended_ms", "Created on Sep 7, 2020 # author: <NAME> # contact:", "%s\\n' % (py[j + 0*4], py[j + 2*4], py[j +", "AC | P MC SB AC | x_0 ===> x_0", "1, i) for i in range(16)] y = ['y_%d_%d' %", "(R, i) for i in range(16)] eqs += 'known\\n' +", "range(4): for j in range(4): if i < 2: eqs", "28 # recommended_ms = 80 # 9 rounds # recommended_mg", "% (r, i) for i in range(16)] tk = ['tk_%d_%d'", "= [0, 1, 2, 3, 7, 4, 5, 6, 10,", "round # recommended_mg = 8 # recommended_ms = 4 #", "4, 5, 6, 7] tk1 = ['tk1_%d' % i for", "# recommended_mg = 22 # recommended_ms = 35 # 6", "+ 4*i]) eqs += '%s, %s, %s\\n' % (xin[j +", "+= '%s, %s, %s, %s\\n' % (py[j + 0*4], py[j", "# 1 round # recommended_mg = 8 # recommended_ms =", "%s, %s, %s\\n' % (py[j + 0*4], py[j + 2*4],", "===> x_0 ===> + ===> y_0 ===> P(y_0) ===> x_1", "# recommended_ms = 35 # 6 rounds # recommended_mg =", "recommended_ms = 80 # 9 rounds # recommended_mg = 28", "| x_0 ===> x_0 ===> x_0 ===> + ===> y_0", "% (py[j + 0*4], py[j + 2*4], py[j + 3*4],", "Apply ShiftRows py = [y[P[i]] for i in range(16)] #", "+ ===> y_0 ===> P(y_0) ===> x_1 ===> x_1 ===>", "% (r + 1, i) for i in range(16)] y", "for i in range(16)] plaintext = ['x_0_%d' % i for", "= 21 # recommended_ms = 27 # 5 rounds #", "i) for i in range(8)] # Generaete AddTweakey relations for", "xout[j + 0*4]) eqs += '%s, %s\\n' % (py[j], xout[j", "= 24 # 4 rounds # recommended_mg = 21 #", "3*4], xout[j + 0*4]) eqs += '%s, %s\\n' % (py[j],", "+= '\\nend' relation_file_path = os.path.join(output_dir, 'relationfile_%s_%dr_mg%d_ms%d.txt' % (cipher_name, R, recommended_mg,", "(py[j], xout[j + 1*4]) eqs += '%s, %s, %s\\n' %", "for i in range(16)] ciphertext = ['x_%d_%d' % (R, i)", "% (cipher_name, R, recommended_mg, recommended_ms)) with open(relation_file_path, 'w') as relation_file:", "% (R, i) for i in range(16)] eqs += 'known\\n'", "py[j + 2*4], xout[j + 2*4]) eqs += '%s, %s,", "%s, %s\\n' % (tk1[j + 4*i], tk2[j + 4*i], tk[j", "10, 11, 8, 9, 13, 14, 15, 12] TKP =", "3, 7, 4, 5, 6, 10, 11, 8, 9, 13,", "x_1 ===> x_1 ===> x_1 ===> + ===> y_1 ===>", "21 # recommended_ms = 27 # 5 rounds # recommended_mg", "rounds # recommended_mg = 16 # recommended_ms = 8 #", "26 # recommended_ms = 70 # 8 rounds # recommended_mg", "+ ciphertext) eqs += '\\nend' relation_file_path = os.path.join(output_dir, 'relationfile_%s_%dr_mg%d_ms%d.txt' %", "(r, i) for i in range(8)] # Generaete AddTweakey relations", "recommended_mg = 19 # recommended_ms = 24 # 4 rounds", "= tk1.copy() temp2 = tk2.copy() tk1 = [temp1[TKP[i]] for i", "tk1 = [temp1[TKP[i]] for i in range(16)] tk2 = [temp2[TKP[i]]", "'%s, %s, %s\\n' % (py[j + 0*4], py[j + 2*4],", "range(16)] tk2 = [temp2[TKP[i]] for i in range(16)] plaintext =", "# 6 rounds # recommended_mg = 25 # recommended_ms =", "rounds # recommended_mg = 28 # recommended_ms = 100 #", "30 recommended_ms = 100 # 11 rounds # recommended_mg =", "'%s, %s\\n' % (py[j], xout[j + 1*4]) eqs += '%s,", "'relationfile_%s_%dr_mg%d_ms%d.txt' % (cipher_name, R, recommended_mg, recommended_ms)) with open(relation_file_path, 'w') as", "3, 4, 5, 6, 7] tk1 = ['tk1_%d' % i", "% (py[j + 0*4], py[j + 2*4], xout[j + 3*4])", "# recommended_mg = 28 # recommended_ms = 80 # 9", "tk[j + 4*i]) eqs += '%s, %s, %s\\n' % (xin[j", "recommended_ms = 100 # 11 rounds # recommended_mg = 31", "0*4]) eqs += '%s, %s\\n' % (py[j], xout[j + 1*4])", "in range(16)] y = ['y_%d_%d' % (r, i) for i", "relations of Skinny-n-n for R rounds. tk ================================================> TWEAKEY_P(tk) ===>", "2, 3, 7, 4, 5, 6, 10, 11, 8, 9,", "6, 10, 11, 8, 9, 13, 14, 15, 12] TKP", "1*4], py[j + 2*4], xout[j + 2*4]) eqs += '%s,", "i in range(16)] # 1 round # recommended_mg = 8", "14, 12, 11, 0, 1, 2, 3, 4, 5, 6,", "= 19 # recommended_ms = 24 # 4 rounds #", "cipher_name = 'skinnytk2' P = [0, 1, 2, 3, 7,", "# recommended_ms = 80 # 9 rounds # recommended_mg =", "+= '%s, %s\\n' % (xin[j + 4*i], y[j + 4*i])", "8, 9, 13, 14, 15, 12] TKP = [9, 15,", "i in range(16)] tk2 = [temp2[TKP[i]] for i in range(16)]", "+ 0*4], py[j + 2*4], xout[j + 3*4]) # Update", "===> x_1 ===> x_1 ===> x_1 ===> + ===> y_1", "# 10 rounds recommended_mg = 30 recommended_ms = 100 #", "Generaete AddTweakey relations for i in range(4): for j in", "4*i]) eqs += '%s, %s, %s\\n' % (xin[j + 4*i],", "28 # recommended_ms = 100 # 10 rounds recommended_mg =", "relation_file_path = os.path.join(output_dir, 'relationfile_%s_%dr_mg%d_ms%d.txt' % (cipher_name, R, recommended_mg, recommended_ms)) with", "range(16)] plaintext = ['x_0_%d' % i for i in range(16)]", "temp2 = tk2.copy() tk1 = [temp1[TKP[i]] for i in range(16)]", "11, 8, 9, 13, 14, 15, 12] TKP = [9,", "for i in range(16)] tk2 = [temp2[TKP[i]] for i in", "= [9, 15, 8, 13, 10, 14, 12, 11, 0,", "Rounds\\n' % (cipher_name, R) eqs += 'connection relations\\n' for r", "= ['x_%d_%d' % (R, i) for i in range(16)] eqs", "plaintext = ['x_0_%d' % i for i in range(16)] ciphertext", "# recommended_mg = 19 # recommended_ms = 24 # 4", "[9, 15, 8, 13, 10, 14, 12, 11, 0, 1,", "%d Rounds\\n' % (cipher_name, R) eqs += 'connection relations\\n' for", "100 eqs = '#%s %d Rounds\\n' % (cipher_name, R) eqs", "%s\\n' % (xin[j + 4*i], y[j + 4*i]) # Apply", "i) for i in range(16)] y = ['y_%d_%d' % (r,", "x_0 ===> x_0 ===> x_0 ===> + ===> y_0 ===>", "eqs += '%s, %s\\n' % (xin[j + 4*i], y[j +", "= 40 # 7 rounds # recommended_mg = 26 #", "80 # 9 rounds # recommended_mg = 28 # recommended_ms", "py[j + 2*4], xout[j + 3*4]) # Update Tweakey temp1", "i in range(16)] ciphertext = ['x_%d_%d' % (R, i) for", "35 # 6 rounds # recommended_mg = 25 # recommended_ms", "range(4): eqs += '%s, %s, %s, %s\\n' % (py[j +", "12, 11, 0, 1, 2, 3, 4, 5, 6, 7]", "= 28 # recommended_ms = 80 # 9 rounds #", "recommended_mg = 28 # recommended_ms = 80 # 9 rounds", "recommended_mg = 21 # recommended_ms = 27 # 5 rounds", "x_1 ===> + ===> y_1 ===> --- \"\"\" cipher_name =", "if i < 2: eqs += '%s, %s, %s\\n' %", "ciphertext) eqs += '\\nend' relation_file_path = os.path.join(output_dir, 'relationfile_%s_%dr_mg%d_ms%d.txt' % (cipher_name,", "range(16)] # Generate MixColumn relations for j in range(4): eqs", "tk1.copy() temp2 = tk2.copy() tk1 = [temp1[TKP[i]] for i in", "TWEAKEY_P(tk) ===> --- SB AC | P MC SB AC", "= ['x_%d_%d' % (r + 1, i) for i in", "MixColumn relations for j in range(4): eqs += '%s, %s,", "15, 8, 13, 10, 14, 12, 11, 0, 1, 2,", "2, 3, 4, 5, 6, 7] tk1 = ['tk1_%d' %", "+= '%s, %s, %s\\n' % (py[j + 1*4], py[j +", "7, 4, 5, 6, 10, 11, 8, 9, 13, 14,", "= ['x_0_%d' % i for i in range(16)] ciphertext =", "<NAME> # contact: <EMAIL> import os output_dir = os.path.curdir def", "range(8)] # Generaete AddTweakey relations for i in range(4): for", "This function generates the relations of Skinny-n-n for R rounds.", "contact: <EMAIL> import os output_dir = os.path.curdir def skinnytk2(R=1): \"\"\"", "xout[j + 1*4]) eqs += '%s, %s, %s\\n' % (py[j", "# Generaete AddTweakey relations for i in range(4): for j", "2 rounds # recommended_mg = 16 # recommended_ms = 8", "+= '%s, %s\\n' % (py[j], xout[j + 1*4]) eqs +=", "7 rounds # recommended_mg = 26 # recommended_ms = 70", "24 # 4 rounds # recommended_mg = 21 # recommended_ms", "8 # 3 rounds # recommended_mg = 19 # recommended_ms", "# Update Tweakey temp1 = tk1.copy() temp2 = tk2.copy() tk1", "for i in range(16)] # 1 round # recommended_mg =", "= 22 # recommended_ms = 35 # 6 rounds #", "i in range(16)] plaintext = ['x_0_%d' % i for i", "70 # 8 rounds # recommended_mg = 28 # recommended_ms", "\"\"\" This function generates the relations of Skinny-n-n for R", "8, 13, 10, 14, 12, 11, 0, 1, 2, 3,", "[temp2[TKP[i]] for i in range(16)] plaintext = ['x_0_%d' % i", "y_1 ===> --- \"\"\" cipher_name = 'skinnytk2' P = [0,", "function generates the relations of Skinny-n-n for R rounds. tk", "= 27 # 5 rounds # recommended_mg = 22 #", "%s, %s\\n' % (py[j + 0*4], py[j + 2*4], xout[j", "--- \"\"\" cipher_name = 'skinnytk2' P = [0, 1, 2,", "9, 13, 14, 15, 12] TKP = [9, 15, 8,", "eqs += '\\nend' relation_file_path = os.path.join(output_dir, 'relationfile_%s_%dr_mg%d_ms%d.txt' % (cipher_name, R,", "===> y_1 ===> --- \"\"\" cipher_name = 'skinnytk2' P =", "rounds. tk ================================================> TWEAKEY_P(tk) ===> --- SB AC | P", "xin = ['x_%d_%d' % (r, i) for i in range(16)]", "(r + 1, i) for i in range(16)] y =", "xout = ['x_%d_%d' % (r + 1, i) for i", "+= 'connection relations\\n' for r in range(R): xin = ['x_%d_%d'", "% (cipher_name, R) eqs += 'connection relations\\n' for r in", "range(4): if i < 2: eqs += '%s, %s, %s\\n'", "'%s, %s, %s\\n' % (xin[j + 4*i], tk[j + 4*i],", "Generate MixColumn relations for j in range(4): eqs += '%s,", "i in range(8)] # Generaete AddTweakey relations for i in", "TKP = [9, 15, 8, 13, 10, 14, 12, 11,", "(cipher_name, R, recommended_mg, recommended_ms)) with open(relation_file_path, 'w') as relation_file: relation_file.write(eqs)", "recommended_ms = 40 # 7 rounds # recommended_mg = 26", "Update Tweakey temp1 = tk1.copy() temp2 = tk2.copy() tk1 =", "['x_%d_%d' % (r + 1, i) for i in range(16)]", "+ 0*4]) eqs += '%s, %s\\n' % (py[j], xout[j +", "P(y_0) ===> x_1 ===> x_1 ===> x_1 ===> + ===>", "rounds # recommended_mg = 28 # recommended_ms = 80 #", "range(16)] y = ['y_%d_%d' % (r, i) for i in", "+= '%s, %s, %s\\n' % (py[j + 0*4], py[j +", "rounds # recommended_mg = 25 # recommended_ms = 40 #", "% (r, i) for i in range(16)] xout = ['x_%d_%d'", "(cipher_name, R) eqs += 'connection relations\\n' for r in range(R):", "< 2: eqs += '%s, %s, %s\\n' % (tk1[j +", "rounds # recommended_mg = 22 # recommended_ms = 35 #", "0*4], py[j + 2*4], xout[j + 3*4]) # Update Tweakey", "= 30 recommended_ms = 100 # 11 rounds # recommended_mg", "tk1 = ['tk1_%d' % i for i in range(16)] tk2", "in range(4): for j in range(4): if i < 2:", "+ 4*i]) else: eqs += '%s, %s\\n' % (xin[j +", "'%s, %s, %s\\n' % (tk1[j + 4*i], tk2[j + 4*i],", "'#%s %d Rounds\\n' % (cipher_name, R) eqs += 'connection relations\\n'", "os.path.join(output_dir, 'relationfile_%s_%dr_mg%d_ms%d.txt' % (cipher_name, R, recommended_mg, recommended_ms)) with open(relation_file_path, 'w')", "4 rounds # recommended_mg = 21 # recommended_ms = 27", "= ['y_%d_%d' % (r, i) for i in range(16)] tk", "P MC SB AC | x_0 ===> x_0 ===> x_0", "+ 0*4], py[j + 2*4], py[j + 3*4], xout[j +", "Skinny-n-n for R rounds. tk ================================================> TWEAKEY_P(tk) ===> --- SB", "recommended_ms = 100 eqs = '#%s %d Rounds\\n' % (cipher_name,", "['tk1_%d' % i for i in range(16)] tk2 = ['tk2_%d'", "7] tk1 = ['tk1_%d' % i for i in range(16)]", "===> y_0 ===> P(y_0) ===> x_1 ===> x_1 ===> x_1", "+ 4*i], tk[j + 4*i]) eqs += '%s, %s, %s\\n'", "% (py[j], xout[j + 1*4]) eqs += '%s, %s, %s\\n'", "= ['tk2_%d' % i for i in range(16)] # 1", "# recommended_ms = 8 # 3 rounds # recommended_mg =", "relation_file: relation_file.write(eqs) def main(): skinnytk2(R=10) if __name__ == '__main__': main()", "# 8 rounds # recommended_mg = 28 # recommended_ms =", "# recommended_ms = 100 # 10 rounds recommended_mg = 30", "SB AC | x_0 ===> x_0 ===> x_0 ===> +", "25 # recommended_ms = 40 # 7 rounds # recommended_mg", "31 # recommended_ms = 100 eqs = '#%s %d Rounds\\n'", "# 3 rounds # recommended_mg = 19 # recommended_ms =", "= 31 # recommended_ms = 100 eqs = '#%s %d", "eqs += '%s, %s, %s, %s\\n' % (py[j + 0*4],", "+ 2*4]) eqs += '%s, %s, %s\\n' % (py[j +", "1, 2, 3, 7, 4, 5, 6, 10, 11, 8,", "i in range(16)] # Generate MixColumn relations for j in", "===> x_1 ===> x_1 ===> + ===> y_1 ===> ---", "recommended_ms = 100 # 10 rounds recommended_mg = 30 recommended_ms", "relations\\n' for r in range(R): xin = ['x_%d_%d' % (r,", "import os output_dir = os.path.curdir def skinnytk2(R=1): \"\"\" This function", "open(relation_file_path, 'w') as relation_file: relation_file.write(eqs) def main(): skinnytk2(R=10) if __name__", "['y_%d_%d' % (r, i) for i in range(16)] tk =", "ShiftRows py = [y[P[i]] for i in range(16)] # Generate", "= ['tk1_%d' % i for i in range(16)] tk2 =", "recommended_mg = 31 # recommended_ms = 100 eqs = '#%s", "# 4 rounds # recommended_mg = 21 # recommended_ms =", "author: <NAME> # contact: <EMAIL> import os output_dir = os.path.curdir", "for i in range(8)] # Generaete AddTweakey relations for i", "2: eqs += '%s, %s, %s\\n' % (tk1[j + 4*i],", "xout[j + 2*4]) eqs += '%s, %s, %s\\n' % (py[j", "eqs += '%s, %s, %s\\n' % (tk1[j + 4*i], tk2[j", "i) for i in range(16)] tk = ['tk_%d_%d' % (r,", "in range(8)] # Generaete AddTweakey relations for i in range(4):", "y_0 ===> P(y_0) ===> x_1 ===> x_1 ===> x_1 ===>", "recommended_mg = 28 # recommended_ms = 100 # 10 rounds", "%s, %s\\n' % (xin[j + 4*i], tk[j + 4*i], y[j", "['tk_%d_%d' % (r, i) for i in range(8)] # Generaete", "range(16)] tk2 = ['tk2_%d' % i for i in range(16)]", "(xin[j + 4*i], y[j + 4*i]) # Apply ShiftRows py", "j in range(4): eqs += '%s, %s, %s, %s\\n' %", "r in range(R): xin = ['x_%d_%d' % (r, i) for", "'connection relations\\n' for r in range(R): xin = ['x_%d_%d' %", "= os.path.join(output_dir, 'relationfile_%s_%dr_mg%d_ms%d.txt' % (cipher_name, R, recommended_mg, recommended_ms)) with open(relation_file_path,", "= 100 # 10 rounds recommended_mg = 30 recommended_ms =", "4*i], tk[j + 4*i]) eqs += '%s, %s, %s\\n' %", "4*i], y[j + 4*i]) else: eqs += '%s, %s\\n' %", "= 'skinnytk2' P = [0, 1, 2, 3, 7, 4,", "+= '%s, %s, %s\\n' % (xin[j + 4*i], tk[j +", "100 # 11 rounds # recommended_mg = 31 # recommended_ms", "# contact: <EMAIL> import os output_dir = os.path.curdir def skinnytk2(R=1):", "5, 6, 7] tk1 = ['tk1_%d' % i for i", "['x_0_%d' % i for i in range(16)] ciphertext = ['x_%d_%d'", "i) for i in range(16)] eqs += 'known\\n' + '\\n'.join(plaintext", "for i in range(16)] tk = ['tk_%d_%d' % (r, i)", "# 7 rounds # recommended_mg = 26 # recommended_ms =", "1*4]) eqs += '%s, %s, %s\\n' % (py[j + 1*4],", "os.path.curdir def skinnytk2(R=1): \"\"\" This function generates the relations of", "generates the relations of Skinny-n-n for R rounds. tk ================================================>", "for i in range(16)] y = ['y_%d_%d' % (r, i)", "+ 1*4], py[j + 2*4], xout[j + 2*4]) eqs +=", "in range(16)] tk2 = ['tk2_%d' % i for i in", "for j in range(4): eqs += '%s, %s, %s, %s\\n'", "'%s, %s, %s\\n' % (py[j + 1*4], py[j + 2*4],", "(py[j + 0*4], py[j + 2*4], xout[j + 3*4]) #", "= [temp1[TKP[i]] for i in range(16)] tk2 = [temp2[TKP[i]] for", "= 16 # recommended_ms = 8 # 3 rounds #", "5 rounds # recommended_mg = 22 # recommended_ms = 35", "= [y[P[i]] for i in range(16)] # Generate MixColumn relations", "# Created on Sep 7, 2020 # author: <NAME> #", "0*4], py[j + 2*4], py[j + 3*4], xout[j + 0*4])", "for i in range(16)] xout = ['x_%d_%d' % (r +", "= tk2.copy() tk1 = [temp1[TKP[i]] for i in range(16)] tk2", "0, 1, 2, 3, 4, 5, 6, 7] tk1 =", "+ 2*4], py[j + 3*4], xout[j + 0*4]) eqs +=", "%s, %s\\n' % (py[j + 0*4], py[j + 2*4], py[j", "(xin[j + 4*i], tk[j + 4*i], y[j + 4*i]) else:", "py = [y[P[i]] for i in range(16)] # Generate MixColumn", "in range(R): xin = ['x_%d_%d' % (r, i) for i", "# 11 rounds # recommended_mg = 31 # recommended_ms =", "11 rounds # recommended_mg = 31 # recommended_ms = 100", "AddTweakey relations for i in range(4): for j in range(4):", "# recommended_mg = 8 # recommended_ms = 4 # 2", "2*4], xout[j + 2*4]) eqs += '%s, %s, %s\\n' %", "(r, i) for i in range(16)] xout = ['x_%d_%d' %", "rounds # recommended_mg = 21 # recommended_ms = 27 #", "2020 # author: <NAME> # contact: <EMAIL> import os output_dir", "relations for i in range(4): for j in range(4): if", "temp1 = tk1.copy() temp2 = tk2.copy() tk1 = [temp1[TKP[i]] for", "output_dir = os.path.curdir def skinnytk2(R=1): \"\"\" This function generates the", "tk2.copy() tk1 = [temp1[TKP[i]] for i in range(16)] tk2 =", "+ 4*i], y[j + 4*i]) # Apply ShiftRows py =", "eqs += 'known\\n' + '\\n'.join(plaintext + ciphertext) eqs += '\\nend'", "= ['x_%d_%d' % (r, i) for i in range(16)] xout", "'known\\n' + '\\n'.join(plaintext + ciphertext) eqs += '\\nend' relation_file_path =", "rounds # recommended_mg = 31 # recommended_ms = 100 eqs", "1, 2, 3, 4, 5, 6, 7] tk1 = ['tk1_%d'", "12] TKP = [9, 15, 8, 13, 10, 14, 12,", "# 5 rounds # recommended_mg = 22 # recommended_ms =", "+ 3*4], xout[j + 0*4]) eqs += '%s, %s\\n' %", "# recommended_ms = 70 # 8 rounds # recommended_mg =", "def skinnytk2(R=1): \"\"\" This function generates the relations of Skinny-n-n", "recommended_ms = 8 # 3 rounds # recommended_mg = 19", "j in range(4): if i < 2: eqs += '%s,", "for i in range(16)] eqs += 'known\\n' + '\\n'.join(plaintext +", "with open(relation_file_path, 'w') as relation_file: relation_file.write(eqs) def main(): skinnytk2(R=10) if", "===> x_0 ===> x_0 ===> + ===> y_0 ===> P(y_0)", "as relation_file: relation_file.write(eqs) def main(): skinnytk2(R=10) if __name__ == '__main__':", "100 # 10 rounds recommended_mg = 30 recommended_ms = 100", "['tk2_%d' % i for i in range(16)] # 1 round", "= 8 # 3 rounds # recommended_mg = 19 #", "range(16)] ciphertext = ['x_%d_%d' % (R, i) for i in", "+ 1, i) for i in range(16)] y = ['y_%d_%d'", "[0, 1, 2, 3, 7, 4, 5, 6, 10, 11,", "9 rounds # recommended_mg = 28 # recommended_ms = 100", "% i for i in range(16)] tk2 = ['tk2_%d' %", "eqs += '%s, %s, %s\\n' % (py[j + 1*4], py[j", "py[j + 3*4], xout[j + 0*4]) eqs += '%s, %s\\n'", "in range(16)] tk = ['tk_%d_%d' % (r, i) for i", "1 round # recommended_mg = 8 # recommended_ms = 4", "tk ================================================> TWEAKEY_P(tk) ===> --- SB AC | P MC", "= 100 # 11 rounds # recommended_mg = 31 #", "8 # recommended_ms = 4 # 2 rounds # recommended_mg", "4*i]) # Apply ShiftRows py = [y[P[i]] for i in", "recommended_ms)) with open(relation_file_path, 'w') as relation_file: relation_file.write(eqs) def main(): skinnytk2(R=10)", "3 rounds # recommended_mg = 19 # recommended_ms = 24", "on Sep 7, 2020 # author: <NAME> # contact: <EMAIL>", "P = [0, 1, 2, 3, 7, 4, 5, 6,", "4*i], tk2[j + 4*i], tk[j + 4*i]) eqs += '%s,", "tk2[j + 4*i], tk[j + 4*i]) eqs += '%s, %s,", "# recommended_mg = 21 # recommended_ms = 27 # 5", "'skinnytk2' P = [0, 1, 2, 3, 7, 4, 5,", "--- SB AC | P MC SB AC | x_0", "x_1 ===> x_1 ===> + ===> y_1 ===> --- \"\"\"", "= '#%s %d Rounds\\n' % (cipher_name, R) eqs += 'connection", "recommended_ms = 35 # 6 rounds # recommended_mg = 25", "<EMAIL> import os output_dir = os.path.curdir def skinnytk2(R=1): \"\"\" This", "(tk1[j + 4*i], tk2[j + 4*i], tk[j + 4*i]) eqs", "i for i in range(16)] ciphertext = ['x_%d_%d' % (R,", "+ 2*4], xout[j + 2*4]) eqs += '%s, %s, %s\\n'", "= os.path.curdir def skinnytk2(R=1): \"\"\" This function generates the relations", "'\\n'.join(plaintext + ciphertext) eqs += '\\nend' relation_file_path = os.path.join(output_dir, 'relationfile_%s_%dr_mg%d_ms%d.txt'", "| P MC SB AC | x_0 ===> x_0 ===>", "tk[j + 4*i], y[j + 4*i]) else: eqs += '%s,", "===> P(y_0) ===> x_1 ===> x_1 ===> x_1 ===> +", "= 25 # recommended_ms = 40 # 7 rounds #", "= [temp2[TKP[i]] for i in range(16)] plaintext = ['x_0_%d' %", "for i in range(16)] # Generate MixColumn relations for j", "# 9 rounds # recommended_mg = 28 # recommended_ms =", "in range(16)] # 1 round # recommended_mg = 8 #", "for j in range(4): if i < 2: eqs +=", "= 80 # 9 rounds # recommended_mg = 28 #", "py[j + 2*4], py[j + 3*4], xout[j + 0*4]) eqs", "===> --- SB AC | P MC SB AC |", "7, 2020 # author: <NAME> # contact: <EMAIL> import os", "4*i], tk[j + 4*i], y[j + 4*i]) else: eqs +=", "10, 14, 12, 11, 0, 1, 2, 3, 4, 5,", "i in range(16)] tk = ['tk_%d_%d' % (r, i) for", "===> x_1 ===> + ===> y_1 ===> --- \"\"\" cipher_name", "15, 12] TKP = [9, 15, 8, 13, 10, 14,", "eqs += '%s, %s\\n' % (py[j], xout[j + 1*4]) eqs", "i in range(16)] xout = ['x_%d_%d' % (r + 1,", "in range(4): eqs += '%s, %s, %s, %s\\n' % (py[j", "2*4], xout[j + 3*4]) # Update Tweakey temp1 = tk1.copy()", "% (xin[j + 4*i], tk[j + 4*i], y[j + 4*i])", "in range(16)] xout = ['x_%d_%d' % (r + 1, i)", "16 # recommended_ms = 8 # 3 rounds # recommended_mg", "y[j + 4*i]) else: eqs += '%s, %s\\n' % (xin[j", "\"\"\" cipher_name = 'skinnytk2' P = [0, 1, 2, 3,", "recommended_ms = 70 # 8 rounds # recommended_mg = 28", "+= 'known\\n' + '\\n'.join(plaintext + ciphertext) eqs += '\\nend' relation_file_path", "os output_dir = os.path.curdir def skinnytk2(R=1): \"\"\" This function generates", "# recommended_ms = 40 # 7 rounds # recommended_mg =", "+ 1*4]) eqs += '%s, %s, %s\\n' % (py[j +", "eqs += '%s, %s, %s\\n' % (py[j + 0*4], py[j", "13, 10, 14, 12, 11, 0, 1, 2, 3, 4,", "# recommended_ms = 27 # 5 rounds # recommended_mg =", "xout[j + 3*4]) # Update Tweakey temp1 = tk1.copy() temp2", "% i for i in range(16)] # 1 round #", "i in range(16)] tk2 = ['tk2_%d' % i for i", "6 rounds # recommended_mg = 25 # recommended_ms = 40", "in range(16)] plaintext = ['x_0_%d' % i for i in", "recommended_mg = 25 # recommended_ms = 40 # 7 rounds", "+ 2*4], xout[j + 3*4]) # Update Tweakey temp1 =", "+ 3*4]) # Update Tweakey temp1 = tk1.copy() temp2 =", "= 100 eqs = '#%s %d Rounds\\n' % (cipher_name, R)", "y = ['y_%d_%d' % (r, i) for i in range(16)]", "in range(4): if i < 2: eqs += '%s, %s,", "recommended_mg = 22 # recommended_ms = 35 # 6 rounds", "recommended_mg = 30 recommended_ms = 100 # 11 rounds #", "% i for i in range(16)] ciphertext = ['x_%d_%d' %", "y[j + 4*i]) # Apply ShiftRows py = [y[P[i]] for", "%s, %s\\n' % (py[j + 1*4], py[j + 2*4], xout[j", "R) eqs += 'connection relations\\n' for r in range(R): xin", "relations for j in range(4): eqs += '%s, %s, %s,", "x_0 ===> + ===> y_0 ===> P(y_0) ===> x_1 ===>", "range(16)] xout = ['x_%d_%d' % (r + 1, i) for", "19 # recommended_ms = 24 # 4 rounds # recommended_mg", "14, 15, 12] TKP = [9, 15, 8, 13, 10,", "%s\\n' % (py[j + 0*4], py[j + 2*4], xout[j +", "= 70 # 8 rounds # recommended_mg = 28 #", "(py[j + 1*4], py[j + 2*4], xout[j + 2*4]) eqs", "+ 4*i], tk2[j + 4*i], tk[j + 4*i]) eqs +=", "rounds recommended_mg = 30 recommended_ms = 100 # 11 rounds", "eqs += 'connection relations\\n' for r in range(R): xin =", "# recommended_mg = 25 # recommended_ms = 40 # 7", "recommended_ms = 24 # 4 rounds # recommended_mg = 21", "+ 4*i]) # Apply ShiftRows py = [y[P[i]] for i", "rounds # recommended_mg = 19 # recommended_ms = 24 #", "for i in range(4): for j in range(4): if i", "R rounds. tk ================================================> TWEAKEY_P(tk) ===> --- SB AC |", "(r, i) for i in range(16)] tk = ['tk_%d_%d' %", "%s\\n' % (tk1[j + 4*i], tk2[j + 4*i], tk[j +", "13, 14, 15, 12] TKP = [9, 15, 8, 13,", "rounds # recommended_mg = 26 # recommended_ms = 70 #", "for R rounds. tk ================================================> TWEAKEY_P(tk) ===> --- SB AC", "= ['tk_%d_%d' % (r, i) for i in range(8)] #", "+ '\\n'.join(plaintext + ciphertext) eqs += '\\nend' relation_file_path = os.path.join(output_dir,", "% (r, i) for i in range(8)] # Generaete AddTweakey", "= 8 # recommended_ms = 4 # 2 rounds #", "else: eqs += '%s, %s\\n' % (xin[j + 4*i], y[j", "= 26 # recommended_ms = 70 # 8 rounds #", "x_0 ===> x_0 ===> + ===> y_0 ===> P(y_0) ===>", "recommended_mg = 26 # recommended_ms = 70 # 8 rounds", "eqs += '%s, %s, %s\\n' % (xin[j + 4*i], tk[j", "# recommended_ms = 4 # 2 rounds # recommended_mg =", "in range(16)] ciphertext = ['x_%d_%d' % (R, i) for i", "===> --- \"\"\" cipher_name = 'skinnytk2' P = [0, 1,", "i in range(16)] eqs += 'known\\n' + '\\n'.join(plaintext + ciphertext)", "i) for i in range(16)] xout = ['x_%d_%d' % (r", "'%s, %s, %s, %s\\n' % (py[j + 0*4], py[j +", "27 # 5 rounds # recommended_mg = 22 # recommended_ms", "Sep 7, 2020 # author: <NAME> # contact: <EMAIL> import", "22 # recommended_ms = 35 # 6 rounds # recommended_mg", "# author: <NAME> # contact: <EMAIL> import os output_dir =", "(py[j + 0*4], py[j + 2*4], py[j + 3*4], xout[j", "%s\\n' % (py[j + 1*4], py[j + 2*4], xout[j +", "4, 5, 6, 10, 11, 8, 9, 13, 14, 15,", "recommended_ms = 4 # 2 rounds # recommended_mg = 16", "= 35 # 6 rounds # recommended_mg = 25 #", "tk2 = ['tk2_%d' % i for i in range(16)] #", "R, recommended_mg, recommended_ms)) with open(relation_file_path, 'w') as relation_file: relation_file.write(eqs) def", "4*i]) else: eqs += '%s, %s\\n' % (xin[j + 4*i],", "skinnytk2(R=1): \"\"\" This function generates the relations of Skinny-n-n for", "recommended_ms = 27 # 5 rounds # recommended_mg = 22", "range(R): xin = ['x_%d_%d' % (r, i) for i in", "4*i], y[j + 4*i]) # Apply ShiftRows py = [y[P[i]]", "8 rounds # recommended_mg = 28 # recommended_ms = 80", "= 28 # recommended_ms = 100 # 10 rounds recommended_mg", "recommended_mg = 16 # recommended_ms = 8 # 3 rounds", "===> + ===> y_1 ===> --- \"\"\" cipher_name = 'skinnytk2'", "# recommended_ms = 100 eqs = '#%s %d Rounds\\n' %", "tk2 = [temp2[TKP[i]] for i in range(16)] plaintext = ['x_0_%d'", "4 # 2 rounds # recommended_mg = 16 # recommended_ms", "SB AC | P MC SB AC | x_0 ===>", "the relations of Skinny-n-n for R rounds. tk ================================================> TWEAKEY_P(tk)", "= 4 # 2 rounds # recommended_mg = 16 #", "# Apply ShiftRows py = [y[P[i]] for i in range(16)]", "'\\nend' relation_file_path = os.path.join(output_dir, 'relationfile_%s_%dr_mg%d_ms%d.txt' % (cipher_name, R, recommended_mg, recommended_ms))", "6, 7] tk1 = ['tk1_%d' % i for i in", "tk = ['tk_%d_%d' % (r, i) for i in range(8)]", "[temp1[TKP[i]] for i in range(16)] tk2 = [temp2[TKP[i]] for i", "recommended_mg, recommended_ms)) with open(relation_file_path, 'w') as relation_file: relation_file.write(eqs) def main():", "# recommended_mg = 26 # recommended_ms = 70 # 8", "i in range(4): for j in range(4): if i <", "# recommended_mg = 16 # recommended_ms = 8 # 3", "2*4], py[j + 3*4], xout[j + 0*4]) eqs += '%s,", "'w') as relation_file: relation_file.write(eqs) def main(): skinnytk2(R=10) if __name__ ==", "recommended_mg = 8 # recommended_ms = 4 # 2 rounds", "# recommended_ms = 24 # 4 rounds # recommended_mg =", "+= '%s, %s, %s\\n' % (tk1[j + 4*i], tk2[j +", "================================================> TWEAKEY_P(tk) ===> --- SB AC | P MC SB", "% (xin[j + 4*i], y[j + 4*i]) # Apply ShiftRows", "+ ===> y_1 ===> --- \"\"\" cipher_name = 'skinnytk2' P", "for r in range(R): xin = ['x_%d_%d' % (r, i)", "for i in range(16)] tk2 = ['tk2_%d' % i for" ]
[ "pass def get_grid_face_edges(self, grid, face_edges): pass def get_grid_node_count(self, grid): pass", "pass def initialize(self, config_file): pass def update(self): pass def update_until(self,", "def get_var_nbytes(self, var_name): pass def get_var_itemsize(self, name): pass def get_var_location(self,", "EmptyBmi(Bmi): def __init__(self): pass def initialize(self, config_file): pass def update(self):", "get_grid_edge_count(self, grid): pass def get_grid_edge_nodes(self, grid, edge_nodes): pass def get_grid_face_count(self,", "pass def finalize(self): pass def get_var_type(self, var_name): pass def get_var_units(self,", "grid): pass def get_grid_edge_nodes(self, grid, edge_nodes): pass def get_grid_face_count(self, grid):", "var_name): pass def get_var_units(self, var_name): pass def get_var_nbytes(self, var_name): pass", "pass def get_grid_shape(self, grid_id): pass def get_grid_spacing(self, grid_id): pass def", "pass def get_grid_edge_nodes(self, grid, edge_nodes): pass def get_grid_face_count(self, grid): pass", "def get_var_grid(self, var_name): pass def get_grid_rank(self, grid_id): pass def get_grid_size(self,", "grid_id): pass def get_grid_origin(self, grid_id): pass def get_grid_type(self, grid_id): pass", "def get_grid_face_nodes(self, grid, face_nodes): pass def get_grid_face_edges(self, grid, face_edges): pass", "get_input_var_names(self): pass def get_output_var_names(self): pass def get_grid_shape(self, grid_id): pass def", "nodes_per_face): pass def get_grid_x(self, grid, x): pass def get_grid_y(self, grid,", "get_time_step(self): pass def get_time_units(self): pass def get_grid_edge_count(self, grid): pass def", "pass def get_var_grid(self, var_name): pass def get_grid_rank(self, grid_id): pass def", "config_file): pass def update(self): pass def update_until(self, then): pass def", "def get_grid_size(self, grid_id): pass def get_value_ptr(self, var_name): pass def get_value(self,", "pass def get_output_var_names(self): pass def get_grid_shape(self, grid_id): pass def get_grid_spacing(self,", "face_edges): pass def get_grid_node_count(self, grid): pass def get_grid_nodes_per_face(self, grid, nodes_per_face):", "def get_value_ptr(self, var_name): pass def get_value(self, var_name): pass def get_value_at_indices(self,", "def get_grid_z(self, grid, z): pass def test_bmi_not_implemented(): class MyBmi(Bmi): pass", "pass def update_until(self, then): pass def finalize(self): pass def get_var_type(self,", "def get_var_location(self, name): pass def get_var_grid(self, var_name): pass def get_grid_rank(self,", "def get_grid_y(self, grid, y): pass def get_grid_z(self, grid, z): pass", "pass def get_grid_edge_count(self, grid): pass def get_grid_edge_nodes(self, grid, edge_nodes): pass", "get_grid_nodes_per_face(self, grid, nodes_per_face): pass def get_grid_x(self, grid, x): pass def", "def get_time_units(self): pass def get_grid_edge_count(self, grid): pass def get_grid_edge_nodes(self, grid,", "def initialize(self, config_file): pass def update(self): pass def update_until(self, then):", "pass def set_value(self, var_name, src): pass def set_value_at_indices(self, var_name, src,", "pass def get_start_time(self): pass def get_end_time(self): pass def get_current_time(self): pass", "def get_current_time(self): pass def get_time_step(self): pass def get_time_units(self): pass def", "def get_value_at_indices(self, var_name, indices): pass def set_value(self, var_name, src): pass", "def get_grid_face_edges(self, grid, face_edges): pass def get_grid_node_count(self, grid): pass def", "def get_output_var_names(self): pass def get_grid_shape(self, grid_id): pass def get_grid_spacing(self, grid_id):", "get_var_itemsize(self, name): pass def get_var_location(self, name): pass def get_var_grid(self, var_name):", "grid): pass def get_grid_face_nodes(self, grid, face_nodes): pass def get_grid_face_edges(self, grid,", "get_grid_x(self, grid, x): pass def get_grid_y(self, grid, y): pass def", "grid_id): pass def get_grid_type(self, grid_id): pass def get_start_time(self): pass def", "update(self): pass def update_until(self, then): pass def finalize(self): pass def", "pass def get_time_units(self): pass def get_grid_edge_count(self, grid): pass def get_grid_edge_nodes(self,", "get_var_grid(self, var_name): pass def get_grid_rank(self, grid_id): pass def get_grid_size(self, grid_id):", "pass def get_grid_face_nodes(self, grid, face_nodes): pass def get_grid_face_edges(self, grid, face_edges):", "class EmptyBmi(Bmi): def __init__(self): pass def initialize(self, config_file): pass def", "def get_component_name(self): pass def get_input_item_count(self): pass def get_output_item_count(self): pass def", "var_name): pass def get_value_at_indices(self, var_name, indices): pass def set_value(self, var_name,", "get_output_var_names(self): pass def get_grid_shape(self, grid_id): pass def get_grid_spacing(self, grid_id): pass", "get_grid_shape(self, grid_id): pass def get_grid_spacing(self, grid_id): pass def get_grid_origin(self, grid_id):", "pass def get_input_item_count(self): pass def get_output_item_count(self): pass def get_input_var_names(self): pass", "bmipy import Bmi class EmptyBmi(Bmi): def __init__(self): pass def initialize(self,", "var_name, indices): pass def set_value(self, var_name, src): pass def set_value_at_indices(self,", "pass def get_grid_rank(self, grid_id): pass def get_grid_size(self, grid_id): pass def", "def get_grid_node_count(self, grid): pass def get_grid_nodes_per_face(self, grid, nodes_per_face): pass def", "finalize(self): pass def get_var_type(self, var_name): pass def get_var_units(self, var_name): pass", "pass def get_var_nbytes(self, var_name): pass def get_var_itemsize(self, name): pass def", "grid, x): pass def get_grid_y(self, grid, y): pass def get_grid_z(self,", "var_name): pass def get_var_nbytes(self, var_name): pass def get_var_itemsize(self, name): pass", "get_input_item_count(self): pass def get_output_item_count(self): pass def get_input_var_names(self): pass def get_output_var_names(self):", "def get_grid_type(self, grid_id): pass def get_start_time(self): pass def get_end_time(self): pass", "def get_value(self, var_name): pass def get_value_at_indices(self, var_name, indices): pass def", "import pytest from bmipy import Bmi class EmptyBmi(Bmi): def __init__(self):", "pass def get_current_time(self): pass def get_time_step(self): pass def get_time_units(self): pass", "def get_grid_rank(self, grid_id): pass def get_grid_size(self, grid_id): pass def get_value_ptr(self,", "var_name): pass def get_value(self, var_name): pass def get_value_at_indices(self, var_name, indices):", "indices): pass def set_value(self, var_name, src): pass def set_value_at_indices(self, var_name,", "get_time_units(self): pass def get_grid_edge_count(self, grid): pass def get_grid_edge_nodes(self, grid, edge_nodes):", "pass def get_value_at_indices(self, var_name, indices): pass def set_value(self, var_name, src):", "get_output_item_count(self): pass def get_input_var_names(self): pass def get_output_var_names(self): pass def get_grid_shape(self,", "grid_id): pass def get_grid_spacing(self, grid_id): pass def get_grid_origin(self, grid_id): pass", "import Bmi class EmptyBmi(Bmi): def __init__(self): pass def initialize(self, config_file):", "var_name, src): pass def set_value_at_indices(self, var_name, src, indices): pass def", "pass def get_grid_origin(self, grid_id): pass def get_grid_type(self, grid_id): pass def", "pass def test_bmi_not_implemented(): class MyBmi(Bmi): pass with pytest.raises(TypeError): Bmi() def", "pass def get_end_time(self): pass def get_current_time(self): pass def get_time_step(self): pass", "get_var_nbytes(self, var_name): pass def get_var_itemsize(self, name): pass def get_var_location(self, name):", "get_value_at_indices(self, var_name, indices): pass def set_value(self, var_name, src): pass def", "get_value_ptr(self, var_name): pass def get_value(self, var_name): pass def get_value_at_indices(self, var_name,", "get_grid_z(self, grid, z): pass def test_bmi_not_implemented(): class MyBmi(Bmi): pass with", "get_grid_origin(self, grid_id): pass def get_grid_type(self, grid_id): pass def get_start_time(self): pass", "from bmipy import Bmi class EmptyBmi(Bmi): def __init__(self): pass def", "get_grid_node_count(self, grid): pass def get_grid_nodes_per_face(self, grid, nodes_per_face): pass def get_grid_x(self,", "name): pass def get_var_location(self, name): pass def get_var_grid(self, var_name): pass", "def get_input_item_count(self): pass def get_output_item_count(self): pass def get_input_var_names(self): pass def", "def get_input_var_names(self): pass def get_output_var_names(self): pass def get_grid_shape(self, grid_id): pass", "grid, y): pass def get_grid_z(self, grid, z): pass def test_bmi_not_implemented():", "pass def get_grid_nodes_per_face(self, grid, nodes_per_face): pass def get_grid_x(self, grid, x):", "get_grid_y(self, grid, y): pass def get_grid_z(self, grid, z): pass def", "src): pass def set_value_at_indices(self, var_name, src, indices): pass def get_component_name(self):", "set_value(self, var_name, src): pass def set_value_at_indices(self, var_name, src, indices): pass", "def get_grid_origin(self, grid_id): pass def get_grid_type(self, grid_id): pass def get_start_time(self):", "get_grid_face_nodes(self, grid, face_nodes): pass def get_grid_face_edges(self, grid, face_edges): pass def", "pass def get_output_item_count(self): pass def get_input_var_names(self): pass def get_output_var_names(self): pass", "get_end_time(self): pass def get_current_time(self): pass def get_time_step(self): pass def get_time_units(self):", "get_current_time(self): pass def get_time_step(self): pass def get_time_units(self): pass def get_grid_edge_count(self,", "pass def get_time_step(self): pass def get_time_units(self): pass def get_grid_edge_count(self, grid):", "y): pass def get_grid_z(self, grid, z): pass def test_bmi_not_implemented(): class", "pass def get_component_name(self): pass def get_input_item_count(self): pass def get_output_item_count(self): pass", "def get_grid_nodes_per_face(self, grid, nodes_per_face): pass def get_grid_x(self, grid, x): pass", "get_grid_size(self, grid_id): pass def get_value_ptr(self, var_name): pass def get_value(self, var_name):", "class MyBmi(Bmi): pass with pytest.raises(TypeError): Bmi() def test_bmi_implemented(): assert isinstance(EmptyBmi(),", "pass def set_value_at_indices(self, var_name, src, indices): pass def get_component_name(self): pass", "var_name, src, indices): pass def get_component_name(self): pass def get_input_item_count(self): pass", "def get_grid_shape(self, grid_id): pass def get_grid_spacing(self, grid_id): pass def get_grid_origin(self,", "pass def get_grid_type(self, grid_id): pass def get_start_time(self): pass def get_end_time(self):", "pass def get_grid_face_count(self, grid): pass def get_grid_face_nodes(self, grid, face_nodes): pass", "def get_grid_spacing(self, grid_id): pass def get_grid_origin(self, grid_id): pass def get_grid_type(self,", "def get_grid_x(self, grid, x): pass def get_grid_y(self, grid, y): pass", "get_grid_edge_nodes(self, grid, edge_nodes): pass def get_grid_face_count(self, grid): pass def get_grid_face_nodes(self,", "grid): pass def get_grid_nodes_per_face(self, grid, nodes_per_face): pass def get_grid_x(self, grid,", "pass def get_var_location(self, name): pass def get_var_grid(self, var_name): pass def", "var_name): pass def get_grid_rank(self, grid_id): pass def get_grid_size(self, grid_id): pass", "pass def get_grid_size(self, grid_id): pass def get_value_ptr(self, var_name): pass def", "pass def get_var_itemsize(self, name): pass def get_var_location(self, name): pass def", "pass def get_grid_spacing(self, grid_id): pass def get_grid_origin(self, grid_id): pass def", "def update_until(self, then): pass def finalize(self): pass def get_var_type(self, var_name):", "def __init__(self): pass def initialize(self, config_file): pass def update(self): pass", "grid, z): pass def test_bmi_not_implemented(): class MyBmi(Bmi): pass with pytest.raises(TypeError):", "initialize(self, config_file): pass def update(self): pass def update_until(self, then): pass", "pass def get_value(self, var_name): pass def get_value_at_indices(self, var_name, indices): pass", "def get_start_time(self): pass def get_end_time(self): pass def get_current_time(self): pass def", "indices): pass def get_component_name(self): pass def get_input_item_count(self): pass def get_output_item_count(self):", "get_grid_face_count(self, grid): pass def get_grid_face_nodes(self, grid, face_nodes): pass def get_grid_face_edges(self,", "grid, face_edges): pass def get_grid_node_count(self, grid): pass def get_grid_nodes_per_face(self, grid,", "pass def get_grid_y(self, grid, y): pass def get_grid_z(self, grid, z):", "get_value(self, var_name): pass def get_value_at_indices(self, var_name, indices): pass def set_value(self,", "def get_grid_edge_nodes(self, grid, edge_nodes): pass def get_grid_face_count(self, grid): pass def", "var_name): pass def get_var_itemsize(self, name): pass def get_var_location(self, name): pass", "name): pass def get_var_grid(self, var_name): pass def get_grid_rank(self, grid_id): pass", "test_bmi_not_implemented(): class MyBmi(Bmi): pass with pytest.raises(TypeError): Bmi() def test_bmi_implemented(): assert", "def set_value_at_indices(self, var_name, src, indices): pass def get_component_name(self): pass def", "def test_bmi_not_implemented(): class MyBmi(Bmi): pass with pytest.raises(TypeError): Bmi() def test_bmi_implemented():", "def get_output_item_count(self): pass def get_input_var_names(self): pass def get_output_var_names(self): pass def", "pass def get_grid_z(self, grid, z): pass def test_bmi_not_implemented(): class MyBmi(Bmi):", "get_grid_type(self, grid_id): pass def get_start_time(self): pass def get_end_time(self): pass def", "MyBmi(Bmi): pass with pytest.raises(TypeError): Bmi() def test_bmi_implemented(): assert isinstance(EmptyBmi(), Bmi)", "pass def get_value_ptr(self, var_name): pass def get_value(self, var_name): pass def", "z): pass def test_bmi_not_implemented(): class MyBmi(Bmi): pass with pytest.raises(TypeError): Bmi()", "<filename>tests/test_bmipy.py<gh_stars>10-100 import pytest from bmipy import Bmi class EmptyBmi(Bmi): def", "def set_value(self, var_name, src): pass def set_value_at_indices(self, var_name, src, indices):", "pass def get_grid_node_count(self, grid): pass def get_grid_nodes_per_face(self, grid, nodes_per_face): pass", "pass def update(self): pass def update_until(self, then): pass def finalize(self):", "def get_var_units(self, var_name): pass def get_var_nbytes(self, var_name): pass def get_var_itemsize(self,", "pytest from bmipy import Bmi class EmptyBmi(Bmi): def __init__(self): pass", "def finalize(self): pass def get_var_type(self, var_name): pass def get_var_units(self, var_name):", "def get_end_time(self): pass def get_current_time(self): pass def get_time_step(self): pass def", "def get_grid_face_count(self, grid): pass def get_grid_face_nodes(self, grid, face_nodes): pass def", "def get_time_step(self): pass def get_time_units(self): pass def get_grid_edge_count(self, grid): pass", "grid, edge_nodes): pass def get_grid_face_count(self, grid): pass def get_grid_face_nodes(self, grid,", "def get_var_type(self, var_name): pass def get_var_units(self, var_name): pass def get_var_nbytes(self,", "update_until(self, then): pass def finalize(self): pass def get_var_type(self, var_name): pass", "get_start_time(self): pass def get_end_time(self): pass def get_current_time(self): pass def get_time_step(self):", "then): pass def finalize(self): pass def get_var_type(self, var_name): pass def", "grid, face_nodes): pass def get_grid_face_edges(self, grid, face_edges): pass def get_grid_node_count(self,", "def get_grid_edge_count(self, grid): pass def get_grid_edge_nodes(self, grid, edge_nodes): pass def", "grid_id): pass def get_value_ptr(self, var_name): pass def get_value(self, var_name): pass", "Bmi class EmptyBmi(Bmi): def __init__(self): pass def initialize(self, config_file): pass", "def update(self): pass def update_until(self, then): pass def finalize(self): pass", "__init__(self): pass def initialize(self, config_file): pass def update(self): pass def", "pass def get_var_type(self, var_name): pass def get_var_units(self, var_name): pass def", "get_grid_spacing(self, grid_id): pass def get_grid_origin(self, grid_id): pass def get_grid_type(self, grid_id):", "grid_id): pass def get_start_time(self): pass def get_end_time(self): pass def get_current_time(self):", "get_var_type(self, var_name): pass def get_var_units(self, var_name): pass def get_var_nbytes(self, var_name):", "def get_var_itemsize(self, name): pass def get_var_location(self, name): pass def get_var_grid(self,", "edge_nodes): pass def get_grid_face_count(self, grid): pass def get_grid_face_nodes(self, grid, face_nodes):", "face_nodes): pass def get_grid_face_edges(self, grid, face_edges): pass def get_grid_node_count(self, grid):", "pass def get_grid_x(self, grid, x): pass def get_grid_y(self, grid, y):", "get_component_name(self): pass def get_input_item_count(self): pass def get_output_item_count(self): pass def get_input_var_names(self):", "get_var_location(self, name): pass def get_var_grid(self, var_name): pass def get_grid_rank(self, grid_id):", "pass def get_input_var_names(self): pass def get_output_var_names(self): pass def get_grid_shape(self, grid_id):", "x): pass def get_grid_y(self, grid, y): pass def get_grid_z(self, grid,", "grid, nodes_per_face): pass def get_grid_x(self, grid, x): pass def get_grid_y(self,", "grid_id): pass def get_grid_size(self, grid_id): pass def get_value_ptr(self, var_name): pass", "get_grid_face_edges(self, grid, face_edges): pass def get_grid_node_count(self, grid): pass def get_grid_nodes_per_face(self,", "get_var_units(self, var_name): pass def get_var_nbytes(self, var_name): pass def get_var_itemsize(self, name):", "src, indices): pass def get_component_name(self): pass def get_input_item_count(self): pass def", "pass def get_var_units(self, var_name): pass def get_var_nbytes(self, var_name): pass def", "get_grid_rank(self, grid_id): pass def get_grid_size(self, grid_id): pass def get_value_ptr(self, var_name):", "set_value_at_indices(self, var_name, src, indices): pass def get_component_name(self): pass def get_input_item_count(self):" ]
[ "selector = None, **kwargs ): #unify value format if isinstance(", "format if isinstance( value, str ): value = { \"_type\":", ".field import FuncField as BaseField class StringField( BaseField ): process_timing", "None, selector = None, **kwargs ): #unify value format if", "key = key, value = value, selector = selector, **kwargs", "FuncField as BaseField class StringField( BaseField ): process_timing = [", "value = None, selector = None, **kwargs ): #unify value", "<reponame>Sphynx-HenryAY/scrapy-compose from scrapy_compose.utils.context import realize from .field import FuncField as", "StringField( BaseField ): process_timing = [ \"post_pack\" ] def __init__(", "**kwargs ): return { realize( selector, key ): self.post_pack( realize(", "= None, **kwargs ): #unify value format if isinstance( value,", "from scrapy_compose.utils.context import realize from .field import FuncField as BaseField", "[ \"post_pack\" ] def __init__( self, key = None, value", ").__init__( key = key, value = value, selector = selector,", "\"_type\": \"string\", \"value\": value } super( StringField, self ).__init__( key", "super( StringField, self ).__init__( key = key, value = value,", "key, value = value, selector = selector, **kwargs ) def", "as BaseField class StringField( BaseField ): process_timing = [ \"post_pack\"", "key = None, value = None, selector = None, **kwargs", "value } super( StringField, self ).__init__( key = key, value", "value, str ): value = { \"_type\": \"string\", \"value\": value", "process_timing = [ \"post_pack\" ] def __init__( self, key =", "\"value\": value } super( StringField, self ).__init__( key = key,", "realize from .field import FuncField as BaseField class StringField( BaseField", "{ realize( selector, key ): self.post_pack( realize( selector, value )", "value = value, selector = selector, **kwargs ) def make_field(", "\"string\", \"value\": value } super( StringField, self ).__init__( key =", "def __init__( self, key = None, value = None, selector", "selector, key ): self.post_pack( realize( selector, value ) ) }", "} super( StringField, self ).__init__( key = key, value =", "): #unify value format if isinstance( value, str ): value", "None, **kwargs ): #unify value format if isinstance( value, str", "**kwargs ): #unify value format if isinstance( value, str ):", "): process_timing = [ \"post_pack\" ] def __init__( self, key", "] def __init__( self, key = None, value = None,", "{ \"_type\": \"string\", \"value\": value } super( StringField, self ).__init__(", "value, selector = selector, **kwargs ) def make_field( self, selector,", "= None, value = None, **kwargs ): return { realize(", "= value, selector = selector, **kwargs ) def make_field( self,", "None, **kwargs ): return { realize( selector, key ): self.post_pack(", "None, value = None, **kwargs ): return { realize( selector,", "value = { \"_type\": \"string\", \"value\": value } super( StringField,", "= None, **kwargs ): return { realize( selector, key ):", "scrapy_compose.utils.context import realize from .field import FuncField as BaseField class", "selector, **kwargs ) def make_field( self, selector, key = None,", "make_field( self, selector, key = None, value = None, **kwargs", "def make_field( self, selector, key = None, value = None,", "import realize from .field import FuncField as BaseField class StringField(", "self ).__init__( key = key, value = value, selector =", ") def make_field( self, selector, key = None, value =", "realize( selector, key ): self.post_pack( realize( selector, value ) )", "import FuncField as BaseField class StringField( BaseField ): process_timing =", "__init__( self, key = None, value = None, selector =", "self, key = None, value = None, selector = None,", "selector, key = None, value = None, **kwargs ): return", "None, value = None, selector = None, **kwargs ): #unify", "class StringField( BaseField ): process_timing = [ \"post_pack\" ] def", "BaseField class StringField( BaseField ): process_timing = [ \"post_pack\" ]", "\"post_pack\" ] def __init__( self, key = None, value =", "value = None, **kwargs ): return { realize( selector, key", "StringField, self ).__init__( key = key, value = value, selector", "BaseField ): process_timing = [ \"post_pack\" ] def __init__( self,", "= selector, **kwargs ) def make_field( self, selector, key =", "from .field import FuncField as BaseField class StringField( BaseField ):", "= key, value = value, selector = selector, **kwargs )", "key = None, value = None, **kwargs ): return {", "#unify value format if isinstance( value, str ): value =", "isinstance( value, str ): value = { \"_type\": \"string\", \"value\":", "value format if isinstance( value, str ): value = {", "self, selector, key = None, value = None, **kwargs ):", "= None, value = None, selector = None, **kwargs ):", "str ): value = { \"_type\": \"string\", \"value\": value }", "= { \"_type\": \"string\", \"value\": value } super( StringField, self", "): value = { \"_type\": \"string\", \"value\": value } super(", "= [ \"post_pack\" ] def __init__( self, key = None,", "): return { realize( selector, key ): self.post_pack( realize( selector,", "selector = selector, **kwargs ) def make_field( self, selector, key", "= None, selector = None, **kwargs ): #unify value format", "**kwargs ) def make_field( self, selector, key = None, value", "if isinstance( value, str ): value = { \"_type\": \"string\",", "return { realize( selector, key ): self.post_pack( realize( selector, value" ]
[ "movie base url base_url = None def configure_request(app): global api_key,base_url", "print(get_news_source_response) source_result = None if get_news_source_response['articles']: source_result_list = get_news_source_response['articles'] source_result", "function processes the results and converts them into a list", "= source_item.get('url') urlToImage = source_item.get('urlToImage') publishedAt = source_item.get('publishedAt') if urlToImage:", "= app.config['NEWS_API_BASE_URL'] def get_news_source(country,category): ''' Function that gets the json", "list the source list is a list of dictionaries containing", "source_item.get('publishedAt') if urlToImage: source_object = News(source,author,title,description,url,urlToImage,publishedAt) source_result.append(source_object) return source_result def", "''' this function processes the results and converts them into", "source_object = News(source,author,title,description,url,urlToImage,publishedAt) source_result.append(source_object) return source_result def get_news(source): get_news_details_url =", "return source_result def process_result(source_list): ''' this function processes the results", "= None def configure_request(app): global api_key,base_url api_key = app.config['NEWS_API_KEY'] base_url", "if news_details_response: source = news_details_response.get('source') author = news_details_response.get('original_author') title =", "news_details_response.get('title') description = news_details_response.get('description') url = news_details_response.get('url') urlToImage = news_details_response.get('urlToImage')", "def get_news_source(country,category): ''' Function that gets the json response to", "publishedAt = source_item.get('publishedAt') if urlToImage: source_object = News(source,author,title,description,url,urlToImage,publishedAt) source_result.append(source_object) return", ".models import News # Getting api key api_key = None", "converts them into a list the source list is a", "= None # Getting the movie base url base_url =", "source_list: source = source_item.get('source') author = source_item.get('author') title = source_item.get('title')", "from .models import News # Getting api key api_key =", "= get_news_source_response['articles'] source_result = process_result(source_result_list) return source_result def process_result(source_list): '''", "request ''' get_news_source_url = base_url.format(country,category,api_key) with urllib.request.urlopen(get_news_source_url)as url: get_news_source_data =", "url: news_details_data = url.read() news_details_response = json.loads(news_details_data) news_object = None", "= news_details_response.get('original_author') title = news_details_response.get('title') description = news_details_response.get('description') url =", "gets the json response to our url request ''' get_news_source_url", "results ''' source_result= [] for source_item in source_list: source =", "source = news_details_response.get('source') author = news_details_response.get('original_author') title = news_details_response.get('title') description", "None if get_news_source_response['articles']: source_result_list = get_news_source_response['articles'] source_result = process_result(source_result_list) return", "[] for source_item in source_list: source = source_item.get('source') author =", "description = news_details_response.get('description') url = news_details_response.get('url') urlToImage = news_details_response.get('urlToImage') news_object", "''' Function that gets the json response to our url", "news_details_response.get('description') url = news_details_response.get('url') urlToImage = news_details_response.get('urlToImage') news_object = news(source,author,title,description,url,urlToImage,publishedAt)", "title = source_item.get('title') description = source_item.get('description') url = source_item.get('url') urlToImage", "None def configure_request(app): global api_key,base_url api_key = app.config['NEWS_API_KEY'] base_url =", "= source_item.get('title') description = source_item.get('description') url = source_item.get('url') urlToImage =", "= json.loads(news_details_data) news_object = None if news_details_response: source = news_details_response.get('source')", "the source list is a list of dictionaries containing news", "import News # Getting api key api_key = None #", "in source_list: source = source_item.get('source') author = source_item.get('author') title =", "= news_details_response.get('description') url = news_details_response.get('url') urlToImage = news_details_response.get('urlToImage') news_object =", "author = source_item.get('author') title = source_item.get('title') description = source_item.get('description') url", "if urlToImage: source_object = News(source,author,title,description,url,urlToImage,publishedAt) source_result.append(source_object) return source_result def get_news(source):", "# Getting api key api_key = None # Getting the", "def configure_request(app): global api_key,base_url api_key = app.config['NEWS_API_KEY'] base_url = app.config['NEWS_API_BASE_URL']", "None if news_details_response: source = news_details_response.get('source') author = news_details_response.get('original_author') title", "get_news(source): get_news_details_url = base_url.format(source,api_key) with urllib.request.urlopen(get_news_details_url) as url: news_details_data =", "as url: news_details_data = url.read() news_details_response = json.loads(news_details_data) news_object =", "import json from .models import News # Getting api key", "processes the results and converts them into a list the", "base_url.format(country,category,api_key) with urllib.request.urlopen(get_news_source_url)as url: get_news_source_data = url.read() get_news_source_response = json.loads(get_news_source_data)", "= base_url.format(country,category,api_key) with urllib.request.urlopen(get_news_source_url)as url: get_news_source_data = url.read() get_news_source_response =", "with urllib.request.urlopen(get_news_details_url) as url: news_details_data = url.read() news_details_response = json.loads(news_details_data)", "= news_details_response.get('source') author = news_details_response.get('original_author') title = news_details_response.get('title') description =", "urlToImage: source_object = News(source,author,title,description,url,urlToImage,publishedAt) source_result.append(source_object) return source_result def get_news(source): get_news_details_url", "= news_details_response.get('url') urlToImage = news_details_response.get('urlToImage') news_object = news(source,author,title,description,url,urlToImage,publishedAt) return news_object", "list of dictionaries containing news results ''' source_result= [] for", "= source_item.get('urlToImage') publishedAt = source_item.get('publishedAt') if urlToImage: source_object = News(source,author,title,description,url,urlToImage,publishedAt)", "source list is a list of dictionaries containing news results", "the movie base url base_url = None def configure_request(app): global", "get_news_source_response = json.loads(get_news_source_data) print(get_news_source_response) source_result = None if get_news_source_response['articles']: source_result_list", "json.loads(news_details_data) news_object = None if news_details_response: source = news_details_response.get('source') author", "containing news results ''' source_result= [] for source_item in source_list:", "= news_details_response.get('title') description = news_details_response.get('description') url = news_details_response.get('url') urlToImage =", "def process_result(source_list): ''' this function processes the results and converts", "app.config['NEWS_API_KEY'] base_url = app.config['NEWS_API_BASE_URL'] def get_news_source(country,category): ''' Function that gets", "key api_key = None # Getting the movie base url", "= url.read() news_details_response = json.loads(news_details_data) news_object = None if news_details_response:", "the json response to our url request ''' get_news_source_url =", "news_details_data = url.read() news_details_response = json.loads(news_details_data) news_object = None if", "urllib.request import json from .models import News # Getting api", "dictionaries containing news results ''' source_result= [] for source_item in", "source_item.get('title') description = source_item.get('description') url = source_item.get('url') urlToImage = source_item.get('urlToImage')", "get_news_source_response['articles']: source_result_list = get_news_source_response['articles'] source_result = process_result(source_result_list) return source_result def", "base url base_url = None def configure_request(app): global api_key,base_url api_key", "is a list of dictionaries containing news results ''' source_result=", "source_item.get('author') title = source_item.get('title') description = source_item.get('description') url = source_item.get('url')", "def get_news(source): get_news_details_url = base_url.format(source,api_key) with urllib.request.urlopen(get_news_details_url) as url: news_details_data", "urllib.request.urlopen(get_news_details_url) as url: news_details_data = url.read() news_details_response = json.loads(news_details_data) news_object", "news_details_response: source = news_details_response.get('source') author = news_details_response.get('original_author') title = news_details_response.get('title')", "source_result = None if get_news_source_response['articles']: source_result_list = get_news_source_response['articles'] source_result =", "json response to our url request ''' get_news_source_url = base_url.format(country,category,api_key)", "source_result= [] for source_item in source_list: source = source_item.get('source') author", "get_news_source_data = url.read() get_news_source_response = json.loads(get_news_source_data) print(get_news_source_response) source_result = None", "= app.config['NEWS_API_KEY'] base_url = app.config['NEWS_API_BASE_URL'] def get_news_source(country,category): ''' Function that", "url.read() get_news_source_response = json.loads(get_news_source_data) print(get_news_source_response) source_result = None if get_news_source_response['articles']:", "source = source_item.get('source') author = source_item.get('author') title = source_item.get('title') description", "url.read() news_details_response = json.loads(news_details_data) news_object = None if news_details_response: source", "urlToImage = source_item.get('urlToImage') publishedAt = source_item.get('publishedAt') if urlToImage: source_object =", "url: get_news_source_data = url.read() get_news_source_response = json.loads(get_news_source_data) print(get_news_source_response) source_result =", "news_details_response = json.loads(news_details_data) news_object = None if news_details_response: source =", "source_item.get('description') url = source_item.get('url') urlToImage = source_item.get('urlToImage') publishedAt = source_item.get('publishedAt')", "the results and converts them into a list the source", "source_result def process_result(source_list): ''' this function processes the results and", "News(source,author,title,description,url,urlToImage,publishedAt) source_result.append(source_object) return source_result def get_news(source): get_news_details_url = base_url.format(source,api_key) with", "news results ''' source_result= [] for source_item in source_list: source", "news_details_response.get('original_author') title = news_details_response.get('title') description = news_details_response.get('description') url = news_details_response.get('url')", "= None if news_details_response: source = news_details_response.get('source') author = news_details_response.get('original_author')", "return source_result def get_news(source): get_news_details_url = base_url.format(source,api_key) with urllib.request.urlopen(get_news_details_url) as", "= json.loads(get_news_source_data) print(get_news_source_response) source_result = None if get_news_source_response['articles']: source_result_list =", "= source_item.get('publishedAt') if urlToImage: source_object = News(source,author,title,description,url,urlToImage,publishedAt) source_result.append(source_object) return source_result", "url = source_item.get('url') urlToImage = source_item.get('urlToImage') publishedAt = source_item.get('publishedAt') if", "source_result = process_result(source_result_list) return source_result def process_result(source_list): ''' this function", "our url request ''' get_news_source_url = base_url.format(country,category,api_key) with urllib.request.urlopen(get_news_source_url)as url:", "url base_url = None def configure_request(app): global api_key,base_url api_key =", "''' get_news_source_url = base_url.format(country,category,api_key) with urllib.request.urlopen(get_news_source_url)as url: get_news_source_data = url.read()", "author = news_details_response.get('original_author') title = news_details_response.get('title') description = news_details_response.get('description') url", "list is a list of dictionaries containing news results '''", "api key api_key = None # Getting the movie base", "a list of dictionaries containing news results ''' source_result= []", "process_result(source_list): ''' this function processes the results and converts them", "''' source_result= [] for source_item in source_list: source = source_item.get('source')", "title = news_details_response.get('title') description = news_details_response.get('description') url = news_details_response.get('url') urlToImage", "base_url.format(source,api_key) with urllib.request.urlopen(get_news_details_url) as url: news_details_data = url.read() news_details_response =", "= url.read() get_news_source_response = json.loads(get_news_source_data) print(get_news_source_response) source_result = None if", "None # Getting the movie base url base_url = None", "source_item.get('source') author = source_item.get('author') title = source_item.get('title') description = source_item.get('description')", "app.config['NEWS_API_BASE_URL'] def get_news_source(country,category): ''' Function that gets the json response", "= source_item.get('description') url = source_item.get('url') urlToImage = source_item.get('urlToImage') publishedAt =", "= None if get_news_source_response['articles']: source_result_list = get_news_source_response['articles'] source_result = process_result(source_result_list)", "url = news_details_response.get('url') urlToImage = news_details_response.get('urlToImage') news_object = news(source,author,title,description,url,urlToImage,publishedAt) return", "api_key = app.config['NEWS_API_KEY'] base_url = app.config['NEWS_API_BASE_URL'] def get_news_source(country,category): ''' Function", "description = source_item.get('description') url = source_item.get('url') urlToImage = source_item.get('urlToImage') publishedAt", "news_details_response.get('source') author = news_details_response.get('original_author') title = news_details_response.get('title') description = news_details_response.get('description')", "Getting the movie base url base_url = None def configure_request(app):", "get_news_source_response['articles'] source_result = process_result(source_result_list) return source_result def process_result(source_list): ''' this", "a list the source list is a list of dictionaries", "source_result.append(source_object) return source_result def get_news(source): get_news_details_url = base_url.format(source,api_key) with urllib.request.urlopen(get_news_details_url)", "Getting api key api_key = None # Getting the movie", "and converts them into a list the source list is", "source_item.get('url') urlToImage = source_item.get('urlToImage') publishedAt = source_item.get('publishedAt') if urlToImage: source_object", "source_item.get('urlToImage') publishedAt = source_item.get('publishedAt') if urlToImage: source_object = News(source,author,title,description,url,urlToImage,publishedAt) source_result.append(source_object)", "for source_item in source_list: source = source_item.get('source') author = source_item.get('author')", "base_url = None def configure_request(app): global api_key,base_url api_key = app.config['NEWS_API_KEY']", "configure_request(app): global api_key,base_url api_key = app.config['NEWS_API_KEY'] base_url = app.config['NEWS_API_BASE_URL'] def", "Function that gets the json response to our url request", "= process_result(source_result_list) return source_result def process_result(source_list): ''' this function processes", "news_object = None if news_details_response: source = news_details_response.get('source') author =", "import urllib.request import json from .models import News # Getting", "json.loads(get_news_source_data) print(get_news_source_response) source_result = None if get_news_source_response['articles']: source_result_list = get_news_source_response['articles']", "get_news_details_url = base_url.format(source,api_key) with urllib.request.urlopen(get_news_details_url) as url: news_details_data = url.read()", "global api_key,base_url api_key = app.config['NEWS_API_KEY'] base_url = app.config['NEWS_API_BASE_URL'] def get_news_source(country,category):", "base_url = app.config['NEWS_API_BASE_URL'] def get_news_source(country,category): ''' Function that gets the", "this function processes the results and converts them into a", "source_item in source_list: source = source_item.get('source') author = source_item.get('author') title", "if get_news_source_response['articles']: source_result_list = get_news_source_response['articles'] source_result = process_result(source_result_list) return source_result", "source_result def get_news(source): get_news_details_url = base_url.format(source,api_key) with urllib.request.urlopen(get_news_details_url) as url:", "= base_url.format(source,api_key) with urllib.request.urlopen(get_news_details_url) as url: news_details_data = url.read() news_details_response", "results and converts them into a list the source list", "get_news_source(country,category): ''' Function that gets the json response to our", "response to our url request ''' get_news_source_url = base_url.format(country,category,api_key) with", "= News(source,author,title,description,url,urlToImage,publishedAt) source_result.append(source_object) return source_result def get_news(source): get_news_details_url = base_url.format(source,api_key)", "News # Getting api key api_key = None # Getting", "that gets the json response to our url request '''", "# Getting the movie base url base_url = None def", "with urllib.request.urlopen(get_news_source_url)as url: get_news_source_data = url.read() get_news_source_response = json.loads(get_news_source_data) print(get_news_source_response)", "api_key = None # Getting the movie base url base_url", "into a list the source list is a list of", "to our url request ''' get_news_source_url = base_url.format(country,category,api_key) with urllib.request.urlopen(get_news_source_url)as", "api_key,base_url api_key = app.config['NEWS_API_KEY'] base_url = app.config['NEWS_API_BASE_URL'] def get_news_source(country,category): '''", "json from .models import News # Getting api key api_key", "of dictionaries containing news results ''' source_result= [] for source_item", "urllib.request.urlopen(get_news_source_url)as url: get_news_source_data = url.read() get_news_source_response = json.loads(get_news_source_data) print(get_news_source_response) source_result", "source_result_list = get_news_source_response['articles'] source_result = process_result(source_result_list) return source_result def process_result(source_list):", "get_news_source_url = base_url.format(country,category,api_key) with urllib.request.urlopen(get_news_source_url)as url: get_news_source_data = url.read() get_news_source_response", "process_result(source_result_list) return source_result def process_result(source_list): ''' this function processes the", "= source_item.get('source') author = source_item.get('author') title = source_item.get('title') description =", "= source_item.get('author') title = source_item.get('title') description = source_item.get('description') url =", "them into a list the source list is a list", "url request ''' get_news_source_url = base_url.format(country,category,api_key) with urllib.request.urlopen(get_news_source_url)as url: get_news_source_data" ]
[ "'X': M = [spTh.specie.X * spTh.specie.M for spTh in self.spTh.values()]", "# [J/kg] dcpvdT = [ spTh.specie.Y * spTh.thermo.dcpvdT for spTh", "return np.sum(np.concatenate(n)) # Enthalpy/Energy def he_(self): # [J/kg] he =", "[spTh.specie.Y * spTh.specie.R for spTh in self.spTh.values()] return np.sum(np.concatenate(R)) #", "elif var == 'X': sp.rho = sp.X * n *", "Update mass/molar fractions for name, value in XY.items(): value =", "* n def rhoi_(self, rho=None, n=None, var='Y'): for spTh_ in", "== 'Y': M = [spTh.specie.Y / spTh.specie.M for spTh in", "[spTh.specie.Y / spTh.specie.M for spTh in self.spTh.values()] return 1./np.sum(np.concatenate(M)) elif", "name, spTh in self.spTh.items() ] return np.sum(dhedY) # Species properties", "update(self, XY, var='Y'): # Update mass/molar fractions for name, value", "spTh_ in self.spTh.values(): sp = spTh_.specie sp.Y = sp.X *", "[J/kg] he = [spTh.specie.Y * spTh.thermo.he for spTh in self.spTh.values()]", "for spTh in self.spTh.values()] return np.sum(np.concatenate(R)) # Pressure def p_(self,", "K)] cpv = [spTh.specie.Y * spTh.thermo.cpv for spTh in self.spTh.values()]", "np from hypernet.src.general import const from hypernet.src.general import utils from", "= [ np.sum(dY[name] * spTh.thermo.he) \\ for name, spTh in", "* self.M / sp.M def ni_(self, rho=None, n=None, var='Y'): for", "Mixture properties ------------------------------------------------------ def update(self, XY, var='Y'): # Update mass/molar", "properties ------------------------------------------------------ def update(self, XY, var='Y'): # Update mass/molar fractions", "spTh_.specie if var == 'Y': sp.n = sp.Y * rho", "import numpy as np from hypernet.src.general import const from hypernet.src.general", "return np.sum(np.concatenate(cpv)) def dcpvdT_(self): # [J/kg] dcpvdT = [ spTh.specie.Y", "for spTh_ in self.spTh.values(): sp = spTh_.specie sp.X = sp.Y", "# [J/kg] dhedY = [ np.sum(dY[name] * spTh.thermo.he) \\ for", "value) # Update mixture/species properties self.M = self.M_(var=var) if var", "[kg/mol] if var == 'Y': M = [spTh.specie.Y / spTh.specie.M", "sp.X * sp.M / self.M def Xi_(self): for spTh_ in", "R = [spTh.specie.Y * spTh.specie.R for spTh in self.spTh.values()] return", "def update(self, XY, var='Y'): # Update mass/molar fractions for name,", "'X': self.Yi_() self.R = self.R_() # Mixture properties ------------------------------------------------------ #", "/ self.M def Xi_(self): for spTh_ in self.spTh.values(): sp =", "spTh in self.spTh.values() ] return np.sum(np.concatenate(dcpvdT)) def dhedY_(self, dY): #", "== 'X': sp.rho = sp.X * n * sp.M /", "setattr(self.spTh[name].specie, var, value) # Update mixture/species properties self.M = self.M_(var=var)", "] return np.sum(dhedY) # Species properties ------------------------------------------------------ def Yi_(self): for", "self.Xi_() elif var == 'X': self.Yi_() self.R = self.R_() #", "'X': sp.rho = sp.X * n * sp.M / const.UNA", "for name, value in XY.items(): value = utils.check_XY(utils.convert_to_array(value)) setattr(self.spTh[name].specie, var,", "def p_(self, rho, T): return rho*self.R*T # Density def rho_(self,", "[spTh.specie.Y * spTh.thermo.cpv for spTh in self.spTh.values()] return np.sum(np.concatenate(cpv)) def", "var == 'Y': sp.n = sp.Y * rho / sp.M", "def Yi_(self): for spTh_ in self.spTh.values(): sp = spTh_.specie sp.Y", "= [spTh.specie.Y / spTh.specie.M for spTh in self.spTh.values()] return 1./np.sum(np.concatenate(M))", "# Mass def M_(self, var='Y'): # [kg/mol] if var ==", "var, value) # Update mixture/species properties self.M = self.M_(var=var) if", "in self.spTh.values(): sp = spTh_.specie sp.X = sp.Y * self.M", "= self.M_(var=var) if var == 'Y': self.Xi_() elif var ==", "in self.spTh.values(): sp = spTh_.specie sp.Y = sp.X * sp.M", "elif var == 'X': self.Yi_() self.R = self.R_() # Mixture", "rho): self.ni_(rho=rho, var='Y') n = [spTh.specie.n for spTh in self.spTh.values()]", "------------------------------------------------------ def update(self, XY, var='Y'): # Update mass/molar fractions for", "* spTh.thermo.he for spTh in self.spTh.values()] return np.sum(np.concatenate(he)) def cpv_(self):", "self.spTh.items() ] return np.sum(dhedY) # Species properties ------------------------------------------------------ def Yi_(self):", "[ np.sum(dY[name] * spTh.thermo.he) \\ for name, spTh in self.spTh.items()", "self.R_() # Mixture properties ------------------------------------------------------ # Mass def M_(self, var='Y'):", "fractions for name, value in XY.items(): value = utils.check_XY(utils.convert_to_array(value)) setattr(self.spTh[name].specie,", "Enthalpy/Energy def he_(self): # [J/kg] he = [spTh.specie.Y * spTh.thermo.he", "def ni_(self, rho=None, n=None, var='Y'): for spTh_ in self.spTh.values(): sp", "for spTh_ in self.spTh.values(): sp = spTh_.specie sp.Y = sp.X", "self.spTh.values()] return np.sum(np.concatenate(cpv)) def dcpvdT_(self): # [J/kg] dcpvdT = [", "**kwargs ): super(MultiComponent, self).__init__(specieThermos) # Methods ########################################################################### # Mixture properties", "# Enthalpy/Energy def he_(self): # [J/kg] he = [spTh.specie.Y *", "########################################################################### def __init__( self, specieThermos, *args, **kwargs ): super(MultiComponent, self).__init__(specieThermos)", "np.sum(np.concatenate(cpv)) def dcpvdT_(self): # [J/kg] dcpvdT = [ spTh.specie.Y *", "): super(MultiComponent, self).__init__(specieThermos) # Methods ########################################################################### # Mixture properties ------------------------------------------------------", "return np.sum(np.concatenate(M)) # Specific gas constant def R_(self): R =", "= spTh_.specie sp.X = sp.Y * self.M / sp.M def", "np.sum(np.concatenate(dcpvdT)) def dhedY_(self, dY): # [J/kg] dhedY = [ np.sum(dY[name]", "self.Yi_() self.R = self.R_() # Mixture properties ------------------------------------------------------ # Mass", "# [J/(kg K)] cpv = [spTh.specie.Y * spTh.thermo.cpv for spTh", "[J/kg] dhedY = [ np.sum(dY[name] * spTh.thermo.he) \\ for name,", "rho=None, n=None, var='Y'): for spTh_ in self.spTh.values(): sp = spTh_.specie", "utils.check_XY(utils.convert_to_array(value)) setattr(self.spTh[name].specie, var, value) # Update mixture/species properties self.M =", "rhoi_(self, rho=None, n=None, var='Y'): for spTh_ in self.spTh.values(): sp =", "const.UNA elif var == 'X': sp.n = sp.X * n", "sp.Y * rho elif var == 'X': sp.rho = sp.X", "np.sum(np.concatenate(R)) # Pressure def p_(self, rho, T): return rho*self.R*T #", "self).__init__(specieThermos) # Methods ########################################################################### # Mixture properties ------------------------------------------------------ def update(self,", "self.spTh.values()] return 1./np.sum(np.concatenate(M)) elif var == 'X': M = [spTh.specie.X", "in self.spTh.values()] return np.sum(np.concatenate(M)) # Specific gas constant def R_(self):", "hypernet.src.general import const from hypernet.src.general import utils from hypernet.src.thermophysicalModels.reactionThermo.mixture import", "const from hypernet.src.general import utils from hypernet.src.thermophysicalModels.reactionThermo.mixture import Basic class", "if var == 'Y': self.Xi_() elif var == 'X': self.Yi_()", "== 'Y': sp.n = sp.Y * rho / sp.M *", "Specific gas constant def R_(self): R = [spTh.specie.Y * spTh.specie.R", "sp = spTh_.specie if var == 'Y': sp.n = sp.Y", "if var == 'Y': sp.rho = sp.Y * rho elif", "specieThermos, *args, **kwargs ): super(MultiComponent, self).__init__(specieThermos) # Methods ########################################################################### #", "# [kg/mol] if var == 'Y': M = [spTh.specie.Y /", "XY.items(): value = utils.check_XY(utils.convert_to_array(value)) setattr(self.spTh[name].specie, var, value) # Update mixture/species", "* sp.M / self.M def Xi_(self): for spTh_ in self.spTh.values():", "if var == 'Y': M = [spTh.specie.Y / spTh.specie.M for", "in self.spTh.values() ] return np.sum(np.concatenate(dcpvdT)) def dhedY_(self, dY): # [J/kg]", "/ sp.M * const.UNA elif var == 'X': sp.n =", "1./np.sum(np.concatenate(M)) elif var == 'X': M = [spTh.specie.X * spTh.specie.M", "== 'X': sp.n = sp.X * n def rhoi_(self, rho=None,", "[J/kg] dcpvdT = [ spTh.specie.Y * spTh.thermo.dcpvdT for spTh in", "spTh.thermo.he for spTh in self.spTh.values()] return np.sum(np.concatenate(he)) def cpv_(self): #", "= [spTh.specie.X * spTh.specie.M for spTh in self.spTh.values()] return np.sum(np.concatenate(M))", "dhedY = [ np.sum(dY[name] * spTh.thermo.he) \\ for name, spTh", "# Specific gas constant def R_(self): R = [spTh.specie.Y *", "[J/(kg K)] cpv = [spTh.specie.Y * spTh.thermo.cpv for spTh in", "cpv = [spTh.specie.Y * spTh.thermo.cpv for spTh in self.spTh.values()] return", "name, value in XY.items(): value = utils.check_XY(utils.convert_to_array(value)) setattr(self.spTh[name].specie, var, value)", "spTh in self.spTh.values()] return np.sum(np.concatenate(cpv)) def dcpvdT_(self): # [J/kg] dcpvdT", "* spTh.specie.M for spTh in self.spTh.values()] return np.sum(np.concatenate(M)) # Specific", "def __init__( self, specieThermos, *args, **kwargs ): super(MultiComponent, self).__init__(specieThermos) #", "self.spTh.values(): sp = spTh_.specie sp.Y = sp.X * sp.M /", "spTh_.specie sp.Y = sp.X * sp.M / self.M def Xi_(self):", "value in XY.items(): value = utils.check_XY(utils.convert_to_array(value)) setattr(self.spTh[name].specie, var, value) #", "utils from hypernet.src.thermophysicalModels.reactionThermo.mixture import Basic class MultiComponent(Basic): # Initialization ###########################################################################", "var='Y'): for spTh_ in self.spTh.values(): sp = spTh_.specie if var", "sp.M * const.UNA elif var == 'X': sp.n = sp.X", "properties ------------------------------------------------------ def Yi_(self): for spTh_ in self.spTh.values(): sp =", "Mass def M_(self, var='Y'): # [kg/mol] if var == 'Y':", "* rho elif var == 'X': sp.rho = sp.X *", "spTh in self.spTh.values()] return 1./np.sum(np.concatenate(M)) elif var == 'X': M", "spTh in self.spTh.values()] return np.sum(np.concatenate(R)) # Pressure def p_(self, rho,", "Basic class MultiComponent(Basic): # Initialization ########################################################################### def __init__( self, specieThermos,", "= [ spTh.specie.Y * spTh.thermo.dcpvdT for spTh in self.spTh.values() ]", "Xi_(self): for spTh_ in self.spTh.values(): sp = spTh_.specie sp.X =", "for spTh in self.spTh.values() ] return np.sum(np.concatenate(dcpvdT)) def dhedY_(self, dY):", "numpy as np from hypernet.src.general import const from hypernet.src.general import", "rho, T): return rho*self.R*T # Density def rho_(self, p, T):", "for spTh in self.spTh.values()] return np.sum(np.concatenate(cpv)) def dcpvdT_(self): # [J/kg]", "Number density def n_(self, rho): self.ni_(rho=rho, var='Y') n = [spTh.specie.n", "Mixture properties ------------------------------------------------------ # Mass def M_(self, var='Y'): # [kg/mol]", "= [spTh.specie.Y * spTh.specie.R for spTh in self.spTh.values()] return np.sum(np.concatenate(R))", "p, T): return p/(self.R*T) # Number density def n_(self, rho):", "rho / sp.M * const.UNA elif var == 'X': sp.n", "self.spTh.values()] return np.sum(np.concatenate(n)) # Enthalpy/Energy def he_(self): # [J/kg] he", "properties self.M = self.M_(var=var) if var == 'Y': self.Xi_() elif", "mixture/species properties self.M = self.M_(var=var) if var == 'Y': self.Xi_()", "return np.sum(dhedY) # Species properties ------------------------------------------------------ def Yi_(self): for spTh_", "return p/(self.R*T) # Number density def n_(self, rho): self.ni_(rho=rho, var='Y')", "spTh in self.spTh.values()] return np.sum(np.concatenate(M)) # Specific gas constant def", "# Update mixture/species properties self.M = self.M_(var=var) if var ==", "self.spTh.values() ] return np.sum(np.concatenate(dcpvdT)) def dhedY_(self, dY): # [J/kg] dhedY", "dcpvdT = [ spTh.specie.Y * spTh.thermo.dcpvdT for spTh in self.spTh.values()", "np.sum(dhedY) # Species properties ------------------------------------------------------ def Yi_(self): for spTh_ in", "= sp.X * sp.M / self.M def Xi_(self): for spTh_", "for spTh in self.spTh.values()] return 1./np.sum(np.concatenate(M)) elif var == 'X':", "sp.n = sp.X * n def rhoi_(self, rho=None, n=None, var='Y'):", "if var == 'Y': sp.n = sp.Y * rho /", "rho*self.R*T # Density def rho_(self, p, T): return p/(self.R*T) #", "from hypernet.src.thermophysicalModels.reactionThermo.mixture import Basic class MultiComponent(Basic): # Initialization ########################################################################### def", "n = [spTh.specie.n for spTh in self.spTh.values()] return np.sum(np.concatenate(n)) #", "sp.X = sp.Y * self.M / sp.M def ni_(self, rho=None,", "self.M def Xi_(self): for spTh_ in self.spTh.values(): sp = spTh_.specie", "------------------------------------------------------ def Yi_(self): for spTh_ in self.spTh.values(): sp = spTh_.specie", "for spTh in self.spTh.values()] return np.sum(np.concatenate(M)) # Specific gas constant", "self.M / sp.M def ni_(self, rho=None, n=None, var='Y'): for spTh_", "in self.spTh.values()] return np.sum(np.concatenate(R)) # Pressure def p_(self, rho, T):", "def dhedY_(self, dY): # [J/kg] dhedY = [ np.sum(dY[name] *", "for spTh_ in self.spTh.values(): sp = spTh_.specie if var ==", "return np.sum(np.concatenate(R)) # Pressure def p_(self, rho, T): return rho*self.R*T", "var == 'Y': M = [spTh.specie.Y / spTh.specie.M for spTh", "self.M = self.M_(var=var) if var == 'Y': self.Xi_() elif var", "# Initialization ########################################################################### def __init__( self, specieThermos, *args, **kwargs ):", "Species properties ------------------------------------------------------ def Yi_(self): for spTh_ in self.spTh.values(): sp", "= spTh_.specie if var == 'Y': sp.rho = sp.Y *", "T): return p/(self.R*T) # Number density def n_(self, rho): self.ni_(rho=rho,", "rho_(self, p, T): return p/(self.R*T) # Number density def n_(self,", "\\ for name, spTh in self.spTh.items() ] return np.sum(dhedY) #", "var='Y'): # Update mass/molar fractions for name, value in XY.items():", "* spTh.thermo.cpv for spTh in self.spTh.values()] return np.sum(np.concatenate(cpv)) def dcpvdT_(self):", "as np from hypernet.src.general import const from hypernet.src.general import utils", "var='Y'): # [kg/mol] if var == 'Y': M = [spTh.specie.Y", "Density def rho_(self, p, T): return p/(self.R*T) # Number density", "properties ------------------------------------------------------ # Mass def M_(self, var='Y'): # [kg/mol] if", "= [spTh.specie.n for spTh in self.spTh.values()] return np.sum(np.concatenate(n)) # Enthalpy/Energy", "spTh_.specie if var == 'Y': sp.rho = sp.Y * rho", "= [spTh.specie.Y * spTh.thermo.he for spTh in self.spTh.values()] return np.sum(np.concatenate(he))", "sp = spTh_.specie sp.X = sp.Y * self.M / sp.M", "'X': sp.n = sp.X * n def rhoi_(self, rho=None, n=None,", "self, specieThermos, *args, **kwargs ): super(MultiComponent, self).__init__(specieThermos) # Methods ###########################################################################", "in self.spTh.values()] return np.sum(np.concatenate(n)) # Enthalpy/Energy def he_(self): # [J/kg]", "self.ni_(rho=rho, var='Y') n = [spTh.specie.n for spTh in self.spTh.values()] return", "self.spTh.values()] return np.sum(np.concatenate(he)) def cpv_(self): # [J/(kg K)] cpv =", "spTh.specie.R for spTh in self.spTh.values()] return np.sum(np.concatenate(R)) # Pressure def", "M_(self, var='Y'): # [kg/mol] if var == 'Y': M =", "in self.spTh.values()] return np.sum(np.concatenate(cpv)) def dcpvdT_(self): # [J/kg] dcpvdT =", "ni_(self, rho=None, n=None, var='Y'): for spTh_ in self.spTh.values(): sp =", "sp.Y * self.M / sp.M def ni_(self, rho=None, n=None, var='Y'):", "def n_(self, rho): self.ni_(rho=rho, var='Y') n = [spTh.specie.n for spTh", "var='Y') n = [spTh.specie.n for spTh in self.spTh.values()] return np.sum(np.concatenate(n))", "return rho*self.R*T # Density def rho_(self, p, T): return p/(self.R*T)", "from hypernet.src.general import const from hypernet.src.general import utils from hypernet.src.thermophysicalModels.reactionThermo.mixture", "= sp.Y * rho / sp.M * const.UNA elif var", "n_(self, rho): self.ni_(rho=rho, var='Y') n = [spTh.specie.n for spTh in", "in self.spTh.values(): sp = spTh_.specie if var == 'Y': sp.n", "'Y': sp.n = sp.Y * rho / sp.M * const.UNA", "R_(self): R = [spTh.specie.Y * spTh.specie.R for spTh in self.spTh.values()]", "self.M_(var=var) if var == 'Y': self.Xi_() elif var == 'X':", "*args, **kwargs ): super(MultiComponent, self).__init__(specieThermos) # Methods ########################################################################### # Mixture", "cpv_(self): # [J/(kg K)] cpv = [spTh.specie.Y * spTh.thermo.cpv for", "spTh_.specie sp.X = sp.Y * self.M / sp.M def ni_(self,", "def dcpvdT_(self): # [J/kg] dcpvdT = [ spTh.specie.Y * spTh.thermo.dcpvdT", "spTh.specie.M for spTh in self.spTh.values()] return np.sum(np.concatenate(M)) # Specific gas", "np.sum(dY[name] * spTh.thermo.he) \\ for name, spTh in self.spTh.items() ]", "elif var == 'X': M = [spTh.specie.X * spTh.specie.M for", "# Number density def n_(self, rho): self.ni_(rho=rho, var='Y') n =", "spTh in self.spTh.values()] return np.sum(np.concatenate(n)) # Enthalpy/Energy def he_(self): #", "from hypernet.src.general import utils from hypernet.src.thermophysicalModels.reactionThermo.mixture import Basic class MultiComponent(Basic):", "gas constant def R_(self): R = [spTh.specie.Y * spTh.specie.R for", "= sp.Y * self.M / sp.M def ni_(self, rho=None, n=None,", "for spTh in self.spTh.values()] return np.sum(np.concatenate(he)) def cpv_(self): # [J/(kg", "= utils.check_XY(utils.convert_to_array(value)) setattr(self.spTh[name].specie, var, value) # Update mixture/species properties self.M", "XY, var='Y'): # Update mass/molar fractions for name, value in", "sp = spTh_.specie if var == 'Y': sp.rho = sp.Y", "import utils from hypernet.src.thermophysicalModels.reactionThermo.mixture import Basic class MultiComponent(Basic): # Initialization", "[spTh.specie.n for spTh in self.spTh.values()] return np.sum(np.concatenate(n)) # Enthalpy/Energy def", "var == 'X': sp.n = sp.X * n def rhoi_(self,", "] return np.sum(np.concatenate(dcpvdT)) def dhedY_(self, dY): # [J/kg] dhedY =", "dY): # [J/kg] dhedY = [ np.sum(dY[name] * spTh.thermo.he) \\", "sp.M def ni_(self, rho=None, n=None, var='Y'): for spTh_ in self.spTh.values():", "M = [spTh.specie.X * spTh.specie.M for spTh in self.spTh.values()] return", "n=None, var='Y'): for spTh_ in self.spTh.values(): sp = spTh_.specie if", "sp.n = sp.Y * rho / sp.M * const.UNA elif", "sp.rho = sp.Y * rho elif var == 'X': sp.rho", "/ sp.M def ni_(self, rho=None, n=None, var='Y'): for spTh_ in", "------------------------------------------------------ # Mass def M_(self, var='Y'): # [kg/mol] if var", "= sp.Y * rho elif var == 'X': sp.rho =", "spTh in self.spTh.items() ] return np.sum(dhedY) # Species properties ------------------------------------------------------", "p_(self, rho, T): return rho*self.R*T # Density def rho_(self, p,", "spTh.specie.Y * spTh.thermo.dcpvdT for spTh in self.spTh.values() ] return np.sum(np.concatenate(dcpvdT))", "def R_(self): R = [spTh.specie.Y * spTh.specie.R for spTh in", "* spTh.thermo.dcpvdT for spTh in self.spTh.values() ] return np.sum(np.concatenate(dcpvdT)) def", "def M_(self, var='Y'): # [kg/mol] if var == 'Y': M", "self.spTh.values()] return np.sum(np.concatenate(M)) # Specific gas constant def R_(self): R", "hypernet.src.thermophysicalModels.reactionThermo.mixture import Basic class MultiComponent(Basic): # Initialization ########################################################################### def __init__(", "'Y': M = [spTh.specie.Y / spTh.specie.M for spTh in self.spTh.values()]", "# Density def rho_(self, p, T): return p/(self.R*T) # Number", "return np.sum(np.concatenate(he)) def cpv_(self): # [J/(kg K)] cpv = [spTh.specie.Y", "spTh.thermo.cpv for spTh in self.spTh.values()] return np.sum(np.concatenate(cpv)) def dcpvdT_(self): #", "sp.Y * rho / sp.M * const.UNA elif var ==", "for name, spTh in self.spTh.items() ] return np.sum(dhedY) # Species", "* const.UNA elif var == 'X': sp.n = sp.X *", "= sp.X * n def rhoi_(self, rho=None, n=None, var='Y'): for", "def rho_(self, p, T): return p/(self.R*T) # Number density def", "spTh.thermo.dcpvdT for spTh in self.spTh.values() ] return np.sum(np.concatenate(dcpvdT)) def dhedY_(self,", "# Methods ########################################################################### # Mixture properties ------------------------------------------------------ def update(self, XY,", "var == 'X': self.Yi_() self.R = self.R_() # Mixture properties", "np.sum(np.concatenate(M)) # Specific gas constant def R_(self): R = [spTh.specie.Y", "MultiComponent(Basic): # Initialization ########################################################################### def __init__( self, specieThermos, *args, **kwargs", "def Xi_(self): for spTh_ in self.spTh.values(): sp = spTh_.specie sp.X", "import const from hypernet.src.general import utils from hypernet.src.thermophysicalModels.reactionThermo.mixture import Basic", "* rho / sp.M * const.UNA elif var == 'X':", "self.spTh.values(): sp = spTh_.specie if var == 'Y': sp.rho =", "self.R = self.R_() # Mixture properties ------------------------------------------------------ # Mass def", "sp = spTh_.specie sp.Y = sp.X * sp.M / self.M", "__init__( self, specieThermos, *args, **kwargs ): super(MultiComponent, self).__init__(specieThermos) # Methods", "super(MultiComponent, self).__init__(specieThermos) # Methods ########################################################################### # Mixture properties ------------------------------------------------------ def", "def he_(self): # [J/kg] he = [spTh.specie.Y * spTh.thermo.he for", "dcpvdT_(self): # [J/kg] dcpvdT = [ spTh.specie.Y * spTh.thermo.dcpvdT for", "n def rhoi_(self, rho=None, n=None, var='Y'): for spTh_ in self.spTh.values():", "constant def R_(self): R = [spTh.specie.Y * spTh.specie.R for spTh", "T): return rho*self.R*T # Density def rho_(self, p, T): return", "elif var == 'X': sp.n = sp.X * n def", "Initialization ########################################################################### def __init__( self, specieThermos, *args, **kwargs ): super(MultiComponent,", "sp.X * n def rhoi_(self, rho=None, n=None, var='Y'): for spTh_", "return np.sum(np.concatenate(dcpvdT)) def dhedY_(self, dY): # [J/kg] dhedY = [", "== 'X': self.Yi_() self.R = self.R_() # Mixture properties ------------------------------------------------------", "mass/molar fractions for name, value in XY.items(): value = utils.check_XY(utils.convert_to_array(value))", "# Species properties ------------------------------------------------------ def Yi_(self): for spTh_ in self.spTh.values():", "var == 'X': sp.rho = sp.X * n * sp.M", "sp.Y = sp.X * sp.M / self.M def Xi_(self): for", "= [spTh.specie.Y * spTh.thermo.cpv for spTh in self.spTh.values()] return np.sum(np.concatenate(cpv))", "density def n_(self, rho): self.ni_(rho=rho, var='Y') n = [spTh.specie.n for", "for spTh in self.spTh.values()] return np.sum(np.concatenate(n)) # Enthalpy/Energy def he_(self):", "########################################################################### # Mixture properties ------------------------------------------------------ def update(self, XY, var='Y'): #", "self.spTh.values()] return np.sum(np.concatenate(R)) # Pressure def p_(self, rho, T): return", "he = [spTh.specie.Y * spTh.thermo.he for spTh in self.spTh.values()] return", "spTh.specie.M for spTh in self.spTh.values()] return 1./np.sum(np.concatenate(M)) elif var ==", "self.spTh.values(): sp = spTh_.specie sp.X = sp.Y * self.M /", "in self.spTh.values()] return np.sum(np.concatenate(he)) def cpv_(self): # [J/(kg K)] cpv", "he_(self): # [J/kg] he = [spTh.specie.Y * spTh.thermo.he for spTh", "in self.spTh.items() ] return np.sum(dhedY) # Species properties ------------------------------------------------------ def", "'Y': self.Xi_() elif var == 'X': self.Yi_() self.R = self.R_()", "# Mixture properties ------------------------------------------------------ def update(self, XY, var='Y'): # Update", "def rhoi_(self, rho=None, n=None, var='Y'): for spTh_ in self.spTh.values(): sp", "var == 'X': M = [spTh.specie.X * spTh.specie.M for spTh", "* spTh.thermo.he) \\ for name, spTh in self.spTh.items() ] return", "'Y': sp.rho = sp.Y * rho elif var == 'X':", "== 'X': M = [spTh.specie.X * spTh.specie.M for spTh in", "spTh_ in self.spTh.values(): sp = spTh_.specie sp.X = sp.Y *", "value = utils.check_XY(utils.convert_to_array(value)) setattr(self.spTh[name].specie, var, value) # Update mixture/species properties", "np.sum(np.concatenate(he)) def cpv_(self): # [J/(kg K)] cpv = [spTh.specie.Y *", "var == 'Y': self.Xi_() elif var == 'X': self.Yi_() self.R", "# Mixture properties ------------------------------------------------------ # Mass def M_(self, var='Y'): #", "in self.spTh.values(): sp = spTh_.specie if var == 'Y': sp.rho", "Yi_(self): for spTh_ in self.spTh.values(): sp = spTh_.specie sp.Y =", "spTh_ in self.spTh.values(): sp = spTh_.specie if var == 'Y':", "in self.spTh.values()] return 1./np.sum(np.concatenate(M)) elif var == 'X': M =", "np.sum(np.concatenate(n)) # Enthalpy/Energy def he_(self): # [J/kg] he = [spTh.specie.Y", "dhedY_(self, dY): # [J/kg] dhedY = [ np.sum(dY[name] * spTh.thermo.he)", "self.spTh.values(): sp = spTh_.specie if var == 'Y': sp.n =", "== 'Y': self.Xi_() elif var == 'X': self.Yi_() self.R =", "= self.R_() # Mixture properties ------------------------------------------------------ # Mass def M_(self,", "class MultiComponent(Basic): # Initialization ########################################################################### def __init__( self, specieThermos, *args,", "= spTh_.specie if var == 'Y': sp.n = sp.Y *", "hypernet.src.general import utils from hypernet.src.thermophysicalModels.reactionThermo.mixture import Basic class MultiComponent(Basic): #", "* spTh.specie.R for spTh in self.spTh.values()] return np.sum(np.concatenate(R)) # Pressure", "spTh.thermo.he) \\ for name, spTh in self.spTh.items() ] return np.sum(dhedY)", "== 'Y': sp.rho = sp.Y * rho elif var ==", "Update mixture/species properties self.M = self.M_(var=var) if var == 'Y':", "Methods ########################################################################### # Mixture properties ------------------------------------------------------ def update(self, XY, var='Y'):", "# [J/kg] he = [spTh.specie.Y * spTh.thermo.he for spTh in", "/ spTh.specie.M for spTh in self.spTh.values()] return 1./np.sum(np.concatenate(M)) elif var", "sp.M / self.M def Xi_(self): for spTh_ in self.spTh.values(): sp", "var == 'Y': sp.rho = sp.Y * rho elif var", "[spTh.specie.Y * spTh.thermo.he for spTh in self.spTh.values()] return np.sum(np.concatenate(he)) def", "[spTh.specie.X * spTh.specie.M for spTh in self.spTh.values()] return np.sum(np.concatenate(M)) #", "[ spTh.specie.Y * spTh.thermo.dcpvdT for spTh in self.spTh.values() ] return", "Pressure def p_(self, rho, T): return rho*self.R*T # Density def", "p/(self.R*T) # Number density def n_(self, rho): self.ni_(rho=rho, var='Y') n", "# Pressure def p_(self, rho, T): return rho*self.R*T # Density", "in XY.items(): value = utils.check_XY(utils.convert_to_array(value)) setattr(self.spTh[name].specie, var, value) # Update", "# Update mass/molar fractions for name, value in XY.items(): value", "rho elif var == 'X': sp.rho = sp.X * n", "spTh in self.spTh.values()] return np.sum(np.concatenate(he)) def cpv_(self): # [J/(kg K)]", "return 1./np.sum(np.concatenate(M)) elif var == 'X': M = [spTh.specie.X *", "import Basic class MultiComponent(Basic): # Initialization ########################################################################### def __init__( self,", "def cpv_(self): # [J/(kg K)] cpv = [spTh.specie.Y * spTh.thermo.cpv", "M = [spTh.specie.Y / spTh.specie.M for spTh in self.spTh.values()] return", "= spTh_.specie sp.Y = sp.X * sp.M / self.M def" ]
[ "1.1 - Add user as ForeignKey (URL mapping, we use", "def __str__(self): return self.name def get_absolute_url(self): return reverse('toys_detail', kwargs={'pk': self.id})", "Field.choice return f\"{self.get_meal_display()} on {self.date}\" # change the default sort", "models.TextField(max_length=250) age = models.IntegerField() toys = models.ManyToManyField(Toy) user = models.ForeignKey(User,", "from django.urls import reverse from datetime import date from django.contrib.auth.models", "to our class based views) def __str__(self): return self.name def", "= models.CharField(max_length=50) color = models.CharField(max_length=20) def __str__(self): return self.name def", "date = models.DateField('feeding date') meal = models.CharField( max_length=1, choices=MEALS, default=MEALS[0][0]", "user models MEALS = ( ('B', 'Breakfast'), ('L', 'Lunch'), ('D',", "fed_for_today(self): return self.feeding_set.filter(date=date.today()).count() >= len(MEALS) class Feeding(models.Model): date = models.DateField('feeding", "the default sort class Meta: ordering = ['-date'] class Photo(models.Model):", "models.IntegerField() toys = models.ManyToManyField(Toy) user = models.ForeignKey(User, on_delete=models.CASCADE) #+ 1.1", "Nice method for obtaining the friendly value of a Field.choice", "default=MEALS[0][0] ) cat = models.ForeignKey(Cat, on_delete=models.CASCADE) def __str__(self): # Nice", "class Cat(models.Model): name = models.CharField(max_length=100) breed = models.CharField(max_length=100) description =", "django.urls import reverse from datetime import date from django.contrib.auth.models import", "models.CharField(max_length=100) description = models.TextField(max_length=250) age = models.IntegerField() toys = models.ManyToManyField(Toy)", "(URL mapping, we use this to point to our class", "reverse('detail', kwargs={'cat_id': self.id}) def fed_for_today(self): return self.feeding_set.filter(date=date.today()).count() >= len(MEALS) class", "('B', 'Breakfast'), ('L', 'Lunch'), ('D', 'Dinner') ) class Toy(models.Model): name", "from datetime import date from django.contrib.auth.models import User #! 1", "class Photo(models.Model): url = models.CharField(max_length=200) cat = models.ForeignKey(Cat, on_delete=models.CASCADE) def", "'Dinner') ) class Toy(models.Model): name = models.CharField(max_length=50) color = models.CharField(max_length=20)", "MEALS = ( ('B', 'Breakfast'), ('L', 'Lunch'), ('D', 'Dinner') )", "Add user as ForeignKey (URL mapping, we use this to", "the friendly value of a Field.choice return f\"{self.get_meal_display()} on {self.date}\"", "User #! 1 - Import user models MEALS = (", "views) def __str__(self): return self.name def get_absolute_url(self): return reverse('detail', kwargs={'cat_id':", "# Nice method for obtaining the friendly value of a", "reverse('toys_detail', kwargs={'pk': self.id}) class Cat(models.Model): name = models.CharField(max_length=100) breed =", "len(MEALS) class Feeding(models.Model): date = models.DateField('feeding date') meal = models.CharField(", ") class Toy(models.Model): name = models.CharField(max_length=50) color = models.CharField(max_length=20) def", "models.ManyToManyField(Toy) user = models.ForeignKey(User, on_delete=models.CASCADE) #+ 1.1 - Add user", "we use this to point to our class based views)", "def __str__(self): return self.name def get_absolute_url(self): return reverse('detail', kwargs={'cat_id': self.id})", "to point to our class based views) def __str__(self): return", "from django.contrib.auth.models import User #! 1 - Import user models", "return reverse('detail', kwargs={'cat_id': self.id}) def fed_for_today(self): return self.feeding_set.filter(date=date.today()).count() >= len(MEALS)", "- Import user models MEALS = ( ('B', 'Breakfast'), ('L',", "= models.DateField('feeding date') meal = models.CharField( max_length=1, choices=MEALS, default=MEALS[0][0] )", "import models from django.urls import reverse from datetime import date", "= ( ('B', 'Breakfast'), ('L', 'Lunch'), ('D', 'Dinner') ) class", ">= len(MEALS) class Feeding(models.Model): date = models.DateField('feeding date') meal =", ") cat = models.ForeignKey(Cat, on_delete=models.CASCADE) def __str__(self): # Nice method", "class Toy(models.Model): name = models.CharField(max_length=50) color = models.CharField(max_length=20) def __str__(self):", "class Meta: ordering = ['-date'] class Photo(models.Model): url = models.CharField(max_length=200)", "models.CharField(max_length=20) def __str__(self): return self.name def get_absolute_url(self): return reverse('toys_detail', kwargs={'pk':", "get_absolute_url(self): return reverse('detail', kwargs={'cat_id': self.id}) def fed_for_today(self): return self.feeding_set.filter(date=date.today()).count() >=", "def __str__(self): # Nice method for obtaining the friendly value", "= ['-date'] class Photo(models.Model): url = models.CharField(max_length=200) cat = models.ForeignKey(Cat,", "#! 1 - Import user models MEALS = ( ('B',", "sort class Meta: ordering = ['-date'] class Photo(models.Model): url =", "= models.IntegerField() toys = models.ManyToManyField(Toy) user = models.ForeignKey(User, on_delete=models.CASCADE) #+", "cat = models.ForeignKey(Cat, on_delete=models.CASCADE) def __str__(self): return f\"Photo for cat_id:", "this to point to our class based views) def __str__(self):", "models MEALS = ( ('B', 'Breakfast'), ('L', 'Lunch'), ('D', 'Dinner')", "Toy(models.Model): name = models.CharField(max_length=50) color = models.CharField(max_length=20) def __str__(self): return", "def get_absolute_url(self): return reverse('detail', kwargs={'cat_id': self.id}) def fed_for_today(self): return self.feeding_set.filter(date=date.today()).count()", "models.CharField(max_length=200) cat = models.ForeignKey(Cat, on_delete=models.CASCADE) def __str__(self): return f\"Photo for", "as ForeignKey (URL mapping, we use this to point to", "breed = models.CharField(max_length=100) description = models.TextField(max_length=250) age = models.IntegerField() toys", "reverse from datetime import date from django.contrib.auth.models import User #!", "max_length=1, choices=MEALS, default=MEALS[0][0] ) cat = models.ForeignKey(Cat, on_delete=models.CASCADE) def __str__(self):", "models.CharField(max_length=100) breed = models.CharField(max_length=100) description = models.TextField(max_length=250) age = models.IntegerField()", "import reverse from datetime import date from django.contrib.auth.models import User", "self.name def get_absolute_url(self): return reverse('toys_detail', kwargs={'pk': self.id}) class Cat(models.Model): name", "use this to point to our class based views) def", "return f\"{self.get_meal_display()} on {self.date}\" # change the default sort class", "based views) def __str__(self): return self.name def get_absolute_url(self): return reverse('detail',", "models.CharField( max_length=1, choices=MEALS, default=MEALS[0][0] ) cat = models.ForeignKey(Cat, on_delete=models.CASCADE) def", "choices=MEALS, default=MEALS[0][0] ) cat = models.ForeignKey(Cat, on_delete=models.CASCADE) def __str__(self): #", "from django.db import models from django.urls import reverse from datetime", "meal = models.CharField( max_length=1, choices=MEALS, default=MEALS[0][0] ) cat = models.ForeignKey(Cat,", "description = models.TextField(max_length=250) age = models.IntegerField() toys = models.ManyToManyField(Toy) user", "def get_absolute_url(self): return reverse('toys_detail', kwargs={'pk': self.id}) class Cat(models.Model): name =", "Feeding(models.Model): date = models.DateField('feeding date') meal = models.CharField( max_length=1, choices=MEALS,", "models.ForeignKey(Cat, on_delete=models.CASCADE) def __str__(self): # Nice method for obtaining the", "on {self.date}\" # change the default sort class Meta: ordering", "import date from django.contrib.auth.models import User #! 1 - Import", "self.id}) def fed_for_today(self): return self.feeding_set.filter(date=date.today()).count() >= len(MEALS) class Feeding(models.Model): date", "our class based views) def __str__(self): return self.name def get_absolute_url(self):", "'Lunch'), ('D', 'Dinner') ) class Toy(models.Model): name = models.CharField(max_length=50) color", "a Field.choice return f\"{self.get_meal_display()} on {self.date}\" # change the default", "['-date'] class Photo(models.Model): url = models.CharField(max_length=200) cat = models.ForeignKey(Cat, on_delete=models.CASCADE)", "on_delete=models.CASCADE) #+ 1.1 - Add user as ForeignKey (URL mapping,", "return self.name def get_absolute_url(self): return reverse('detail', kwargs={'cat_id': self.id}) def fed_for_today(self):", "url = models.CharField(max_length=200) cat = models.ForeignKey(Cat, on_delete=models.CASCADE) def __str__(self): return", "= models.TextField(max_length=250) age = models.IntegerField() toys = models.ManyToManyField(Toy) user =", "user as ForeignKey (URL mapping, we use this to point", "cat = models.ForeignKey(Cat, on_delete=models.CASCADE) def __str__(self): # Nice method for", "Cat(models.Model): name = models.CharField(max_length=100) breed = models.CharField(max_length=100) description = models.TextField(max_length=250)", "('D', 'Dinner') ) class Toy(models.Model): name = models.CharField(max_length=50) color =", "name = models.CharField(max_length=100) breed = models.CharField(max_length=100) description = models.TextField(max_length=250) age", "Photo(models.Model): url = models.CharField(max_length=200) cat = models.ForeignKey(Cat, on_delete=models.CASCADE) def __str__(self):", "= models.ManyToManyField(Toy) user = models.ForeignKey(User, on_delete=models.CASCADE) #+ 1.1 - Add", "= models.ForeignKey(Cat, on_delete=models.CASCADE) def __str__(self): # Nice method for obtaining", "return self.name def get_absolute_url(self): return reverse('toys_detail', kwargs={'pk': self.id}) class Cat(models.Model):", "self.name def get_absolute_url(self): return reverse('detail', kwargs={'cat_id': self.id}) def fed_for_today(self): return", "of a Field.choice return f\"{self.get_meal_display()} on {self.date}\" # change the", "= models.CharField(max_length=100) description = models.TextField(max_length=250) age = models.IntegerField() toys =", "self.id}) class Cat(models.Model): name = models.CharField(max_length=100) breed = models.CharField(max_length=100) description", "django.db import models from django.urls import reverse from datetime import", "models.ForeignKey(User, on_delete=models.CASCADE) #+ 1.1 - Add user as ForeignKey (URL", "kwargs={'cat_id': self.id}) def fed_for_today(self): return self.feeding_set.filter(date=date.today()).count() >= len(MEALS) class Feeding(models.Model):", "'Breakfast'), ('L', 'Lunch'), ('D', 'Dinner') ) class Toy(models.Model): name =", "method for obtaining the friendly value of a Field.choice return", "default sort class Meta: ordering = ['-date'] class Photo(models.Model): url", "( ('B', 'Breakfast'), ('L', 'Lunch'), ('D', 'Dinner') ) class Toy(models.Model):", "django.contrib.auth.models import User #! 1 - Import user models MEALS", "<filename>Exercises/W08D04_Exercise_01_Django_Cat_Collector/main_app/models.py from django.db import models from django.urls import reverse from", "__str__(self): # Nice method for obtaining the friendly value of", "Meta: ordering = ['-date'] class Photo(models.Model): url = models.CharField(max_length=200) cat", "= models.CharField(max_length=100) breed = models.CharField(max_length=100) description = models.TextField(max_length=250) age =", "def fed_for_today(self): return self.feeding_set.filter(date=date.today()).count() >= len(MEALS) class Feeding(models.Model): date =", "return self.feeding_set.filter(date=date.today()).count() >= len(MEALS) class Feeding(models.Model): date = models.DateField('feeding date')", "{self.date}\" # change the default sort class Meta: ordering =", "date from django.contrib.auth.models import User #! 1 - Import user", "models from django.urls import reverse from datetime import date from", "friendly value of a Field.choice return f\"{self.get_meal_display()} on {self.date}\" #", "models.CharField(max_length=50) color = models.CharField(max_length=20) def __str__(self): return self.name def get_absolute_url(self):", "value of a Field.choice return f\"{self.get_meal_display()} on {self.date}\" # change", "toys = models.ManyToManyField(Toy) user = models.ForeignKey(User, on_delete=models.CASCADE) #+ 1.1 -", "#+ 1.1 - Add user as ForeignKey (URL mapping, we", "on_delete=models.CASCADE) def __str__(self): # Nice method for obtaining the friendly", "name = models.CharField(max_length=50) color = models.CharField(max_length=20) def __str__(self): return self.name", "= models.ForeignKey(Cat, on_delete=models.CASCADE) def __str__(self): return f\"Photo for cat_id: {self.cat_id}", "= models.CharField( max_length=1, choices=MEALS, default=MEALS[0][0] ) cat = models.ForeignKey(Cat, on_delete=models.CASCADE)", "date') meal = models.CharField( max_length=1, choices=MEALS, default=MEALS[0][0] ) cat =", "= models.CharField(max_length=200) cat = models.ForeignKey(Cat, on_delete=models.CASCADE) def __str__(self): return f\"Photo", "models.ForeignKey(Cat, on_delete=models.CASCADE) def __str__(self): return f\"Photo for cat_id: {self.cat_id} @{self.url}\"", "f\"{self.get_meal_display()} on {self.date}\" # change the default sort class Meta:", "self.feeding_set.filter(date=date.today()).count() >= len(MEALS) class Feeding(models.Model): date = models.DateField('feeding date') meal", "= models.CharField(max_length=20) def __str__(self): return self.name def get_absolute_url(self): return reverse('toys_detail',", "__str__(self): return self.name def get_absolute_url(self): return reverse('toys_detail', kwargs={'pk': self.id}) class", "user = models.ForeignKey(User, on_delete=models.CASCADE) #+ 1.1 - Add user as", "return reverse('toys_detail', kwargs={'pk': self.id}) class Cat(models.Model): name = models.CharField(max_length=100) breed", "= models.ForeignKey(User, on_delete=models.CASCADE) #+ 1.1 - Add user as ForeignKey", "get_absolute_url(self): return reverse('toys_detail', kwargs={'pk': self.id}) class Cat(models.Model): name = models.CharField(max_length=100)", "1 - Import user models MEALS = ( ('B', 'Breakfast'),", "point to our class based views) def __str__(self): return self.name", "obtaining the friendly value of a Field.choice return f\"{self.get_meal_display()} on", "datetime import date from django.contrib.auth.models import User #! 1 -", "class based views) def __str__(self): return self.name def get_absolute_url(self): return", "('L', 'Lunch'), ('D', 'Dinner') ) class Toy(models.Model): name = models.CharField(max_length=50)", "kwargs={'pk': self.id}) class Cat(models.Model): name = models.CharField(max_length=100) breed = models.CharField(max_length=100)", "ordering = ['-date'] class Photo(models.Model): url = models.CharField(max_length=200) cat =", "for obtaining the friendly value of a Field.choice return f\"{self.get_meal_display()}", "Import user models MEALS = ( ('B', 'Breakfast'), ('L', 'Lunch'),", "age = models.IntegerField() toys = models.ManyToManyField(Toy) user = models.ForeignKey(User, on_delete=models.CASCADE)", "change the default sort class Meta: ordering = ['-date'] class", "color = models.CharField(max_length=20) def __str__(self): return self.name def get_absolute_url(self): return", "import User #! 1 - Import user models MEALS =", "# change the default sort class Meta: ordering = ['-date']", "ForeignKey (URL mapping, we use this to point to our", "class Feeding(models.Model): date = models.DateField('feeding date') meal = models.CharField( max_length=1,", "models.DateField('feeding date') meal = models.CharField( max_length=1, choices=MEALS, default=MEALS[0][0] ) cat", "__str__(self): return self.name def get_absolute_url(self): return reverse('detail', kwargs={'cat_id': self.id}) def", "- Add user as ForeignKey (URL mapping, we use this", "mapping, we use this to point to our class based" ]
[ "Kedro plugin for running a project with Airflow \"\"\" __version__", "for running a project with Airflow \"\"\" __version__ = \"0.5.0\"", "plugin for running a project with Airflow \"\"\" __version__ =", "<gh_stars>1-10 \"\"\" Kedro plugin for running a project with Airflow", "\"\"\" Kedro plugin for running a project with Airflow \"\"\"" ]
[ "import constants import time import math ## This isn't a", "class DebugWindowEvaluator(play.Play): def __init__(self): super().__init__(continuous=True) self.add_transition(behavior.Behavior.State.start, behavior.Behavior.State.running, lambda: True, 'immediately')", "__init__(self): super().__init__(continuous=True) self.add_transition(behavior.Behavior.State.start, behavior.Behavior.State.running, lambda: True, 'immediately') def execute_running(self): win_eval", "play, but it's pretty useful # Turn it on and", "import play import behavior import main import robocup import constants", "on-screen from the ball to our goal class DebugWindowEvaluator(play.Play): def", "we'll draw the window evaluator stuff on-screen from the ball", "import robocup import constants import time import math ## This", "robocup import constants import time import math ## This isn't", "useful # Turn it on and we'll draw the window", "Turn it on and we'll draw the window evaluator stuff", "on and we'll draw the window evaluator stuff on-screen from", "behavior.Behavior.State.running, lambda: True, 'immediately') def execute_running(self): win_eval = robocup.WindowEvaluator(main.context()) win_eval.debug", "def execute_running(self): win_eval = robocup.WindowEvaluator(main.context()) win_eval.debug = True windows, best", "## This isn't a real play, but it's pretty useful", "it on and we'll draw the window evaluator stuff on-screen", "import behavior import main import robocup import constants import time", "the ball to our goal class DebugWindowEvaluator(play.Play): def __init__(self): super().__init__(continuous=True)", "super().__init__(continuous=True) self.add_transition(behavior.Behavior.State.start, behavior.Behavior.State.running, lambda: True, 'immediately') def execute_running(self): win_eval =", "win_eval = robocup.WindowEvaluator(main.context()) win_eval.debug = True windows, best = win_eval.eval_pt_to_our_goal(main.ball().pos)", "isn't a real play, but it's pretty useful # Turn", "DebugWindowEvaluator(play.Play): def __init__(self): super().__init__(continuous=True) self.add_transition(behavior.Behavior.State.start, behavior.Behavior.State.running, lambda: True, 'immediately') def", "behavior import main import robocup import constants import time import", "ball to our goal class DebugWindowEvaluator(play.Play): def __init__(self): super().__init__(continuous=True) self.add_transition(behavior.Behavior.State.start,", "goal class DebugWindowEvaluator(play.Play): def __init__(self): super().__init__(continuous=True) self.add_transition(behavior.Behavior.State.start, behavior.Behavior.State.running, lambda: True,", "execute_running(self): win_eval = robocup.WindowEvaluator(main.context()) win_eval.debug = True windows, best =", "This isn't a real play, but it's pretty useful #", "our goal class DebugWindowEvaluator(play.Play): def __init__(self): super().__init__(continuous=True) self.add_transition(behavior.Behavior.State.start, behavior.Behavior.State.running, lambda:", "but it's pretty useful # Turn it on and we'll", "to our goal class DebugWindowEvaluator(play.Play): def __init__(self): super().__init__(continuous=True) self.add_transition(behavior.Behavior.State.start, behavior.Behavior.State.running,", "evaluator stuff on-screen from the ball to our goal class", "window evaluator stuff on-screen from the ball to our goal", "constants import time import math ## This isn't a real", "stuff on-screen from the ball to our goal class DebugWindowEvaluator(play.Play):", "draw the window evaluator stuff on-screen from the ball to", "# Turn it on and we'll draw the window evaluator", "def __init__(self): super().__init__(continuous=True) self.add_transition(behavior.Behavior.State.start, behavior.Behavior.State.running, lambda: True, 'immediately') def execute_running(self):", "'immediately') def execute_running(self): win_eval = robocup.WindowEvaluator(main.context()) win_eval.debug = True windows,", "play import behavior import main import robocup import constants import", "from the ball to our goal class DebugWindowEvaluator(play.Play): def __init__(self):", "import time import math ## This isn't a real play,", "True, 'immediately') def execute_running(self): win_eval = robocup.WindowEvaluator(main.context()) win_eval.debug = True", "the window evaluator stuff on-screen from the ball to our", "real play, but it's pretty useful # Turn it on", "<reponame>AniruddhaG123/robocup-software import play import behavior import main import robocup import", "import math ## This isn't a real play, but it's", "a real play, but it's pretty useful # Turn it", "self.add_transition(behavior.Behavior.State.start, behavior.Behavior.State.running, lambda: True, 'immediately') def execute_running(self): win_eval = robocup.WindowEvaluator(main.context())", "math ## This isn't a real play, but it's pretty", "time import math ## This isn't a real play, but", "it's pretty useful # Turn it on and we'll draw", "main import robocup import constants import time import math ##", "pretty useful # Turn it on and we'll draw the", "import main import robocup import constants import time import math", "and we'll draw the window evaluator stuff on-screen from the", "lambda: True, 'immediately') def execute_running(self): win_eval = robocup.WindowEvaluator(main.context()) win_eval.debug =" ]
[ "a metallicity into a PHOENIX-style string. Parameters ---------- Z :", "\"\"\" Convert a metallicity into a PHOENIX-style string. Parameters ----------", "for solar) \"\"\" if Z <= 0: return \"-{:03.1f}\".format(np.abs(Z)) else:", ": float [Fe/H]-style metallicity (= 0.0 for solar) \"\"\" if", "solar) \"\"\" if Z <= 0: return \"-{:03.1f}\".format(np.abs(Z)) else: return", "...imports import * def stringify_metallicity(Z): \"\"\" Convert a metallicity into", "0.0 for solar) \"\"\" if Z <= 0: return \"-{:03.1f}\".format(np.abs(Z))", "Parameters ---------- Z : float [Fe/H]-style metallicity (= 0.0 for", "into a PHOENIX-style string. Parameters ---------- Z : float [Fe/H]-style", "def stringify_metallicity(Z): \"\"\" Convert a metallicity into a PHOENIX-style string.", "PHOENIX-style string. Parameters ---------- Z : float [Fe/H]-style metallicity (=", "import * def stringify_metallicity(Z): \"\"\" Convert a metallicity into a", "a PHOENIX-style string. Parameters ---------- Z : float [Fe/H]-style metallicity", "Convert a metallicity into a PHOENIX-style string. Parameters ---------- Z", "\"\"\" if Z <= 0: return \"-{:03.1f}\".format(np.abs(Z)) else: return \"+{:03.1f}\".format(Z)", "metallicity (= 0.0 for solar) \"\"\" if Z <= 0:", "from ...imports import * def stringify_metallicity(Z): \"\"\" Convert a metallicity", "stringify_metallicity(Z): \"\"\" Convert a metallicity into a PHOENIX-style string. Parameters", "Z : float [Fe/H]-style metallicity (= 0.0 for solar) \"\"\"", "* def stringify_metallicity(Z): \"\"\" Convert a metallicity into a PHOENIX-style", "float [Fe/H]-style metallicity (= 0.0 for solar) \"\"\" if Z", "(= 0.0 for solar) \"\"\" if Z <= 0: return", "---------- Z : float [Fe/H]-style metallicity (= 0.0 for solar)", "string. Parameters ---------- Z : float [Fe/H]-style metallicity (= 0.0", "[Fe/H]-style metallicity (= 0.0 for solar) \"\"\" if Z <=", "metallicity into a PHOENIX-style string. Parameters ---------- Z : float" ]
[ "__init__(self, **kwargs): self._completed_at = kwargs.get('completed_at') self._type = kwargs.get('type') self._symbol =", "return False if self.amount != other.amount: return False return True", "def __init__(self, **kwargs): self._completed_at = kwargs.get('completed_at') self._type = kwargs.get('type') self._symbol", "kwargs.get('amount') def __eq__(self, other): if self.completed_at != other.completed_at: return False", "other.symbol: return False if self.price != other.price: return False if", "if self.price != other.price: return False if self.amount != other.amount:", "value): self._completed_at = value @property def type(self): return self._type @type.setter", "False return True def get_cn_type(self): return u'买入' if self.type ==", "return self._type @type.setter def type(self, value): self._type = value @property", "@property def type(self): return self._type @type.setter def type(self, value): self._type", "@property def completed_at(self): return self._completed_at @completed_at.setter def completed_at(self, value): self._completed_at", "return self._completed_at @completed_at.setter def completed_at(self, value): self._completed_at = value @property", "= value @property def amount(self): return self._amount @amount.setter def amount(self,", "return True def get_cn_type(self): return u'买入' if self.type == 'BUY'", "'BUY' else u'卖出' @property def completed_at(self): return self._completed_at @completed_at.setter def", "= kwargs.get('amount') def __eq__(self, other): if self.completed_at != other.completed_at: return", "type(self, value): self._type = value @property def symbol(self): return self._symbol", "return self._price @price.setter def price(self, value): self._price = value @property", "other): if self.completed_at != other.completed_at: return False if self.type !=", "def symbol(self): return self._symbol @symbol.setter def symbol(self, value): self._symbol =", "if self.completed_at != other.completed_at: return False if self.type != other.type:", "self._price = value @property def amount(self): return self._amount @amount.setter def", "return False if self.price != other.price: return False if self.amount", "if self.type == 'BUY' else u'卖出' @property def completed_at(self): return", "= kwargs.get('price') self._amount = kwargs.get('amount') def __eq__(self, other): if self.completed_at", "def completed_at(self): return self._completed_at @completed_at.setter def completed_at(self, value): self._completed_at =", "if self.symbol != other.symbol: return False if self.price != other.price:", "self._amount = kwargs.get('amount') def __eq__(self, other): if self.completed_at != other.completed_at:", "Transaction(object): def __init__(self, **kwargs): self._completed_at = kwargs.get('completed_at') self._type = kwargs.get('type')", "False if self.symbol != other.symbol: return False if self.price !=", "def symbol(self, value): self._symbol = value @property def price(self): return", "self._price @price.setter def price(self, value): self._price = value @property def", "symbol(self, value): self._symbol = value @property def price(self): return self._price", "!= other.symbol: return False if self.price != other.price: return False", "!= other.type: return False if self.symbol != other.symbol: return False", "u'卖出' @property def completed_at(self): return self._completed_at @completed_at.setter def completed_at(self, value):", "other.amount: return False return True def get_cn_type(self): return u'买入' if", "@property def price(self): return self._price @price.setter def price(self, value): self._price", "value): self._symbol = value @property def price(self): return self._price @price.setter", "class Transaction(object): def __init__(self, **kwargs): self._completed_at = kwargs.get('completed_at') self._type =", "self._type = kwargs.get('type') self._symbol = kwargs.get('symbol') self._price = kwargs.get('price') self._amount", "self._type = value @property def symbol(self): return self._symbol @symbol.setter def", "self.price != other.price: return False if self.amount != other.amount: return", "def completed_at(self, value): self._completed_at = value @property def type(self): return", "value @property def price(self): return self._price @price.setter def price(self, value):", "price(self, value): self._price = value @property def amount(self): return self._amount", "value @property def type(self): return self._type @type.setter def type(self, value):", "def type(self, value): self._type = value @property def symbol(self): return", "def type(self): return self._type @type.setter def type(self, value): self._type =", "if self.type != other.type: return False if self.symbol != other.symbol:", "True def get_cn_type(self): return u'买入' if self.type == 'BUY' else", "value @property def amount(self): return self._amount @amount.setter def amount(self, value):", "self._symbol = kwargs.get('symbol') self._price = kwargs.get('price') self._amount = kwargs.get('amount') def", "return self._symbol @symbol.setter def symbol(self, value): self._symbol = value @property", "-*- class Transaction(object): def __init__(self, **kwargs): self._completed_at = kwargs.get('completed_at') self._type", "coding: utf-8 -*- class Transaction(object): def __init__(self, **kwargs): self._completed_at =", "if self.amount != other.amount: return False return True def get_cn_type(self):", "!= other.amount: return False return True def get_cn_type(self): return u'买入'", "value @property def symbol(self): return self._symbol @symbol.setter def symbol(self, value):", "self._symbol = value @property def price(self): return self._price @price.setter def", "self.type != other.type: return False if self.symbol != other.symbol: return", "@property def symbol(self): return self._symbol @symbol.setter def symbol(self, value): self._symbol", "price(self): return self._price @price.setter def price(self, value): self._price = value", "def price(self): return self._price @price.setter def price(self, value): self._price =", "False if self.price != other.price: return False if self.amount !=", "= value @property def price(self): return self._price @price.setter def price(self,", "self._completed_at = kwargs.get('completed_at') self._type = kwargs.get('type') self._symbol = kwargs.get('symbol') self._price", "False if self.amount != other.amount: return False return True def", "kwargs.get('completed_at') self._type = kwargs.get('type') self._symbol = kwargs.get('symbol') self._price = kwargs.get('price')", "utf-8 -*- class Transaction(object): def __init__(self, **kwargs): self._completed_at = kwargs.get('completed_at')", "kwargs.get('price') self._amount = kwargs.get('amount') def __eq__(self, other): if self.completed_at !=", "self._completed_at @completed_at.setter def completed_at(self, value): self._completed_at = value @property def", "= kwargs.get('symbol') self._price = kwargs.get('price') self._amount = kwargs.get('amount') def __eq__(self,", "symbol(self): return self._symbol @symbol.setter def symbol(self, value): self._symbol = value", "value): self._price = value @property def amount(self): return self._amount @amount.setter", "def __eq__(self, other): if self.completed_at != other.completed_at: return False if", "self.completed_at != other.completed_at: return False if self.type != other.type: return", "**kwargs): self._completed_at = kwargs.get('completed_at') self._type = kwargs.get('type') self._symbol = kwargs.get('symbol')", "return u'买入' if self.type == 'BUY' else u'卖出' @property def", "= value @property def type(self): return self._type @type.setter def type(self,", "!= other.completed_at: return False if self.type != other.type: return False", "-*- coding: utf-8 -*- class Transaction(object): def __init__(self, **kwargs): self._completed_at", "amount(self): return self._amount @amount.setter def amount(self, value): self._amount = value", "@type.setter def type(self, value): self._type = value @property def symbol(self):", "!= other.price: return False if self.amount != other.amount: return False", "self._completed_at = value @property def type(self): return self._type @type.setter def", "return False if self.type != other.type: return False if self.symbol", "__eq__(self, other): if self.completed_at != other.completed_at: return False if self.type", "other.completed_at: return False if self.type != other.type: return False if", "kwargs.get('type') self._symbol = kwargs.get('symbol') self._price = kwargs.get('price') self._amount = kwargs.get('amount')", "False if self.type != other.type: return False if self.symbol !=", "u'买入' if self.type == 'BUY' else u'卖出' @property def completed_at(self):", "type(self): return self._type @type.setter def type(self, value): self._type = value", "self._price = kwargs.get('price') self._amount = kwargs.get('amount') def __eq__(self, other): if", "== 'BUY' else u'卖出' @property def completed_at(self): return self._completed_at @completed_at.setter", "self.symbol != other.symbol: return False if self.price != other.price: return", "self._type @type.setter def type(self, value): self._type = value @property def", "self._symbol @symbol.setter def symbol(self, value): self._symbol = value @property def", "self.amount != other.amount: return False return True def get_cn_type(self): return", "def price(self, value): self._price = value @property def amount(self): return", "def amount(self): return self._amount @amount.setter def amount(self, value): self._amount =", "get_cn_type(self): return u'买入' if self.type == 'BUY' else u'卖出' @property", "completed_at(self): return self._completed_at @completed_at.setter def completed_at(self, value): self._completed_at = value", "@completed_at.setter def completed_at(self, value): self._completed_at = value @property def type(self):", "@price.setter def price(self, value): self._price = value @property def amount(self):", "@symbol.setter def symbol(self, value): self._symbol = value @property def price(self):", "= value @property def symbol(self): return self._symbol @symbol.setter def symbol(self,", "completed_at(self, value): self._completed_at = value @property def type(self): return self._type", "= kwargs.get('type') self._symbol = kwargs.get('symbol') self._price = kwargs.get('price') self._amount =", "self.type == 'BUY' else u'卖出' @property def completed_at(self): return self._completed_at", "return False if self.symbol != other.symbol: return False if self.price", "# -*- coding: utf-8 -*- class Transaction(object): def __init__(self, **kwargs):", "other.price: return False if self.amount != other.amount: return False return", "value): self._type = value @property def symbol(self): return self._symbol @symbol.setter", "kwargs.get('symbol') self._price = kwargs.get('price') self._amount = kwargs.get('amount') def __eq__(self, other):", "else u'卖出' @property def completed_at(self): return self._completed_at @completed_at.setter def completed_at(self,", "return False return True def get_cn_type(self): return u'买入' if self.type", "= kwargs.get('completed_at') self._type = kwargs.get('type') self._symbol = kwargs.get('symbol') self._price =", "@property def amount(self): return self._amount @amount.setter def amount(self, value): self._amount", "def get_cn_type(self): return u'买入' if self.type == 'BUY' else u'卖出'", "other.type: return False if self.symbol != other.symbol: return False if" ]
[ "= tf.constant(0.0, name='scale') with self.assertRaisesOpError('Argument `scale` must be positive.'): laplace", "2.0 scale_v = 3.0 x = np.array([2.5, 2.5, 4.0, 0.1,", "= sp_stats.laplace.cdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(cdf), expected_cdf) def testLaplaceLogCDF(self): batch_size =", "= tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.variance().shape, (3,)) expected_variances = sp_stats.laplace.var(loc_v, scale=scale_v)", "log_pdf = laplace.log_prob(x) log_pdf_values = self.evaluate(log_pdf) self.assertEqual(log_pdf.shape, (6, 2)) pdf", "testLaplaceFullyReparameterized(self): loc = tf.constant(4.0) scale = tf.constant(3.0) _, [grad_loc, grad_scale]", "err=0.02) self._assertIntegral(sample_vals[:, 1, 0], pdf_vals[:, 1, 0], err=0.02) self._assertIntegral(sample_vals[:, 1,", "rtol=0.05, atol=0.) self.assertTrue(self._kstest(loc_v, scale_v, sample_values)) def testLaplaceFullyReparameterized(self): loc = tf.constant(4.0)", "scale=np.array([[5., 5.], [6., 6.]])), sample_vals.mean(axis=0), rtol=0.05, atol=0.) self.assertAllClose( sp_stats.laplace.var([[7., 11.],", "2.0 (the \"License\"); # you may not use this file", "11, dtype=np.float32)]).T # 10 x 1 laplace = tfd.Laplace(loc=loc_v, scale=scale_v,", "= laplace.sample(n, seed=test_util.test_seed()) sample_values = self.evaluate(samples) self.assertEqual(samples.shape, (n,)) self.assertEqual(sample_values.shape, (n,))", "sp_stats.laplace.var(loc_bc, scale=scale_bc), rtol=0.10, atol=0.) fails = 0 trials = 0", "4.0]] * batch_size) loc_v = np.array([2.0, 4.0]) scale_v = np.array([3.0,", "tf.constant(1.0, name='loc') scale_v = tf.constant(0.0, name='scale') with self.assertRaisesOpError('Argument `scale` must", "= self.evaluate(pdf) self.assertEqual(pdf.shape, (6, 2)) expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v, scale=scale_v)", "0) total = 0 for k in sorted(s_p, key=lambda x:", "laplace.log_prob(x) log_pdf_values = self.evaluate(log_pdf) self.assertEqual(log_pdf.shape, (6, 2)) pdf = laplace.prob(x)", "self.evaluate( tf.concat( [[0., 1], samplers.uniform([10], minval=.1, maxval=.9, seed=test_util.test_seed())], axis=0)) d", "= tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.mode().shape, (3,)) self.assertAllClose(self.evaluate(laplace.mode()), loc_v) def testLaplaceVariance(self):", "* event_size] * batch_size, dtype=np.float32) a_scale = np.array([[0.1] * event_size]", "* event_size] * batch_size, dtype=np.float32) b_scale = np.array([[0.2] * event_size]", "self.assertAllClose(self.evaluate(cdf), expected_cdf) def testLaplaceLogCDF(self): batch_size = 6 loc = tf.constant([2.0]", "scale=scale, validate_args=True) sf = laplace.log_survival_function(x) self.assertEqual(sf.shape, (6,)) expected_sf = sp_stats.laplace.logsf(x,", "samples = laplace.sample(n, seed=test_util.test_seed()) sample_values = self.evaluate(samples) self.assertEqual(samples.shape, (n,)) self.assertEqual(sample_values.shape,", "scale=scale, validate_args=True) with tf.GradientTape() as tape: loss = -d.log_prob([1., 2.,", "x 1 laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) n = 10000", "(k[0] - prev[0]) * pair_pdf prev = k self.assertNear(1., total,", "= 3 a_loc = np.array([[0.5] * event_size] * batch_size, dtype=np.float32)", "4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.stddev().shape, (3,)) expected_stddev", "true_kl_, kl_, kl_sample_ = self.evaluate([true_kl, kl, kl_sample]) self.assertAllClose(true_kl_, kl_, atol=1e-5,", "-3.]) self.evaluate(scale.initializer) with self.assertRaisesOpError('Argument `scale` must be positive.'): d =", "6 loc = tf.constant([[2.0, 4.0]] * batch_size) scale = tf.constant(3.0)", "[[0., 1], samplers.uniform([10], minval=.1, maxval=.9, seed=test_util.test_seed())], axis=0)) d = tfd.Laplace(loc=1.,", "scale=scale_v) self.assertAllClose(log_pdf_values, expected_log_pdf) self.assertAllClose(pdf_values, np.exp(expected_log_pdf)) def testLaplaceLogPDFMultidimensionalBroadcasting(self): batch_size = 6", "expected_entropy) def testLaplaceSample(self): loc_v = 4.0 scale_v = 3.0 loc", "a) true_zero_kl_, zero_kl_ = self.evaluate([tf.zeros_like(true_kl), zero_kl]) self.assertAllEqual(true_zero_kl_, zero_kl_) @test_util.tf_tape_safety_test def", "= 10000 samples = laplace.sample(n, seed=test_util.test_seed()) sample_values = self.evaluate(samples) self.assertEqual(samples.shape,", "batch_size, dtype=np.float32) a_scale = np.array([[0.1] * event_size] * batch_size, dtype=np.float32)", "of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless", "= tfd.Laplace(loc=a_loc, scale=a_scale, validate_args=True) b = tfd.Laplace(loc=b_loc, scale=b_scale, validate_args=True) distance", "tf.constant(3.0) loc_v = np.array([2.0, 4.0]) scale_v = 3.0 x =", "self.assertAllClose(true_kl_, kl_, atol=1e-5, rtol=1e-5) self.assertAllClose(true_kl_, kl_sample_, atol=0., rtol=1e-1) zero_kl =", "x[0]): pair_pdf = (k[1] + prev[1]) / 2 total +=", "self.evaluate([tf.zeros_like(true_kl), zero_kl]) self.assertAllEqual(true_zero_kl_, zero_kl_) @test_util.tf_tape_safety_test def testGradientThroughParams(self): loc = tf.Variable([-5.,", "4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.mean().shape, (3,)) expected_means", "<reponame>wataruhashimoto52/probability # Copyright 2018 The TensorFlow Probability Authors. # #", "< 0.02 def testLaplacePdfOfSampleMultiDims(self): laplace = tfd.Laplace(loc=[7., 11.], scale=[[5.], [6.]],", "= tf.constant([2.0] * batch_size) scale = tf.constant([3.0] * batch_size) loc_v", "(num, 2, 2)) self._assertIntegral(sample_vals[:, 0, 0], pdf_vals[:, 0, 0], err=0.02)", "a_scale = np.array([[0.1] * event_size] * batch_size, dtype=np.float32) b_loc =", "2.0], dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) cdf = laplace.log_cdf(x)", "`scale` must be positive.'): laplace = tfd.Laplace( loc=loc_v, scale=scale_v, validate_args=True)", "tf.constant(4.0) scale = tf.constant(3.0) _, [grad_loc, grad_scale] = tfp.math.value_and_gradient( lambda", "= a.sample(int(1e4), seed=test_util.test_seed()) kl_sample = tf.reduce_mean(a.log_prob(x) - b.log_prob(x), axis=0) true_kl_,", "prev = k self.assertNear(1., total, err=err) def testLaplaceNonPositiveInitializationParamsRaises(self): loc_v =", "def testLaplaceLogCDF(self): batch_size = 6 loc = tf.constant([2.0] * batch_size)", "11.], scale=[[5.], [6.]], validate_args=True) num = 50000 samples = laplace.sample(num,", "class LaplaceTest(test_util.TestCase): def testLaplaceShape(self): loc = tf.constant([3.0] * 5) scale", "num = 50000 samples = laplace.sample(num, seed=test_util.test_seed()) pdfs = laplace.prob(samples)", "seed=test_util.test_seed()) sample_values = self.evaluate(samples) self.assertEqual(samples.shape, (n, 10, 100)) self.assertEqual(sample_values.shape, (n,", "= tfd.Laplace(loc=loc, scale=scale, validate_args=True) log_pdf = laplace.log_prob(x) self.assertEqual(log_pdf.shape, (6,)) expected_log_pdf", "d = tfd.Laplace(loc=0, scale=scale, validate_args=True) self.evaluate(d.sample(seed=test_util.test_seed())) def testLaplaceLaplaceKL(self): batch_size =", "tf.constant(11.0) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) self.assertEqual(self.evaluate(laplace.batch_shape_tensor()), (5,)) self.assertEqual(laplace.batch_shape, tf.TensorShape([5]))", "log_pdf = laplace.log_prob(x) self.assertEqual(log_pdf.shape, (6,)) expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v, scale=scale_v)", "# Copyright 2018 The TensorFlow Probability Authors. # # Licensed", "sp_stats.laplace.logpdf(x, loc_v, scale=scale_v) self.assertAllClose(log_pdf_values, expected_log_pdf) self.assertAllClose(pdf_values, np.exp(expected_log_pdf)) def testLaplaceCDF(self): batch_size", "validate_args=True) self.evaluate([v.initializer for v in d.variables]) with self.assertRaisesOpError('Argument `scale` must", "sample_vals.var(axis=0), rtol=0.05, atol=0.) def _assertIntegral(self, sample_vals, pdf_vals, err=1e-3): s_p =", "kl_sample]) self.assertAllClose(true_kl_, kl_, atol=1e-5, rtol=1e-5) self.assertAllClose(true_kl_, kl_sample_, atol=0., rtol=1e-1) zero_kl", "use this file except in compliance with the License. #", "validate_args=True) vals = d.quantile(qs) self.assertAllClose([-np.inf, np.inf], vals[:2]) self.assertAllClose(qs[2:], d.cdf(vals[2:])) def", "4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.variance().shape, (3,)) expected_variances", "scale=[[5.], [6.]], validate_args=True) num = 50000 samples = laplace.sample(num, seed=test_util.test_seed())", "= d.quantile(qs) self.assertAllClose([-np.inf, np.inf], vals[:2]) self.assertAllClose(qs[2:], d.cdf(vals[2:])) def testLaplaceLogSurvivalFunction(self): batch_size", "np from scipy import stats as sp_stats import tensorflow.compat.v2 as", "(3,)) expected_entropy = sp_stats.laplace.entropy(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.entropy()), expected_entropy) def testLaplaceSample(self): loc_v", "2018 The TensorFlow Probability Authors. # # Licensed under the", "0, 0], err=0.02) self._assertIntegral(sample_vals[:, 0, 1], pdf_vals[:, 0, 1], err=0.02)", "scale_v = np.array([1.0, 4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True)", "sp_stats.laplace.var(loc_v, scale=scale_v), rtol=0.05, atol=0.) self.assertTrue(self._kstest(loc_v, scale_v, sample_values)) def testLaplaceFullyReparameterized(self): loc", "with tf.GradientTape() as tape: loss = -d.log_prob([1., 2., 3.]) grad", "__future__ import division from __future__ import print_function # Dependency imports", "the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required", "scale_v = 3.0 x = np.array([-2.5, 2.5, -4.0, 0.1, 1.0,", "dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) log_pdf = laplace.log_prob(x) self.assertEqual(log_pdf.shape,", "1 laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) n = 10000 samples", "the Kolmogorov-Smirnov test for goodness of fit. ks, _ =", "- b_loc) ratio = a_scale / b_scale true_kl = (-tf.math.log(ratio)", "self.assertAllNotNone(grad) def testAssertsPositiveScaleAfterMutation(self): scale = tf.Variable([1., 2., 3.]) d =", "def testAssertParamsAreFloats(self): loc = tf.convert_to_tensor(0, dtype=tf.int32) scale = tf.convert_to_tensor(1, dtype=tf.int32)", "0.1, 1.0, 2.0]], dtype=np.float32).T laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) log_pdf", "License. # You may obtain a copy of the License", "laplace = tfd.Laplace(loc=[7., 11.], scale=[[5.], [6.]], validate_args=True) num = 50000", "[]) self.assertEqual(laplace.event_shape, tf.TensorShape([])) def testLaplaceLogPDF(self): batch_size = 6 loc =", "[6., 6.]])), sample_vals.mean(axis=0), rtol=0.05, atol=0.) self.assertAllClose( sp_stats.laplace.var([[7., 11.], [7., 11.]],", "validate_args=True) with tf.GradientTape() as tape: loss = -d.log_prob([1., 2., 3.])", "loc_v = tf.constant(1.0, name='loc') scale_v = tf.constant(0.0, name='scale') with self.assertRaisesOpError('Argument", "for bi, b in enumerate(np.reshape(scale_v, [-1])): s = sample_values[:, bi,", "def testLaplaceSample(self): loc_v = 4.0 scale_v = 3.0 loc =", "= np.array([1.0, 4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.variance().shape,", "name='scale') with self.assertRaisesOpError('Argument `scale` must be positive.'): laplace = tfd.Laplace(", "loc_v = 4.0 scale_v = 3.0 loc = tf.constant(loc_v) scale", "0], err=0.02) self._assertIntegral(sample_vals[:, 0, 1], pdf_vals[:, 0, 1], err=0.02) self._assertIntegral(sample_vals[:,", "under the License is distributed on an \"AS IS\" BASIS,", "= tfp.math.value_and_gradient( lambda l, s: tfd.Laplace(loc=l, scale=s, validate_args=True).sample( # pylint:", "self.assertAllClose(self.evaluate(log_pdf), expected_log_pdf) pdf = laplace.prob(x) self.assertEqual(pdf.shape, (6,)) self.assertAllClose(self.evaluate(pdf), np.exp(expected_log_pdf)) def", "3.0 x = np.array([2.5, 2.5, 4.0, 0.1, 1.0, 2.0], dtype=np.float32)", "License for the specific language governing permissions and # limitations", "= sp_stats.laplace.logpdf(x, loc_v, scale=scale_v) self.assertAllClose(log_pdf_values, expected_log_pdf) self.assertAllClose(pdf_values, np.exp(expected_log_pdf)) def testLaplaceCDF(self):", "positive.'): with tf.control_dependencies([scale.assign([1., 2., -3.])]): self.evaluate(tfd.Laplace(loc=0., scale=1.).kl_divergence(d)) def testAssertParamsAreFloats(self): loc", "tf.constant([2.0] * batch_size) scale = tf.constant([3.0] * batch_size) loc_v =", "sp_stats.laplace.std(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.stddev()), expected_stddev) def testLaplaceEntropy(self): loc_v = np.array([1.0, 3.0,", "stats as sp_stats import tensorflow.compat.v2 as tf import tensorflow_probability as", "scale=scale, validate_args=True) cdf = laplace.cdf(x) self.assertEqual(cdf.shape, (6,)) expected_cdf = sp_stats.laplace.cdf(x,", "# Dependency imports import numpy as np from scipy import", "tf.constant([3.0] * 5) scale = tf.constant(11.0) laplace = tfd.Laplace(loc=loc, scale=scale,", "dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) cdf = laplace.cdf(x) self.assertEqual(cdf.shape,", "= laplace.cdf(x) self.assertEqual(cdf.shape, (6,)) expected_cdf = sp_stats.laplace.cdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(cdf),", "cdf = laplace.log_cdf(x) self.assertEqual(cdf.shape, (6,)) expected_cdf = sp_stats.laplace.logcdf(x, loc_v, scale=scale_v)", "-d.log_prob([1., 2., 3.]) grad = tape.gradient(loss, d.trainable_variables) self.assertLen(grad, 2) self.assertAllNotNone(grad)", "= tfd.Laplace(loc=loc, scale=scale, validate_args=True) sf = laplace.log_survival_function(x) self.assertEqual(sf.shape, (6,)) expected_sf", "expected_stddev = sp_stats.laplace.std(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.stddev()), expected_stddev) def testLaplaceEntropy(self): loc_v =", "self.assertEqual(cdf.shape, (6,)) expected_cdf = sp_stats.laplace.cdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(cdf), expected_cdf) def", "x 100 loc_bc = loc_v + zeros scale_bc = scale_v", "passes. return ks < 0.02 def testLaplacePdfOfSampleMultiDims(self): laplace = tfd.Laplace(loc=[7.,", "expected_entropy = sp_stats.laplace.entropy(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.entropy()), expected_entropy) def testLaplaceSample(self): loc_v =", "+ ratio * tf.exp(-distance / a_scale)) kl = tfd.kl_divergence(a, b)", "x = np.array([-2.5, 2.5, -4.0, 0.1, 1.0, 2.0], dtype=np.float32) laplace", "pylint: disable=g-long-lambda 100, seed=test_util.test_seed()), [loc, scale]) self.assertIsNotNone(grad_loc) self.assertIsNotNone(grad_scale) def testLaplaceSampleMultiDimensional(self):", "1.0, 2.0], dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) sf =", "bi, b in enumerate(np.reshape(scale_v, [-1])): s = sample_values[:, bi, ai]", "expected_log_pdf) self.assertAllClose(pdf_values, np.exp(expected_log_pdf)) def testLaplaceCDF(self): batch_size = 6 loc =", "tfd.Laplace(loc=loc, scale=scale, validate_args=True) sf = laplace.log_survival_function(x) self.assertEqual(sf.shape, (6,)) expected_sf =", "# Uses the Kolmogorov-Smirnov test for goodness of fit. ks,", "true_kl = (-tf.math.log(ratio) - 1 + distance / b_scale +", "= tfd.Laplace(loc=loc, scale=scale, validate_args=True) cdf = laplace.cdf(x) self.assertEqual(cdf.shape, (6,)) expected_cdf", "loc = tf.constant(4.0) scale = tf.constant(3.0) _, [grad_loc, grad_scale] =", "= tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.mean().shape, (3,)) expected_means = sp_stats.laplace.mean(loc_v, scale=scale_v)", "= np.array([-2.5, 2.5, -4.0, 0.1, 1.0, 2.0], dtype=np.float32) laplace =", "validate_args=True) samples = laplace.sample(n, seed=test_util.test_seed()) sample_values = self.evaluate(samples) self.assertEqual(samples.shape, (n,))", "sp_stats.kstest(samples, sp_stats.laplace(loc, scale=scale).cdf) # Return True when the test passes.", "self.assertEqual(log_pdf.shape, (6,)) expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(log_pdf), expected_log_pdf) pdf", "from __future__ import absolute_import from __future__ import division from __future__", "101, dtype=np.float32)]) # 1 x 100 scale_v = np.array([np.arange(1, 11,", "goodness of fit. ks, _ = sp_stats.kstest(samples, sp_stats.laplace(loc, scale=scale).cdf) #", "in compliance with the License. # You may obtain a", "sample_values = self.evaluate(samples) self.assertEqual(samples.shape, (n,)) self.assertEqual(sample_values.shape, (n,)) self.assertAllClose( sample_values.mean(), sp_stats.laplace.mean(loc_v,", "software # distributed under the License is distributed on an", "import tensorflow.compat.v2 as tf import tensorflow_probability as tfp from tensorflow_probability.python.internal", "2 total += (k[0] - prev[0]) * pair_pdf prev =", "testLaplaceMean(self): loc_v = np.array([1.0, 3.0, 2.5]) scale_v = np.array([1.0, 4.0,", "TensorFlow Probability Authors. # # Licensed under the Apache License,", "a in enumerate(np.reshape(loc_v, [-1])): for bi, b in enumerate(np.reshape(scale_v, [-1])):", "s) else 1 self.assertLess(fails, trials * 0.03) def _kstest(self, loc,", "__future__ import print_function # Dependency imports import numpy as np", "laplace.sample(n, seed=test_util.test_seed()) sample_values = self.evaluate(samples) self.assertEqual(samples.shape, (n,)) self.assertEqual(sample_values.shape, (n,)) self.assertAllClose(", "axis=0)) d = tfd.Laplace(loc=1., scale=1.3, validate_args=True) vals = d.quantile(qs) self.assertAllClose([-np.inf,", "prev = (0, 0) total = 0 for k in", "import print_function # Dependency imports import numpy as np from", "testLaplaceVariance(self): loc_v = np.array([1.0, 3.0, 2.5]) scale_v = np.array([1.0, 4.0,", "b in enumerate(np.reshape(scale_v, [-1])): s = sample_values[:, bi, ai] trials", "from __future__ import print_function # Dependency imports import numpy as", "the License. # ============================================================================ from __future__ import absolute_import from __future__", "2.0], dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) cdf = laplace.cdf(x)", "* 5) scale = tf.constant(11.0) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True)", "tf.constant(0.0, name='loc') scale_v = tf.constant(-1.0, name='scale') with self.assertRaisesOpError('Argument `scale` must", "from tensorflow_probability.python.internal import test_util tfd = tfp.distributions @test_util.test_all_tf_execution_regimes class LaplaceTest(test_util.TestCase):", "self.assertEqual(samples.shape, (num, 2, 2)) self.assertEqual(pdfs.shape, (num, 2, 2)) self._assertIntegral(sample_vals[:, 0,", "as tape: loss = -d.log_prob([1., 2., 3.]) grad = tape.gradient(loss,", "expected_cdf = sp_stats.laplace.cdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(cdf), expected_cdf) def testLaplaceLogCDF(self): batch_size", "sp_stats.laplace(loc, scale=scale).cdf) # Return True when the test passes. return", "= 2.0 scale_v = 3.0 x = np.array([-2.5, 2.5, -4.0,", "tfp.math.value_and_gradient( lambda l, s: tfd.Laplace(loc=l, scale=s, validate_args=True).sample( # pylint: disable=g-long-lambda", "zero_kl]) self.assertAllEqual(true_zero_kl_, zero_kl_) @test_util.tf_tape_safety_test def testGradientThroughParams(self): loc = tf.Variable([-5., 0.,", "Copyright 2018 The TensorFlow Probability Authors. # # Licensed under", "= tfd.Laplace(loc=loc, scale=scale, validate_args=True) log_pdf = laplace.log_prob(x) log_pdf_values = self.evaluate(log_pdf)", "= np.array([[0.1] * event_size] * batch_size, dtype=np.float32) b_loc = np.array([[0.4]", "Probability Authors. # # Licensed under the Apache License, Version", "as sp_stats import tensorflow.compat.v2 as tf import tensorflow_probability as tfp", "from tensorflow_probability.python.internal import samplers from tensorflow_probability.python.internal import test_util tfd =", "scale=scale_v) self.assertAllClose(self.evaluate(sf), expected_sf) def testLaplaceMean(self): loc_v = np.array([1.0, 3.0, 2.5])", "def testLaplaceStd(self): loc_v = np.array([1.0, 3.0, 2.5]) scale_v = np.array([1.0,", "scale_v = 3.0 loc = tf.constant(loc_v) scale = tf.constant(scale_v) n", "batch_size) loc_v = 2.0 scale_v = 3.0 x = np.array([2.5,", "(3,)) self.assertAllClose(self.evaluate(laplace.mode()), loc_v) def testLaplaceVariance(self): loc_v = np.array([1.0, 3.0, 2.5])", "(3,)) expected_means = sp_stats.laplace.mean(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.mean()), expected_means) def testLaplaceMode(self): loc_v", "expected_variances) def testLaplaceStd(self): loc_v = np.array([1.0, 3.0, 2.5]) scale_v =", "scale=scale).cdf) # Return True when the test passes. return ks", "tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) n = 10000 samples = laplace.sample(n, seed=test_util.test_seed())", "tfd.Laplace(loc=[7., 11.], scale=[[5.], [6.]], validate_args=True) num = 50000 samples =", "if self._kstest(a, b, s) else 1 self.assertLess(fails, trials * 0.03)", "scale_v) # 10 x 100 loc_bc = loc_v + zeros", "seed=test_util.test_seed())], axis=0)) d = tfd.Laplace(loc=1., scale=1.3, validate_args=True) vals = d.quantile(qs)", "testLaplaceLogCDF(self): batch_size = 6 loc = tf.constant([2.0] * batch_size) scale", "testLaplaceLaplaceKL(self): batch_size = 6 event_size = 3 a_loc = np.array([[0.5]", "= zip(sample_vals, pdf_vals) prev = (0, 0) total = 0", "scale = tf.Variable([1., 2., 3.]) d = tfd.Laplace(loc=0., scale=scale, validate_args=True)", "LaplaceTest(test_util.TestCase): def testLaplaceShape(self): loc = tf.constant([3.0] * 5) scale =", "n = 100000 laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) samples =", "laplace.cdf(x) self.assertEqual(cdf.shape, (6,)) expected_cdf = sp_stats.laplace.cdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(cdf), expected_cdf)", "as tfp from tensorflow_probability.python.internal import samplers from tensorflow_probability.python.internal import test_util", "v in d.variables]) with self.assertRaisesOpError('Argument `scale` must be positive.'): with", "ks < 0.02 def testLaplacePdfOfSampleMultiDims(self): laplace = tfd.Laplace(loc=[7., 11.], scale=[[5.],", "rtol=1e-1) zero_kl = tfd.kl_divergence(a, a) true_zero_kl_, zero_kl_ = self.evaluate([tf.zeros_like(true_kl), zero_kl])", "loc_v, scale=scale_v) self.assertAllClose(self.evaluate(cdf), expected_cdf) def testLaplaceLogCDF(self): batch_size = 6 loc", "= self.evaluate(samples) self.assertEqual(samples.shape, (n,)) self.assertEqual(sample_values.shape, (n,)) self.assertAllClose( sample_values.mean(), sp_stats.laplace.mean(loc_v, scale=scale_v),", "4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.mode().shape, (3,)) self.assertAllClose(self.evaluate(laplace.mode()),", "expected_log_pdf) self.assertAllClose(pdf_values, np.exp(expected_log_pdf)) def testLaplaceLogPDFMultidimensionalBroadcasting(self): batch_size = 6 loc =", "validate_args=True).sample( # pylint: disable=g-long-lambda 100, seed=test_util.test_seed()), [loc, scale]) self.assertIsNotNone(grad_loc) self.assertIsNotNone(grad_scale)", "= tfd.Laplace( loc=loc_v, scale=scale_v, validate_args=True) self.evaluate(laplace.mean()) scale = tf.Variable([1., 2.,", "of fit. ks, _ = sp_stats.kstest(samples, sp_stats.laplace(loc, scale=scale).cdf) # Return", "scale=scale_v) self.assertAllClose(self.evaluate(laplace.entropy()), expected_entropy) def testLaplaceSample(self): loc_v = 4.0 scale_v =", "+ zeros self.assertAllClose( sample_values.mean(axis=0), sp_stats.laplace.mean(loc_bc, scale=scale_bc), rtol=0.35, atol=0.) self.assertAllClose( sample_values.var(axis=0),", "with self.assertRaisesOpError('Argument `scale` must be positive.'): laplace = tfd.Laplace( loc=loc_v,", "OF ANY KIND, either express or implied. # See the", "WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", "loc_bc = loc_v + zeros scale_bc = scale_v + zeros", "zero_kl_ = self.evaluate([tf.zeros_like(true_kl), zero_kl]) self.assertAllEqual(true_zero_kl_, zero_kl_) @test_util.tf_tape_safety_test def testGradientThroughParams(self): loc", "ANY KIND, either express or implied. # See the License", "See the License for the specific language governing permissions and", "sp_stats import tensorflow.compat.v2 as tf import tensorflow_probability as tfp from", "0.1, 1.0, 2.0], dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) cdf", "zero_kl = tfd.kl_divergence(a, a) true_zero_kl_, zero_kl_ = self.evaluate([tf.zeros_like(true_kl), zero_kl]) self.assertAllEqual(true_zero_kl_,", "the License. # You may obtain a copy of the", "at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable", "for the specific language governing permissions and # limitations under", "from __future__ import division from __future__ import print_function # Dependency", "def testLaplaceLogSurvivalFunction(self): batch_size = 6 loc = tf.constant([2.0] * batch_size)", "0 trials = 0 for ai, a in enumerate(np.reshape(loc_v, [-1])):", "to in writing, software # distributed under the License is", "100)) zeros = np.zeros_like(loc_v + scale_v) # 10 x 100", "def testLaplaceNonPositiveInitializationParamsRaises(self): loc_v = tf.constant(0.0, name='loc') scale_v = tf.constant(-1.0, name='scale')", "(n, 10, 100)) zeros = np.zeros_like(loc_v + scale_v) # 10", "tf.Variable(2.) d = tfd.Laplace(loc=loc, scale=scale, validate_args=True) with tf.GradientTape() as tape:", "samples): # Uses the Kolmogorov-Smirnov test for goodness of fit.", "1], err=0.02) self.assertAllClose( sp_stats.laplace.mean( [[7., 11.], [7., 11.]], scale=np.array([[5., 5.],", "# See the License for the specific language governing permissions", "4.0, 0.1, 1.0, 2.0], dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True)", "validate_args=True) num = 50000 samples = laplace.sample(num, seed=test_util.test_seed()) pdfs =", "tfd.Laplace(loc=b_loc, scale=b_scale, validate_args=True) distance = tf.abs(a_loc - b_loc) ratio =", "1], err=0.02) self._assertIntegral(sample_vals[:, 1, 0], pdf_vals[:, 1, 0], err=0.02) self._assertIntegral(sample_vals[:,", "self.evaluate(log_pdf) self.assertEqual(log_pdf.shape, (6, 2)) pdf = laplace.prob(x) pdf_values = self.evaluate(pdf)", "language governing permissions and # limitations under the License. #", "testLaplaceEntropy(self): loc_v = np.array([1.0, 3.0, 2.5]) scale_v = np.array([1.0, 4.0,", "or agreed to in writing, software # distributed under the", "4.0]) x = np.array([[2.5, 2.5, 4.0, 0.1, 1.0, 2.0]], dtype=np.float32).T", "4.0]] * batch_size) scale = tf.constant(3.0) loc_v = np.array([2.0, 4.0])", "loc, scale, samples): # Uses the Kolmogorov-Smirnov test for goodness", "+= (k[0] - prev[0]) * pair_pdf prev = k self.assertNear(1.,", "validate_args=True) cdf = laplace.log_cdf(x) self.assertEqual(cdf.shape, (6,)) expected_cdf = sp_stats.laplace.logcdf(x, loc_v,", "required by applicable law or agreed to in writing, software", "= 2.0 scale_v = 3.0 x = np.array([2.5, 2.5, 4.0,", "self._kstest(a, b, s) else 1 self.assertLess(fails, trials * 0.03) def", "b_scale + ratio * tf.exp(-distance / a_scale)) kl = tfd.kl_divergence(a,", "_ = sp_stats.kstest(samples, sp_stats.laplace(loc, scale=scale).cdf) # Return True when the", "= tfd.kl_divergence(a, a) true_zero_kl_, zero_kl_ = self.evaluate([tf.zeros_like(true_kl), zero_kl]) self.assertAllEqual(true_zero_kl_, zero_kl_)", "6 loc = tf.constant([[2.0, 4.0]] * batch_size) scale = tf.constant([[3.0,", "self.assertAllClose(self.evaluate(laplace.stddev()), expected_stddev) def testLaplaceEntropy(self): loc_v = np.array([1.0, 3.0, 2.5]) scale_v", "BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either", "= laplace.prob(samples) sample_vals, pdf_vals = self.evaluate([samples, pdfs]) self.assertEqual(samples.shape, (num, 2,", "validate_args=True) cdf = laplace.cdf(x) self.assertEqual(cdf.shape, (6,)) expected_cdf = sp_stats.laplace.cdf(x, loc_v,", "tf.Variable([-5., 0., 5.]) scale = tf.Variable(2.) d = tfd.Laplace(loc=loc, scale=scale,", "with the License. # You may obtain a copy of", "self.evaluate([samples, pdfs]) self.assertEqual(samples.shape, (num, 2, 2)) self.assertEqual(pdfs.shape, (num, 2, 2))", "* batch_size, dtype=np.float32) b_scale = np.array([[0.2] * event_size] * batch_size,", "tf.concat( [[0., 1], samplers.uniform([10], minval=.1, maxval=.9, seed=test_util.test_seed())], axis=0)) d =", "tf.TensorShape([5])) self.assertAllEqual(self.evaluate(laplace.event_shape_tensor()), []) self.assertEqual(laplace.event_shape, tf.TensorShape([])) def testLaplaceLogPDF(self): batch_size = 6", "[7., 11.]], scale=np.array([[5., 5.], [6., 6.]])), sample_vals.var(axis=0), rtol=0.05, atol=0.) def", "cdf = laplace.cdf(x) self.assertEqual(cdf.shape, (6,)) expected_cdf = sp_stats.laplace.cdf(x, loc_v, scale=scale_v)", "0], pdf_vals[:, 1, 0], err=0.02) self._assertIntegral(sample_vals[:, 1, 1], pdf_vals[:, 1,", "# 10 x 1 laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) n", "6.]])), sample_vals.mean(axis=0), rtol=0.05, atol=0.) self.assertAllClose( sp_stats.laplace.var([[7., 11.], [7., 11.]], scale=np.array([[5.,", "* 0.03) def _kstest(self, loc, scale, samples): # Uses the", "0 for k in sorted(s_p, key=lambda x: x[0]): pair_pdf =", "np.exp(expected_log_pdf)) def testLaplaceLogPDFMultidimensionalBroadcasting(self): batch_size = 6 loc = tf.constant([[2.0, 4.0]]", "self.evaluate([v.initializer for v in d.variables]) with self.assertRaisesOpError('Argument `scale` must be", "sp_stats.laplace.entropy(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.entropy()), expected_entropy) def testLaplaceSample(self): loc_v = 4.0 scale_v", "vals = d.quantile(qs) self.assertAllClose([-np.inf, np.inf], vals[:2]) self.assertAllClose(qs[2:], d.cdf(vals[2:])) def testLaplaceLogSurvivalFunction(self):", "self.assertAllClose(self.evaluate(pdf), np.exp(expected_log_pdf)) def testLaplaceLogPDFMultidimensional(self): batch_size = 6 loc = tf.constant([[2.0,", "atol=0.) self.assertAllClose( sample_values.var(axis=0), sp_stats.laplace.var(loc_bc, scale=scale_bc), rtol=0.10, atol=0.) fails = 0", "compliance with the License. # You may obtain a copy", "bi, ai] trials += 1 fails += 0 if self._kstest(a,", "agreed to in writing, software # distributed under the License", "scale=scale, validate_args=True) self.evaluate([v.initializer for v in d.variables]) with self.assertRaisesOpError('Argument `scale`", "(6,)) expected_cdf = sp_stats.laplace.cdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(cdf), expected_cdf) def testLaplaceLogCDF(self):", "1], pdf_vals[:, 1, 1], err=0.02) self.assertAllClose( sp_stats.laplace.mean( [[7., 11.], [7.,", "= tf.constant(0.0, name='loc') scale_v = tf.constant(-1.0, name='scale') with self.assertRaisesOpError('Argument `scale`", "-4.0, 0.1, 1.0, 2.0], dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True)", "np.array([0.5, 3.0, 2.5]) scale_v = np.array([1.0, 4.0, 5.0]) laplace =", "= np.array([1.0, 4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.mean().shape,", "= self.evaluate([samples, pdfs]) self.assertEqual(samples.shape, (num, 2, 2)) self.assertEqual(pdfs.shape, (num, 2,", "distributed under the License is distributed on an \"AS IS\"", "sample_values.mean(axis=0), sp_stats.laplace.mean(loc_bc, scale=scale_bc), rtol=0.35, atol=0.) self.assertAllClose( sample_values.var(axis=0), sp_stats.laplace.var(loc_bc, scale=scale_bc), rtol=0.10,", "Kolmogorov-Smirnov test for goodness of fit. ks, _ = sp_stats.kstest(samples,", "1, 1], err=0.02) self.assertAllClose( sp_stats.laplace.mean( [[7., 11.], [7., 11.]], scale=np.array([[5.,", "sp_stats.laplace.mean(loc_bc, scale=scale_bc), rtol=0.35, atol=0.) self.assertAllClose( sample_values.var(axis=0), sp_stats.laplace.var(loc_bc, scale=scale_bc), rtol=0.10, atol=0.)", "sp_stats.laplace.var([[7., 11.], [7., 11.]], scale=np.array([[5., 5.], [6., 6.]])), sample_vals.var(axis=0), rtol=0.05,", "kl_sample_, atol=0., rtol=1e-1) zero_kl = tfd.kl_divergence(a, a) true_zero_kl_, zero_kl_ =", "tf.constant(0.0, name='scale') with self.assertRaisesOpError('Argument `scale` must be positive.'): laplace =", "self._assertIntegral(sample_vals[:, 0, 0], pdf_vals[:, 0, 0], err=0.02) self._assertIntegral(sample_vals[:, 0, 1],", "np.array([1.0, 4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.mean().shape, (3,))", "[grad_loc, grad_scale] = tfp.math.value_and_gradient( lambda l, s: tfd.Laplace(loc=l, scale=s, validate_args=True).sample(", "np.array([3.0, 4.0]) x = np.array([[2.5, 2.5, 4.0, 0.1, 1.0, 2.0]],", "2.5, 4.0, 0.1, 1.0, 2.0], dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale,", "from scipy import stats as sp_stats import tensorflow.compat.v2 as tf", "# pylint: disable=g-long-lambda 100, seed=test_util.test_seed()), [loc, scale]) self.assertIsNotNone(grad_loc) self.assertIsNotNone(grad_scale) def", "+ scale_v) # 10 x 100 loc_bc = loc_v +", "express or implied. # See the License for the specific", "0.03) def _kstest(self, loc, scale, samples): # Uses the Kolmogorov-Smirnov", "except in compliance with the License. # You may obtain", "= sp_stats.laplace.logpdf(x, loc_v, scale=scale_v) self.assertAllClose(log_pdf_values, expected_log_pdf) self.assertAllClose(pdf_values, np.exp(expected_log_pdf)) def testLaplaceLogPDFMultidimensionalBroadcasting(self):", "tf.constant(loc_v) scale = tf.constant(scale_v) n = 100000 laplace = tfd.Laplace(loc=loc,", "1, 0], err=0.02) self._assertIntegral(sample_vals[:, 1, 1], pdf_vals[:, 1, 1], err=0.02)", "scale_v = 3.0 x = np.array([2.5, 2.5, 4.0, 0.1, 1.0,", "= np.array([2.0, 4.0]) scale_v = np.array([3.0, 4.0]) x = np.array([[2.5,", "expected_sf) def testLaplaceMean(self): loc_v = np.array([1.0, 3.0, 2.5]) scale_v =", "ratio = a_scale / b_scale true_kl = (-tf.math.log(ratio) - 1", "self.assertEqual(laplace.stddev().shape, (3,)) expected_stddev = sp_stats.laplace.std(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.stddev()), expected_stddev) def testLaplaceEntropy(self):", "Licensed under the Apache License, Version 2.0 (the \"License\"); #", "expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v, scale=scale_v) self.assertAllClose(log_pdf_values, expected_log_pdf) self.assertAllClose(pdf_values, np.exp(expected_log_pdf)) def", "5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.variance().shape, (3,)) expected_variances =", "= tf.constant(scale_v) n = 100000 laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True)", "not use this file except in compliance with the License.", "validate_args=True) n = 10000 samples = laplace.sample(n, seed=test_util.test_seed()) sample_values =", "`scale` must be positive.'): with tf.control_dependencies([scale.assign([1., 2., -3.])]): self.evaluate(tfd.Laplace(loc=0., scale=1.).kl_divergence(d))", "(6,)) expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(log_pdf), expected_log_pdf) pdf =", "3.]) d = tfd.Laplace(loc=0., scale=scale, validate_args=True) self.evaluate([v.initializer for v in", "laplace.sample(n, seed=test_util.test_seed()) sample_values = self.evaluate(samples) self.assertEqual(samples.shape, (n, 10, 100)) self.assertEqual(sample_values.shape,", "rtol=0.10, atol=0.) fails = 0 trials = 0 for ai,", "writing, software # distributed under the License is distributed on", "10, 100)) zeros = np.zeros_like(loc_v + scale_v) # 10 x", "total += (k[0] - prev[0]) * pair_pdf prev = k", "tf.constant(3.0) _, [grad_loc, grad_scale] = tfp.math.value_and_gradient( lambda l, s: tfd.Laplace(loc=l,", "you may not use this file except in compliance with", "scale_v, sample_values)) def testLaplaceFullyReparameterized(self): loc = tf.constant(4.0) scale = tf.constant(3.0)", "scale]) self.assertIsNotNone(grad_loc) self.assertIsNotNone(grad_scale) def testLaplaceSampleMultiDimensional(self): loc_v = np.array([np.arange(1, 101, dtype=np.float32)])", "tfd.Laplace(loc=0, scale=scale, validate_args=True) self.evaluate(d.sample(seed=test_util.test_seed())) def testLaplaceLaplaceKL(self): batch_size = 6 event_size", "# Licensed under the Apache License, Version 2.0 (the \"License\");", "scipy import stats as sp_stats import tensorflow.compat.v2 as tf import", "batch_size = 6 loc = tf.constant([[2.0, 4.0]] * batch_size) scale", "np.array([1.0, 4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.variance().shape, (3,))", "= tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) n = 10000 samples = laplace.sample(n,", "d = tfd.Laplace(loc=1., scale=1.3, validate_args=True) vals = d.quantile(qs) self.assertAllClose([-np.inf, np.inf],", "loc_v = tf.constant(0.0, name='loc') scale_v = tf.constant(-1.0, name='scale') with self.assertRaisesOpError('Argument", "3.0 loc = tf.constant(loc_v) scale = tf.constant(scale_v) n = 100000", "True when the test passes. return ks < 0.02 def", "b = tfd.Laplace(loc=b_loc, scale=b_scale, validate_args=True) distance = tf.abs(a_loc - b_loc)", "tfd.Laplace(loc=loc, scale=scale, validate_args=True) cdf = laplace.cdf(x) self.assertEqual(cdf.shape, (6,)) expected_cdf =", "= laplace.prob(x) self.assertEqual(pdf.shape, (6,)) self.assertAllClose(self.evaluate(pdf), np.exp(expected_log_pdf)) def testLaplaceLogPDFMultidimensional(self): batch_size =", "tensorflow_probability as tfp from tensorflow_probability.python.internal import samplers from tensorflow_probability.python.internal import", "= np.array([2.5, 2.5, 4.0, 0.1, 1.0, 2.0], dtype=np.float32) laplace =", "loc_v, scale=scale_v) self.assertAllClose(self.evaluate(sf), expected_sf) def testLaplaceMean(self): loc_v = np.array([1.0, 3.0,", "loc_v = np.array([1.0, 3.0, 2.5]) scale_v = np.array([1.0, 4.0, 5.0])", "testLaplaceStd(self): loc_v = np.array([1.0, 3.0, 2.5]) scale_v = np.array([1.0, 4.0,", "pdf_vals[:, 0, 0], err=0.02) self._assertIntegral(sample_vals[:, 0, 1], pdf_vals[:, 0, 1],", "samplers.uniform([10], minval=.1, maxval=.9, seed=test_util.test_seed())], axis=0)) d = tfd.Laplace(loc=1., scale=1.3, validate_args=True)", "5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.entropy().shape, (3,)) expected_entropy =", "dtype=np.float32) a = tfd.Laplace(loc=a_loc, scale=a_scale, validate_args=True) b = tfd.Laplace(loc=b_loc, scale=b_scale,", "/ a_scale)) kl = tfd.kl_divergence(a, b) x = a.sample(int(1e4), seed=test_util.test_seed())", "tape: loss = -d.log_prob([1., 2., 3.]) grad = tape.gradient(loss, d.trainable_variables)", "(6,)) expected_sf = sp_stats.laplace.logsf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(sf), expected_sf) def testLaplaceMean(self):", "1], samplers.uniform([10], minval=.1, maxval=.9, seed=test_util.test_seed())], axis=0)) d = tfd.Laplace(loc=1., scale=1.3,", "sample_vals, pdf_vals = self.evaluate([samples, pdfs]) self.assertEqual(samples.shape, (num, 2, 2)) self.assertEqual(pdfs.shape,", "CONDITIONS OF ANY KIND, either express or implied. # See", "def testLaplaceLogPDFMultidimensional(self): batch_size = 6 loc = tf.constant([[2.0, 4.0]] *", "# 10 x 100 loc_bc = loc_v + zeros scale_bc", "rtol=0.35, atol=0.) self.assertAllClose( sample_values.var(axis=0), sp_stats.laplace.var(loc_bc, scale=scale_bc), rtol=0.10, atol=0.) fails =", "scale=scale_v, validate_args=True) self.assertEqual(laplace.variance().shape, (3,)) expected_variances = sp_stats.laplace.var(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.variance()), expected_variances)", "loc = tf.constant(loc_v) scale = tf.constant(scale_v) n = 100000 laplace", "= tfd.Laplace(loc=[7., 11.], scale=[[5.], [6.]], validate_args=True) num = 50000 samples", "testLaplacePdfOfSampleMultiDims(self): laplace = tfd.Laplace(loc=[7., 11.], scale=[[5.], [6.]], validate_args=True) num =", "is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES", "2., 3.]) grad = tape.gradient(loss, d.trainable_variables) self.assertLen(grad, 2) self.assertAllNotNone(grad) def", "= tf.Variable([1., 2., -3.]) self.evaluate(scale.initializer) with self.assertRaisesOpError('Argument `scale` must be", "self.assertIsNotNone(grad_loc) self.assertIsNotNone(grad_scale) def testLaplaceSampleMultiDimensional(self): loc_v = np.array([np.arange(1, 101, dtype=np.float32)]) #", "expected_means) def testLaplaceMode(self): loc_v = np.array([0.5, 3.0, 2.5]) scale_v =", "loc = tf.constant([2.0] * batch_size) scale = tf.constant([3.0] * batch_size)", "self.assertEqual(samples.shape, (n,)) self.assertEqual(sample_values.shape, (n,)) self.assertAllClose( sample_values.mean(), sp_stats.laplace.mean(loc_v, scale=scale_v), rtol=0.05, atol=0.)", "self.evaluate(samples) self.assertEqual(samples.shape, (n, 10, 100)) self.assertEqual(sample_values.shape, (n, 10, 100)) zeros", "self.assertEqual(pdfs.shape, (num, 2, 2)) self._assertIntegral(sample_vals[:, 0, 0], pdf_vals[:, 0, 0],", "distance / b_scale + ratio * tf.exp(-distance / a_scale)) kl", "scale=scale_v, validate_args=True) self.evaluate(laplace.mean()) scale = tf.Variable([1., 2., -3.]) self.evaluate(scale.initializer) with", "tfd.Laplace(loc=loc, scale=scale, validate_args=True) with tf.GradientTape() as tape: loss = -d.log_prob([1.,", "name='loc') scale_v = tf.constant(0.0, name='scale') with self.assertRaisesOpError('Argument `scale` must be", "tensorflow.compat.v2 as tf import tensorflow_probability as tfp from tensorflow_probability.python.internal import", "= laplace.log_survival_function(x) self.assertEqual(sf.shape, (6,)) expected_sf = sp_stats.laplace.logsf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(sf),", "atol=0., rtol=1e-1) zero_kl = tfd.kl_divergence(a, a) true_zero_kl_, zero_kl_ = self.evaluate([tf.zeros_like(true_kl),", "self.assertEqual(laplace.mean().shape, (3,)) expected_means = sp_stats.laplace.mean(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.mean()), expected_means) def testLaplaceMode(self):", "self.evaluate([true_kl, kl, kl_sample]) self.assertAllClose(true_kl_, kl_, atol=1e-5, rtol=1e-5) self.assertAllClose(true_kl_, kl_sample_, atol=0.,", "kl_sample = tf.reduce_mean(a.log_prob(x) - b.log_prob(x), axis=0) true_kl_, kl_, kl_sample_ =", "* batch_size, dtype=np.float32) b_loc = np.array([[0.4] * event_size] * batch_size,", "self.assertAllClose(true_kl_, kl_sample_, atol=0., rtol=1e-1) zero_kl = tfd.kl_divergence(a, a) true_zero_kl_, zero_kl_", "testLaplaceSampleMultiDimensional(self): loc_v = np.array([np.arange(1, 101, dtype=np.float32)]) # 1 x 100", "ai] trials += 1 fails += 0 if self._kstest(a, b,", "in sorted(s_p, key=lambda x: x[0]): pair_pdf = (k[1] + prev[1])", "sample_values[:, bi, ai] trials += 1 fails += 0 if", "2., -3.]) self.evaluate(scale.initializer) with self.assertRaisesOpError('Argument `scale` must be positive.'): d", "= tf.constant(11.0) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) self.assertEqual(self.evaluate(laplace.batch_shape_tensor()), (5,)) self.assertEqual(laplace.batch_shape,", "positive.'): laplace = tfd.Laplace( loc=loc_v, scale=scale_v, validate_args=True) self.evaluate(laplace.mean()) loc_v =", "3.]) grad = tape.gradient(loss, d.trainable_variables) self.assertLen(grad, 2) self.assertAllNotNone(grad) def testAssertsPositiveScaleAfterMutation(self):", "= tf.constant([[2.0, 4.0]] * batch_size) scale = tf.constant([[3.0, 4.0]] *", "d = tfd.Laplace(loc=loc, scale=scale, validate_args=True) with tf.GradientTape() as tape: loss", "= 3.0 loc = tf.constant(loc_v) scale = tf.constant(scale_v) n =", "4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.entropy().shape, (3,)) expected_entropy", "0, 1], pdf_vals[:, 0, 1], err=0.02) self._assertIntegral(sample_vals[:, 1, 0], pdf_vals[:,", "= np.array([1.0, 4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.entropy().shape,", "self._assertIntegral(sample_vals[:, 0, 1], pdf_vals[:, 0, 1], err=0.02) self._assertIntegral(sample_vals[:, 1, 0],", "as tf import tensorflow_probability as tfp from tensorflow_probability.python.internal import samplers", "loc=loc_v, scale=scale_v, validate_args=True) self.evaluate(laplace.mean()) scale = tf.Variable([1., 2., -3.]) self.evaluate(scale.initializer)", "scale = tf.Variable([1., 2., -3.]) self.evaluate(scale.initializer) with self.assertRaisesOpError('Argument `scale` must", "OR CONDITIONS OF ANY KIND, either express or implied. #", "2, 2)) self.assertEqual(pdfs.shape, (num, 2, 2)) self._assertIntegral(sample_vals[:, 0, 0], pdf_vals[:,", "sp_stats.laplace.logsf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(sf), expected_sf) def testLaplaceMean(self): loc_v = np.array([1.0,", "d = tfd.Laplace(loc=0., scale=scale, validate_args=True) self.evaluate([v.initializer for v in d.variables])", "self.assertRaisesOpError('Argument `scale` must be positive.'): with tf.control_dependencies([scale.assign([1., 2., -3.])]): self.evaluate(tfd.Laplace(loc=0.,", "Dependency imports import numpy as np from scipy import stats", "the License is distributed on an \"AS IS\" BASIS, #", "self.assertAllClose([-np.inf, np.inf], vals[:2]) self.assertAllClose(qs[2:], d.cdf(vals[2:])) def testLaplaceLogSurvivalFunction(self): batch_size = 6", "err=0.02) self.assertAllClose( sp_stats.laplace.mean( [[7., 11.], [7., 11.]], scale=np.array([[5., 5.], [6.,", "scale_v = tf.constant(-1.0, name='scale') with self.assertRaisesOpError('Argument `scale` must be positive.'):", "= tfd.kl_divergence(a, b) x = a.sample(int(1e4), seed=test_util.test_seed()) kl_sample = tf.reduce_mean(a.log_prob(x)", "testLaplaceMode(self): loc_v = np.array([0.5, 3.0, 2.5]) scale_v = np.array([1.0, 4.0,", "scale_v = np.array([3.0, 4.0]) x = np.array([[2.5, 2.5, 4.0, 0.1,", "self.evaluate(laplace.mean()) loc_v = tf.constant(1.0, name='loc') scale_v = tf.constant(0.0, name='scale') with", "laplace.log_cdf(x) self.assertEqual(cdf.shape, (6,)) expected_cdf = sp_stats.laplace.logcdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(cdf), expected_cdf)", "scale=scale_v) self.assertAllClose(self.evaluate(cdf), expected_cdf) def testLaplaceQuantile(self): qs = self.evaluate( tf.concat( [[0.,", "= np.array([0.5, 3.0, 2.5]) scale_v = np.array([1.0, 4.0, 5.0]) laplace", "b_loc = np.array([[0.4] * event_size] * batch_size, dtype=np.float32) b_scale =", "4.0, 0.1, 1.0, 2.0]], dtype=np.float32).T laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True)", "import numpy as np from scipy import stats as sp_stats", "tfd.Laplace(loc=loc, scale=scale, validate_args=True) self.assertEqual(self.evaluate(laplace.batch_shape_tensor()), (5,)) self.assertEqual(laplace.batch_shape, tf.TensorShape([5])) self.assertAllEqual(self.evaluate(laplace.event_shape_tensor()), []) self.assertEqual(laplace.event_shape,", "loc_v, scale=scale_v) self.assertAllClose(self.evaluate(log_pdf), expected_log_pdf) pdf = laplace.prob(x) self.assertEqual(pdf.shape, (6,)) self.assertAllClose(self.evaluate(pdf),", "tf import tensorflow_probability as tfp from tensorflow_probability.python.internal import samplers from", "self.assertIsNotNone(grad_scale) def testLaplaceSampleMultiDimensional(self): loc_v = np.array([np.arange(1, 101, dtype=np.float32)]) # 1", "6 event_size = 3 a_loc = np.array([[0.5] * event_size] *", "= tf.constant(loc_v) scale = tf.constant(scale_v) n = 100000 laplace =", "= tfd.Laplace(loc=loc, scale=scale, validate_args=True) cdf = laplace.log_cdf(x) self.assertEqual(cdf.shape, (6,)) expected_cdf", "testLaplaceShape(self): loc = tf.constant([3.0] * 5) scale = tf.constant(11.0) laplace", "testGradientThroughParams(self): loc = tf.Variable([-5., 0., 5.]) scale = tf.Variable(2.) d", "grad = tape.gradient(loss, d.trainable_variables) self.assertLen(grad, 2) self.assertAllNotNone(grad) def testAssertsPositiveScaleAfterMutation(self): scale", "self.assertAllClose(self.evaluate(laplace.mode()), loc_v) def testLaplaceVariance(self): loc_v = np.array([1.0, 3.0, 2.5]) scale_v", "loc_v = np.array([2.0, 4.0]) scale_v = 3.0 x = np.array([[2.5,", "testLaplaceSample(self): loc_v = 4.0 scale_v = 3.0 loc = tf.constant(loc_v)", "testLaplaceLogPDFMultidimensionalBroadcasting(self): batch_size = 6 loc = tf.constant([[2.0, 4.0]] * batch_size)", "= np.array([1.0, 4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.mode().shape,", "self._assertIntegral(sample_vals[:, 1, 0], pdf_vals[:, 1, 0], err=0.02) self._assertIntegral(sample_vals[:, 1, 1],", "self.assertRaisesOpError('Argument `scale` must be positive.'): laplace = tfd.Laplace( loc=loc_v, scale=scale_v,", "= np.array([[0.5] * event_size] * batch_size, dtype=np.float32) a_scale = np.array([[0.1]", "expected_variances = sp_stats.laplace.var(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.variance()), expected_variances) def testLaplaceStd(self): loc_v =", "1, 0], pdf_vals[:, 1, 0], err=0.02) self._assertIntegral(sample_vals[:, 1, 1], pdf_vals[:,", "= tf.constant([[3.0, 4.0]] * batch_size) loc_v = np.array([2.0, 4.0]) scale_v", "expected_stddev) def testLaplaceEntropy(self): loc_v = np.array([1.0, 3.0, 2.5]) scale_v =", "limitations under the License. # ============================================================================ from __future__ import absolute_import", "tf.Variable([1., 2., 3.]) d = tfd.Laplace(loc=0., scale=scale, validate_args=True) self.evaluate([v.initializer for", "= np.array([[0.2] * event_size] * batch_size, dtype=np.float32) a = tfd.Laplace(loc=a_loc,", "- 1 + distance / b_scale + ratio * tf.exp(-distance", "(0, 0) total = 0 for k in sorted(s_p, key=lambda", "np.exp(expected_log_pdf)) def testLaplaceCDF(self): batch_size = 6 loc = tf.constant([2.0] *", "10000 samples = laplace.sample(n, seed=test_util.test_seed()) sample_values = self.evaluate(samples) self.assertEqual(samples.shape, (n,", "sample_values.var(axis=0), sp_stats.laplace.var(loc_bc, scale=scale_bc), rtol=0.10, atol=0.) fails = 0 trials =", "self.assertAllEqual(true_zero_kl_, zero_kl_) @test_util.tf_tape_safety_test def testGradientThroughParams(self): loc = tf.Variable([-5., 0., 5.])", "law or agreed to in writing, software # distributed under", "= 100000 laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) samples = laplace.sample(n,", "scale=scale, validate_args=True) self.assertEqual(self.evaluate(laplace.batch_shape_tensor()), (5,)) self.assertEqual(laplace.batch_shape, tf.TensorShape([5])) self.assertAllEqual(self.evaluate(laplace.event_shape_tensor()), []) self.assertEqual(laplace.event_shape, tf.TensorShape([]))", "4.0]) scale_v = np.array([3.0, 4.0]) x = np.array([[2.5, 2.5, 4.0,", "loc_v, scale=scale_v) self.assertAllClose(self.evaluate(cdf), expected_cdf) def testLaplaceQuantile(self): qs = self.evaluate( tf.concat(", "scale=scale_v, validate_args=True) n = 10000 samples = laplace.sample(n, seed=test_util.test_seed()) sample_values", "grad_scale] = tfp.math.value_and_gradient( lambda l, s: tfd.Laplace(loc=l, scale=s, validate_args=True).sample( #", "a.sample(int(1e4), seed=test_util.test_seed()) kl_sample = tf.reduce_mean(a.log_prob(x) - b.log_prob(x), axis=0) true_kl_, kl_,", "dtype=tf.int32) scale = tf.convert_to_tensor(1, dtype=tf.int32) with self.assertRaisesRegexp(ValueError, 'Expected floating point'):", "self.assertEqual(laplace.batch_shape, tf.TensorShape([5])) self.assertAllEqual(self.evaluate(laplace.event_shape_tensor()), []) self.assertEqual(laplace.event_shape, tf.TensorShape([])) def testLaplaceLogPDF(self): batch_size =", "= 3.0 x = np.array([2.5, 2.5, 4.0, 0.1, 1.0, 2.0],", "= k self.assertNear(1., total, err=err) def testLaplaceNonPositiveInitializationParamsRaises(self): loc_v = tf.constant(0.0,", "validate_args=True) self.assertEqual(laplace.mean().shape, (3,)) expected_means = sp_stats.laplace.mean(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.mean()), expected_means) def", "atol=0.) self.assertAllClose( sample_values.var(), sp_stats.laplace.var(loc_v, scale=scale_v), rtol=0.05, atol=0.) self.assertTrue(self._kstest(loc_v, scale_v, sample_values))", "dtype=np.float32) b_scale = np.array([[0.2] * event_size] * batch_size, dtype=np.float32) a", "np.array([1.0, 4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.entropy().shape, (3,))", "= tfd.Laplace( loc=loc_v, scale=scale_v, validate_args=True) self.evaluate(laplace.mean()) loc_v = tf.constant(1.0, name='loc')", "np.array([1.0, 4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.mode().shape, (3,))", "sample_vals, pdf_vals, err=1e-3): s_p = zip(sample_vals, pdf_vals) prev = (0,", "laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.entropy().shape, (3,)) expected_entropy = sp_stats.laplace.entropy(loc_v,", "np.array([np.arange(1, 101, dtype=np.float32)]) # 1 x 100 scale_v = np.array([np.arange(1,", "tfd.Laplace(loc=1., scale=1.3, validate_args=True) vals = d.quantile(qs) self.assertAllClose([-np.inf, np.inf], vals[:2]) self.assertAllClose(qs[2:],", "scale = tf.constant([3.0] * batch_size) loc_v = 2.0 scale_v =", "with self.assertRaisesOpError('Argument `scale` must be positive.'): with tf.control_dependencies([scale.assign([1., 2., -3.])]):", "= self.evaluate(log_pdf) self.assertEqual(log_pdf.shape, (6, 2)) pdf = laplace.prob(x) pdf_values =", "1], pdf_vals[:, 0, 1], err=0.02) self._assertIntegral(sample_vals[:, 1, 0], pdf_vals[:, 1,", "laplace.sample(num, seed=test_util.test_seed()) pdfs = laplace.prob(samples) sample_vals, pdf_vals = self.evaluate([samples, pdfs])", "= self.evaluate([true_kl, kl, kl_sample]) self.assertAllClose(true_kl_, kl_, atol=1e-5, rtol=1e-5) self.assertAllClose(true_kl_, kl_sample_,", "np.array([1.0, 4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.stddev().shape, (3,))", "prev[1]) / 2 total += (k[0] - prev[0]) * pair_pdf", "* batch_size) loc_v = 2.0 scale_v = 3.0 x =", "kl, kl_sample]) self.assertAllClose(true_kl_, kl_, atol=1e-5, rtol=1e-5) self.assertAllClose(true_kl_, kl_sample_, atol=0., rtol=1e-1)", "2.0], dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) sf = laplace.log_survival_function(x)", "= tape.gradient(loss, d.trainable_variables) self.assertLen(grad, 2) self.assertAllNotNone(grad) def testAssertsPositiveScaleAfterMutation(self): scale =", "(n,)) self.assertEqual(sample_values.shape, (n,)) self.assertAllClose( sample_values.mean(), sp_stats.laplace.mean(loc_v, scale=scale_v), rtol=0.05, atol=0.) self.assertAllClose(", "* batch_size, dtype=np.float32) a_scale = np.array([[0.1] * event_size] * batch_size,", "may obtain a copy of the License at # #", "scale=scale_bc), rtol=0.35, atol=0.) self.assertAllClose( sample_values.var(axis=0), sp_stats.laplace.var(loc_bc, scale=scale_bc), rtol=0.10, atol=0.) fails", "0], err=0.02) self._assertIntegral(sample_vals[:, 1, 1], pdf_vals[:, 1, 1], err=0.02) self.assertAllClose(", "division from __future__ import print_function # Dependency imports import numpy", "tfd.kl_divergence(a, b) x = a.sample(int(1e4), seed=test_util.test_seed()) kl_sample = tf.reduce_mean(a.log_prob(x) -", "= 6 loc = tf.constant([2.0] * batch_size) scale = tf.constant([3.0]", "scale=scale_bc), rtol=0.10, atol=0.) fails = 0 trials = 0 for", "positive.'): laplace = tfd.Laplace( loc=loc_v, scale=scale_v, validate_args=True) self.evaluate(laplace.mean()) scale =", "samples = laplace.sample(num, seed=test_util.test_seed()) pdfs = laplace.prob(samples) sample_vals, pdf_vals =", "validate_args=True) self.evaluate(d.sample(seed=test_util.test_seed())) def testLaplaceLaplaceKL(self): batch_size = 6 event_size = 3", "tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.mean().shape, (3,)) expected_means = sp_stats.laplace.mean(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.mean()),", "expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(log_pdf), expected_log_pdf) pdf = laplace.prob(x)", "dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) sf = laplace.log_survival_function(x) self.assertEqual(sf.shape,", "= tf.constant(-1.0, name='scale') with self.assertRaisesOpError('Argument `scale` must be positive.'): laplace", "be positive.'): d = tfd.Laplace(loc=0, scale=scale, validate_args=True) self.evaluate(d.sample(seed=test_util.test_seed())) def testLaplaceLaplaceKL(self):", "* event_size] * batch_size, dtype=np.float32) b_loc = np.array([[0.4] * event_size]", "IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,", "import samplers from tensorflow_probability.python.internal import test_util tfd = tfp.distributions @test_util.test_all_tf_execution_regimes", "pdf = laplace.prob(x) pdf_values = self.evaluate(pdf) self.assertEqual(pdf.shape, (6, 2)) expected_log_pdf", "d.trainable_variables) self.assertLen(grad, 2) self.assertAllNotNone(grad) def testAssertsPositiveScaleAfterMutation(self): scale = tf.Variable([1., 2.,", "laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) n = 10000 samples =", "event_size] * batch_size, dtype=np.float32) a = tfd.Laplace(loc=a_loc, scale=a_scale, validate_args=True) b", "2.5, -4.0, 0.1, 1.0, 2.0], dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale,", "11.], [7., 11.]], scale=np.array([[5., 5.], [6., 6.]])), sample_vals.mean(axis=0), rtol=0.05, atol=0.)", "# 1 x 100 scale_v = np.array([np.arange(1, 11, dtype=np.float32)]).T #", "loc_v = 2.0 scale_v = 3.0 x = np.array([-2.5, 2.5,", "may not use this file except in compliance with the", "scale=scale_v) self.assertAllClose(self.evaluate(laplace.variance()), expected_variances) def testLaplaceStd(self): loc_v = np.array([1.0, 3.0, 2.5])", "x = a.sample(int(1e4), seed=test_util.test_seed()) kl_sample = tf.reduce_mean(a.log_prob(x) - b.log_prob(x), axis=0)", "loc_v = np.array([2.0, 4.0]) scale_v = np.array([3.0, 4.0]) x =", "seed=test_util.test_seed()), [loc, scale]) self.assertIsNotNone(grad_loc) self.assertIsNotNone(grad_scale) def testLaplaceSampleMultiDimensional(self): loc_v = np.array([np.arange(1,", "def testAssertsPositiveScaleAfterMutation(self): scale = tf.Variable([1., 2., 3.]) d = tfd.Laplace(loc=0.,", "scale=a_scale, validate_args=True) b = tfd.Laplace(loc=b_loc, scale=b_scale, validate_args=True) distance = tf.abs(a_loc", "self.assertAllClose(self.evaluate(sf), expected_sf) def testLaplaceMean(self): loc_v = np.array([1.0, 3.0, 2.5]) scale_v", "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or", "= tfd.Laplace(loc=b_loc, scale=b_scale, validate_args=True) distance = tf.abs(a_loc - b_loc) ratio", "this file except in compliance with the License. # You", "sample_values.mean(), sp_stats.laplace.mean(loc_v, scale=scale_v), rtol=0.05, atol=0.) self.assertAllClose( sample_values.var(), sp_stats.laplace.var(loc_v, scale=scale_v), rtol=0.05,", "tfd.Laplace( loc=loc_v, scale=scale_v, validate_args=True) self.evaluate(laplace.mean()) loc_v = tf.constant(1.0, name='loc') scale_v", "as np from scipy import stats as sp_stats import tensorflow.compat.v2", "_, [grad_loc, grad_scale] = tfp.math.value_and_gradient( lambda l, s: tfd.Laplace(loc=l, scale=s,", "self.assertAllClose( sp_stats.laplace.var([[7., 11.], [7., 11.]], scale=np.array([[5., 5.], [6., 6.]])), sample_vals.var(axis=0),", "@test_util.test_all_tf_execution_regimes class LaplaceTest(test_util.TestCase): def testLaplaceShape(self): loc = tf.constant([3.0] * 5)", "5.], [6., 6.]])), sample_vals.var(axis=0), rtol=0.05, atol=0.) def _assertIntegral(self, sample_vals, pdf_vals,", "import absolute_import from __future__ import division from __future__ import print_function", "= tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.entropy().shape, (3,)) expected_entropy = sp_stats.laplace.entropy(loc_v, scale=scale_v)", "tfd.Laplace( loc=loc_v, scale=scale_v, validate_args=True) self.evaluate(laplace.mean()) scale = tf.Variable([1., 2., -3.])", "= tf.constant([3.0] * batch_size) loc_v = 2.0 scale_v = 3.0", "batch_size = 6 event_size = 3 a_loc = np.array([[0.5] *", "= 6 event_size = 3 a_loc = np.array([[0.5] * event_size]", "scale=b_scale, validate_args=True) distance = tf.abs(a_loc - b_loc) ratio = a_scale", "# limitations under the License. # ============================================================================ from __future__ import", "scale=scale_v, validate_args=True) self.assertEqual(laplace.mode().shape, (3,)) self.assertAllClose(self.evaluate(laplace.mode()), loc_v) def testLaplaceVariance(self): loc_v =", "tf.TensorShape([])) def testLaplaceLogPDF(self): batch_size = 6 loc = tf.constant([2.0] *", "laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.stddev().shape, (3,)) expected_stddev = sp_stats.laplace.std(loc_v,", "validate_args=True) self.assertEqual(laplace.variance().shape, (3,)) expected_variances = sp_stats.laplace.var(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.variance()), expected_variances) def", "10 x 1 laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) n =", "np.array([2.0, 4.0]) scale_v = 3.0 x = np.array([[2.5, 2.5, 4.0,", "2.0 scale_v = 3.0 x = np.array([-2.5, 2.5, -4.0, 0.1,", "self.assertAllClose(self.evaluate(laplace.variance()), expected_variances) def testLaplaceStd(self): loc_v = np.array([1.0, 3.0, 2.5]) scale_v", "= sp_stats.laplace.std(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.stddev()), expected_stddev) def testLaplaceEntropy(self): loc_v = np.array([1.0,", "100 loc_bc = loc_v + zeros scale_bc = scale_v +", "test passes. return ks < 0.02 def testLaplacePdfOfSampleMultiDims(self): laplace =", "testLaplaceNonPositiveInitializationParamsRaises(self): loc_v = tf.constant(0.0, name='loc') scale_v = tf.constant(-1.0, name='scale') with", "+ distance / b_scale + ratio * tf.exp(-distance / a_scale))", "tf.GradientTape() as tape: loss = -d.log_prob([1., 2., 3.]) grad =", "# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law", "self.assertRaisesRegexp(ValueError, 'Expected floating point'): tfd.Laplace(loc=loc, scale=scale) if __name__ == '__main__':", "3.0 x = np.array([[2.5, 2.5, 4.0, 0.1, 1.0, 2.0]], dtype=np.float32).T", "= self.evaluate(samples) self.assertEqual(samples.shape, (n, 10, 100)) self.assertEqual(sample_values.shape, (n, 10, 100))", "# # Licensed under the Apache License, Version 2.0 (the", "0 if self._kstest(a, b, s) else 1 self.assertLess(fails, trials *", "file except in compliance with the License. # You may", "on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS", "Return True when the test passes. return ks < 0.02", "(6, 2)) expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v, scale=scale_v) self.assertAllClose(log_pdf_values, expected_log_pdf) self.assertAllClose(pdf_values,", "scale_v = 3.0 x = np.array([[2.5, 2.5, 4.0, 0.1, 1.0,", "`scale` must be positive.'): d = tfd.Laplace(loc=0, scale=scale, validate_args=True) self.evaluate(d.sample(seed=test_util.test_seed()))", "under the License. # ============================================================================ from __future__ import absolute_import from", "tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.entropy().shape, (3,)) expected_entropy = sp_stats.laplace.entropy(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.entropy()),", "rtol=0.05, atol=0.) self.assertAllClose( sample_values.var(), sp_stats.laplace.var(loc_v, scale=scale_v), rtol=0.05, atol=0.) self.assertTrue(self._kstest(loc_v, scale_v,", "(3,)) expected_stddev = sp_stats.laplace.std(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.stddev()), expected_stddev) def testLaplaceEntropy(self): loc_v", "tfd.Laplace(loc=loc, scale=scale, validate_args=True) cdf = laplace.log_cdf(x) self.assertEqual(cdf.shape, (6,)) expected_cdf =", "def testLaplaceMode(self): loc_v = np.array([0.5, 3.0, 2.5]) scale_v = np.array([1.0,", "laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) log_pdf = laplace.log_prob(x) log_pdf_values =", "dtype=np.float32)]).T # 10 x 1 laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True)", "def _assertIntegral(self, sample_vals, pdf_vals, err=1e-3): s_p = zip(sample_vals, pdf_vals) prev", "self.assertLess(fails, trials * 0.03) def _kstest(self, loc, scale, samples): #", "scale=scale_v, validate_args=True) self.assertEqual(laplace.entropy().shape, (3,)) expected_entropy = sp_stats.laplace.entropy(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.entropy()), expected_entropy)", "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express", "testLaplaceLogSurvivalFunction(self): batch_size = 6 loc = tf.constant([2.0] * batch_size) scale", "np.zeros_like(loc_v + scale_v) # 10 x 100 loc_bc = loc_v", "x = np.array([[2.5, 2.5, 4.0, 0.1, 1.0, 2.0]], dtype=np.float32).T laplace", "= tfd.Laplace(loc=loc, scale=scale, validate_args=True) samples = laplace.sample(n, seed=test_util.test_seed()) sample_values =", "atol=0.) self.assertAllClose( sp_stats.laplace.var([[7., 11.], [7., 11.]], scale=np.array([[5., 5.], [6., 6.]])),", "License. # ============================================================================ from __future__ import absolute_import from __future__ import", "loc_v = 2.0 scale_v = 3.0 x = np.array([2.5, 2.5,", "batch_size) loc_v = 2.0 scale_v = 3.0 x = np.array([-2.5,", "s = sample_values[:, bi, ai] trials += 1 fails +=", "scale = tf.constant(scale_v) n = 100000 laplace = tfd.Laplace(loc=loc, scale=scale,", "self.assertLen(grad, 2) self.assertAllNotNone(grad) def testAssertsPositiveScaleAfterMutation(self): scale = tf.Variable([1., 2., 3.])", "self.assertAllClose(qs[2:], d.cdf(vals[2:])) def testLaplaceLogSurvivalFunction(self): batch_size = 6 loc = tf.constant([2.0]", "event_size] * batch_size, dtype=np.float32) b_loc = np.array([[0.4] * event_size] *", "tf.constant([3.0] * batch_size) loc_v = 2.0 scale_v = 3.0 x", "2) self.assertAllNotNone(grad) def testAssertsPositiveScaleAfterMutation(self): scale = tf.Variable([1., 2., 3.]) d", "laplace.log_survival_function(x) self.assertEqual(sf.shape, (6,)) expected_sf = sp_stats.laplace.logsf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(sf), expected_sf)", "_kstest(self, loc, scale, samples): # Uses the Kolmogorov-Smirnov test for", "= tf.Variable([-5., 0., 5.]) scale = tf.Variable(2.) d = tfd.Laplace(loc=loc,", "= tf.convert_to_tensor(1, dtype=tf.int32) with self.assertRaisesRegexp(ValueError, 'Expected floating point'): tfd.Laplace(loc=loc, scale=scale)", "event_size] * batch_size, dtype=np.float32) a_scale = np.array([[0.1] * event_size] *", "laplace = tfd.Laplace( loc=loc_v, scale=scale_v, validate_args=True) self.evaluate(laplace.mean()) scale = tf.Variable([1.,", "self.evaluate(d.sample(seed=test_util.test_seed())) def testLaplaceLaplaceKL(self): batch_size = 6 event_size = 3 a_loc", "total = 0 for k in sorted(s_p, key=lambda x: x[0]):", "np.array([[0.5] * event_size] * batch_size, dtype=np.float32) a_scale = np.array([[0.1] *", "def testLaplaceShape(self): loc = tf.constant([3.0] * 5) scale = tf.constant(11.0)", "* batch_size) loc_v = np.array([2.0, 4.0]) scale_v = np.array([3.0, 4.0])", "= tfd.Laplace(loc=1., scale=1.3, validate_args=True) vals = d.quantile(qs) self.assertAllClose([-np.inf, np.inf], vals[:2])", "expected_means = sp_stats.laplace.mean(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.mean()), expected_means) def testLaplaceMode(self): loc_v =", "tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.mode().shape, (3,)) self.assertAllClose(self.evaluate(laplace.mode()), loc_v) def testLaplaceVariance(self): loc_v", "enumerate(np.reshape(loc_v, [-1])): for bi, b in enumerate(np.reshape(scale_v, [-1])): s =", "tfd.Laplace(loc=a_loc, scale=a_scale, validate_args=True) b = tfd.Laplace(loc=b_loc, scale=b_scale, validate_args=True) distance =", "loc = tf.convert_to_tensor(0, dtype=tf.int32) scale = tf.convert_to_tensor(1, dtype=tf.int32) with self.assertRaisesRegexp(ValueError,", "tape.gradient(loss, d.trainable_variables) self.assertLen(grad, 2) self.assertAllNotNone(grad) def testAssertsPositiveScaleAfterMutation(self): scale = tf.Variable([1.,", "sp_stats.laplace.cdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(cdf), expected_cdf) def testLaplaceLogCDF(self): batch_size = 6", "tfd = tfp.distributions @test_util.test_all_tf_execution_regimes class LaplaceTest(test_util.TestCase): def testLaplaceShape(self): loc =", "(6,)) self.assertAllClose(self.evaluate(pdf), np.exp(expected_log_pdf)) def testLaplaceLogPDFMultidimensional(self): batch_size = 6 loc =", "= sp_stats.laplace.logsf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(sf), expected_sf) def testLaplaceMean(self): loc_v =", "scale_v = np.array([np.arange(1, 11, dtype=np.float32)]).T # 10 x 1 laplace", "0 for ai, a in enumerate(np.reshape(loc_v, [-1])): for bi, b", "http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed", "samplers from tensorflow_probability.python.internal import test_util tfd = tfp.distributions @test_util.test_all_tf_execution_regimes class", "1 + distance / b_scale + ratio * tf.exp(-distance /", "sample_values.var(), sp_stats.laplace.var(loc_v, scale=scale_v), rtol=0.05, atol=0.) self.assertTrue(self._kstest(loc_v, scale_v, sample_values)) def testLaplaceFullyReparameterized(self):", "= tf.Variable([1., 2., 3.]) d = tfd.Laplace(loc=0., scale=scale, validate_args=True) self.evaluate([v.initializer", "scale=scale_v) self.assertAllClose(self.evaluate(laplace.mean()), expected_means) def testLaplaceMode(self): loc_v = np.array([0.5, 3.0, 2.5])", "must be positive.'): with tf.control_dependencies([scale.assign([1., 2., -3.])]): self.evaluate(tfd.Laplace(loc=0., scale=1.).kl_divergence(d)) def", "sample_vals.mean(axis=0), rtol=0.05, atol=0.) self.assertAllClose( sp_stats.laplace.var([[7., 11.], [7., 11.]], scale=np.array([[5., 5.],", "sample_values = self.evaluate(samples) self.assertEqual(samples.shape, (n, 10, 100)) self.assertEqual(sample_values.shape, (n, 10,", "[[7., 11.], [7., 11.]], scale=np.array([[5., 5.], [6., 6.]])), sample_vals.mean(axis=0), rtol=0.05,", "batch_size) scale = tf.constant([[3.0, 4.0]] * batch_size) loc_v = np.array([2.0,", "@test_util.tf_tape_safety_test def testGradientThroughParams(self): loc = tf.Variable([-5., 0., 5.]) scale =", "= tf.Variable(2.) d = tfd.Laplace(loc=loc, scale=scale, validate_args=True) with tf.GradientTape() as", "= laplace.sample(n, seed=test_util.test_seed()) sample_values = self.evaluate(samples) self.assertEqual(samples.shape, (n, 10, 100))", "0], pdf_vals[:, 0, 0], err=0.02) self._assertIntegral(sample_vals[:, 0, 1], pdf_vals[:, 0,", "self.assertEqual(laplace.entropy().shape, (3,)) expected_entropy = sp_stats.laplace.entropy(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.entropy()), expected_entropy) def testLaplaceSample(self):", "or implied. # See the License for the specific language", "kl_sample_ = self.evaluate([true_kl, kl, kl_sample]) self.assertAllClose(true_kl_, kl_, atol=1e-5, rtol=1e-5) self.assertAllClose(true_kl_,", "err=0.02) self._assertIntegral(sample_vals[:, 0, 1], pdf_vals[:, 0, 1], err=0.02) self._assertIntegral(sample_vals[:, 1,", "batch_size, dtype=np.float32) b_scale = np.array([[0.2] * event_size] * batch_size, dtype=np.float32)", "KIND, either express or implied. # See the License for", "specific language governing permissions and # limitations under the License.", "laplace.prob(x) self.assertEqual(pdf.shape, (6,)) self.assertAllClose(self.evaluate(pdf), np.exp(expected_log_pdf)) def testLaplaceLogPDFMultidimensional(self): batch_size = 6", "scale=scale_v), rtol=0.05, atol=0.) self.assertTrue(self._kstest(loc_v, scale_v, sample_values)) def testLaplaceFullyReparameterized(self): loc =", "= np.array([1.0, 3.0, 2.5]) scale_v = np.array([1.0, 4.0, 5.0]) laplace", "trials = 0 for ai, a in enumerate(np.reshape(loc_v, [-1])): for", "name='loc') scale_v = tf.constant(-1.0, name='scale') with self.assertRaisesOpError('Argument `scale` must be", "b_loc) ratio = a_scale / b_scale true_kl = (-tf.math.log(ratio) -", "(-tf.math.log(ratio) - 1 + distance / b_scale + ratio *", "scale=s, validate_args=True).sample( # pylint: disable=g-long-lambda 100, seed=test_util.test_seed()), [loc, scale]) self.assertIsNotNone(grad_loc)", "np.array([[2.5, 2.5, 4.0, 0.1, 1.0, 2.0]], dtype=np.float32).T laplace = tfd.Laplace(loc=loc,", "self.assertEqual(self.evaluate(laplace.batch_shape_tensor()), (5,)) self.assertEqual(laplace.batch_shape, tf.TensorShape([5])) self.assertAllEqual(self.evaluate(laplace.event_shape_tensor()), []) self.assertEqual(laplace.event_shape, tf.TensorShape([])) def testLaplaceLogPDF(self):", "sp_stats.laplace.logpdf(x, loc_v, scale=scale_v) self.assertAllClose(log_pdf_values, expected_log_pdf) self.assertAllClose(pdf_values, np.exp(expected_log_pdf)) def testLaplaceLogPDFMultidimensionalBroadcasting(self): batch_size", "laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) samples = laplace.sample(n, seed=test_util.test_seed()) sample_values", "axis=0) true_kl_, kl_, kl_sample_ = self.evaluate([true_kl, kl, kl_sample]) self.assertAllClose(true_kl_, kl_,", "- prev[0]) * pair_pdf prev = k self.assertNear(1., total, err=err)", "testLaplaceLogPDF(self): batch_size = 6 loc = tf.constant([2.0] * batch_size) scale", "scale = tf.convert_to_tensor(1, dtype=tf.int32) with self.assertRaisesRegexp(ValueError, 'Expected floating point'): tfd.Laplace(loc=loc,", "be positive.'): with tf.control_dependencies([scale.assign([1., 2., -3.])]): self.evaluate(tfd.Laplace(loc=0., scale=1.).kl_divergence(d)) def testAssertParamsAreFloats(self):", "laplace.prob(samples) sample_vals, pdf_vals = self.evaluate([samples, pdfs]) self.assertEqual(samples.shape, (num, 2, 2))", "License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by", "scale=scale_v) self.assertAllClose(log_pdf_values, expected_log_pdf) self.assertAllClose(pdf_values, np.exp(expected_log_pdf)) def testLaplaceCDF(self): batch_size = 6", "laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) sf = laplace.log_survival_function(x) self.assertEqual(sf.shape, (6,))", "a = tfd.Laplace(loc=a_loc, scale=a_scale, validate_args=True) b = tfd.Laplace(loc=b_loc, scale=b_scale, validate_args=True)", "0.1, 1.0, 2.0], dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) sf", "atol=0.) def _assertIntegral(self, sample_vals, pdf_vals, err=1e-3): s_p = zip(sample_vals, pdf_vals)", "batch_size) loc_v = np.array([2.0, 4.0]) scale_v = np.array([3.0, 4.0]) x", "scale = tf.constant(3.0) loc_v = np.array([2.0, 4.0]) scale_v = 3.0", "seed=test_util.test_seed()) sample_values = self.evaluate(samples) self.assertEqual(samples.shape, (n,)) self.assertEqual(sample_values.shape, (n,)) self.assertAllClose( sample_values.mean(),", "self._assertIntegral(sample_vals[:, 1, 1], pdf_vals[:, 1, 1], err=0.02) self.assertAllClose( sp_stats.laplace.mean( [[7.,", "2.5, 4.0, 0.1, 1.0, 2.0]], dtype=np.float32).T laplace = tfd.Laplace(loc=loc, scale=scale,", "validate_args=True) distance = tf.abs(a_loc - b_loc) ratio = a_scale /", "self.evaluate(samples) self.assertEqual(samples.shape, (n,)) self.assertEqual(sample_values.shape, (n,)) self.assertAllClose( sample_values.mean(), sp_stats.laplace.mean(loc_v, scale=scale_v), rtol=0.05,", "np.array([2.0, 4.0]) scale_v = np.array([3.0, 4.0]) x = np.array([[2.5, 2.5,", "1 fails += 0 if self._kstest(a, b, s) else 1", "vals[:2]) self.assertAllClose(qs[2:], d.cdf(vals[2:])) def testLaplaceLogSurvivalFunction(self): batch_size = 6 loc =", "self.assertTrue(self._kstest(loc_v, scale_v, sample_values)) def testLaplaceFullyReparameterized(self): loc = tf.constant(4.0) scale =", "enumerate(np.reshape(scale_v, [-1])): s = sample_values[:, bi, ai] trials += 1", "loc = tf.constant([3.0] * 5) scale = tf.constant(11.0) laplace =", "= tfd.Laplace(loc=0., scale=scale, validate_args=True) self.evaluate([v.initializer for v in d.variables]) with", "+ prev[1]) / 2 total += (k[0] - prev[0]) *", "zeros scale_bc = scale_v + zeros self.assertAllClose( sample_values.mean(axis=0), sp_stats.laplace.mean(loc_bc, scale=scale_bc),", "= sp_stats.laplace.entropy(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.entropy()), expected_entropy) def testLaplaceSample(self): loc_v = 4.0", "scale=scale, validate_args=True) self.evaluate(d.sample(seed=test_util.test_seed())) def testLaplaceLaplaceKL(self): batch_size = 6 event_size =", "(the \"License\"); # you may not use this file except", "pdfs = laplace.prob(samples) sample_vals, pdf_vals = self.evaluate([samples, pdfs]) self.assertEqual(samples.shape, (num,", "for v in d.variables]) with self.assertRaisesOpError('Argument `scale` must be positive.'):", "# you may not use this file except in compliance", "= laplace.log_cdf(x) self.assertEqual(cdf.shape, (6,)) expected_cdf = sp_stats.laplace.logcdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(cdf),", "validate_args=True) self.evaluate(laplace.mean()) loc_v = tf.constant(1.0, name='loc') scale_v = tf.constant(0.0, name='scale')", "distance = tf.abs(a_loc - b_loc) ratio = a_scale / b_scale", "2.0]], dtype=np.float32).T laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) log_pdf = laplace.log_prob(x)", "tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.stddev().shape, (3,)) expected_stddev = sp_stats.laplace.std(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.stddev()),", "10, 100)) self.assertEqual(sample_values.shape, (n, 10, 100)) zeros = np.zeros_like(loc_v +", "log_pdf_values = self.evaluate(log_pdf) self.assertEqual(log_pdf.shape, (6, 2)) pdf = laplace.prob(x) pdf_values", "= tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.stddev().shape, (3,)) expected_stddev = sp_stats.laplace.std(loc_v, scale=scale_v)", "sp_stats.laplace.logpdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(log_pdf), expected_log_pdf) pdf = laplace.prob(x) self.assertEqual(pdf.shape, (6,))", "rtol=0.05, atol=0.) self.assertAllClose( sp_stats.laplace.var([[7., 11.], [7., 11.]], scale=np.array([[5., 5.], [6.,", "scale=scale_v) self.assertAllClose(self.evaluate(log_pdf), expected_log_pdf) pdf = laplace.prob(x) self.assertEqual(pdf.shape, (6,)) self.assertAllClose(self.evaluate(pdf), np.exp(expected_log_pdf))", "def testLaplaceSampleMultiDimensional(self): loc_v = np.array([np.arange(1, 101, dtype=np.float32)]) # 1 x", "zeros = np.zeros_like(loc_v + scale_v) # 10 x 100 loc_bc", "zeros self.assertAllClose( sample_values.mean(axis=0), sp_stats.laplace.mean(loc_bc, scale=scale_bc), rtol=0.35, atol=0.) self.assertAllClose( sample_values.var(axis=0), sp_stats.laplace.var(loc_bc,", "k self.assertNear(1., total, err=err) def testLaplaceNonPositiveInitializationParamsRaises(self): loc_v = tf.constant(0.0, name='loc')", "d.cdf(vals[2:])) def testLaplaceLogSurvivalFunction(self): batch_size = 6 loc = tf.constant([2.0] *", "= tf.constant(1.0, name='loc') scale_v = tf.constant(0.0, name='scale') with self.assertRaisesOpError('Argument `scale`", "tf.constant([[3.0, 4.0]] * batch_size) loc_v = np.array([2.0, 4.0]) scale_v =", "/ b_scale true_kl = (-tf.math.log(ratio) - 1 + distance /", "self.assertEqual(pdf.shape, (6,)) self.assertAllClose(self.evaluate(pdf), np.exp(expected_log_pdf)) def testLaplaceLogPDFMultidimensional(self): batch_size = 6 loc", "and # limitations under the License. # ============================================================================ from __future__", "1 self.assertLess(fails, trials * 0.03) def _kstest(self, loc, scale, samples):", "sp_stats.laplace.mean(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.mean()), expected_means) def testLaplaceMode(self): loc_v = np.array([0.5, 3.0,", "= tf.reduce_mean(a.log_prob(x) - b.log_prob(x), axis=0) true_kl_, kl_, kl_sample_ = self.evaluate([true_kl,", "= sp_stats.kstest(samples, sp_stats.laplace(loc, scale=scale).cdf) # Return True when the test", "/ b_scale + ratio * tf.exp(-distance / a_scale)) kl =", "# # Unless required by applicable law or agreed to", "batch_size, dtype=np.float32) a = tfd.Laplace(loc=a_loc, scale=a_scale, validate_args=True) b = tfd.Laplace(loc=b_loc,", "s: tfd.Laplace(loc=l, scale=s, validate_args=True).sample( # pylint: disable=g-long-lambda 100, seed=test_util.test_seed()), [loc,", "pdf_vals[:, 1, 1], err=0.02) self.assertAllClose( sp_stats.laplace.mean( [[7., 11.], [7., 11.]],", "= (-tf.math.log(ratio) - 1 + distance / b_scale + ratio", "sample_values)) def testLaplaceFullyReparameterized(self): loc = tf.constant(4.0) scale = tf.constant(3.0) _,", "a_scale)) kl = tfd.kl_divergence(a, b) x = a.sample(int(1e4), seed=test_util.test_seed()) kl_sample", "obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0", "1.0, 2.0], dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) cdf =", "self.assertEqual(sample_values.shape, (n,)) self.assertAllClose( sample_values.mean(), sp_stats.laplace.mean(loc_v, scale=scale_v), rtol=0.05, atol=0.) self.assertAllClose( sample_values.var(),", "a_scale / b_scale true_kl = (-tf.math.log(ratio) - 1 + distance", "err=0.02) self._assertIntegral(sample_vals[:, 1, 1], pdf_vals[:, 1, 1], err=0.02) self.assertAllClose( sp_stats.laplace.mean(", "= -d.log_prob([1., 2., 3.]) grad = tape.gradient(loss, d.trainable_variables) self.assertLen(grad, 2)", "Version 2.0 (the \"License\"); # you may not use this", "np.array([[0.1] * event_size] * batch_size, dtype=np.float32) b_loc = np.array([[0.4] *", "zero_kl_) @test_util.tf_tape_safety_test def testGradientThroughParams(self): loc = tf.Variable([-5., 0., 5.]) scale", "sp_stats.laplace.mean(loc_v, scale=scale_v), rtol=0.05, atol=0.) self.assertAllClose( sample_values.var(), sp_stats.laplace.var(loc_v, scale=scale_v), rtol=0.05, atol=0.)", "= self.evaluate([tf.zeros_like(true_kl), zero_kl]) self.assertAllEqual(true_zero_kl_, zero_kl_) @test_util.tf_tape_safety_test def testGradientThroughParams(self): loc =", "* event_size] * batch_size, dtype=np.float32) a = tfd.Laplace(loc=a_loc, scale=a_scale, validate_args=True)", "laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) self.assertEqual(self.evaluate(laplace.batch_shape_tensor()), (5,)) self.assertEqual(laplace.batch_shape, tf.TensorShape([5])) self.assertAllEqual(self.evaluate(laplace.event_shape_tensor()),", "= scale_v + zeros self.assertAllClose( sample_values.mean(axis=0), sp_stats.laplace.mean(loc_bc, scale=scale_bc), rtol=0.35, atol=0.)", "batch_size, dtype=np.float32) b_loc = np.array([[0.4] * event_size] * batch_size, dtype=np.float32)", "============================================================================ from __future__ import absolute_import from __future__ import division from", "self.assertAllClose(self.evaluate(laplace.mean()), expected_means) def testLaplaceMode(self): loc_v = np.array([0.5, 3.0, 2.5]) scale_v", "sp_stats.laplace.var(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.variance()), expected_variances) def testLaplaceStd(self): loc_v = np.array([1.0, 3.0,", "def _kstest(self, loc, scale, samples): # Uses the Kolmogorov-Smirnov test", "2., -3.])]): self.evaluate(tfd.Laplace(loc=0., scale=1.).kl_divergence(d)) def testAssertParamsAreFloats(self): loc = tf.convert_to_tensor(0, dtype=tf.int32)", "testLaplaceQuantile(self): qs = self.evaluate( tf.concat( [[0., 1], samplers.uniform([10], minval=.1, maxval=.9,", "k in sorted(s_p, key=lambda x: x[0]): pair_pdf = (k[1] +", "= tfp.distributions @test_util.test_all_tf_execution_regimes class LaplaceTest(test_util.TestCase): def testLaplaceShape(self): loc = tf.constant([3.0]", "__future__ import absolute_import from __future__ import division from __future__ import", "laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) cdf = laplace.log_cdf(x) self.assertEqual(cdf.shape, (6,))", "testAssertsPositiveScaleAfterMutation(self): scale = tf.Variable([1., 2., 3.]) d = tfd.Laplace(loc=0., scale=scale,", "implied. # See the License for the specific language governing", "0, 0], pdf_vals[:, 0, 0], err=0.02) self._assertIntegral(sample_vals[:, 0, 1], pdf_vals[:,", "pdf_vals, err=1e-3): s_p = zip(sample_vals, pdf_vals) prev = (0, 0)", "= np.zeros_like(loc_v + scale_v) # 10 x 100 loc_bc =", "* pair_pdf prev = k self.assertNear(1., total, err=err) def testLaplaceNonPositiveInitializationParamsRaises(self):", "under the Apache License, Version 2.0 (the \"License\"); # you", "pdfs]) self.assertEqual(samples.shape, (num, 2, 2)) self.assertEqual(pdfs.shape, (num, 2, 2)) self._assertIntegral(sample_vals[:,", "self.assertEqual(log_pdf.shape, (6, 2)) pdf = laplace.prob(x) pdf_values = self.evaluate(pdf) self.assertEqual(pdf.shape,", "[-1])): for bi, b in enumerate(np.reshape(scale_v, [-1])): s = sample_values[:,", "import stats as sp_stats import tensorflow.compat.v2 as tf import tensorflow_probability", "absolute_import from __future__ import division from __future__ import print_function #", "b) x = a.sample(int(1e4), seed=test_util.test_seed()) kl_sample = tf.reduce_mean(a.log_prob(x) - b.log_prob(x),", "testAssertParamsAreFloats(self): loc = tf.convert_to_tensor(0, dtype=tf.int32) scale = tf.convert_to_tensor(1, dtype=tf.int32) with", "x = np.array([2.5, 2.5, 4.0, 0.1, 1.0, 2.0], dtype=np.float32) laplace", "scale=scale, validate_args=True) samples = laplace.sample(n, seed=test_util.test_seed()) sample_values = self.evaluate(samples) self.assertEqual(samples.shape,", "'Expected floating point'): tfd.Laplace(loc=loc, scale=scale) if __name__ == '__main__': tf.test.main()", "validate_args=True) log_pdf = laplace.log_prob(x) log_pdf_values = self.evaluate(log_pdf) self.assertEqual(log_pdf.shape, (6, 2))", "by applicable law or agreed to in writing, software #", "tf.constant(scale_v) n = 100000 laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) samples", "validate_args=True) b = tfd.Laplace(loc=b_loc, scale=b_scale, validate_args=True) distance = tf.abs(a_loc -", "np.array([[0.4] * event_size] * batch_size, dtype=np.float32) b_scale = np.array([[0.2] *", "self.evaluate(tfd.Laplace(loc=0., scale=1.).kl_divergence(d)) def testAssertParamsAreFloats(self): loc = tf.convert_to_tensor(0, dtype=tf.int32) scale =", "np.array([2.5, 2.5, 4.0, 0.1, 1.0, 2.0], dtype=np.float32) laplace = tfd.Laplace(loc=loc,", "3.0, 2.5]) scale_v = np.array([1.0, 4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v,", "event_size = 3 a_loc = np.array([[0.5] * event_size] * batch_size,", "expected_sf = sp_stats.laplace.logsf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(sf), expected_sf) def testLaplaceMean(self): loc_v", "(n, 10, 100)) self.assertEqual(sample_values.shape, (n, 10, 100)) zeros = np.zeros_like(loc_v", "2)) self._assertIntegral(sample_vals[:, 0, 0], pdf_vals[:, 0, 0], err=0.02) self._assertIntegral(sample_vals[:, 0,", "loc_v = np.array([0.5, 3.0, 2.5]) scale_v = np.array([1.0, 4.0, 5.0])", "event_size] * batch_size, dtype=np.float32) b_scale = np.array([[0.2] * event_size] *", "10 x 100 loc_bc = loc_v + zeros scale_bc =", "scale=1.3, validate_args=True) vals = d.quantile(qs) self.assertAllClose([-np.inf, np.inf], vals[:2]) self.assertAllClose(qs[2:], d.cdf(vals[2:]))", "= sample_values[:, bi, ai] trials += 1 fails += 0", "ratio * tf.exp(-distance / a_scale)) kl = tfd.kl_divergence(a, b) x", "1.0, 2.0], dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) log_pdf =", "= np.array([2.0, 4.0]) scale_v = 3.0 x = np.array([[2.5, 2.5,", "with self.assertRaisesRegexp(ValueError, 'Expected floating point'): tfd.Laplace(loc=loc, scale=scale) if __name__ ==", "self.assertEqual(laplace.event_shape, tf.TensorShape([])) def testLaplaceLogPDF(self): batch_size = 6 loc = tf.constant([2.0]", "loc_v, scale=scale_v) self.assertAllClose(log_pdf_values, expected_log_pdf) self.assertAllClose(pdf_values, np.exp(expected_log_pdf)) def testLaplaceLogPDFMultidimensionalBroadcasting(self): batch_size =", "11.]], scale=np.array([[5., 5.], [6., 6.]])), sample_vals.var(axis=0), rtol=0.05, atol=0.) def _assertIntegral(self,", "# ============================================================================ from __future__ import absolute_import from __future__ import division", "laplace.prob(x) pdf_values = self.evaluate(pdf) self.assertEqual(pdf.shape, (6, 2)) expected_log_pdf = sp_stats.laplace.logpdf(x,", "batch_size) scale = tf.constant([3.0] * batch_size) loc_v = 2.0 scale_v", "self.assertEqual(laplace.mode().shape, (3,)) self.assertAllClose(self.evaluate(laplace.mode()), loc_v) def testLaplaceVariance(self): loc_v = np.array([1.0, 3.0,", "np.exp(expected_log_pdf)) def testLaplaceLogPDFMultidimensional(self): batch_size = 6 loc = tf.constant([[2.0, 4.0]]", "self.assertAllEqual(self.evaluate(laplace.event_shape_tensor()), []) self.assertEqual(laplace.event_shape, tf.TensorShape([])) def testLaplaceLogPDF(self): batch_size = 6 loc", "scale = tf.Variable(2.) d = tfd.Laplace(loc=loc, scale=scale, validate_args=True) with tf.GradientTape()", "[6.]], validate_args=True) num = 50000 samples = laplace.sample(num, seed=test_util.test_seed()) pdfs", "0.02 def testLaplacePdfOfSampleMultiDims(self): laplace = tfd.Laplace(loc=[7., 11.], scale=[[5.], [6.]], validate_args=True)", "= sp_stats.laplace.mean(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.mean()), expected_means) def testLaplaceMode(self): loc_v = np.array([0.5,", "scale=scale, validate_args=True) log_pdf = laplace.log_prob(x) self.assertEqual(log_pdf.shape, (6,)) expected_log_pdf = sp_stats.laplace.logpdf(x,", "scale = tf.constant(3.0) _, [grad_loc, grad_scale] = tfp.math.value_and_gradient( lambda l,", "be positive.'): laplace = tfd.Laplace( loc=loc_v, scale=scale_v, validate_args=True) self.evaluate(laplace.mean()) scale", "return ks < 0.02 def testLaplacePdfOfSampleMultiDims(self): laplace = tfd.Laplace(loc=[7., 11.],", "tf.exp(-distance / a_scale)) kl = tfd.kl_divergence(a, b) x = a.sample(int(1e4),", "1 x 100 scale_v = np.array([np.arange(1, 11, dtype=np.float32)]).T # 10", "validate_args=True) self.assertEqual(self.evaluate(laplace.batch_shape_tensor()), (5,)) self.assertEqual(laplace.batch_shape, tf.TensorShape([5])) self.assertAllEqual(self.evaluate(laplace.event_shape_tensor()), []) self.assertEqual(laplace.event_shape, tf.TensorShape([])) def", "dtype=np.float32) a_scale = np.array([[0.1] * event_size] * batch_size, dtype=np.float32) b_loc", "def testLaplaceMean(self): loc_v = np.array([1.0, 3.0, 2.5]) scale_v = np.array([1.0,", "2, 2)) self._assertIntegral(sample_vals[:, 0, 0], pdf_vals[:, 0, 0], err=0.02) self._assertIntegral(sample_vals[:,", "= tf.constant([[2.0, 4.0]] * batch_size) scale = tf.constant(3.0) loc_v =", "tfp from tensorflow_probability.python.internal import samplers from tensorflow_probability.python.internal import test_util tfd", "validate_args=True) log_pdf = laplace.log_prob(x) self.assertEqual(log_pdf.shape, (6,)) expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v,", "when the test passes. return ks < 0.02 def testLaplacePdfOfSampleMultiDims(self):", "= 0 for k in sorted(s_p, key=lambda x: x[0]): pair_pdf", "testLaplaceCDF(self): batch_size = 6 loc = tf.constant([2.0] * batch_size) scale", "dtype=tf.int32) with self.assertRaisesRegexp(ValueError, 'Expected floating point'): tfd.Laplace(loc=loc, scale=scale) if __name__", "self.assertAllClose( sample_values.mean(), sp_stats.laplace.mean(loc_v, scale=scale_v), rtol=0.05, atol=0.) self.assertAllClose( sample_values.var(), sp_stats.laplace.var(loc_v, scale=scale_v),", "pdf_vals) prev = (0, 0) total = 0 for k", "tfd.Laplace(loc=loc, scale=scale, validate_args=True) samples = laplace.sample(n, seed=test_util.test_seed()) sample_values = self.evaluate(samples)", "scale=scale_v), rtol=0.05, atol=0.) self.assertAllClose( sample_values.var(), sp_stats.laplace.var(loc_v, scale=scale_v), rtol=0.05, atol=0.) self.assertTrue(self._kstest(loc_v,", "= tfd.Laplace(loc=loc, scale=scale, validate_args=True) with tf.GradientTape() as tape: loss =", "an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF", "= (0, 0) total = 0 for k in sorted(s_p,", "= tf.constant(4.0) scale = tf.constant(3.0) _, [grad_loc, grad_scale] = tfp.math.value_and_gradient(", "Unless required by applicable law or agreed to in writing,", "validate_args=True) self.assertEqual(laplace.stddev().shape, (3,)) expected_stddev = sp_stats.laplace.std(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.stddev()), expected_stddev) def", "scale = tf.constant([[3.0, 4.0]] * batch_size) loc_v = np.array([2.0, 4.0])", "def testLaplaceCDF(self): batch_size = 6 loc = tf.constant([2.0] * batch_size)", "self.assertAllClose( sample_values.var(axis=0), sp_stats.laplace.var(loc_bc, scale=scale_bc), rtol=0.10, atol=0.) fails = 0 trials", "def testLaplaceLogPDFMultidimensionalBroadcasting(self): batch_size = 6 loc = tf.constant([[2.0, 4.0]] *", "x 100 scale_v = np.array([np.arange(1, 11, dtype=np.float32)]).T # 10 x", "err=1e-3): s_p = zip(sample_vals, pdf_vals) prev = (0, 0) total", "tfd.kl_divergence(a, a) true_zero_kl_, zero_kl_ = self.evaluate([tf.zeros_like(true_kl), zero_kl]) self.assertAllEqual(true_zero_kl_, zero_kl_) @test_util.tf_tape_safety_test", "scale, samples): # Uses the Kolmogorov-Smirnov test for goodness of", "* batch_size, dtype=np.float32) a = tfd.Laplace(loc=a_loc, scale=a_scale, validate_args=True) b =", "kl_, kl_sample_ = self.evaluate([true_kl, kl, kl_sample]) self.assertAllClose(true_kl_, kl_, atol=1e-5, rtol=1e-5)", "tfd.Laplace(loc=l, scale=s, validate_args=True).sample( # pylint: disable=g-long-lambda 100, seed=test_util.test_seed()), [loc, scale])", "loc = tf.Variable([-5., 0., 5.]) scale = tf.Variable(2.) d =", "self.assertAllClose(self.evaluate(laplace.entropy()), expected_entropy) def testLaplaceSample(self): loc_v = 4.0 scale_v = 3.0", "sf = laplace.log_survival_function(x) self.assertEqual(sf.shape, (6,)) expected_sf = sp_stats.laplace.logsf(x, loc_v, scale=scale_v)", "rtol=0.05, atol=0.) def _assertIntegral(self, sample_vals, pdf_vals, err=1e-3): s_p = zip(sample_vals,", "the specific language governing permissions and # limitations under the", "for k in sorted(s_p, key=lambda x: x[0]): pair_pdf = (k[1]", "x: x[0]): pair_pdf = (k[1] + prev[1]) / 2 total", "2., 3.]) d = tfd.Laplace(loc=0., scale=scale, validate_args=True) self.evaluate([v.initializer for v", "[loc, scale]) self.assertIsNotNone(grad_loc) self.assertIsNotNone(grad_scale) def testLaplaceSampleMultiDimensional(self): loc_v = np.array([np.arange(1, 101,", "expected_cdf) def testLaplaceLogCDF(self): batch_size = 6 loc = tf.constant([2.0] *", "= (k[1] + prev[1]) / 2 total += (k[0] -", "= sp_stats.laplace.logcdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(cdf), expected_cdf) def testLaplaceQuantile(self): qs =", "laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.variance().shape, (3,)) expected_variances = sp_stats.laplace.var(loc_v,", "seed=test_util.test_seed()) kl_sample = tf.reduce_mean(a.log_prob(x) - b.log_prob(x), axis=0) true_kl_, kl_, kl_sample_", "(n,)) self.assertAllClose( sample_values.mean(), sp_stats.laplace.mean(loc_v, scale=scale_v), rtol=0.05, atol=0.) self.assertAllClose( sample_values.var(), sp_stats.laplace.var(loc_v,", "applicable law or agreed to in writing, software # distributed", "err=err) def testLaplaceNonPositiveInitializationParamsRaises(self): loc_v = tf.constant(0.0, name='loc') scale_v = tf.constant(-1.0,", "(6,)) expected_cdf = sp_stats.laplace.logcdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(cdf), expected_cdf) def testLaplaceQuantile(self):", "rtol=1e-5) self.assertAllClose(true_kl_, kl_sample_, atol=0., rtol=1e-1) zero_kl = tfd.kl_divergence(a, a) true_zero_kl_,", "key=lambda x: x[0]): pair_pdf = (k[1] + prev[1]) / 2", "dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) cdf = laplace.log_cdf(x) self.assertEqual(cdf.shape,", "fails = 0 trials = 0 for ai, a in", "for goodness of fit. ks, _ = sp_stats.kstest(samples, sp_stats.laplace(loc, scale=scale).cdf)", "+ zeros scale_bc = scale_v + zeros self.assertAllClose( sample_values.mean(axis=0), sp_stats.laplace.mean(loc_bc,", "= laplace.sample(num, seed=test_util.test_seed()) pdfs = laplace.prob(samples) sample_vals, pdf_vals = self.evaluate([samples,", "must be positive.'): laplace = tfd.Laplace( loc=loc_v, scale=scale_v, validate_args=True) self.evaluate(laplace.mean())", "laplace = tfd.Laplace( loc=loc_v, scale=scale_v, validate_args=True) self.evaluate(laplace.mean()) loc_v = tf.constant(1.0,", "self.assertRaisesOpError('Argument `scale` must be positive.'): d = tfd.Laplace(loc=0, scale=scale, validate_args=True)", "loc_v) def testLaplaceVariance(self): loc_v = np.array([1.0, 3.0, 2.5]) scale_v =", "= tf.constant(3.0) _, [grad_loc, grad_scale] = tfp.math.value_and_gradient( lambda l, s:", "tf.constant([[2.0, 4.0]] * batch_size) scale = tf.constant(3.0) loc_v = np.array([2.0,", "50000 samples = laplace.sample(num, seed=test_util.test_seed()) pdfs = laplace.prob(samples) sample_vals, pdf_vals", "in writing, software # distributed under the License is distributed", "4.0 scale_v = 3.0 loc = tf.constant(loc_v) scale = tf.constant(scale_v)", "0.1, 1.0, 2.0], dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) log_pdf", "tf.constant([[2.0, 4.0]] * batch_size) scale = tf.constant([[3.0, 4.0]] * batch_size)", "self.assertAllClose( sample_values.mean(axis=0), sp_stats.laplace.mean(loc_bc, scale=scale_bc), rtol=0.35, atol=0.) self.assertAllClose( sample_values.var(axis=0), sp_stats.laplace.var(loc_bc, scale=scale_bc),", "11.]], scale=np.array([[5., 5.], [6., 6.]])), sample_vals.mean(axis=0), rtol=0.05, atol=0.) self.assertAllClose( sp_stats.laplace.var([[7.,", "(k[1] + prev[1]) / 2 total += (k[0] - prev[0])", "* batch_size) scale = tf.constant([[3.0, 4.0]] * batch_size) loc_v =", "total, err=err) def testLaplaceNonPositiveInitializationParamsRaises(self): loc_v = tf.constant(0.0, name='loc') scale_v =", "1, 1], pdf_vals[:, 1, 1], err=0.02) self.assertAllClose( sp_stats.laplace.mean( [[7., 11.],", "3.0 x = np.array([-2.5, 2.5, -4.0, 0.1, 1.0, 2.0], dtype=np.float32)", "pdf_vals[:, 1, 0], err=0.02) self._assertIntegral(sample_vals[:, 1, 1], pdf_vals[:, 1, 1],", "zip(sample_vals, pdf_vals) prev = (0, 0) total = 0 for", "= tfd.Laplace(loc=loc, scale=scale, validate_args=True) self.assertEqual(self.evaluate(laplace.batch_shape_tensor()), (5,)) self.assertEqual(laplace.batch_shape, tf.TensorShape([5])) self.assertAllEqual(self.evaluate(laplace.event_shape_tensor()), [])", "def testLaplaceQuantile(self): qs = self.evaluate( tf.concat( [[0., 1], samplers.uniform([10], minval=.1,", "sorted(s_p, key=lambda x: x[0]): pair_pdf = (k[1] + prev[1]) /", "scale=scale, validate_args=True) log_pdf = laplace.log_prob(x) log_pdf_values = self.evaluate(log_pdf) self.assertEqual(log_pdf.shape, (6,", "import division from __future__ import print_function # Dependency imports import", "scale=1.).kl_divergence(d)) def testAssertParamsAreFloats(self): loc = tf.convert_to_tensor(0, dtype=tf.int32) scale = tf.convert_to_tensor(1,", "self.assertAllClose(self.evaluate(cdf), expected_cdf) def testLaplaceQuantile(self): qs = self.evaluate( tf.concat( [[0., 1],", "ai, a in enumerate(np.reshape(loc_v, [-1])): for bi, b in enumerate(np.reshape(scale_v,", "0, 1], err=0.02) self._assertIntegral(sample_vals[:, 1, 0], pdf_vals[:, 1, 0], err=0.02)", "0., 5.]) scale = tf.Variable(2.) d = tfd.Laplace(loc=loc, scale=scale, validate_args=True)", "- b.log_prob(x), axis=0) true_kl_, kl_, kl_sample_ = self.evaluate([true_kl, kl, kl_sample])", "= self.evaluate( tf.concat( [[0., 1], samplers.uniform([10], minval=.1, maxval=.9, seed=test_util.test_seed())], axis=0))", "samples = laplace.sample(n, seed=test_util.test_seed()) sample_values = self.evaluate(samples) self.assertEqual(samples.shape, (n, 10,", "with tf.control_dependencies([scale.assign([1., 2., -3.])]): self.evaluate(tfd.Laplace(loc=0., scale=1.).kl_divergence(d)) def testAssertParamsAreFloats(self): loc =", "[7., 11.]], scale=np.array([[5., 5.], [6., 6.]])), sample_vals.mean(axis=0), rtol=0.05, atol=0.) self.assertAllClose(", "Authors. # # Licensed under the Apache License, Version 2.0", "tensorflow_probability.python.internal import samplers from tensorflow_probability.python.internal import test_util tfd = tfp.distributions", "b.log_prob(x), axis=0) true_kl_, kl_, kl_sample_ = self.evaluate([true_kl, kl, kl_sample]) self.assertAllClose(true_kl_,", "tf.abs(a_loc - b_loc) ratio = a_scale / b_scale true_kl =", "-3.])]): self.evaluate(tfd.Laplace(loc=0., scale=1.).kl_divergence(d)) def testAssertParamsAreFloats(self): loc = tf.convert_to_tensor(0, dtype=tf.int32) scale", "self.evaluate(scale.initializer) with self.assertRaisesOpError('Argument `scale` must be positive.'): d = tfd.Laplace(loc=0,", "b, s) else 1 self.assertLess(fails, trials * 0.03) def _kstest(self,", "License is distributed on an \"AS IS\" BASIS, # WITHOUT", "= tf.convert_to_tensor(0, dtype=tf.int32) scale = tf.convert_to_tensor(1, dtype=tf.int32) with self.assertRaisesRegexp(ValueError, 'Expected", "atol=0.) self.assertTrue(self._kstest(loc_v, scale_v, sample_values)) def testLaplaceFullyReparameterized(self): loc = tf.constant(4.0) scale", "2.0], dtype=np.float32) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) log_pdf = laplace.log_prob(x)", "License, Version 2.0 (the \"License\"); # you may not use", "self.assertAllClose( sample_values.var(), sp_stats.laplace.var(loc_v, scale=scale_v), rtol=0.05, atol=0.) self.assertTrue(self._kstest(loc_v, scale_v, sample_values)) def", "3 a_loc = np.array([[0.5] * event_size] * batch_size, dtype=np.float32) a_scale", "= tf.abs(a_loc - b_loc) ratio = a_scale / b_scale true_kl", "scale=scale_v) self.assertAllClose(self.evaluate(cdf), expected_cdf) def testLaplaceLogCDF(self): batch_size = 6 loc =", "# You may obtain a copy of the License at", "pdf_vals = self.evaluate([samples, pdfs]) self.assertEqual(samples.shape, (num, 2, 2)) self.assertEqual(pdfs.shape, (num,", "validate_args=True) self.evaluate(laplace.mean()) scale = tf.Variable([1., 2., -3.]) self.evaluate(scale.initializer) with self.assertRaisesOpError('Argument", "testLaplaceLogPDFMultidimensional(self): batch_size = 6 loc = tf.constant([[2.0, 4.0]] * batch_size)", "= sp_stats.laplace.logpdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(log_pdf), expected_log_pdf) pdf = laplace.prob(x) self.assertEqual(pdf.shape,", "* batch_size) scale = tf.constant([3.0] * batch_size) loc_v = 2.0", "def testLaplaceFullyReparameterized(self): loc = tf.constant(4.0) scale = tf.constant(3.0) _, [grad_loc,", "laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.mode().shape, (3,)) self.assertAllClose(self.evaluate(laplace.mode()), loc_v) def", "copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #", "scale=scale_v, validate_args=True) self.evaluate(laplace.mean()) loc_v = tf.constant(1.0, name='loc') scale_v = tf.constant(0.0,", "d.variables]) with self.assertRaisesOpError('Argument `scale` must be positive.'): with tf.control_dependencies([scale.assign([1., 2.,", "Uses the Kolmogorov-Smirnov test for goodness of fit. ks, _", "def testGradientThroughParams(self): loc = tf.Variable([-5., 0., 5.]) scale = tf.Variable(2.)", "100000 laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) samples = laplace.sample(n, seed=test_util.test_seed())", "self.assertAllClose(pdf_values, np.exp(expected_log_pdf)) def testLaplaceLogPDFMultidimensionalBroadcasting(self): batch_size = 6 loc = tf.constant([[2.0,", "b_scale true_kl = (-tf.math.log(ratio) - 1 + distance / b_scale", "disable=g-long-lambda 100, seed=test_util.test_seed()), [loc, scale]) self.assertIsNotNone(grad_loc) self.assertIsNotNone(grad_scale) def testLaplaceSampleMultiDimensional(self): loc_v", "def testLaplaceLaplaceKL(self): batch_size = 6 event_size = 3 a_loc =", "= np.array([np.arange(1, 11, dtype=np.float32)]).T # 10 x 1 laplace =", "= tf.constant([3.0] * 5) scale = tf.constant(11.0) laplace = tfd.Laplace(loc=loc,", "1.0, 2.0]], dtype=np.float32).T laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) log_pdf =", "self.assertAllClose(log_pdf_values, expected_log_pdf) self.assertAllClose(pdf_values, np.exp(expected_log_pdf)) def testLaplaceLogPDFMultidimensionalBroadcasting(self): batch_size = 6 loc", "np.inf], vals[:2]) self.assertAllClose(qs[2:], d.cdf(vals[2:])) def testLaplaceLogSurvivalFunction(self): batch_size = 6 loc", "scale_bc = scale_v + zeros self.assertAllClose( sample_values.mean(axis=0), sp_stats.laplace.mean(loc_bc, scale=scale_bc), rtol=0.35,", "sp_stats.laplace.mean( [[7., 11.], [7., 11.]], scale=np.array([[5., 5.], [6., 6.]])), sample_vals.mean(axis=0),", "100, seed=test_util.test_seed()), [loc, scale]) self.assertIsNotNone(grad_loc) self.assertIsNotNone(grad_scale) def testLaplaceSampleMultiDimensional(self): loc_v =", "tf.convert_to_tensor(1, dtype=tf.int32) with self.assertRaisesRegexp(ValueError, 'Expected floating point'): tfd.Laplace(loc=loc, scale=scale) if", "= tfd.Laplace(loc=0, scale=scale, validate_args=True) self.evaluate(d.sample(seed=test_util.test_seed())) def testLaplaceLaplaceKL(self): batch_size = 6", "fit. ks, _ = sp_stats.kstest(samples, sp_stats.laplace(loc, scale=scale).cdf) # Return True", "in d.variables]) with self.assertRaisesOpError('Argument `scale` must be positive.'): with tf.control_dependencies([scale.assign([1.,", "4.0]] * batch_size) scale = tf.constant([[3.0, 4.0]] * batch_size) loc_v", "2)) expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v, scale=scale_v) self.assertAllClose(log_pdf_values, expected_log_pdf) self.assertAllClose(pdf_values, np.exp(expected_log_pdf))", "= np.array([3.0, 4.0]) x = np.array([[2.5, 2.5, 4.0, 0.1, 1.0,", "test_util tfd = tfp.distributions @test_util.test_all_tf_execution_regimes class LaplaceTest(test_util.TestCase): def testLaplaceShape(self): loc", "* batch_size) scale = tf.constant(3.0) loc_v = np.array([2.0, 4.0]) scale_v", "scale=scale, validate_args=True) cdf = laplace.log_cdf(x) self.assertEqual(cdf.shape, (6,)) expected_cdf = sp_stats.laplace.logcdf(x,", "the License for the specific language governing permissions and #", "= 0 for ai, a in enumerate(np.reshape(loc_v, [-1])): for bi,", "= 50000 samples = laplace.sample(num, seed=test_util.test_seed()) pdfs = laplace.prob(samples) sample_vals,", "import tensorflow_probability as tfp from tensorflow_probability.python.internal import samplers from tensorflow_probability.python.internal", "must be positive.'): d = tfd.Laplace(loc=0, scale=scale, validate_args=True) self.evaluate(d.sample(seed=test_util.test_seed())) def", "a_loc = np.array([[0.5] * event_size] * batch_size, dtype=np.float32) a_scale =", "Apache License, Version 2.0 (the \"License\"); # you may not", "in enumerate(np.reshape(scale_v, [-1])): s = sample_values[:, bi, ai] trials +=", "the test passes. return ks < 0.02 def testLaplacePdfOfSampleMultiDims(self): laplace", "either express or implied. # See the License for the", "permissions and # limitations under the License. # ============================================================================ from", "5.], [6., 6.]])), sample_vals.mean(axis=0), rtol=0.05, atol=0.) self.assertAllClose( sp_stats.laplace.var([[7., 11.], [7.,", "prev[0]) * pair_pdf prev = k self.assertNear(1., total, err=err) def", "true_zero_kl_, zero_kl_ = self.evaluate([tf.zeros_like(true_kl), zero_kl]) self.assertAllEqual(true_zero_kl_, zero_kl_) @test_util.tf_tape_safety_test def testGradientThroughParams(self):", "= 4.0 scale_v = 3.0 loc = tf.constant(loc_v) scale =", "kl_, atol=1e-5, rtol=1e-5) self.assertAllClose(true_kl_, kl_sample_, atol=0., rtol=1e-1) zero_kl = tfd.kl_divergence(a,", "pdf = laplace.prob(x) self.assertEqual(pdf.shape, (6,)) self.assertAllClose(self.evaluate(pdf), np.exp(expected_log_pdf)) def testLaplaceLogPDFMultidimensional(self): batch_size", "tfd.Laplace(loc=loc, scale=scale, validate_args=True) log_pdf = laplace.log_prob(x) self.assertEqual(log_pdf.shape, (6,)) expected_log_pdf =", "self.assertEqual(laplace.variance().shape, (3,)) expected_variances = sp_stats.laplace.var(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.variance()), expected_variances) def testLaplaceStd(self):", "# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or", "= np.array([[2.5, 2.5, 4.0, 0.1, 1.0, 2.0]], dtype=np.float32).T laplace =", "= laplace.log_prob(x) self.assertEqual(log_pdf.shape, (6,)) expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(log_pdf),", "seed=test_util.test_seed()) pdfs = laplace.prob(samples) sample_vals, pdf_vals = self.evaluate([samples, pdfs]) self.assertEqual(samples.shape,", "self.assertEqual(pdf.shape, (6, 2)) expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v, scale=scale_v) self.assertAllClose(log_pdf_values, expected_log_pdf)", "+= 1 fails += 0 if self._kstest(a, b, s) else", "5) scale = tf.constant(11.0) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) self.assertEqual(self.evaluate(laplace.batch_shape_tensor()),", "tfd.Laplace(loc=loc, scale=scale, validate_args=True) log_pdf = laplace.log_prob(x) log_pdf_values = self.evaluate(log_pdf) self.assertEqual(log_pdf.shape,", "positive.'): d = tfd.Laplace(loc=0, scale=scale, validate_args=True) self.evaluate(d.sample(seed=test_util.test_seed())) def testLaplaceLaplaceKL(self): batch_size", "np.array([[0.2] * event_size] * batch_size, dtype=np.float32) a = tfd.Laplace(loc=a_loc, scale=a_scale,", "b_scale = np.array([[0.2] * event_size] * batch_size, dtype=np.float32) a =", "/ 2 total += (k[0] - prev[0]) * pair_pdf prev", "[-1])): s = sample_values[:, bi, ai] trials += 1 fails", "scale_v = tf.constant(0.0, name='scale') with self.assertRaisesOpError('Argument `scale` must be positive.'):", "scale=scale_v, validate_args=True) self.assertEqual(laplace.mean().shape, (3,)) expected_means = sp_stats.laplace.mean(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.mean()), expected_means)", "minval=.1, maxval=.9, seed=test_util.test_seed())], axis=0)) d = tfd.Laplace(loc=1., scale=1.3, validate_args=True) vals", "kl = tfd.kl_divergence(a, b) x = a.sample(int(1e4), seed=test_util.test_seed()) kl_sample =", "def testLaplaceEntropy(self): loc_v = np.array([1.0, 3.0, 2.5]) scale_v = np.array([1.0,", "(3,)) expected_variances = sp_stats.laplace.var(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.variance()), expected_variances) def testLaplaceStd(self): loc_v", "expected_cdf = sp_stats.laplace.logcdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(cdf), expected_cdf) def testLaplaceQuantile(self): qs", "6.]])), sample_vals.var(axis=0), rtol=0.05, atol=0.) def _assertIntegral(self, sample_vals, pdf_vals, err=1e-3): s_p", "def testLaplaceLogPDF(self): batch_size = 6 loc = tf.constant([2.0] * batch_size)", "= 3.0 x = np.array([-2.5, 2.5, -4.0, 0.1, 1.0, 2.0],", "(num, 2, 2)) self.assertEqual(pdfs.shape, (num, 2, 2)) self._assertIntegral(sample_vals[:, 0, 0],", "test for goodness of fit. ks, _ = sp_stats.kstest(samples, sp_stats.laplace(loc,", "d.quantile(qs) self.assertAllClose([-np.inf, np.inf], vals[:2]) self.assertAllClose(qs[2:], d.cdf(vals[2:])) def testLaplaceLogSurvivalFunction(self): batch_size =", "for ai, a in enumerate(np.reshape(loc_v, [-1])): for bi, b in", "= 6 loc = tf.constant([[2.0, 4.0]] * batch_size) scale =", "a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #", "laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) cdf = laplace.cdf(x) self.assertEqual(cdf.shape, (6,))", "s_p = zip(sample_vals, pdf_vals) prev = (0, 0) total =", "The TensorFlow Probability Authors. # # Licensed under the Apache", "loc = tf.constant([[2.0, 4.0]] * batch_size) scale = tf.constant([[3.0, 4.0]]", "self.assertEqual(cdf.shape, (6,)) expected_cdf = sp_stats.laplace.logcdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(cdf), expected_cdf) def", "tfp.distributions @test_util.test_all_tf_execution_regimes class LaplaceTest(test_util.TestCase): def testLaplaceShape(self): loc = tf.constant([3.0] *", "numpy as np from scipy import stats as sp_stats import", "6 loc = tf.constant([2.0] * batch_size) scale = tf.constant([3.0] *", "2)) pdf = laplace.prob(x) pdf_values = self.evaluate(pdf) self.assertEqual(pdf.shape, (6, 2))", "expected_log_pdf) pdf = laplace.prob(x) self.assertEqual(pdf.shape, (6,)) self.assertAllClose(self.evaluate(pdf), np.exp(expected_log_pdf)) def testLaplaceLogPDFMultidimensional(self):", "batch_size = 6 loc = tf.constant([2.0] * batch_size) scale =", "self.assertAllClose(log_pdf_values, expected_log_pdf) self.assertAllClose(pdf_values, np.exp(expected_log_pdf)) def testLaplaceCDF(self): batch_size = 6 loc", "self.assertEqual(sf.shape, (6,)) expected_sf = sp_stats.laplace.logsf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(sf), expected_sf) def", "import test_util tfd = tfp.distributions @test_util.test_all_tf_execution_regimes class LaplaceTest(test_util.TestCase): def testLaplaceShape(self):", "100)) self.assertEqual(sample_values.shape, (n, 10, 100)) zeros = np.zeros_like(loc_v + scale_v)", "= laplace.log_prob(x) log_pdf_values = self.evaluate(log_pdf) self.assertEqual(log_pdf.shape, (6, 2)) pdf =", "validate_args=True) sf = laplace.log_survival_function(x) self.assertEqual(sf.shape, (6,)) expected_sf = sp_stats.laplace.logsf(x, loc_v,", "def testLaplacePdfOfSampleMultiDims(self): laplace = tfd.Laplace(loc=[7., 11.], scale=[[5.], [6.]], validate_args=True) num", "atol=1e-5, rtol=1e-5) self.assertAllClose(true_kl_, kl_sample_, atol=0., rtol=1e-1) zero_kl = tfd.kl_divergence(a, a)", "else 1 self.assertLess(fails, trials * 0.03) def _kstest(self, loc, scale,", "* tf.exp(-distance / a_scale)) kl = tfd.kl_divergence(a, b) x =", "self.evaluate(pdf) self.assertEqual(pdf.shape, (6, 2)) expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v, scale=scale_v) self.assertAllClose(log_pdf_values,", "+= 0 if self._kstest(a, b, s) else 1 self.assertLess(fails, trials", "expected_cdf) def testLaplaceQuantile(self): qs = self.evaluate( tf.concat( [[0., 1], samplers.uniform([10],", "trials += 1 fails += 0 if self._kstest(a, b, s)", "trials * 0.03) def _kstest(self, loc, scale, samples): # Uses", "dtype=np.float32) b_loc = np.array([[0.4] * event_size] * batch_size, dtype=np.float32) b_scale", "tf.convert_to_tensor(0, dtype=tf.int32) scale = tf.convert_to_tensor(1, dtype=tf.int32) with self.assertRaisesRegexp(ValueError, 'Expected floating", "ks, _ = sp_stats.kstest(samples, sp_stats.laplace(loc, scale=scale).cdf) # Return True when", "self.assertEqual(samples.shape, (n, 10, 100)) self.assertEqual(sample_values.shape, (n, 10, 100)) zeros =", "pdf_values = self.evaluate(pdf) self.assertEqual(pdf.shape, (6, 2)) expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v,", "laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.mean().shape, (3,)) expected_means = sp_stats.laplace.mean(loc_v,", "np.array([np.arange(1, 11, dtype=np.float32)]).T # 10 x 1 laplace = tfd.Laplace(loc=loc_v,", "= tf.constant(3.0) loc_v = np.array([2.0, 4.0]) scale_v = 3.0 x", "= np.array([1.0, 4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.stddev().shape,", "100 scale_v = np.array([np.arange(1, 11, dtype=np.float32)]).T # 10 x 1", "be positive.'): laplace = tfd.Laplace( loc=loc_v, scale=scale_v, validate_args=True) self.evaluate(laplace.mean()) loc_v", "= laplace.prob(x) pdf_values = self.evaluate(pdf) self.assertEqual(pdf.shape, (6, 2)) expected_log_pdf =", "atol=0.) fails = 0 trials = 0 for ai, a", "5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.mode().shape, (3,)) self.assertAllClose(self.evaluate(laplace.mode()), loc_v)", "self.evaluate(laplace.mean()) scale = tf.Variable([1., 2., -3.]) self.evaluate(scale.initializer) with self.assertRaisesOpError('Argument `scale`", "self.assertAllClose(pdf_values, np.exp(expected_log_pdf)) def testLaplaceCDF(self): batch_size = 6 loc = tf.constant([2.0]", "tf.control_dependencies([scale.assign([1., 2., -3.])]): self.evaluate(tfd.Laplace(loc=0., scale=1.).kl_divergence(d)) def testAssertParamsAreFloats(self): loc = tf.convert_to_tensor(0,", "\"License\"); # you may not use this file except in", "laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) log_pdf = laplace.log_prob(x) self.assertEqual(log_pdf.shape, (6,))", "validate_args=True) self.assertEqual(laplace.mode().shape, (3,)) self.assertAllClose(self.evaluate(laplace.mode()), loc_v) def testLaplaceVariance(self): loc_v = np.array([1.0,", "tf.reduce_mean(a.log_prob(x) - b.log_prob(x), axis=0) true_kl_, kl_, kl_sample_ = self.evaluate([true_kl, kl,", "scale=scale_v) self.assertAllClose(self.evaluate(laplace.stddev()), expected_stddev) def testLaplaceEntropy(self): loc_v = np.array([1.0, 3.0, 2.5])", "maxval=.9, seed=test_util.test_seed())], axis=0)) d = tfd.Laplace(loc=1., scale=1.3, validate_args=True) vals =", "batch_size) scale = tf.constant(3.0) loc_v = np.array([2.0, 4.0]) scale_v =", "validate_args=True) self.assertEqual(laplace.entropy().shape, (3,)) expected_entropy = sp_stats.laplace.entropy(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.entropy()), expected_entropy) def", "distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR", "= 0 trials = 0 for ai, a in enumerate(np.reshape(loc_v,", "self.assertAllClose( sp_stats.laplace.mean( [[7., 11.], [7., 11.]], scale=np.array([[5., 5.], [6., 6.]])),", "loc_v, scale=scale_v) self.assertAllClose(log_pdf_values, expected_log_pdf) self.assertAllClose(pdf_values, np.exp(expected_log_pdf)) def testLaplaceCDF(self): batch_size =", "def testLaplaceVariance(self): loc_v = np.array([1.0, 3.0, 2.5]) scale_v = np.array([1.0,", "dtype=np.float32)]) # 1 x 100 scale_v = np.array([np.arange(1, 11, dtype=np.float32)]).T", "sp_stats.laplace.logcdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(cdf), expected_cdf) def testLaplaceQuantile(self): qs = self.evaluate(", "loc_v = np.array([np.arange(1, 101, dtype=np.float32)]) # 1 x 100 scale_v", "5.]) scale = tf.Variable(2.) d = tfd.Laplace(loc=loc, scale=scale, validate_args=True) with", "# distributed under the License is distributed on an \"AS", "tfd.Laplace(loc=0., scale=scale, validate_args=True) self.evaluate([v.initializer for v in d.variables]) with self.assertRaisesOpError('Argument", "(5,)) self.assertEqual(laplace.batch_shape, tf.TensorShape([5])) self.assertAllEqual(self.evaluate(laplace.event_shape_tensor()), []) self.assertEqual(laplace.event_shape, tf.TensorShape([])) def testLaplaceLogPDF(self): batch_size", "loc_v + zeros scale_bc = scale_v + zeros self.assertAllClose( sample_values.mean(axis=0),", "# Unless required by applicable law or agreed to in", "print_function # Dependency imports import numpy as np from scipy", "tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.variance().shape, (3,)) expected_variances = sp_stats.laplace.var(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.variance()),", "in enumerate(np.reshape(loc_v, [-1])): for bi, b in enumerate(np.reshape(scale_v, [-1])): s", "scale=np.array([[5., 5.], [6., 6.]])), sample_vals.var(axis=0), rtol=0.05, atol=0.) def _assertIntegral(self, sample_vals,", "self.assertNear(1., total, err=err) def testLaplaceNonPositiveInitializationParamsRaises(self): loc_v = tf.constant(0.0, name='loc') scale_v", "l, s: tfd.Laplace(loc=l, scale=s, validate_args=True).sample( # pylint: disable=g-long-lambda 100, seed=test_util.test_seed()),", "\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY", "loc = tf.constant([[2.0, 4.0]] * batch_size) scale = tf.constant(3.0) loc_v", "5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.stddev().shape, (3,)) expected_stddev =", "# Return True when the test passes. return ks <", "5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v, validate_args=True) self.assertEqual(laplace.mean().shape, (3,)) expected_means =", "= sp_stats.laplace.var(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.variance()), expected_variances) def testLaplaceStd(self): loc_v = np.array([1.0,", "(6, 2)) pdf = laplace.prob(x) pdf_values = self.evaluate(pdf) self.assertEqual(pdf.shape, (6,", "qs = self.evaluate( tf.concat( [[0., 1], samplers.uniform([10], minval=.1, maxval=.9, seed=test_util.test_seed())],", "lambda l, s: tfd.Laplace(loc=l, scale=s, validate_args=True).sample( # pylint: disable=g-long-lambda 100,", "11.], [7., 11.]], scale=np.array([[5., 5.], [6., 6.]])), sample_vals.var(axis=0), rtol=0.05, atol=0.)", "_assertIntegral(self, sample_vals, pdf_vals, err=1e-3): s_p = zip(sample_vals, pdf_vals) prev =", "n = 10000 samples = laplace.sample(n, seed=test_util.test_seed()) sample_values = self.evaluate(samples)", "imports import numpy as np from scipy import stats as", "4.0]) scale_v = 3.0 x = np.array([[2.5, 2.5, 4.0, 0.1,", "You may obtain a copy of the License at #", "= np.array([np.arange(1, 101, dtype=np.float32)]) # 1 x 100 scale_v =", "pair_pdf prev = k self.assertNear(1., total, err=err) def testLaplaceNonPositiveInitializationParamsRaises(self): loc_v", "= np.array([[0.4] * event_size] * batch_size, dtype=np.float32) b_scale = np.array([[0.2]", "tf.constant(-1.0, name='scale') with self.assertRaisesOpError('Argument `scale` must be positive.'): laplace =", "loss = -d.log_prob([1., 2., 3.]) grad = tape.gradient(loss, d.trainable_variables) self.assertLen(grad,", "loc=loc_v, scale=scale_v, validate_args=True) self.evaluate(laplace.mean()) loc_v = tf.constant(1.0, name='loc') scale_v =", "np.array([-2.5, 2.5, -4.0, 0.1, 1.0, 2.0], dtype=np.float32) laplace = tfd.Laplace(loc=loc,", "tf.Variable([1., 2., -3.]) self.evaluate(scale.initializer) with self.assertRaisesOpError('Argument `scale` must be positive.'):", "= loc_v + zeros scale_bc = scale_v + zeros self.assertAllClose(", "= 3.0 x = np.array([[2.5, 2.5, 4.0, 0.1, 1.0, 2.0]],", "fails += 0 if self._kstest(a, b, s) else 1 self.assertLess(fails,", "= a_scale / b_scale true_kl = (-tf.math.log(ratio) - 1 +", "scale=scale_v, validate_args=True) self.assertEqual(laplace.stddev().shape, (3,)) expected_stddev = sp_stats.laplace.std(loc_v, scale=scale_v) self.assertAllClose(self.evaluate(laplace.stddev()), expected_stddev)", "[6., 6.]])), sample_vals.var(axis=0), rtol=0.05, atol=0.) def _assertIntegral(self, sample_vals, pdf_vals, err=1e-3):", "2)) self.assertEqual(pdfs.shape, (num, 2, 2)) self._assertIntegral(sample_vals[:, 0, 0], pdf_vals[:, 0,", "with self.assertRaisesOpError('Argument `scale` must be positive.'): d = tfd.Laplace(loc=0, scale=scale,", "the Apache License, Version 2.0 (the \"License\"); # you may", "2.5]) scale_v = np.array([1.0, 4.0, 5.0]) laplace = tfd.Laplace(loc=loc_v, scale=scale_v,", "dtype=np.float32).T laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) log_pdf = laplace.log_prob(x) log_pdf_values", "scale = tf.constant(11.0) laplace = tfd.Laplace(loc=loc, scale=scale, validate_args=True) self.assertEqual(self.evaluate(laplace.batch_shape_tensor()), (5,))", "self.assertEqual(sample_values.shape, (n, 10, 100)) zeros = np.zeros_like(loc_v + scale_v) #", "scale_v + zeros self.assertAllClose( sample_values.mean(axis=0), sp_stats.laplace.mean(loc_bc, scale=scale_bc), rtol=0.35, atol=0.) self.assertAllClose(", "np.array([1.0, 3.0, 2.5]) scale_v = np.array([1.0, 4.0, 5.0]) laplace =", "governing permissions and # limitations under the License. # ============================================================================", "laplace.log_prob(x) self.assertEqual(log_pdf.shape, (6,)) expected_log_pdf = sp_stats.laplace.logpdf(x, loc_v, scale=scale_v) self.assertAllClose(self.evaluate(log_pdf), expected_log_pdf)", "pdf_vals[:, 0, 1], err=0.02) self._assertIntegral(sample_vals[:, 1, 0], pdf_vals[:, 1, 0],", "tensorflow_probability.python.internal import test_util tfd = tfp.distributions @test_util.test_all_tf_execution_regimes class LaplaceTest(test_util.TestCase): def", "pair_pdf = (k[1] + prev[1]) / 2 total += (k[0]" ]
[ "dash from flask import Flask from flask.helpers import get_root_path from", "title, base_pathname, layout, register_callbacks_fun): # Meta tags for viewport responsiveness", "from pytz import timezone from config import BaseConfig csrf =", "app.dashapp2.callbacks import register_callbacks as register_callbacks_2 from app.dashapp3.layout import layout as", "return server def format_datetime(date,fmt=None): western = timezone(\"America/Los_Angeles\") native=pytz.utc.localize(date, is_dst=None).astimezone(western) #date", "#native = date.astimezone(western) format='%m-%d-%Y %I:%M %p' return native.strftime(format) def register_dashapp(app,", "flask_login import login_required from flask_wtf.csrf import CSRFProtect from flask_admin import", "viewport responsiveness meta_viewport = {\"name\": \"viewport\", \"content\": \"width=device-width, initial-scale=1, shrink-to-fit=no\"}", "assets_folder=get_root_path(__name__) + f'/{base_pathname}/assets/', meta_tags=[meta_viewport]) with app.app_context(): my_dashapp.title = title my_dashapp.layout", "dashapp.server.view_functions: if view_func.startswith(dashapp.config.url_base_pathname): dashapp.server.view_functions[view_func] = login_required(dashapp.server.view_functions[view_func]) def register_extensions(server): from app.extensions", "\"content\": \"width=device-width, initial-scale=1, shrink-to-fit=no\"} my_dashapp = dash.Dash(__name__, server=app, url_base_pathname=f'/{base_pathname}/', assets_folder=get_root_path(__name__)", "meta_tags=[meta_viewport]) with app.app_context(): my_dashapp.title = title my_dashapp.layout = layout register_callbacks_fun(my_dashapp)", "as layout_3 from app.dashapp3.callbacks import register_callbacks as register_callbacks_3 server =", "= title my_dashapp.layout = layout register_callbacks_fun(my_dashapp) #_protect_dashviews(my_dashapp) def _protect_dashviews(dashapp): for", "from app.models import Blog, User, MyModelView, Contact from app.extensions import", "Flask(__name__) server.config.from_object(BaseConfig) csrf.init_app(server) csrf._exempt_views.add('dash.dash.dispatch') admin = Admin(server) admin.add_view(MyModelView(User, db.session)) admin.add_view(MyModelView(Blog,", "= CSRFProtect() def create_app(): from app.models import Blog, User, MyModelView,", "def format_datetime(date,fmt=None): western = timezone(\"America/Los_Angeles\") native=pytz.utc.localize(date, is_dst=None).astimezone(western) #date = parser.parse(str(date))", "Admin(server) admin.add_view(MyModelView(User, db.session)) admin.add_view(MyModelView(Blog, db.session)) admin.add_view(MyModelView(Contact, db.session)) register_dashapp(server, 'dashapp1', 'dashboard1',", "register_callbacks_3 server = Flask(__name__) server.config.from_object(BaseConfig) csrf.init_app(server) csrf._exempt_views.add('dash.dash.dispatch') admin = Admin(server)", "flask_admin import Admin, BaseView, expose from flask_admin.contrib.sqla import ModelView from", "BaseView, expose from flask_admin.contrib.sqla import ModelView from datetime import datetime", "flask_admin.contrib.sqla import ModelView from datetime import datetime from dateutil import", "#from app.dashapp2.callbacks import register_callbacks as register_callbacks_2 from app.dashapp3.layout import layout", "app.app_context(): my_dashapp.title = title my_dashapp.layout = layout register_callbacks_fun(my_dashapp) #_protect_dashviews(my_dashapp) def", "app.dashapp2.layout import layout as layout_2 #from app.dashapp2.callbacks import register_callbacks as", "def create_app(): from app.models import Blog, User, MyModelView, Contact from", "my_dashapp.layout = layout register_callbacks_fun(my_dashapp) #_protect_dashviews(my_dashapp) def _protect_dashviews(dashapp): for view_func in", "<reponame>credwood/bitplayers<filename>app/__init__.py import dash from flask import Flask from flask.helpers import", "server def format_datetime(date,fmt=None): western = timezone(\"America/Los_Angeles\") native=pytz.utc.localize(date, is_dst=None).astimezone(western) #date =", "import parser import pytz from pytz import timezone from config", "import layout as layout_2 #from app.dashapp2.callbacks import register_callbacks as register_callbacks_2", "as register_callbacks_3 server = Flask(__name__) server.config.from_object(BaseConfig) csrf.init_app(server) csrf._exempt_views.add('dash.dash.dispatch') admin =", "layout as layout_3 from app.dashapp3.callbacks import register_callbacks as register_callbacks_3 server", "= 'main.login' migrate.init_app(server, db) mail.init_app(server) def register_blueprints(server): from app.webapp import", "#register_dashapp(server, 'dashapp2', 'dashboard2', layout_2, register_callbacks_2) register_dashapp(server, 'dashapp3', 'dashboard3', layout_3, register_callbacks_3)", "layout_2, register_callbacks_2) register_dashapp(server, 'dashapp3', 'dashboard3', layout_3, register_callbacks_3) register_extensions(server) register_blueprints(server) server.jinja_env.filters['formatdatetime']", "register_callbacks_fun(my_dashapp) #_protect_dashviews(my_dashapp) def _protect_dashviews(dashapp): for view_func in dashapp.server.view_functions: if view_func.startswith(dashapp.config.url_base_pathname):", "initial-scale=1, shrink-to-fit=no\"} my_dashapp = dash.Dash(__name__, server=app, url_base_pathname=f'/{base_pathname}/', assets_folder=get_root_path(__name__) + f'/{base_pathname}/assets/',", "register_callbacks as register_callbacks_2 from app.dashapp3.layout import layout as layout_3 from", "as register_callbacks_1 #from app.dashapp2.layout import layout as layout_2 #from app.dashapp2.callbacks", "= timezone(\"America/Los_Angeles\") native=pytz.utc.localize(date, is_dst=None).astimezone(western) #date = parser.parse(str(date)) #native = date.astimezone(western)", "config import BaseConfig csrf = CSRFProtect() def create_app(): from app.models", "CSRFProtect() def create_app(): from app.models import Blog, User, MyModelView, Contact", "import Flask from flask.helpers import get_root_path from flask_login import login_required", "pytz from pytz import timezone from config import BaseConfig csrf", "dateutil import parser import pytz from pytz import timezone from", "from app.dashapp3.callbacks import register_callbacks as register_callbacks_3 server = Flask(__name__) server.config.from_object(BaseConfig)", "# Meta tags for viewport responsiveness meta_viewport = {\"name\": \"viewport\",", "import login_inst from app.extensions import migrate from app.extensions import mail", "register_callbacks_1 #from app.dashapp2.layout import layout as layout_2 #from app.dashapp2.callbacks import", "format_datetime return server def format_datetime(date,fmt=None): western = timezone(\"America/Los_Angeles\") native=pytz.utc.localize(date, is_dst=None).astimezone(western)", "as register_callbacks_2 from app.dashapp3.layout import layout as layout_3 from app.dashapp3.callbacks", "server = Flask(__name__) server.config.from_object(BaseConfig) csrf.init_app(server) csrf._exempt_views.add('dash.dash.dispatch') admin = Admin(server) admin.add_view(MyModelView(User,", "login_inst.login_view = 'main.login' migrate.init_app(server, db) mail.init_app(server) def register_blueprints(server): from app.webapp", "= login_required(dashapp.server.view_functions[view_func]) def register_extensions(server): from app.extensions import db from app.extensions", "from app.extensions import migrate from app.extensions import mail db.init_app(server) login_inst.init_app(server)", "\"viewport\", \"content\": \"width=device-width, initial-scale=1, shrink-to-fit=no\"} my_dashapp = dash.Dash(__name__, server=app, url_base_pathname=f'/{base_pathname}/',", "Admin, BaseView, expose from flask_admin.contrib.sqla import ModelView from datetime import", "flask.helpers import get_root_path from flask_login import login_required from flask_wtf.csrf import", "in dashapp.server.view_functions: if view_func.startswith(dashapp.config.url_base_pathname): dashapp.server.view_functions[view_func] = login_required(dashapp.server.view_functions[view_func]) def register_extensions(server): from", "admin.add_view(MyModelView(User, db.session)) admin.add_view(MyModelView(Blog, db.session)) admin.add_view(MyModelView(Contact, db.session)) register_dashapp(server, 'dashapp1', 'dashboard1', layout_1,", "def _protect_dashviews(dashapp): for view_func in dashapp.server.view_functions: if view_func.startswith(dashapp.config.url_base_pathname): dashapp.server.view_functions[view_func] =", "date.astimezone(western) format='%m-%d-%Y %I:%M %p' return native.strftime(format) def register_dashapp(app, title, base_pathname,", "for view_func in dashapp.server.view_functions: if view_func.startswith(dashapp.config.url_base_pathname): dashapp.server.view_functions[view_func] = login_required(dashapp.server.view_functions[view_func]) def", "migrate.init_app(server, db) mail.init_app(server) def register_blueprints(server): from app.webapp import server_bp server.register_blueprint(server_bp)", "'dashapp2', 'dashboard2', layout_2, register_callbacks_2) register_dashapp(server, 'dashapp3', 'dashboard3', layout_3, register_callbacks_3) register_extensions(server)", "import mail db.init_app(server) login_inst.init_app(server) login_inst.login_view = 'main.login' migrate.init_app(server, db) mail.init_app(server)", "register_dashapp(server, 'dashapp3', 'dashboard3', layout_3, register_callbacks_3) register_extensions(server) register_blueprints(server) server.jinja_env.filters['formatdatetime'] = format_datetime", "= dash.Dash(__name__, server=app, url_base_pathname=f'/{base_pathname}/', assets_folder=get_root_path(__name__) + f'/{base_pathname}/assets/', meta_tags=[meta_viewport]) with app.app_context():", "= format_datetime return server def format_datetime(date,fmt=None): western = timezone(\"America/Los_Angeles\") native=pytz.utc.localize(date,", "Meta tags for viewport responsiveness meta_viewport = {\"name\": \"viewport\", \"content\":", "layout as layout_1 from app.dashapp1.callbacks import register_callbacks as register_callbacks_1 #from", "register_callbacks_2) register_dashapp(server, 'dashapp3', 'dashboard3', layout_3, register_callbacks_3) register_extensions(server) register_blueprints(server) server.jinja_env.filters['formatdatetime'] =", "= Admin(server) admin.add_view(MyModelView(User, db.session)) admin.add_view(MyModelView(Blog, db.session)) admin.add_view(MyModelView(Contact, db.session)) register_dashapp(server, 'dashapp1',", "layout_3, register_callbacks_3) register_extensions(server) register_blueprints(server) server.jinja_env.filters['formatdatetime'] = format_datetime return server def", "import datetime from dateutil import parser import pytz from pytz", "app.dashapp3.callbacks import register_callbacks as register_callbacks_3 server = Flask(__name__) server.config.from_object(BaseConfig) csrf.init_app(server)", "dash.Dash(__name__, server=app, url_base_pathname=f'/{base_pathname}/', assets_folder=get_root_path(__name__) + f'/{base_pathname}/assets/', meta_tags=[meta_viewport]) with app.app_context(): my_dashapp.title", "import register_callbacks as register_callbacks_1 #from app.dashapp2.layout import layout as layout_2", "+ f'/{base_pathname}/assets/', meta_tags=[meta_viewport]) with app.app_context(): my_dashapp.title = title my_dashapp.layout =", "title my_dashapp.layout = layout register_callbacks_fun(my_dashapp) #_protect_dashviews(my_dashapp) def _protect_dashviews(dashapp): for view_func", "layout as layout_2 #from app.dashapp2.callbacks import register_callbacks as register_callbacks_2 from", "server.config.from_object(BaseConfig) csrf.init_app(server) csrf._exempt_views.add('dash.dash.dispatch') admin = Admin(server) admin.add_view(MyModelView(User, db.session)) admin.add_view(MyModelView(Blog, db.session))", "db.session)) register_dashapp(server, 'dashapp1', 'dashboard1', layout_1, register_callbacks_1) #register_dashapp(server, 'dashapp2', 'dashboard2', layout_2,", "western = timezone(\"America/Los_Angeles\") native=pytz.utc.localize(date, is_dst=None).astimezone(western) #date = parser.parse(str(date)) #native =", "{\"name\": \"viewport\", \"content\": \"width=device-width, initial-scale=1, shrink-to-fit=no\"} my_dashapp = dash.Dash(__name__, server=app,", "import get_root_path from flask_login import login_required from flask_wtf.csrf import CSRFProtect", "register_callbacks as register_callbacks_3 server = Flask(__name__) server.config.from_object(BaseConfig) csrf.init_app(server) csrf._exempt_views.add('dash.dash.dispatch') admin", "from flask.helpers import get_root_path from flask_login import login_required from flask_wtf.csrf", "from flask import Flask from flask.helpers import get_root_path from flask_login", "from flask_admin import Admin, BaseView, expose from flask_admin.contrib.sqla import ModelView", "ModelView from datetime import datetime from dateutil import parser import", "tags for viewport responsiveness meta_viewport = {\"name\": \"viewport\", \"content\": \"width=device-width,", "from flask_admin.contrib.sqla import ModelView from datetime import datetime from dateutil", "pytz import timezone from config import BaseConfig csrf = CSRFProtect()", "register_callbacks_1) #register_dashapp(server, 'dashapp2', 'dashboard2', layout_2, register_callbacks_2) register_dashapp(server, 'dashapp3', 'dashboard3', layout_3,", "'main.login' migrate.init_app(server, db) mail.init_app(server) def register_blueprints(server): from app.webapp import server_bp", "app.extensions import migrate from app.extensions import mail db.init_app(server) login_inst.init_app(server) login_inst.login_view", "from flask_wtf.csrf import CSRFProtect from flask_admin import Admin, BaseView, expose", "from dateutil import parser import pytz from pytz import timezone", "layout_1 from app.dashapp1.callbacks import register_callbacks as register_callbacks_1 #from app.dashapp2.layout import", "migrate from app.extensions import mail db.init_app(server) login_inst.init_app(server) login_inst.login_view = 'main.login'", "Contact from app.extensions import db from app.dashapp1.layout import layout as", "register_blueprints(server) server.jinja_env.filters['formatdatetime'] = format_datetime return server def format_datetime(date,fmt=None): western =", "flask_wtf.csrf import CSRFProtect from flask_admin import Admin, BaseView, expose from", "parser import pytz from pytz import timezone from config import", "register_callbacks as register_callbacks_1 #from app.dashapp2.layout import layout as layout_2 #from", "register_callbacks_2 from app.dashapp3.layout import layout as layout_3 from app.dashapp3.callbacks import", "timezone(\"America/Los_Angeles\") native=pytz.utc.localize(date, is_dst=None).astimezone(western) #date = parser.parse(str(date)) #native = date.astimezone(western) format='%m-%d-%Y", "from app.extensions import db from app.extensions import login_inst from app.extensions", "= {\"name\": \"viewport\", \"content\": \"width=device-width, initial-scale=1, shrink-to-fit=no\"} my_dashapp = dash.Dash(__name__,", "from app.dashapp3.layout import layout as layout_3 from app.dashapp3.callbacks import register_callbacks", "for viewport responsiveness meta_viewport = {\"name\": \"viewport\", \"content\": \"width=device-width, initial-scale=1,", "#_protect_dashviews(my_dashapp) def _protect_dashviews(dashapp): for view_func in dashapp.server.view_functions: if view_func.startswith(dashapp.config.url_base_pathname): dashapp.server.view_functions[view_func]", "flask import Flask from flask.helpers import get_root_path from flask_login import", "import db from app.extensions import login_inst from app.extensions import migrate", "layout register_callbacks_fun(my_dashapp) #_protect_dashviews(my_dashapp) def _protect_dashviews(dashapp): for view_func in dashapp.server.view_functions: if", "from app.dashapp1.callbacks import register_callbacks as register_callbacks_1 #from app.dashapp2.layout import layout", "login_inst.init_app(server) login_inst.login_view = 'main.login' migrate.init_app(server, db) mail.init_app(server) def register_blueprints(server): from", "register_extensions(server) register_blueprints(server) server.jinja_env.filters['formatdatetime'] = format_datetime return server def format_datetime(date,fmt=None): western", "my_dashapp.title = title my_dashapp.layout = layout register_callbacks_fun(my_dashapp) #_protect_dashviews(my_dashapp) def _protect_dashviews(dashapp):", "import pytz from pytz import timezone from config import BaseConfig", "app.extensions import db from app.dashapp1.layout import layout as layout_1 from", "csrf.init_app(server) csrf._exempt_views.add('dash.dash.dispatch') admin = Admin(server) admin.add_view(MyModelView(User, db.session)) admin.add_view(MyModelView(Blog, db.session)) admin.add_view(MyModelView(Contact,", "'dashapp3', 'dashboard3', layout_3, register_callbacks_3) register_extensions(server) register_blueprints(server) server.jinja_env.filters['formatdatetime'] = format_datetime return", "import ModelView from datetime import datetime from dateutil import parser", "if view_func.startswith(dashapp.config.url_base_pathname): dashapp.server.view_functions[view_func] = login_required(dashapp.server.view_functions[view_func]) def register_extensions(server): from app.extensions import", "from app.extensions import login_inst from app.extensions import migrate from app.extensions", "expose from flask_admin.contrib.sqla import ModelView from datetime import datetime from", "app.extensions import login_inst from app.extensions import migrate from app.extensions import", "login_required(dashapp.server.view_functions[view_func]) def register_extensions(server): from app.extensions import db from app.extensions import", "#date = parser.parse(str(date)) #native = date.astimezone(western) format='%m-%d-%Y %I:%M %p' return", "url_base_pathname=f'/{base_pathname}/', assets_folder=get_root_path(__name__) + f'/{base_pathname}/assets/', meta_tags=[meta_viewport]) with app.app_context(): my_dashapp.title = title", "import register_callbacks as register_callbacks_2 from app.dashapp3.layout import layout as layout_3", "native.strftime(format) def register_dashapp(app, title, base_pathname, layout, register_callbacks_fun): # Meta tags", "import dash from flask import Flask from flask.helpers import get_root_path", "app.dashapp1.callbacks import register_callbacks as register_callbacks_1 #from app.dashapp2.layout import layout as", "'dashapp1', 'dashboard1', layout_1, register_callbacks_1) #register_dashapp(server, 'dashapp2', 'dashboard2', layout_2, register_callbacks_2) register_dashapp(server,", "timezone from config import BaseConfig csrf = CSRFProtect() def create_app():", "layout, register_callbacks_fun): # Meta tags for viewport responsiveness meta_viewport =", "f'/{base_pathname}/assets/', meta_tags=[meta_viewport]) with app.app_context(): my_dashapp.title = title my_dashapp.layout = layout", "admin.add_view(MyModelView(Blog, db.session)) admin.add_view(MyModelView(Contact, db.session)) register_dashapp(server, 'dashapp1', 'dashboard1', layout_1, register_callbacks_1) #register_dashapp(server,", "db from app.dashapp1.layout import layout as layout_1 from app.dashapp1.callbacks import", "register_dashapp(app, title, base_pathname, layout, register_callbacks_fun): # Meta tags for viewport", "import migrate from app.extensions import mail db.init_app(server) login_inst.init_app(server) login_inst.login_view =", "from flask_login import login_required from flask_wtf.csrf import CSRFProtect from flask_admin", "register_callbacks_fun): # Meta tags for viewport responsiveness meta_viewport = {\"name\":", "server=app, url_base_pathname=f'/{base_pathname}/', assets_folder=get_root_path(__name__) + f'/{base_pathname}/assets/', meta_tags=[meta_viewport]) with app.app_context(): my_dashapp.title =", "format_datetime(date,fmt=None): western = timezone(\"America/Los_Angeles\") native=pytz.utc.localize(date, is_dst=None).astimezone(western) #date = parser.parse(str(date)) #native", "MyModelView, Contact from app.extensions import db from app.dashapp1.layout import layout", "= parser.parse(str(date)) #native = date.astimezone(western) format='%m-%d-%Y %I:%M %p' return native.strftime(format)", "datetime from dateutil import parser import pytz from pytz import", "csrf._exempt_views.add('dash.dash.dispatch') admin = Admin(server) admin.add_view(MyModelView(User, db.session)) admin.add_view(MyModelView(Blog, db.session)) admin.add_view(MyModelView(Contact, db.session))", "admin = Admin(server) admin.add_view(MyModelView(User, db.session)) admin.add_view(MyModelView(Blog, db.session)) admin.add_view(MyModelView(Contact, db.session)) register_dashapp(server,", "import db from app.dashapp1.layout import layout as layout_1 from app.dashapp1.callbacks", "= Flask(__name__) server.config.from_object(BaseConfig) csrf.init_app(server) csrf._exempt_views.add('dash.dash.dispatch') admin = Admin(server) admin.add_view(MyModelView(User, db.session))", "db.session)) admin.add_view(MyModelView(Blog, db.session)) admin.add_view(MyModelView(Contact, db.session)) register_dashapp(server, 'dashapp1', 'dashboard1', layout_1, register_callbacks_1)", "register_dashapp(server, 'dashapp1', 'dashboard1', layout_1, register_callbacks_1) #register_dashapp(server, 'dashapp2', 'dashboard2', layout_2, register_callbacks_2)", "app.extensions import mail db.init_app(server) login_inst.init_app(server) login_inst.login_view = 'main.login' migrate.init_app(server, db)", "Blog, User, MyModelView, Contact from app.extensions import db from app.dashapp1.layout", "import login_required from flask_wtf.csrf import CSRFProtect from flask_admin import Admin,", "app.models import Blog, User, MyModelView, Contact from app.extensions import db", "BaseConfig csrf = CSRFProtect() def create_app(): from app.models import Blog,", "register_extensions(server): from app.extensions import db from app.extensions import login_inst from", "import CSRFProtect from flask_admin import Admin, BaseView, expose from flask_admin.contrib.sqla", "Flask from flask.helpers import get_root_path from flask_login import login_required from", "shrink-to-fit=no\"} my_dashapp = dash.Dash(__name__, server=app, url_base_pathname=f'/{base_pathname}/', assets_folder=get_root_path(__name__) + f'/{base_pathname}/assets/', meta_tags=[meta_viewport])", "with app.app_context(): my_dashapp.title = title my_dashapp.layout = layout register_callbacks_fun(my_dashapp) #_protect_dashviews(my_dashapp)", "from app.extensions import db from app.dashapp1.layout import layout as layout_1", "User, MyModelView, Contact from app.extensions import db from app.dashapp1.layout import", "layout_1, register_callbacks_1) #register_dashapp(server, 'dashapp2', 'dashboard2', layout_2, register_callbacks_2) register_dashapp(server, 'dashapp3', 'dashboard3',", "layout_2 #from app.dashapp2.callbacks import register_callbacks as register_callbacks_2 from app.dashapp3.layout import", "datetime import datetime from dateutil import parser import pytz from", "responsiveness meta_viewport = {\"name\": \"viewport\", \"content\": \"width=device-width, initial-scale=1, shrink-to-fit=no\"} my_dashapp", "layout_3 from app.dashapp3.callbacks import register_callbacks as register_callbacks_3 server = Flask(__name__)", "\"width=device-width, initial-scale=1, shrink-to-fit=no\"} my_dashapp = dash.Dash(__name__, server=app, url_base_pathname=f'/{base_pathname}/', assets_folder=get_root_path(__name__) +", "import layout as layout_3 from app.dashapp3.callbacks import register_callbacks as register_callbacks_3", "as layout_2 #from app.dashapp2.callbacks import register_callbacks as register_callbacks_2 from app.dashapp3.layout", "%p' return native.strftime(format) def register_dashapp(app, title, base_pathname, layout, register_callbacks_fun): #", "from config import BaseConfig csrf = CSRFProtect() def create_app(): from", "'dashboard1', layout_1, register_callbacks_1) #register_dashapp(server, 'dashapp2', 'dashboard2', layout_2, register_callbacks_2) register_dashapp(server, 'dashapp3',", "admin.add_view(MyModelView(Contact, db.session)) register_dashapp(server, 'dashapp1', 'dashboard1', layout_1, register_callbacks_1) #register_dashapp(server, 'dashapp2', 'dashboard2',", "'dashboard3', layout_3, register_callbacks_3) register_extensions(server) register_blueprints(server) server.jinja_env.filters['formatdatetime'] = format_datetime return server", "import layout as layout_1 from app.dashapp1.callbacks import register_callbacks as register_callbacks_1", "create_app(): from app.models import Blog, User, MyModelView, Contact from app.extensions", "%I:%M %p' return native.strftime(format) def register_dashapp(app, title, base_pathname, layout, register_callbacks_fun):", "import Blog, User, MyModelView, Contact from app.extensions import db from", "db from app.extensions import login_inst from app.extensions import migrate from", "login_required from flask_wtf.csrf import CSRFProtect from flask_admin import Admin, BaseView,", "_protect_dashviews(dashapp): for view_func in dashapp.server.view_functions: if view_func.startswith(dashapp.config.url_base_pathname): dashapp.server.view_functions[view_func] = login_required(dashapp.server.view_functions[view_func])", "my_dashapp = dash.Dash(__name__, server=app, url_base_pathname=f'/{base_pathname}/', assets_folder=get_root_path(__name__) + f'/{base_pathname}/assets/', meta_tags=[meta_viewport]) with", "base_pathname, layout, register_callbacks_fun): # Meta tags for viewport responsiveness meta_viewport", "from datetime import datetime from dateutil import parser import pytz", "db.session)) admin.add_view(MyModelView(Contact, db.session)) register_dashapp(server, 'dashapp1', 'dashboard1', layout_1, register_callbacks_1) #register_dashapp(server, 'dashapp2',", "view_func.startswith(dashapp.config.url_base_pathname): dashapp.server.view_functions[view_func] = login_required(dashapp.server.view_functions[view_func]) def register_extensions(server): from app.extensions import db", "mail db.init_app(server) login_inst.init_app(server) login_inst.login_view = 'main.login' migrate.init_app(server, db) mail.init_app(server) def", "app.extensions import db from app.extensions import login_inst from app.extensions import", "return native.strftime(format) def register_dashapp(app, title, base_pathname, layout, register_callbacks_fun): # Meta", "server.jinja_env.filters['formatdatetime'] = format_datetime return server def format_datetime(date,fmt=None): western = timezone(\"America/Los_Angeles\")", "import register_callbacks as register_callbacks_3 server = Flask(__name__) server.config.from_object(BaseConfig) csrf.init_app(server) csrf._exempt_views.add('dash.dash.dispatch')", "CSRFProtect from flask_admin import Admin, BaseView, expose from flask_admin.contrib.sqla import", "app.dashapp3.layout import layout as layout_3 from app.dashapp3.callbacks import register_callbacks as", "= layout register_callbacks_fun(my_dashapp) #_protect_dashviews(my_dashapp) def _protect_dashviews(dashapp): for view_func in dashapp.server.view_functions:", "register_callbacks_3) register_extensions(server) register_blueprints(server) server.jinja_env.filters['formatdatetime'] = format_datetime return server def format_datetime(date,fmt=None):", "import BaseConfig csrf = CSRFProtect() def create_app(): from app.models import", "app.dashapp1.layout import layout as layout_1 from app.dashapp1.callbacks import register_callbacks as", "'dashboard2', layout_2, register_callbacks_2) register_dashapp(server, 'dashapp3', 'dashboard3', layout_3, register_callbacks_3) register_extensions(server) register_blueprints(server)", "is_dst=None).astimezone(western) #date = parser.parse(str(date)) #native = date.astimezone(western) format='%m-%d-%Y %I:%M %p'", "import timezone from config import BaseConfig csrf = CSRFProtect() def", "csrf = CSRFProtect() def create_app(): from app.models import Blog, User,", "from app.dashapp1.layout import layout as layout_1 from app.dashapp1.callbacks import register_callbacks", "login_inst from app.extensions import migrate from app.extensions import mail db.init_app(server)", "dashapp.server.view_functions[view_func] = login_required(dashapp.server.view_functions[view_func]) def register_extensions(server): from app.extensions import db from", "from app.extensions import mail db.init_app(server) login_inst.init_app(server) login_inst.login_view = 'main.login' migrate.init_app(server,", "get_root_path from flask_login import login_required from flask_wtf.csrf import CSRFProtect from", "native=pytz.utc.localize(date, is_dst=None).astimezone(western) #date = parser.parse(str(date)) #native = date.astimezone(western) format='%m-%d-%Y %I:%M", "parser.parse(str(date)) #native = date.astimezone(western) format='%m-%d-%Y %I:%M %p' return native.strftime(format) def", "import Admin, BaseView, expose from flask_admin.contrib.sqla import ModelView from datetime", "def register_extensions(server): from app.extensions import db from app.extensions import login_inst", "as layout_1 from app.dashapp1.callbacks import register_callbacks as register_callbacks_1 #from app.dashapp2.layout", "def register_dashapp(app, title, base_pathname, layout, register_callbacks_fun): # Meta tags for", "meta_viewport = {\"name\": \"viewport\", \"content\": \"width=device-width, initial-scale=1, shrink-to-fit=no\"} my_dashapp =", "view_func in dashapp.server.view_functions: if view_func.startswith(dashapp.config.url_base_pathname): dashapp.server.view_functions[view_func] = login_required(dashapp.server.view_functions[view_func]) def register_extensions(server):", "= date.astimezone(western) format='%m-%d-%Y %I:%M %p' return native.strftime(format) def register_dashapp(app, title,", "db.init_app(server) login_inst.init_app(server) login_inst.login_view = 'main.login' migrate.init_app(server, db) mail.init_app(server) def register_blueprints(server):", "#from app.dashapp2.layout import layout as layout_2 #from app.dashapp2.callbacks import register_callbacks", "format='%m-%d-%Y %I:%M %p' return native.strftime(format) def register_dashapp(app, title, base_pathname, layout," ]
[ "= soln[group_mask] / norm(soln[group_mask]) ordered_opt.append(norm(soln[group_mask])) else: overall[group_mask] = False self.selection_variable", "proposed_value = objective(proposal) if proposed_value <= current_value: break step *=", "use_lasso=True, # should lasso solver be used when applicable -", "= block_diag(*[np.ones((1, ug.size - 1)) for ug in active_dirs.values()]) #", "an exception if it finds any problems. Sorting feature groups", "self._initial_omega is None: self._initial_omega = self.randomizer.sample() quad = rr.identity_quadratic(self.ridge_term, 0,", "= [] # gamma's ordered by group labels ordered_vars =", "are size one, C will be an empty array return", "not integers\") # check starts with 0 if not np.amin(agroups)", "con_linear.dot(gs)) / scaling)).sum() return p1 + p2 + p3 +", "else: ngrid = 100 self.stat_grid = np.zeros((ntarget, ngrid)) for j", "for decomposing o eta = -self.prec_opt.dot(self.logdens_linear.dot(target_score_cov.T)) implied_mean = np.asscalar(eta.T.dot(cond_mean_grid)) implied_cov", "* self.randomizer_prec) - target_lin.T.dot( prec_opt).dot( target_lin) else: _P = target_linear.T.dot(self.randomizer_prec).dot(target_offset)", "# use regular lasso penalty if all groups are size", "np.sqrt(np.diag(inverse_info)) if useIP == False: ngrid = 1000 self.stat_grid =", "= cond_cov.dot(self.opt_linear.T) * prec else: cond_precision = self.opt_linear.T.dot(prec.dot(self.opt_linear)) cond_cov =", "are sorted in increasing order, start at 0, and have", "that is not adapted for the group_lasso. Also, assumes you", "sorted_active_dirs] L = block_diag(*Ls) # unpack the list XE =", "init_soln, linear_part, offset, self.C, self.active_dirs, useJacobian, **solve_args) final_estimator = target_cov.dot(_prec).dot(observed_target)", "self.loglike.data n, p = X.shape XE = self.XE Q =", "[] for m in range(self.ntarget): p = self.target_score_cov.shape[1] observed_target_uni =", "of group lasso (self.initial_soln, self.initial_subgrad) = self._solve_randomized_problem(perturb=perturb, solve_args=solve_args) # initialize", "score_offset - target_linear.dot(observed_target) target_lin = - logdens_linear.dot(target_linear) target_off = cond_mean", "- self.observed_target[m]) / var_target, x=self.observed_target[m]) print(\"variable completed \", m) if", "1 if use_lasso and groups.size == np.unique(groups).size: # need to", "= rr.weighted_l1norm(weights=weights_np, lagrange=1.) else: self.penalty = rr.group_lasso(groups, weights=weights, lagrange=1.) #", "pivots = None pvalues = self._approx_pivots(np.zeros_like(self.observed_target), alternatives=alternatives) lower, upper =", "% 4 == 0: step *= 2 hess = inv(precision", "C U = block_diag(*[ug for ug in sorted_active_dirs.values()]).T self.opt_linear =", "is None: ridge_term = np.std(Y) * np.sqrt(mean_diag) / np.sqrt(n -", "gammas cond_mean = self.cond_mean cond_cov = self.cond_cov logdens_linear = self.logdens_linear", "self.randomizer_prec _r = (1. / _prec).dot(target_lin.T.dot(self.prec_opt).dot(target_off) - _P) _S =", "= target_cov.dot(observed_info_natural.dot(target_cov)) Z_scores = final_estimator / np.sqrt(np.diag(observed_info_mean)) pvalues = ndist.cdf(Z_scores)", "p = self.target_score_cov.shape[1] observed_target_uni = (self.observed_target[m]).reshape((1,)) target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1, 1))", "* var_target + observed_target) return np.asarray(lower), np.asarray(upper) ### Private method", "self.r = r def solve_barrier_affine_jacobian_py(conjugate_arg, precision, feasible_point, con_linear, con_offset, C,", "log-Jacobian (scalar), gradient (gamma.size vector) and hessian (gamma.size square matrix)", "for m in range(self.ntarget): p = self.target_score_cov.shape[1] observed_target_uni = (self.observed_target[m]).reshape((1,))", "the user and in future we might do this for", "alternatives = ['twosided'] * len(self.active) if dispersion is None: #", "= self.groups == g soln = self.initial_soln # do not", "* 0.5 * np.std(Y) * np.sqrt(n / (n - 1.))", "of optimization variables # vary with target # logdens_linear determines", "groups.size == np.unique(groups).size: # need to provide weights an an", "_prec self.precs = precs self.S = S self.r = r", "k in range(grid.shape[0]): # in the usual D = N", "C: V^T Q^{-1} \\\\Lambda V active_dirs: \"\"\" scaling = np.sqrt(np.diag(con_linear.dot(precision).dot(con_linear.T)))", "break current = proposal current_value = proposed_value if itercount %", "is empty return Vg def compute_Lg(g): pg = active_dirs[g].size Lg", "step * cur_grad proposed_value = objective(proposal) if proposed_value <= current_value:", "NaN: %f, %f' % (proposed_value, current_value)) # stop if relative", "not hasattr(self, \"_families\"): self._construct_families() if alternatives is None: alternatives =", "rr.weighted_l1norm(weights=weights_np, lagrange=1.) else: self.penalty = rr.group_lasso(groups, weights=weights, lagrange=1.) # store", "p1 = -gs.T.dot(conjugate_arg) p2 = gs.T.dot(precision).dot(gs) / 2. if useJacobian:", "python or C solver JacobianPieces: (use self.C defined in fitting)", "= np.linalg.inv(target_cov) target_lin = - self.logdens_linear.dot(target_score_cov.T.dot(prec_target)) ref_hat = [] for", "weights, sigma=1., quadratic=None, ridge_term=0., perturb=None, use_lasso=True, # should lasso solver", "__init__(self, loglike, groups, weights, ridge_term, randomizer, use_lasso=True, # should lasso", "(target_lin.dot(np.atleast_1d(grid[k] - observed_target)) + self.cond_mean) #direction for decomposing o eta", "((y - self.loglike.saturated_loss.mean_function( XE.dot(observed_target))) ** 2 / self._W).sum() / (n", "0, 0, 0 else: GammaMinus = calc_GammaMinus(gamma, active_dirs) # eigendecomposition", "2. if useJacobian: p3 = - jacobian_grad_hess(gs, C, active_dirs)[0] else:", "we are collecting the directions and norms of the active", "as before self.observed_opt_state = np.hstack(ordered_opt) # gammas as array _beta_unpenalized", "- target_lin.T.dot( prec_opt).dot( target_lin) else: _P = target_linear.T.dot(self.randomizer_prec).dot(target_offset) _prec =", "= self.linear_part.dot(_A).reshape((-1,)) b = self.offset-self.linear_part.dot(R).dot(self.init_soln) conjugate_arg = implied_mean * implied_prec", "observed_target[j] + 1.5 * _scale[j], num=ngrid) self.opt_linear = query.opt_linear self.useIP", "0: raise ValueError(\"Groups are not sorted\") # check integers if", "r def solve_barrier_affine_jacobian_py(conjugate_arg, precision, feasible_point, con_linear, con_offset, C, active_dirs, useJacobian=True,", "not need to keep setting this if norm(soln[group_mask]) > tol", "= loglike self.nfeature = self.loglike.shape[0] # ridge parameter self.ridge_term =", "= - self.logdens_linear.dot(target_score_cov.T.dot(prec_target)) ref_hat = [] for k in range(grid.shape[0]):", "class group_lasso(object): def __init__(self, loglike, groups, weights, ridge_term, randomizer, use_lasso=True,", "_construct_density(self): precs = {} S = {} r = {}", "grad_J, hess_J def _check_groups(groups): \"\"\"Make sure that the user-specific groups", "is None: randomizer_scale = np.sqrt(mean_diag) * 0.5 * np.std(Y) *", "solve_barrier_affine_jacobian_py(conjugate_arg, precision, feasible_point, con_linear, con_offset, C, active_dirs, useJacobian=True, step=1, nstep=2000,", "-S.dot(np.multiply(GpC_inv, GpC_inv.T).dot(S.T)) return J, grad_J, hess_J def _check_groups(groups): \"\"\"Make sure", "self.logdens_linear = logdens_linear return cond_mean, cond_cov, cond_precision, logdens_linear def selective_MLE(self,", "step *= 0.5 if count >= 40: raise ValueError('not finding", "0]) mean = self.S[m].dot(mean_parameter[m].reshape((1,))) + self.r[m] _cdf = family.cdf((mean[0] -", "size of g'th group if pg > 1: Z =", "minus sign target_linear = target_score_cov.T.dot(prec_target) target_offset = score_offset - target_linear.dot(observed_target)", "level=0.9): \"\"\" Produce p-values and confidence intervals for targets of", "to hessian p1 = con_linear.T.dot(np.diag(-1. / ((scaling + con_offset -", "return p1 + p2 current = feasible_point current_value = np.inf", "if self.useIP == False: logW = (log_ref - 0.5 *", "the non-group lasso doesn't self.groups = groups self._initial_omega = perturb", "optimization density # depends on the score, not how the", "(np.diag(self.target_cov)[m]).reshape((1, 1)) prec_target = 1. / target_cov_uni target_score_cov_uni = self.target_score_cov[m,", "offset, self.C, self.active_dirs, useJacobian, **solve_args) final_estimator = target_cov.dot(_prec).dot(observed_target) \\ +", "-self.prec_opt.dot(self.logdens_linear.dot(target_score_cov.T)) implied_mean = np.asscalar(eta.T.dot(cond_mean_grid)) implied_cov = np.asscalar(eta.T.dot(self.cond_cov).dot(eta)) implied_prec = 1./implied_cov", "def _construct_density(self): precs = {} S = {} r =", "for barrier function con_offset: offset part of affine constraint used", "= -(self.loglike.smooth_objective(initial_soln, 'grad') + quad.objective(initial_soln, 'grad')) return initial_soln, initial_subgrad @staticmethod", "ValueError('no target specified') observed_target = np.atleast_1d(observed_target) prec_target = inv(target_cov) prec_opt", "logW -= logW.max() self._families.append(discrete_family(self.stat_grid[m], np.exp(logW))) else: approx_fn = interp1d(self.stat_grid[m], log_ref,", "** 2 / self._W).sum() / (n - XE.shape[1]) cov_target =", "import randomization from ..base import restricted_estimator from ..algorithms.barrier_affine import solve_barrier_affine_py", "result, observed_info_mean, log_ref def selected_targets(self, dispersion=None, solve_args={'tol': 1.e-12, 'min_its': 50}):", "if self.penalty.weights[g] == 0: unpenalized.append(g) else: active_groups.append(g) active_dirs[g] = soln[group_mask]", "def selected_targets(self, dispersion=None, solve_args={'tol': 1.e-12, 'min_its': 50}): X, y =", "gaussian(X, Y, groups, weights, sigma=1., quadratic=None, ridge_term=0., perturb=None, use_lasso=True, #", "# cond_mean is \"something\" times D # Gamma is target_score_cov.T.dot(prec_target)", "S self.r = r def solve_barrier_affine_jacobian_py(conjugate_arg, precision, feasible_point, con_linear, con_offset,", "+ quantile * np.sqrt(np.diag(observed_info_mean))]).T log_ref = val + conjugate_arg.T.dot(cond_cov).dot(conjugate_arg) /", "an empty array return 0, 0, 0 else: GammaMinus =", "ridge_term is None: ridge_term = np.std(Y) * np.sqrt(mean_diag) / np.sqrt(n", "to True perturb=None): _check_groups(groups) # make sure groups looks sensible", "on score, hence the minus sign target_linear = target_score_cov.T.dot(prec_target) target_offset", "= collections.OrderedDict(sorted(active_dirs.items())) Vs = [compute_Vg(ug) for ug in sorted_active_dirs.values()] V", "= opt_linearNoU.dot(U) self.active_dirs = active_dirs self.opt_offset = opt_offset self.ordered_vars =", "+ observed_target) return np.asarray(lower), np.asarray(upper) ### Private method def _construct_density(self):", "+ self.opt_offset) self.cond_mean = cond_mean self.cond_cov = cond_cov self.cond_precision =", "1. / ((self.precs[m])[0, 0]) mean = self.S[m].dot(mean_parameter[m].reshape((1,))) + self.r[m] _cdf", "grad(gs): p1 = -conjugate_arg + precision.dot(gs) p2 = -con_linear.T.dot(1. /", "'parameter', parameter) return result def log_reference(self, observed_target, target_cov, target_score_cov, grid):", "ordered_vars.extend(np.flatnonzero(group_mask)) if self.penalty.weights[g] == 0: unpenalized.append(g) else: active_groups.append(g) active_dirs[g] =", "summary(self, alternatives=None, parameter=None, level=0.9): \"\"\" Produce p-values and confidence intervals", "level. \"\"\" if parameter is not None: pivots = self._approx_pivots(parameter,", "con_linear.dot(gs)) ** 2.))).dot(con_linear) if useJacobian: p2 = - jacobian_grad_hess(gs, C,", "user-specific groups are ok There are a number of assumptions", "on to solver level: level of confidence intervals useC: whether", "= np.sign(self.initial_soln) active = np.flatnonzero(active_signs) self.active = active def compute_Vg(ug):", "**self.solve_args) gamma_ = _A.dot(soln) + R.dot(self.init_soln) log_jacob = jacobian_grad_hess(gamma_, self.C,", "np.inf for itercount in range(nstep): cur_grad = grad(current) # make", "/ 2.) intervals = np.vstack([final_estimator - quantile * np.sqrt(np.diag(observed_info_mean)), final_estimator", "ordered_groups # exception if no groups are selected if len(self.selection_variable['active_groups'])", "def calc_GammaMinus(gamma, active_dirs): \"\"\"Calculate Gamma^minus (as a function of gamma", "import solve_barrier_affine_py as solver from ..distributions.discrete_family import discrete_family class group_lasso(object):", "lasso doesn't self.groups = groups self._initial_omega = perturb # gaussian", "(0, 0): # when all groups are size one, C", "== 0: raise ValueError(\"First group is not 0\") # check", "rr.identity_quadratic(self.ridge_term, 0, -self._initial_omega, 0) problem = rr.simple_problem(self.loglike, self.penalty) # if", "m in range(self.ntarget): p = self.target_score_cov.shape[1] observed_target_uni = (self.observed_target[m]).reshape((1,)) target_cov_uni", "= 2 * np.minimum(pvalues, 1 - pvalues) alpha = 1", "self.active_dirs, useJacobian, **solve_args) final_estimator = target_cov.dot(_prec).dot(observed_target) \\ + target_cov.dot(target_lin.T.dot(prec_opt.dot(cond_mean -", "= ndist.ppf(1 - alpha / 2.) intervals = np.vstack([final_estimator -", "in range(self.ntarget): p = self.target_score_cov.shape[1] observed_target_uni = (self.observed_target[m]).reshape((1,)) target_cov_uni =", "-con_linear.T.dot(1. / (scaling + con_offset - con_linear.dot(gs))) if useJacobian: p3", "con_linear: linear part of affine constraint used for barrier function", "optional Sequence of strings describing the alternatives, should be values", "check array_like agroups = np.array(groups) # check dimension if len(agroups.shape)", "prec_target + (target_linear.T.dot(target_linear) * self.randomizer_prec) - target_lin.T.dot( self.prec_opt).dot(target_lin) _P =", "group labels tol = 1.e-20 _, self.randomizer_prec = self.randomizer.cov_prec #", "the conditional mean of optimization variables # vary with target", "and score of randomized query. solve_args : dict, optional Arguments", "from scipy.linalg import block_diag from scipy.stats import norm as ndist", "to_diag = [[g] * (ug.size - 1) for (g, ug)", "= np.flatnonzero(active_signs) self.active = active def compute_Vg(ug): pg = ug.size", "np from numpy import log from numpy.linalg import norm, qr,", "\"\"\" if parameter is not None: pivots = self._approx_pivots(parameter, alternatives=alternatives)", "the group_lasso. Also, assumes you have already run the fit", "JacobianPieces: (use self.C defined in fitting) \"\"\" self._setup_implied_gaussian() # Calculate", "+ C unbiased_estimator = target_cov.dot(_prec).dot(observed_target) + target_cov.dot( _P - target_lin.T.dot(prec_opt).dot(target_off))", "# should lasso solver be used where applicable - defaults", "= 1. / scaling def objective(gs): p1 = -gs.T.dot(conjugate_arg) p2", "jacobian_grad_hess(gamma, C, active_dirs): \"\"\" Calculate the log-Jacobian (scalar), gradient (gamma.size", "feasible_point current_value = np.inf for itercount in range(nstep): cur_grad =", "# just the gammas cond_mean = self.cond_mean cond_cov = self.cond_cov", "variables (model on _setup_implied_gaussian) cond_cov: conditional variance of optimization variables", "- 1.5 * _scale[j], observed_target[j] + 1.5 * _scale[j], num=ngrid)", "of the reference density on a grid. \"\"\" if np.asarray(observed_target).shape", "= gs.T.dot(precision).dot(gs) / 2. if useJacobian: p3 = - jacobian_grad_hess(gs,", "norm(soln): # is group g appreciably nonzero ordered_groups.append(g) # variables", "* np.std(Y) * np.sqrt(n / (n - 1.)) randomizer =", "_prec = prec_target + (target_linear.T.dot(target_linear) * self.randomizer_prec) - target_lin.T.dot( self.prec_opt).dot(target_lin)", "ridge_term=0., perturb=None, use_lasso=True, # should lasso solver be used when", "groups are size 1 if use_lasso and groups.size == np.unique(groups).size:", "count += 1 proposal = current - step * cur_grad", "C)) # inverse #GpC_inv = evectors.dot(np.diag(1 / evalues).dot(evectors.T)) GpC_inv =", "new perturbation if supplied if perturb is not None: self._initial_omega", "starts with 0 if not np.amin(agroups) == 0: raise ValueError(\"First", "uses results from that method. Parameters ---------- observed_target: from selected_targets", "* prec else: cond_precision = self.opt_linear.T.dot(prec.dot(self.opt_linear)) cond_cov = inv(cond_precision) logdens_linear", "= (self.cond_mean - target_lin.dot(observed_target_uni)).reshape((target_lin.shape[0],)) _prec = prec_target + (target_linear.T.dot(target_linear) *", "['twosided'] * self.ntarget pivot = [] for m in range(self.ntarget):", "> agroups[1:]) < 0: raise ValueError(\"Groups are not sorted\") #", "conditional variance of optimization variables (model on _setup_implied_gaussian) logdens_linear: (model", "not adapted for the group_lasso. Also, assumes you have already", "val, soln, hess = solve_barrier_affine_jacobian_py(conjugate_arg, prec_opt, init_soln, linear_part, offset, self.C,", "np.asarray(upper) ### Private method def _construct_density(self): precs = {} S", "= {} # dictionary: keys are group labels, values are", "- logdens_linear.dot(target_linear) target_off = cond_mean - target_lin.dot(observed_target) if np.asarray(self.randomizer_prec).shape in", "observed_target : ndarray Observed estimate of target. target_cov : ndarray", "self.observed_target[m]) ** 2 / var_target) logW -= logW.max() self._families.append(discrete_family(grid, np.exp(logW)))", "gammas as array _beta_unpenalized = restricted_estimator(self.loglike, # refit OLS on", "self.opt_offset) self.cond_mean = cond_mean self.cond_cov = cond_cov self.cond_precision = cond_precision", "cond_cov = self.cond_cov logdens_linear = self.logdens_linear linear_part = self.linear_part offset", "cov_target, crosscov_target_score, alternatives) class approximate_grid_inference(object): def __init__(self, query, dispersion, solve_args={'tol':", "be in [\"twosided\", \"less\", \"greater\"]') return pivot def _approx_intervals(self, level=0.9):", "J, grad_J, hess_J def _check_groups(groups): \"\"\"Make sure that the user-specific", "alternatives=alternatives) lower, upper = self._approx_intervals(level=level) result = pd.DataFrame({'target': self.observed_target, 'pvalue':", "self._approx_pivots(np.zeros_like(self.observed_target), alternatives=alternatives) lower, upper = self._approx_intervals(level=level) result = pd.DataFrame({'target': self.observed_target,", "interp1d(self.stat_grid[m], log_ref, kind='quadratic', bounds_error=False, fill_value='extrapolate') grid = np.linspace(self.stat_grid[m].min(), self.stat_grid[m].max(), 1000)", "block_diag from scipy.stats import norm as ndist from scipy.interpolate import", "if all groups are size 1 if use_lasso and groups.size", "= self.cond_precision score_offset = self.observed_score_state + self.opt_offset # target_lin determines", "if count >= 20: if not (np.isnan(proposed_value) or np.isnan(current_value)): break", "if relative decrease is small if np.fabs(current_value - proposed_value) <", "(see existing code)... initial_soln = problem.solve(quad, **solve_args) initial_subgrad = -(self.loglike.smooth_objective(initial_soln,", "logdens_linear = cond_cov.dot(self.opt_linear.T) * prec else: cond_precision = self.opt_linear.T.dot(prec.dot(self.opt_linear)) cond_cov", "# do not need to keep setting this if norm(soln[group_mask])", "logW -= logW.max() self._families.append(discrete_family(grid, np.exp(logW))) def _approx_pivots(self, mean_parameter, alternatives=None): if", "target_offset = score_offset - target_linear.dot(observed_target) target_lin = - logdens_linear.dot(target_linear) target_off", "+ quad.objective(initial_soln, 'grad')) return initial_soln, initial_subgrad @staticmethod def gaussian(X, Y,", "groups are selected if len(self.selection_variable['active_groups']) == 0: return np.sign(soln), soln", "self.randomizer = randomizer def fit(self, solve_args={'tol': 1.e-12, 'min_its': 50}, perturb=None):", "* np.sqrt(np.diag(inverse_info)) if useIP == False: ngrid = 1000 self.stat_grid", "con_offset, C, active_dirs, useJacobian=True, step=1, nstep=2000, min_its=500, tol=1.e-12): \"\"\" This", "mean of optimization variables # vary with target # logdens_linear", ":] = np.linspace(observed_target[j] - 1.5 * _scale[j], observed_target[j] + 1.5", "p)) target_linear = target_score_cov_uni.T.dot(prec_target) target_offset = (self.score_offset - target_linear.dot(observed_target_uni)).reshape( (target_linear.shape[0],))", "= restricted_estimator(self.loglike, # refit OLS on E overall, solve_args=solve_args) beta_bar", "from numpy.linalg import norm, qr, inv, eig import pandas as", "= [] # active group labels sorted by label ordered_opt", "group_mask = self.groups == g soln = self.initial_soln # do", ":].reshape((1, p)) target_linear = target_score_cov_uni.T.dot(prec_target) target_offset = (self.score_offset - target_linear.dot(observed_target_uni)).reshape(", "solver... (see existing code)... initial_soln = problem.solve(quad, **solve_args) initial_subgrad =", "observed_target[j] + 1.5 * _scale[j], num=ngrid) else: ngrid = 100", "= np.linspace(observed_target[j] - 1.5 * _scale[j], observed_target[j] + 1.5 *", "groups, weights, ridge_term, randomizer, use_lasso, perturb) def _setup_implied_gaussian(self): _, prec", "labels ordered_vars = [] # indices \"ordered\" by sorting group", "this if norm(soln[group_mask]) > tol * norm(soln): # is group", "linear_part = self.linear_part offset = self.offset if np.asarray(observed_target).shape in [(),", "<= current_value: break step *= 0.5 if count >= 20:", "np.issubdtype(agroups.dtype, np.integer): raise TypeError(\"Groups are not integers\") # check starts", "defaults to True perturb=None): _check_groups(groups) # make sure groups looks", "self.randomizer.sample() quad = rr.identity_quadratic(self.ridge_term, 0, -self._initial_omega, 0) problem = rr.simple_problem(self.loglike,", "1. / target_cov_uni target_score_cov_uni = self.target_score_cov[m, :].reshape((1, p)) target_linear =", "= np.atleast_1d(observed_target) prec_target = inv(target_cov) prec_opt = self.cond_precision score_offset =", "= eig(GammaMinus + C) # log Jacobian #J = log(evalues).sum()", "None: alternatives = ['twosided'] * self.ntarget pivot = [] for", "grad(current) # make sure proposal is feasible count = 0", "np.asscalar(eta.T.dot(cond_mean_grid)) implied_cov = np.asscalar(eta.T.dot(self.cond_cov).dot(eta)) implied_prec = 1./implied_cov _A = self.cond_cov.dot(eta)", "of strings describing the alternatives, should be values of ['twosided',", "ug.size - 1)) for ug in active_dirs.values()]) # gradient grad_J", "final_estimator / np.sqrt(np.diag(observed_info_mean)) pvalues = ndist.cdf(Z_scores) pvalues = 2 *", "(proposed_value, current_value)) # stop if relative decrease is small if", "Gaussian # cond_mean is \"something\" times D # Gamma is", "/ 2. result = pd.DataFrame({'MLE': final_estimator, 'SE': np.sqrt(np.diag(observed_info_mean)), 'Zvalue': Z_scores,", "else: Vg = np.zeros((1, 0)) # if the group is", "query. solve_args : dict, optional Arguments passed to solver. \"\"\"", "b_scaling (from lasso) solve_args: passed on to solver level: level", "unpenalized.append(g) else: active_groups.append(g) active_dirs[g] = soln[group_mask] / norm(soln[group_mask]) ordered_opt.append(norm(soln[group_mask])) else:", "(in self.C) arguments conjugate_arg: \\\\bar{\\\\Sigma}^{-1} \\bar{\\\\mu} precision: \\\\bar{\\\\Sigma}^{-1} feasible_point: gamma's", "= _score_linear.dot(self.QI).T * dispersion return (observed_target, cov_target, crosscov_target_score, alternatives) class", "- target_linear.dot(observed_target_uni)).reshape( (target_linear.shape[0],)) target_lin = -self.logdens_linear.dot(target_linear) target_off = (self.cond_mean -", "to use python or C solver JacobianPieces: (use self.C defined", "take a new perturbation if supplied if perturb is not", "p = X.shape XE = self.XE Q = self.Q observed_target", "np.array rather than a dictionary weights_np = np.array([w[1] for w", "solve_args=solve_args) _score_linear = -XE.T.dot(self._W[:, None] * X).T alternatives = ['twosided']", "the minus sign target_linear = target_score_cov.T.dot(prec_target) target_offset = score_offset -", "of model including selected features Parameters ---------- query : `gaussian_query`", "1. / ((self.precs[m])[0, 0]) lower.append(l * var_target + observed_target) upper.append(u", "with 0 if not np.amin(agroups) == 0: raise ValueError(\"First group", "'lower_confidence': lower, 'upper_confidence': upper}) if not np.all(parameter == 0): result.insert(4,", "_, prec = self.randomizer.cov_prec if np.asarray(prec).shape in [(), (0,)]: cond_precision", "self._families.append(discrete_family(self.stat_grid[m], np.exp(logW))) else: approx_fn = interp1d(self.stat_grid[m], log_ref, kind='quadratic', bounds_error=False, fill_value='extrapolate')", "implied_cov)/ 2. + log_jacob[0]) return np.asarray(ref_hat) def _construct_families(self): self._construct_density() self._families", "(np.isnan(proposed_value) or np.isnan(current_value)): break else: raise ValueError('value is NaN: %f,", "useC: whether to use python or C solver JacobianPieces: (use", "### Private method def _construct_density(self): precs = {} S =", "ridge_term # group lasso penalty (from regreg) # use regular", "mean_diag = np.mean((X ** 2).sum(0)) if ridge_term is None: ridge_term", "= (target_lin.dot(np.atleast_1d(grid[k] - observed_target)) + self.cond_mean) #direction for decomposing o", "= self.target_score_cov.shape[1] for m in range(self.ntarget): observed_target_uni = (self.observed_target[m]).reshape((1,)) target_cov_uni", "This function checks the user-specified group scheme and raises an", "targets of model including selected features Parameters ---------- alternatives :", "= np.asscalar(eta.T.dot(cond_mean_grid)) implied_cov = np.asscalar(eta.T.dot(self.cond_cov).dot(eta)) implied_prec = 1./implied_cov _A =", "= -con_linear.T.dot(1. / (scaling + con_offset - con_linear.dot(gs))) if useJacobian:", "a 1-d array_like of integers that are sorted in increasing", "np.isnan(current_value)): break else: raise ValueError('value is NaN: %f, %f' %", "when all groups are size one, C will be an", "1-d array_like of integers that are sorted in increasing order,", "solve_args=solve_args) # initialize variables active_groups = [] # active group", "pivots) result.insert(5, 'parameter', parameter) return result def log_reference(self, observed_target, target_cov,", "XE.shape[1]) cov_target = self.QI * dispersion crosscov_target_score = _score_linear.dot(self.QI).T *", "XE.T.dot(self._W[:, None] * XE) QI = inv(Q) C = V.T.dot(QI).dot(L).dot(V)", "target_linear = target_score_cov_uni.T.dot(prec_target) target_offset = (self.score_offset - target_linear.dot(observed_target_uni)).reshape( (target_linear.shape[0],)) target_lin", "Q, _ = qr(Z) Vg = Q[:, 1:] # drop", "`gaussian_query` A Gaussian query which has information to describe implied", "ngrid = 1000 self.stat_grid = np.zeros((ntarget, ngrid)) for j in", "(observed) value of optimization variables cond_mean: conditional mean of optimization", "usual D = N + Gamma theta.hat, # target_lin is", "variables # vary with target # logdens_linear determines how the", "selected_targets target_cov: from selected_targets target_cov_score: from selected_targets init_soln: (opt_state) initial", "-= logW.max() self._families.append(discrete_family(self.stat_grid[m], np.exp(logW))) else: approx_fn = interp1d(self.stat_grid[m], log_ref, kind='quadratic',", "1], 'unbiased': unbiased_estimator}) return result, observed_info_mean, log_ref def selected_targets(self, dispersion=None,", "1. / ((con_offset - con_linear.dot(gs)) / scaling)).sum() return p1 +", "ug in sorted_active_dirs.values()] V = block_diag(*Vs) # unpack the list", "defaults to 0. level : float Confidence level. \"\"\" if", "hess = inv(precision + barrier_hessian(current)) return current_value, current, hess #", "of ['twosided', 'less', 'greater'] parameter : np.array Hypothesized value for", "target_lin.T.dot(prec_opt).dot(target_off)) L = target_lin.T.dot(prec_opt) observed_info_natural = _prec + L.dot(target_lin) -", "self.loglike.shape[0] # ridge parameter self.ridge_term = ridge_term # group lasso", "part of affine constraint used for barrier function C: V^T", "solve_args={'tol': 1.e-12, 'min_its': 50}, perturb=None): # solve the randomized version", "# make sure proposal is a descent count = 0", "query.selected_targets(dispersion) self.observed_target = observed_target self.target_score_cov = target_score_cov self.target_cov = target_cov", "masks the selective_MLE inherited from query because that is not", "N + Gamma theta.hat, # target_lin is \"something\" times Gamma,", "sorted if np.any(agroups[:-1] > agroups[1:]) < 0: raise ValueError(\"Groups are", "- con_linear.dot(gs)) ** 2.))).dot(con_linear) if useJacobian: p2 = - jacobian_grad_hess(gs,", "\\\\bar{\\\\Sigma}^{-1} \\bar{\\\\mu} precision: \\\\bar{\\\\Sigma}^{-1} feasible_point: gamma's from fitting con_linear: linear", "1 proposal = current - step * cur_grad proposed_value =", "= S self.r = r def solve_barrier_affine_jacobian_py(conjugate_arg, precision, feasible_point, con_linear,", "of affine constraint used for barrier function con_offset: offset part", "= self.QI * dispersion crosscov_target_score = _score_linear.dot(self.QI).T * dispersion return", "_scale[j], num=ngrid) else: ngrid = 100 self.stat_grid = np.zeros((ntarget, ngrid))", "0], 'upper_confidence': intervals[:, 1], 'unbiased': unbiased_estimator}) return result, observed_info_mean, log_ref", "the reference density on a grid. \"\"\" if np.asarray(observed_target).shape in", "** 2).sum(0)) if ridge_term is None: ridge_term = np.std(Y) *", "current_value = proposed_value break current = proposal current_value = proposed_value", "penalty if all groups are size 1 if use_lasso and", "= self.cond_cov.dot(eta) * implied_prec R = np.identity(num_opt) - _A.dot(eta.T) A", "precision.dot(gs) p2 = -con_linear.T.dot(1. / (scaling + con_offset - con_linear.dot(gs)))", "one feature in group 3). This function checks the user-specified", "p2 = 0 return p1 + p2 current = feasible_point", "Gamma, # where \"something\" comes from implied Gaussian # cond_mean", "np.array(groups) # check dimension if len(agroups.shape) != 1: raise ValueError(\"Groups", "np.any(agroups[:-1] > agroups[1:]) < 0: raise ValueError(\"Groups are not sorted\")", "for targets of model including selected features Parameters ---------- query", "self.randomizer.cov_prec if np.asarray(prec).shape in [(), (0,)]: cond_precision = self.opt_linear.T.dot(self.opt_linear) *", "target_linear = target_score_cov.T.dot(prec_target) target_offset = score_offset - target_linear.dot(observed_target) target_lin =", "np.sqrt(np.diag(con_linear.dot(precision).dot(con_linear.T))) if feasible_point is None: feasible_point = 1. / scaling", "0, and have no gaps (e.g., if there is a", "opt_linearNoU.dot(U) self.active_dirs = active_dirs self.opt_offset = opt_offset self.ordered_vars = ordered_vars", "useful quantities (observed_target, target_cov, target_score_cov, alternatives) = self.selected_targets(dispersion) init_soln =", "solver(np.asarray([conjugate_arg]), np.reshape(implied_prec, (1,1)), eta.T.dot(self.init_soln), A.reshape((A.shape[0],1)), b, **self.solve_args) gamma_ = _A.dot(soln)", "= (np.diag(self.target_cov)[m]).reshape((1, 1)) prec_target = 1. / target_cov_uni target_score_cov_uni =", "= target_score_cov self.target_cov = target_cov self.init_soln = query.observed_opt_state self.randomizer_prec =", "scheme and raises an exception if it finds any problems.", "g appreciably nonzero ordered_groups.append(g) # variables in active group ordered_vars.extend(np.flatnonzero(group_mask))", "eta = -self.prec_opt.dot(self.logdens_linear.dot(target_score_cov.T)) implied_mean = np.asscalar(eta.T.dot(cond_mean_grid)) implied_cov = np.asscalar(eta.T.dot(self.cond_cov).dot(eta)) implied_prec", "Private method def _construct_density(self): precs = {} S = {}", "= log(1. + 1. / ((con_offset - con_linear.dot(gs)) / scaling)).sum()", "[compute_Vg(ug) for ug in sorted_active_dirs.values()] V = block_diag(*Vs) # unpack", "quantities (observed_target, target_cov, target_score_cov, alternatives) = self.selected_targets(dispersion) init_soln = self.observed_opt_state", "return p1 + p2 + p3 + p4 def barrier_hessian(gs):", "(model on _setup_implied_gaussian) cond_cov: conditional variance of optimization variables (model", "= ordered_groups # exception if no groups are selected if", "[(), (0,)]: cond_precision = self.opt_linear.T.dot(self.opt_linear) * prec cond_cov = inv(cond_precision)", "= 0 p4 = 1. / (con_offset - con_linear.dot(gs)) return", "if np.any(agroups[:-1] > agroups[1:]) < 0: raise ValueError(\"Groups are not", "for no skipped groups if not np.all(np.diff(np.unique(agroups)) == 1): raise", "target_cov: from selected_targets target_cov_score: from selected_targets init_soln: (opt_state) initial (observed)", "log(1. + 1. / ((con_offset - con_linear.dot(gs)) / scaling)).sum() return", "specified') observed_target = np.atleast_1d(observed_target) prec_target = inv(target_cov) prec_opt = self.cond_precision", "use Pearson's X^2 dispersion = ((y - self.loglike.saturated_loss.mean_function( XE.dot(observed_target))) **", "(self.cond_mean - target_lin.dot(observed_target_uni)).reshape((target_lin.shape[0],)) _prec = prec_target + (target_linear.T.dot(target_linear) * self.randomizer_prec)", "the log-Jacobian (scalar), gradient (gamma.size vector) and hessian (gamma.size square", "provide weights an an np.array rather than a dictionary weights_np", "is a 1-d array_like of integers that are sorted in", "X, y = self.loglike.data W = self._W = self.loglike.saturated_loss.hessian(X.dot(beta_bar)) #", "groups is potentially tedious for the user and in future", "for g in sorted_active_dirs] L = block_diag(*Ls) # unpack the", "perturb=None, solve_args={'tol': 1.e-15, 'min_its': 100}): # take a new perturbation", "0]) lower.append(l * var_target + observed_target) upper.append(u * var_target +", "log likelihood : quadratic loss self.loglike = loglike self.nfeature =", "be values of ['twosided', 'less', 'greater'] parameter : np.array Hypothesized", "need to provide weights an an np.array rather than a", "0.5 if count >= 40: raise ValueError('not finding a feasible", "variables in active group ordered_vars.extend(np.flatnonzero(group_mask)) if self.penalty.weights[g] == 0: unpenalized.append(g)", "labels, values are unit-norm coefficients unpenalized = [] # selected", "_ = solver(np.asarray([conjugate_arg]), np.reshape(implied_prec, (1,1)), eta.T.dot(self.init_soln), A.reshape((A.shape[0],1)), b, **self.solve_args) gamma_", "con_linear.dot(gs)) return p1 + p2 + p3 + p4 def", "target_cov.dot(_prec).dot(observed_target) \\ + target_cov.dot(target_lin.T.dot(prec_opt.dot(cond_mean - soln))) + C unbiased_estimator =", "fitting con_linear: linear part of affine constraint used for barrier", "# active group labels active_dirs = {} # dictionary: keys", "check starts with 0 if not np.amin(agroups) == 0: raise", "otherwise continue as before self.observed_opt_state = np.hstack(ordered_opt) # gammas as", "(gamma.size vector) and hessian (gamma.size square matrix) \"\"\" if C.shape", "[] # selected groups with no penalty overall = np.ones(self.nfeature,", "raise ValueError('value is NaN: %f, %f' % (proposed_value, current_value)) #", "active features ordered_groups = [] # active group labels sorted", "- con_linear.dot(proposal) > 0): break step *= 0.5 if count", "target_score_cov.T.dot(prec_target) num_opt = self.prec_opt.shape[0] num_con = self.linear_part.shape[0] cond_mean_grid = (target_lin.dot(np.atleast_1d(grid[k]", "if the group is size one, the orthogonal complement is", "are a number of assumptions that group_lasso makes about how", "specified') prec_target = np.linalg.inv(target_cov) target_lin = - self.logdens_linear.dot(target_score_cov.T.dot(prec_target)) ref_hat =", "intervals useC: whether to use python or C solver JacobianPieces:", "/ (scaling + con_offset - con_linear.dot(gs))) if useJacobian: p3 =", "ug in active_dirs.values()]) # gradient grad_J = S.dot(GpC_inv.diagonal()) # hessian", "in [(), (0,)]: raise ValueError('no target specified') observed_target = np.atleast_1d(observed_target)", "'less': pivot.append(_cdf) else: raise ValueError('alternative should be in [\"twosided\", \"less\",", "target_cov : ndarray Estimated covaraince of target. target_score_cov : ndarray", "group labels, values are unit-norm coefficients unpenalized = [] #", "sorted(np.unique(self.groups)): # g is group label group_mask = self.groups ==", "query.selective_MLE(dispersion=dispersion)[:2] self.linear_part = query.linear_part self.offset = query.offset self.logdens_linear = query.logdens_linear", "if np.asarray(prec).shape in [(), (0,)]: cond_precision = self.opt_linear.T.dot(self.opt_linear) * prec", "method since this uses results from that method. Parameters ----------", "cur_grad if np.all(con_offset - con_linear.dot(proposal) > 0): break step *=", "lasso) solve_args: passed on to solver level: level of confidence", "(0,)]: cond_precision = self.opt_linear.T.dot(self.opt_linear) * prec cond_cov = inv(cond_precision) logdens_linear", "1. / ((con_offset - con_linear.dot(gs)) ** 2.))).dot(con_linear) if useJacobian: p2", "* np.fabs(current_value) and itercount >= min_its: current = proposal current_value", "4, there must also be at least one feature in", "log_reference(self, observed_target, target_cov, target_score_cov, grid): \"\"\" Approximate the log of", "which has information to describe implied Gaussian. observed_target : ndarray", "self.C, self.active_dirs) ref_hat.append(-val - ((conjugate_arg ** 2) * implied_cov)/ 2.", "sorted\") # check integers if not np.issubdtype(agroups.dtype, np.integer): raise TypeError(\"Groups", "# inverse #GpC_inv = evectors.dot(np.diag(1 / evalues).dot(evectors.T)) GpC_inv = np.linalg.inv(GammaMinus", "\"\"\" Approximate the log of the reference density on a", "+ p2 current = feasible_point current_value = np.inf for itercount", "barrier_hessian(current)) return current_value, current, hess # Jacobian calculations def calc_GammaMinus(gamma,", "= False self.selection_variable = {'directions': active_dirs, 'active_groups': active_groups} # kind", "target_lin) else: _P = target_linear.T.dot(self.randomizer_prec).dot(target_offset) _prec = prec_target + (target_linear.T.dot(self.randomizer_prec).dot(target_linear))", "== g soln = self.initial_soln # do not need to", "penalty and run usual lasso solver... (see existing code)... initial_soln", "randomization.isotropic_gaussian((p,), randomizer_scale) return group_lasso(loglike, groups, weights, ridge_term, randomizer, use_lasso, perturb)", "- defaults to True randomizer_scale=None): loglike = rr.glm.gaussian(X, Y, coef=1.", "\"\"\" self._setup_implied_gaussian() # Calculate useful quantities (observed_target, target_cov, target_score_cov, alternatives)", "= np.sqrt(mean_diag) * 0.5 * np.std(Y) * np.sqrt(n / (n", "ordered_vars = [] # indices \"ordered\" by sorting group labels", "[] for k in range(grid.shape[0]): # in the usual D", "integers\") # check starts with 0 if not np.amin(agroups) ==", "= self.selected_targets(dispersion) init_soln = self.observed_opt_state # just the gammas cond_mean", "1's for LS opt_linearNoU = np.dot(X.T, X[:, ordered_vars] * W[:,", "beta_bar[overall] = _beta_unpenalized # refit OLS beta with zeros self._beta_full", "for gp in to_diag for i in gp]) def jacobian_grad_hess(gamma,", "restricted_estimator(self.loglike, # refit OLS on E overall, solve_args=solve_args) beta_bar =", "conjugate_arg = prec_opt.dot(cond_mean) val, soln, hess = solve_barrier_affine_jacobian_py(conjugate_arg, prec_opt, init_soln,", "barrier and jacobian to hessian p1 = con_linear.T.dot(np.diag(-1. / ((scaling", "dict, optional Arguments passed to solver. \"\"\" self.solve_args = solve_args", "group_lasso(object): def __init__(self, loglike, groups, weights, ridge_term, randomizer, use_lasso=True, #", "dictionary: keys are group labels, values are unit-norm coefficients unpenalized", "np.zeros(self.nfeature) beta_bar[overall] = _beta_unpenalized # refit OLS beta with zeros", "be at least one feature in group 3). This function", "np.unique(groups).size: # need to provide weights an an np.array rather", "_cdf)) elif alternatives[m] == 'greater': pivot.append(1 - _cdf) elif alternatives[m]", "cond_precision = self.opt_linear.T.dot(self.opt_linear) * prec cond_cov = inv(cond_precision) logdens_linear =", "Pearson's X^2 dispersion = ((y - self.loglike.saturated_loss.mean_function( XE.dot(observed_target))) ** 2", "for i in gp]) def jacobian_grad_hess(gamma, C, active_dirs): \"\"\" Calculate", "inv(target_cov) prec_opt = self.cond_precision score_offset = self.observed_score_state + self.opt_offset #", "min_its=500, tol=1.e-12): \"\"\" This needs to be updated to actually", "you have already run the fit method since this uses", "weights=weights, lagrange=1.) # store groups as a class variable since", "the argument of the optimization density # depends on the", "relative decrease is small if np.fabs(current_value - proposed_value) < tol", "quadratic=quadratic) n, p = X.shape mean_diag = np.mean((X ** 2).sum(0))", "= rr.simple_problem(self.loglike, self.penalty) # if all groups are size 1,", "self.active_dirs) ref_hat.append(-val - ((conjugate_arg ** 2) * implied_cov)/ 2. +", "soln # otherwise continue as before self.observed_opt_state = np.hstack(ordered_opt) #", "# should lasso solver be used when applicable - defaults", "True perturb=None): _check_groups(groups) # make sure groups looks sensible #", "are size 1 if use_lasso and groups.size == np.unique(groups).size: #", "(target_linear.T.dot(target_linear) * self.randomizer_prec) - target_lin.T.dot( prec_opt).dot( target_lin) else: _P =", "Gaussian query which has information to describe implied Gaussian. observed_target", "ridge_term, randomizer, use_lasso=True, # should lasso solver be used where", "np.array Hypothesized value for parameter -- defaults to 0. level", "return pivot def _approx_intervals(self, level=0.9): if not hasattr(self, \"_families\"): self._construct_families()", "\"something\" times Gamma, # where \"something\" comes from implied Gaussian", "= V.T.dot(QI).dot(L).dot(V) self.XE = XE self.Q = Q self.QI =", "0.5 * np.std(Y) * np.sqrt(n / (n - 1.)) randomizer", "self.opt_linear = opt_linearNoU.dot(U) self.active_dirs = active_dirs self.opt_offset = opt_offset self.ordered_vars", "ref_hat.append(-val - ((conjugate_arg ** 2) * implied_cov)/ 2. + log_jacob[0])", "---------- observed_target: from selected_targets target_cov: from selected_targets target_cov_score: from selected_targets", "100 self.stat_grid = np.zeros((ntarget, ngrid)) for j in range(ntarget): self.stat_grid[j,", "self.target_score_cov[m, :].reshape((1, p)) var_target = 1. / ((self.precs[m])[0, 0]) log_ref", "def grad(gs): p1 = -conjugate_arg + precision.dot(gs) p2 = -con_linear.T.dot(1.", "R.dot(self.init_soln) log_jacob = jacobian_grad_hess(gamma_, self.C, self.active_dirs) ref_hat.append(-val - ((conjugate_arg **", "= solve_barrier_affine_jacobian_py(conjugate_arg, prec_opt, init_soln, linear_part, offset, self.C, self.active_dirs, useJacobian, **solve_args)", "1 proposal = current - step * cur_grad if np.all(con_offset", "#direction for decomposing o eta = -self.prec_opt.dot(self.logdens_linear.dot(target_score_cov.T)) implied_mean = np.asscalar(eta.T.dot(cond_mean_grid))", "ug in sorted_active_dirs.values()]).T self.opt_linear = opt_linearNoU.dot(U) self.active_dirs = active_dirs self.opt_offset", "_approx_pivots(self, mean_parameter, alternatives=None): if not hasattr(self, \"_families\"): self._construct_families() if alternatives", "proposal current_value = proposed_value break current = proposal current_value =", "1) for (g, ug) in zip(gamma, active_dirs.values())] return block_diag(*[i for", "of g'th group if pg > 1: Z = np.column_stack((ug,", "= self.penalty.weights[g] * np.eye(pg) return Lg sorted_active_dirs = collections.OrderedDict(sorted(active_dirs.items())) Vs", "self.logdens_linear.dot(target_score_cov.T.dot(prec_target)) ref_hat = [] for k in range(grid.shape[0]): # in", "C = target_cov.dot(_P - target_lin.T.dot(prec_opt).dot(target_off)) conjugate_arg = prec_opt.dot(cond_mean) val, soln,", "self.ntarget = ntarget = target_cov.shape[0] _scale = 4 * np.sqrt(np.diag(inverse_info))", "C.shape[0]) S = block_diag(*[np.ones((1, ug.size - 1)) for ug in", ">= min_its: current = proposal current_value = proposed_value break current", "if no groups are selected if len(self.selection_variable['active_groups']) == 0: return", "i, var in enumerate(ordered_vars): opt_linearNoU[var, i] += self.ridge_term opt_offset =", "self.linear_part = -np.eye(self.observed_opt_state.shape[0]) self.offset = np.zeros(self.observed_opt_state.shape[0]) return active_signs, soln def", "vector) and hessian (gamma.size square matrix) \"\"\" if C.shape ==", "# active group labels sorted by label ordered_opt = []", "np.linalg.inv(_prec).dot(prec_target) S[m] = _S r[m] = _r precs[m] = _prec", "approximate_grid_inference(object): def __init__(self, query, dispersion, solve_args={'tol': 1.e-12}, useIP=True): \"\"\" Produce", "(scaling + con_offset - con_linear.dot(gs))) if useJacobian: p3 = -", "p1 = con_linear.T.dot(np.diag(-1. / ((scaling + con_offset - con_linear.dot(gs)) **", "target_cov.shape[0] _scale = 4 * np.sqrt(np.diag(inverse_info)) if useIP == False:", "this masks the selective_MLE inherited from query because that is", "self.initial_soln # do not need to keep setting this if", "C, active_dirs)[1] else: p3 = 0 p4 = 1. /", "log_ref, kind='quadratic', bounds_error=False, fill_value='extrapolate') grid = np.linspace(self.stat_grid[m].min(), self.stat_grid[m].max(), 1000) logW", "= np.vstack([final_estimator - quantile * np.sqrt(np.diag(observed_info_mean)), final_estimator + quantile *", "a descent count = 0 while True: count += 1", "self._families[m] var_target = 1. / ((self.precs[m])[0, 0]) mean = self.S[m].dot(mean_parameter[m].reshape((1,)))", "= self.loglike.data n, p = X.shape XE = self.XE Q", "ok There are a number of assumptions that group_lasso makes", "scipy.stats import norm as ndist from scipy.interpolate import interp1d import", "active_dirs[g].size Lg = self.penalty.weights[g] * np.eye(pg) return Lg sorted_active_dirs =", "var_target + observed_target) return np.asarray(lower), np.asarray(upper) ### Private method def", "= target_linear.T.dot(self.randomizer_prec).dot(target_offset) _prec = prec_target + (target_linear.T.dot(self.randomizer_prec).dot(target_linear)) - target_lin.T.dot( prec_opt).dot(target_lin)", "cond_cov: conditional variance of optimization variables (model on _setup_implied_gaussian) logdens_linear:", "con_offset: offset part of affine constraint used for barrier function", "matrix (gamma.size by C.shape[0]) S = block_diag(*[np.ones((1, ug.size - 1))", "= -np.eye(self.observed_opt_state.shape[0]) self.offset = np.zeros(self.observed_opt_state.shape[0]) return active_signs, soln def _solve_randomized_problem(self,", "barrier_hessian(gs): # contribution of barrier and jacobian to hessian p1", "eigendecomposition #evalues, evectors = eig(GammaMinus + C) # log Jacobian", "information (in self.C) arguments conjugate_arg: \\\\bar{\\\\Sigma}^{-1} \\bar{\\\\mu} precision: \\\\bar{\\\\Sigma}^{-1} feasible_point:", "C solver JacobianPieces: (use self.C defined in fitting) \"\"\" self._setup_implied_gaussian()", "= query.offset self.logdens_linear = query.logdens_linear self.cond_mean = query.cond_mean self.prec_opt =", "active_groups} # kind of redundant with keys of active_dirs self._ordered_groups", "(grid - self.observed_target[m]) ** 2 / var_target) logW -= logW.max()", "the score, not how the mean depends on score, hence", "np.eye(pg, pg - 1))) Q, _ = qr(Z) Vg =", "pvalues = 2 * np.minimum(pvalues, 1 - pvalues) alpha =", "+ self.opt_offset # target_lin determines how the conditional mean of", "scipy.interpolate import interp1d import collections import numpy as np from", "scipy.linalg import block_diag from scipy.stats import norm as ndist from", "final_estimator + quantile * np.sqrt(np.diag(observed_info_mean))]).T log_ref = val + conjugate_arg.T.dot(cond_cov).dot(conjugate_arg)", "p)) var_target = 1. / ((self.precs[m])[0, 0]) log_ref = self.log_reference(observed_target_uni,", "in range(self.ntarget): family = self._families[m] var_target = 1. / ((self.precs[m])[0,", "ridge_term = np.std(Y) * np.sqrt(mean_diag) / np.sqrt(n - 1) if", "= 100 self.stat_grid = np.zeros((ntarget, ngrid)) for j in range(ntarget):", "= {'directions': active_dirs, 'active_groups': active_groups} # kind of redundant with", "theta.hat, # target_lin is \"something\" times Gamma, # where \"something\"", "do not need to keep setting this if norm(soln[group_mask]) >", "= evectors.dot(np.diag(1 / evalues).dot(evectors.T)) GpC_inv = np.linalg.inv(GammaMinus + C) #", "Sorting feature groups is potentially tedious for the user and", "'pvalue': pvalues, 'lower_confidence': lower, 'upper_confidence': upper}) if not np.all(parameter ==", "and raises an exception if it finds any problems. Sorting", "= {} p = self.target_score_cov.shape[1] for m in range(self.ntarget): observed_target_uni", "has information to describe implied Gaussian. observed_target : ndarray Observed", "target_linear.T.dot(self.randomizer_prec).dot(target_offset) _prec = prec_target + (target_linear.T.dot(self.randomizer_prec).dot(target_linear)) - target_lin.T.dot( prec_opt).dot(target_lin) C", "conditional mean of optimization variables # vary with target #", "logW.max() self._families.append(discrete_family(grid, np.exp(logW))) def _approx_pivots(self, mean_parameter, alternatives=None): if not hasattr(self,", "lasso penalty if all groups are size 1 if use_lasso", "self._initial_omega = perturb # gaussian randomization self.randomizer = randomizer def", "0.5 * (self.stat_grid[m] - self.observed_target[m]) ** 2 / var_target) logW", "check integers if not np.issubdtype(agroups.dtype, np.integer): raise TypeError(\"Groups are not", "break else: raise ValueError('value is NaN: %f, %f' % (proposed_value,", "var in enumerate(ordered_vars): opt_linearNoU[var, i] += self.ridge_term opt_offset = self.initial_subgrad", "= self.cond_mean cond_cov = self.cond_cov logdens_linear = self.logdens_linear linear_part =", "initial_subgrad = -(self.loglike.smooth_objective(initial_soln, 'grad') + quad.objective(initial_soln, 'grad')) return initial_soln, initial_subgrad", "X[:, ordered_vars] # changed to ordered_vars Q = XE.T.dot(self._W[:, None]", "((con_offset - con_linear.dot(gs)) / scaling)).sum() return p1 + p2 +", "level=0.9): if not hasattr(self, \"_families\"): self._construct_families() lower, upper = [],", "(log_ref - 0.5 * (self.stat_grid[m] - self.observed_target[m]) ** 2 /", "by sorting group labels tol = 1.e-20 _, self.randomizer_prec =", "V active_dirs: \"\"\" scaling = np.sqrt(np.diag(con_linear.dot(precision).dot(con_linear.T))) if feasible_point is None:", "D # Gamma is target_score_cov.T.dot(prec_target) num_opt = self.prec_opt.shape[0] num_con =", "if np.fabs(current_value - proposed_value) < tol * np.fabs(current_value) and itercount", "if not np.issubdtype(agroups.dtype, np.integer): raise TypeError(\"Groups are not integers\") #", "else: self.penalty = rr.group_lasso(groups, weights=weights, lagrange=1.) # store groups as", "self.S[m].dot(mean_parameter[m].reshape((1,))) + self.r[m] _cdf = family.cdf((mean[0] - self.observed_target[m]) / var_target,", "def log_reference(self, observed_target, target_cov, target_score_cov, grid): \"\"\" Approximate the log", "= self.observed_score_state + self.opt_offset # target_lin determines how the conditional", "'pivot', pivots) result.insert(5, 'parameter', parameter) return result def log_reference(self, observed_target,", "+ log_jacob[0]) return np.asarray(ref_hat) def _construct_families(self): self._construct_density() self._families = []", "query.logdens_linear self.cond_mean = query.cond_mean self.prec_opt = np.linalg.inv(query.cond_cov) self.cond_cov = query.cond_cov", "feasible_point, con_linear, con_offset, C, active_dirs, useJacobian=True, step=1, nstep=2000, min_its=500, tol=1.e-12):", "proposed_value <= current_value: break step *= 0.5 if count >=", "sorted_active_dirs.values()]).T self.opt_linear = opt_linearNoU.dot(U) self.active_dirs = active_dirs self.opt_offset = opt_offset", "ordered_opt = [] # gamma's ordered by group labels ordered_vars", "= target_cov self.init_soln = query.observed_opt_state self.randomizer_prec = query.randomizer_prec self.score_offset =", "values of ['twosided', 'less', 'greater'] parameter : np.array Hypothesized value", "initial_subgrad @staticmethod def gaussian(X, Y, groups, weights, sigma=1., quadratic=None, ridge_term=0.,", "from selected_targets target_cov_score: from selected_targets init_soln: (opt_state) initial (observed) value", "import numpy as np from numpy import log from numpy.linalg", "alternatives[m] == 'greater': pivot.append(1 - _cdf) elif alternatives[m] == 'less':", "p = X.shape mean_diag = np.mean((X ** 2).sum(0)) if ridge_term", "def compute_Lg(g): pg = active_dirs[g].size Lg = self.penalty.weights[g] * np.eye(pg)", "`groups` is a 1-d array_like of integers that are sorted", "X, y = self.loglike.data n, p = X.shape XE =", "= 0 p4 = log(1. + 1. / ((con_offset -", "= self._families[m] var_target = 1. / ((self.precs[m])[0, 0]) mean =", "fit method since this uses results from that method. Parameters", "= ndist.cdf(Z_scores) pvalues = 2 * np.minimum(pvalues, 1 - pvalues)", "target_lin = - logdens_linear.dot(target_linear) target_off = cond_mean - target_lin.dot(observed_target) if", "+ precision.dot(gs) p2 = -con_linear.T.dot(1. / (scaling + con_offset -", "(self.score_offset - target_linear.dot(observed_target_uni)).reshape( (target_linear.shape[0],)) target_lin = -self.logdens_linear.dot(target_linear) target_off = (self.cond_mean", "quadratic loss self.loglike = loglike self.nfeature = self.loglike.shape[0] # ridge", "np.zeros((1, 0)) # if the group is size one, the", "itercount in range(nstep): cur_grad = grad(current) # make sure proposal", "= np.dot(X.T, X[:, ordered_vars] * W[:, np.newaxis]) for i, var", "Q[:, 1:] # drop the first column else: Vg =", "[[g] * (ug.size - 1) for (g, ug) in zip(gamma,", "hessian (gamma.size square matrix) \"\"\" if C.shape == (0, 0):", "group labels active_dirs = {} # dictionary: keys are group", ": float Confidence level. \"\"\" if parameter is not None:", "supplied if perturb is not None: self._initial_omega = perturb if", "= query.selective_MLE(dispersion=dispersion)[:2] self.linear_part = query.linear_part self.offset = query.offset self.logdens_linear =", "scaling)).sum() return p1 + p2 + p3 + p4 def", "range(self.ntarget): p = self.target_score_cov.shape[1] observed_target_uni = (self.observed_target[m]).reshape((1,)) target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1,", "the alternatives, should be values of ['twosided', 'less', 'greater'] parameter", "selected if len(self.selection_variable['active_groups']) == 0: return np.sign(soln), soln # otherwise", "pvalues = self._approx_pivots(np.zeros_like(self.observed_target), alternatives=alternatives) lower, upper = self._approx_intervals(level=level) result =", "active_groups = [] # active group labels active_dirs = {}", "# changed to ordered_vars Q = XE.T.dot(self._W[:, None] * XE)", "all 1's for LS opt_linearNoU = np.dot(X.T, X[:, ordered_vars] *", "check dimension if len(agroups.shape) != 1: raise ValueError(\"Groups are not", "= 1.e-20 _, self.randomizer_prec = self.randomizer.cov_prec # now we are", "OLS on E overall, solve_args=solve_args) beta_bar = np.zeros(self.nfeature) beta_bar[overall] =", "finds any problems. Sorting feature groups is potentially tedious for", "OLS beta with zeros self._beta_full = beta_bar X, y =", "are unit-norm coefficients unpenalized = [] # selected groups with", "dispersion return (observed_target, cov_target, crosscov_target_score, alternatives) class approximate_grid_inference(object): def __init__(self,", "are not integers\") # check starts with 0 if not", "crosscov_target_score, alternatives) class approximate_grid_inference(object): def __init__(self, query, dispersion, solve_args={'tol': 1.e-12},", "is NaN: %f, %f' % (proposed_value, current_value)) # stop if", "#J = log(evalues).sum() J = np.log(np.linalg.det(GammaMinus + C)) # inverse", "current - step * cur_grad proposed_value = objective(proposal) if proposed_value", "defaults to True randomizer_scale=None): loglike = rr.glm.gaussian(X, Y, coef=1. /", "# need to provide weights an an np.array rather than", "_check_groups(groups): \"\"\"Make sure that the user-specific groups are ok There", "self.ordered_vars, solve_args=solve_args) _score_linear = -XE.T.dot(self._W[:, None] * X).T alternatives =", "np.sign(self.initial_soln) active = np.flatnonzero(active_signs) self.active = active def compute_Vg(ug): pg", "np.minimum(pvalues, 1 - pvalues) alpha = 1 - level quantile", "X[:, ordered_vars] * W[:, np.newaxis]) for i, var in enumerate(ordered_vars):", "1.e-12}, useIP=True): \"\"\" Produce p-values and confidence intervals for targets", "-self.logdens_linear.dot(target_linear) target_off = (self.cond_mean - target_lin.dot(observed_target_uni)).reshape((target_lin.shape[0],)) _prec = prec_target +", "= [] for m in range(self.ntarget): family = self._families[m] var_target", "not a 1D array_like\") # check sorted if np.any(agroups[:-1] >", "/ evalues).dot(evectors.T)) GpC_inv = np.linalg.inv(GammaMinus + C) # summing matrix", "= - logdens_linear.dot(target_linear) target_off = cond_mean - target_lin.dot(observed_target) if np.asarray(self.randomizer_prec).shape", "-= logW.max() self._families.append(discrete_family(grid, np.exp(logW))) def _approx_pivots(self, mean_parameter, alternatives=None): if not", "checks the user-specified group scheme and raises an exception if", "are specified. Specifically, we assume that `groups` is a 1-d", "square matrix) \"\"\" if C.shape == (0, 0): # when", "cond_mean_grid = (target_lin.dot(np.atleast_1d(grid[k] - observed_target)) + self.cond_mean) #direction for decomposing", "= cond_mean - target_lin.dot(observed_target) if np.asarray(self.randomizer_prec).shape in [(), (0,)]: _P", "+ target_cov.dot( _P - target_lin.T.dot(prec_opt).dot(target_off)) L = target_lin.T.dot(prec_opt) observed_info_natural =", "density on a grid. \"\"\" if np.asarray(observed_target).shape in [(), (0,)]:", "determines how the conditional mean of optimization variables # vary", "p4 = log(1. + 1. / ((con_offset - con_linear.dot(gs)) /", "+ C) # summing matrix (gamma.size by C.shape[0]) S =", "/ np.sqrt(np.diag(observed_info_mean)) pvalues = ndist.cdf(Z_scores) pvalues = 2 * np.minimum(pvalues,", "_P = target_linear.T.dot(self.randomizer_prec).dot(target_offset) _prec = prec_target + (target_linear.T.dot(self.randomizer_prec).dot(target_linear)) - target_lin.T.dot(", "0): result.insert(4, 'pivot', pivots) result.insert(5, 'parameter', parameter) return result def", "log_ref = val + conjugate_arg.T.dot(cond_cov).dot(conjugate_arg) / 2. result = pd.DataFrame({'MLE':", "LS opt_linearNoU = np.dot(X.T, X[:, ordered_vars] * W[:, np.newaxis]) for", "initial (observed) value of optimization variables cond_mean: conditional mean of", "Q = XE.T.dot(self._W[:, None] * XE) QI = inv(Q) C", "be used where applicable - defaults to True perturb=None): _check_groups(groups)", "np.sign(soln), soln # otherwise continue as before self.observed_opt_state = np.hstack(ordered_opt)", "enumerate(ordered_vars): opt_linearNoU[var, i] += self.ridge_term opt_offset = self.initial_subgrad self.observed_score_state =", "groups are size one, C will be an empty array", "= self._families[m] observed_target = self.observed_target[m] l, u = family.equal_tailed_interval(observed_target, alpha=1", "and run usual lasso solver... (see existing code)... initial_soln =", "np.all(parameter == 0): result.insert(4, 'pivot', pivots) result.insert(5, 'parameter', parameter) return", "= cond_cov self.cond_precision = cond_precision self.logdens_linear = logdens_linear return cond_mean,", "in active group ordered_vars.extend(np.flatnonzero(group_mask)) if self.penalty.weights[g] == 0: unpenalized.append(g) else:", "100}): # take a new perturbation if supplied if perturb", "self.randomizer_prec _prec = prec_target + (target_linear.T.dot(target_linear) * self.randomizer_prec) - target_lin.T.dot(", "# mask of active features ordered_groups = [] # active", "= np.zeros(self.observed_opt_state.shape[0]) return active_signs, soln def _solve_randomized_problem(self, perturb=None, solve_args={'tol': 1.e-15,", "Vg = np.zeros((1, 0)) # if the group is size", "self._initial_omega = perturb if self._initial_omega is None: self._initial_omega = self.randomizer.sample()", "active group labels active_dirs = {} # dictionary: keys are", "if useJacobian: p2 = - jacobian_grad_hess(gs, C, active_dirs)[2] else: p2", "makes about how groups are specified. Specifically, we assume that", "self.offset = np.zeros(self.observed_opt_state.shape[0]) return active_signs, soln def _solve_randomized_problem(self, perturb=None, solve_args={'tol':", "None: pivots = self._approx_pivots(parameter, alternatives=alternatives) else: pivots = None pvalues", "= 0 while True: count += 1 proposal = current", "GpC_inv.T).dot(S.T)) return J, grad_J, hess_J def _check_groups(groups): \"\"\"Make sure that", "passed on to solver level: level of confidence intervals useC:", "ngrid = 100 self.stat_grid = np.zeros((ntarget, ngrid)) for j in", ": quadratic loss self.loglike = loglike self.nfeature = self.loglike.shape[0] #", "group lasso (self.initial_soln, self.initial_subgrad) = self._solve_randomized_problem(perturb=perturb, solve_args=solve_args) # initialize variables", "self.C, self.active_dirs, useJacobian, **solve_args) final_estimator = target_cov.dot(_prec).dot(observed_target) \\ + target_cov.dot(target_lin.T.dot(prec_opt.dot(cond_mean", "_solve_randomized_problem(self, perturb=None, solve_args={'tol': 1.e-15, 'min_its': 100}): # take a new", "* cur_grad proposed_value = objective(proposal) if proposed_value <= current_value: break", "X^2 dispersion = ((y - self.loglike.saturated_loss.mean_function( XE.dot(observed_target))) ** 2 /", "_beta_unpenalized # refit OLS beta with zeros self._beta_full = beta_bar", "= block_diag(*Vs) # unpack the list Ls = [compute_Lg(g) for", "* W[:, np.newaxis]) for i, var in enumerate(ordered_vars): opt_linearNoU[var, i]", "pivots = self._approx_pivots(parameter, alternatives=alternatives) else: pivots = None pvalues =", "= self.loglike.saturated_loss.hessian(X.dot(beta_bar)) # all 1's for LS opt_linearNoU = np.dot(X.T,", "def _setup_implied_gaussian(self): _, prec = self.randomizer.cov_prec if np.asarray(prec).shape in [(),", "1)) prec_target = 1. / target_cov_uni target_score_cov_uni = self.target_score_cov[m, :].reshape((1,", "# refit OLS beta with zeros self._beta_full = beta_bar X,", "because that is not adapted for the group_lasso. Also, assumes", "target_lin.dot(observed_target_uni)).reshape((target_lin.shape[0],)) _prec = prec_target + (target_linear.T.dot(target_linear) * self.randomizer_prec) - target_lin.T.dot(", "use the Jacobian information (in self.C) arguments conjugate_arg: \\\\bar{\\\\Sigma}^{-1} \\bar{\\\\mu}", "doesn't self.groups = groups self._initial_omega = perturb # gaussian randomization", "# make sure groups looks sensible # log likelihood :", "function con_offset: offset part of affine constraint used for barrier", "\\ + target_cov.dot(target_lin.T.dot(prec_opt.dot(cond_mean - soln))) + C unbiased_estimator = target_cov.dot(_prec).dot(observed_target)", "solve_args={'tol': 1.e-12}, useIP=True): \"\"\" Produce p-values and confidence intervals for", "[] # gamma's ordered by group labels ordered_vars = []", "in group 3). This function checks the user-specified group scheme", "a new perturbation if supplied if perturb is not None:", "* norm(soln): # is group g appreciably nonzero ordered_groups.append(g) #", "observed_info_natural = _prec + L.dot(target_lin) - L.dot(hess.dot(L.T)) observed_info_mean = target_cov.dot(observed_info_natural.dot(target_cov))", "(target_linear.T.dot(target_linear) * self.randomizer_prec) - target_lin.T.dot( self.prec_opt).dot(target_lin) _P = target_linear.T.dot(target_offset) *", "is not 0\") # check for no skipped groups if", "features ordered_groups = [] # active group labels sorted by", "+ 1. / ((con_offset - con_linear.dot(gs)) ** 2.))).dot(con_linear) if useJacobian:", "active_dirs) # eigendecomposition #evalues, evectors = eig(GammaMinus + C) #", "l, u = family.equal_tailed_interval(observed_target, alpha=1 - level) var_target = 1.", "\"\"\"Make sure that the user-specific groups are ok There are", "[] # indices \"ordered\" by sorting group labels tol =", "= 1. / ((self.precs[m])[0, 0]) log_ref = self.log_reference(observed_target_uni, target_cov_uni, target_score_cov_uni,", "= query.active_dirs (observed_target, target_cov, target_score_cov, alternatives) = query.selected_targets(dispersion) self.observed_target =", "= query.cond_cov self.C = query.C self.active_dirs = query.active_dirs (observed_target, target_cov,", "X).T alternatives = ['twosided'] * len(self.active) if dispersion is None:", "= self.opt_linear.T.dot(self.opt_linear) * prec cond_cov = inv(cond_precision) logdens_linear = cond_cov.dot(self.opt_linear.T)", "raise ValueError('not finding a feasible point') # make sure proposal", "one, the orthogonal complement is empty return Vg def compute_Lg(g):", "return initial_soln, initial_subgrad @staticmethod def gaussian(X, Y, groups, weights, sigma=1.,", "quantile * np.sqrt(np.diag(observed_info_mean))]).T log_ref = val + conjugate_arg.T.dot(cond_cov).dot(conjugate_arg) / 2.", "parameter self.ridge_term = ridge_term # group lasso penalty (from regreg)", "/ _prec).dot(target_lin.T.dot(self.prec_opt).dot(target_off) - _P) _S = np.linalg.inv(_prec).dot(prec_target) S[m] = _S", "2 / var_target) logW -= logW.max() self._families.append(discrete_family(self.stat_grid[m], np.exp(logW))) else: approx_fn", "regreg) # use regular lasso penalty if all groups are", "return p1 + p2 + p3 + p4 def grad(gs):", "= -conjugate_arg + precision.dot(gs) p2 = -con_linear.T.dot(1. / (scaling +", "solve_barrier_affine_py as solver from ..distributions.discrete_family import discrete_family class group_lasso(object): def", "in active_dirs.values()]) # gradient grad_J = S.dot(GpC_inv.diagonal()) # hessian hess_J", "useJacobian: p3 = - jacobian_grad_hess(gs, C, active_dirs)[0] else: p3 =", "them. \"\"\" # check array_like agroups = np.array(groups) # check", "= randomization.isotropic_gaussian((p,), randomizer_scale) return group_lasso(loglike, groups, weights, ridge_term, randomizer, use_lasso,", "a class variable since the non-group lasso doesn't self.groups =", "Gaussian. observed_target : ndarray Observed estimate of target. target_cov :", "np.fabs(current_value - proposed_value) < tol * np.fabs(current_value) and itercount >=", "def _check_groups(groups): \"\"\"Make sure that the user-specific groups are ok", "variance of optimization variables (model on _setup_implied_gaussian) logdens_linear: (model on", "cond_mean = self.cond_mean cond_cov = self.cond_cov logdens_linear = self.logdens_linear linear_part", "0.5 if count >= 20: if not (np.isnan(proposed_value) or np.isnan(current_value)):", "0) problem = rr.simple_problem(self.loglike, self.penalty) # if all groups are", "def selective_MLE(self, solve_args={'tol': 1.e-12}, level=0.9, useJacobian=True, dispersion=None): \"\"\"Do selective_MLE for", "existing code)... initial_soln = problem.solve(quad, **solve_args) initial_subgrad = -(self.loglike.smooth_objective(initial_soln, 'grad')", "pivot.append(_cdf) else: raise ValueError('alternative should be in [\"twosided\", \"less\", \"greater\"]')", "the user-specific groups are ok There are a number of", "return result def log_reference(self, observed_target, target_cov, target_score_cov, grid): \"\"\" Approximate", "= self.target_score_cov.shape[1] observed_target_uni = (self.observed_target[m]).reshape((1,)) target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1, 1)) target_score_cov_uni", "{} S = {} r = {} p = self.target_score_cov.shape[1]", "array _beta_unpenalized = restricted_estimator(self.loglike, # refit OLS on E overall,", "of gamma vector, active directions) \"\"\" to_diag = [[g] *", "result, inverse_info = query.selective_MLE(dispersion=dispersion)[:2] self.linear_part = query.linear_part self.offset = query.offset", "S = block_diag(*[np.ones((1, ug.size - 1)) for ug in active_dirs.values()])", "restricted_estimator(self.loglike, self.ordered_vars, solve_args=solve_args) _score_linear = -XE.T.dot(self._W[:, None] * X).T alternatives", "solve_args : dict, optional Arguments passed to solver. \"\"\" self.solve_args", "grid): \"\"\" Approximate the log of the reference density on", "lagrange=1.) # store groups as a class variable since the", "label ordered_opt = [] # gamma's ordered by group labels", "or np.isnan(current_value)): break else: raise ValueError('value is NaN: %f, %f'", "def _approx_pivots(self, mean_parameter, alternatives=None): if not hasattr(self, \"_families\"): self._construct_families() if", "precs = {} S = {} r = {} p", "'upper_confidence': upper}) if not np.all(parameter == 0): result.insert(4, 'pivot', pivots)", "of the optimization density # depends on the score, not", "else: p3 = 0 p4 = log(1. + 1. /", "active_dirs): \"\"\"Calculate Gamma^minus (as a function of gamma vector, active", "do this for them. \"\"\" # check array_like agroups =", "_A.dot(soln) + R.dot(self.init_soln) log_jacob = jacobian_grad_hess(gamma_, self.C, self.active_dirs) ref_hat.append(-val -", "the first column else: Vg = np.zeros((1, 0)) # if", "else: p3 = 0 p4 = 1. / (con_offset -", "indices \"ordered\" by sorting group labels tol = 1.e-20 _,", "b, **self.solve_args) gamma_ = _A.dot(soln) + R.dot(self.init_soln) log_jacob = jacobian_grad_hess(gamma_,", "logdens_linear = self.logdens_linear linear_part = self.linear_part offset = self.offset if", "V = block_diag(*Vs) # unpack the list Ls = [compute_Lg(g)", "applicable - defaults to True perturb=None): _check_groups(groups) # make sure", "are group labels, values are unit-norm coefficients unpenalized = []", "= -gs.T.dot(conjugate_arg) p2 = gs.T.dot(precision).dot(gs) / 2. if useJacobian: p3", "3). This function checks the user-specified group scheme and raises", "= self.randomizer.sample() quad = rr.identity_quadratic(self.ridge_term, 0, -self._initial_omega, 0) problem =", "bounds_error=False, fill_value='extrapolate') grid = np.linspace(self.stat_grid[m].min(), self.stat_grid[m].max(), 1000) logW = (approx_fn(grid)", "Vg = Q[:, 1:] # drop the first column else:", "= -self.prec_opt.dot(self.logdens_linear.dot(target_score_cov.T)) implied_mean = np.asscalar(eta.T.dot(cond_mean_grid)) implied_cov = np.asscalar(eta.T.dot(self.cond_cov).dot(eta)) implied_prec =", "C, active_dirs): \"\"\" Calculate the log-Jacobian (scalar), gradient (gamma.size vector)", "\"less\", \"greater\"]') return pivot def _approx_intervals(self, level=0.9): if not hasattr(self,", "kind of redundant with keys of active_dirs self._ordered_groups = ordered_groups", "* np.eye(pg) return Lg sorted_active_dirs = collections.OrderedDict(sorted(active_dirs.items())) Vs = [compute_Vg(ug)", "= jacobian_grad_hess(gamma_, self.C, self.active_dirs) ref_hat.append(-val - ((conjugate_arg ** 2) *", "gaussian randomization self.randomizer = randomizer def fit(self, solve_args={'tol': 1.e-12, 'min_its':", "coef=1. / sigma ** 2, quadratic=quadratic) n, p = X.shape", "None: # use Pearson's X^2 dispersion = ((y - self.loglike.saturated_loss.mean_function(", "be updated to actually use the Jacobian information (in self.C)", "= self.prec_opt.shape[0] num_con = self.linear_part.shape[0] cond_mean_grid = (target_lin.dot(np.atleast_1d(grid[k] - observed_target))", "_scale[j], observed_target[j] + 1.5 * _scale[j], num=ngrid) self.opt_linear = query.opt_linear", "overall[group_mask] = False self.selection_variable = {'directions': active_dirs, 'active_groups': active_groups} #", "prec_opt.dot(cond_mean) val, soln, hess = solve_barrier_affine_jacobian_py(conjugate_arg, prec_opt, init_soln, linear_part, offset,", "self.ridge_term opt_offset = self.initial_subgrad self.observed_score_state = -opt_linearNoU.dot(_beta_unpenalized) self.observed_score_state[~overall] += self.loglike.smooth_objective(beta_bar,", ": `gaussian_query` A Gaussian query which has information to describe", "import interp1d import collections import numpy as np from numpy", "0, -self._initial_omega, 0) problem = rr.simple_problem(self.loglike, self.penalty) # if all", "setting this if norm(soln[group_mask]) > tol * norm(soln): # is", "in sorted(np.unique(self.groups)): # g is group label group_mask = self.groups", "self._families.append(discrete_family(grid, np.exp(logW))) def _approx_pivots(self, mean_parameter, alternatives=None): if not hasattr(self, \"_families\"):", "False self.selection_variable = {'directions': active_dirs, 'active_groups': active_groups} # kind of", "-- defaults to 0. level : float Confidence level. \"\"\"", "- self.loglike.saturated_loss.mean_function( XE.dot(observed_target))) ** 2 / self._W).sum() / (n -", "Sequence of strings describing the alternatives, should be values of", "- target_lin.dot(observed_target) if np.asarray(self.randomizer_prec).shape in [(), (0,)]: _P = target_linear.T.dot(target_offset)", "self._W).sum() / (n - XE.shape[1]) cov_target = self.QI * dispersion", "self.target_score_cov.shape[1] observed_target_uni = (self.observed_target[m]).reshape((1,)) target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1, 1)) target_score_cov_uni =", "active_dirs: \"\"\" scaling = np.sqrt(np.diag(con_linear.dot(precision).dot(con_linear.T))) if feasible_point is None: feasible_point", "keys of active_dirs self._ordered_groups = ordered_groups # exception if no", "_setup_implied_gaussian) logdens_linear: (model on _setup_implied_gaussian) linear_part: like A_scaling (from lasso)", "target. target_cov : ndarray Estimated covaraince of target. target_score_cov :", "1.5 * _scale[j], num=ngrid) else: ngrid = 100 self.stat_grid =", "Hypothesized value for parameter -- defaults to 0. level :", "= (np.diag(self.target_cov)[m]).reshape((1, 1)) target_score_cov_uni = self.target_score_cov[m, :].reshape((1, p)) var_target =", "A_scaling (from lasso) offset: like b_scaling (from lasso) solve_args: passed", "agroups = np.array(groups) # check dimension if len(agroups.shape) != 1:", "== 0): result.insert(4, 'pivot', pivots) result.insert(5, 'parameter', parameter) return result", "= r def solve_barrier_affine_jacobian_py(conjugate_arg, precision, feasible_point, con_linear, con_offset, C, active_dirs,", "= np.linalg.inv(query.cond_cov) self.cond_cov = query.cond_cov self.C = query.C self.active_dirs =", "ValueError('alternative should be in [\"twosided\", \"less\", \"greater\"]') return pivot def", "observed_target_uni = (self.observed_target[m]).reshape((1,)) target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1, 1)) target_score_cov_uni = self.target_score_cov[m,", "target_cov, target_score_cov, alternatives) = self.selected_targets(dispersion) init_soln = self.observed_opt_state # just", "cond_cov, cond_precision, logdens_linear def selective_MLE(self, solve_args={'tol': 1.e-12}, level=0.9, useJacobian=True, dispersion=None):", "pg = active_dirs[g].size Lg = self.penalty.weights[g] * np.eye(pg) return Lg", "else: pivots = None pvalues = self._approx_pivots(np.zeros_like(self.observed_target), alternatives=alternatives) lower, upper", "_P = target_linear.T.dot(target_offset) * self.randomizer_prec _prec = prec_target + (target_linear.T.dot(target_linear)", "self.stat_grid[m].max(), 1000) logW = (approx_fn(grid) - 0.5 * (grid -", "= [[g] * (ug.size - 1) for (g, ug) in", "self.target_score_cov = target_score_cov self.target_cov = target_cov self.init_soln = query.observed_opt_state self.randomizer_prec", "self.stat_grid[j, :] = np.linspace(observed_target[j] - 1.5 * _scale[j], observed_target[j] +", "for g in sorted(np.unique(self.groups)): # g is group label group_mask", "= self.offset-self.linear_part.dot(R).dot(self.init_soln) conjugate_arg = implied_mean * implied_prec val, soln, _", "target_cov_uni, target_score_cov_uni, self.stat_grid[m]) if self.useIP == False: logW = (log_ref", "def fit(self, solve_args={'tol': 1.e-12, 'min_its': 50}, perturb=None): # solve the", "perturb if self._initial_omega is None: self._initial_omega = self.randomizer.sample() quad =", "def solve_barrier_affine_jacobian_py(conjugate_arg, precision, feasible_point, con_linear, con_offset, C, active_dirs, useJacobian=True, step=1,", "rr from .randomization import randomization from ..base import restricted_estimator from", "+ p2 + p3 + p4 def grad(gs): p1 =", "- jacobian_grad_hess(gs, C, active_dirs)[0] else: p3 = 0 p4 =", "loss self.loglike = loglike self.nfeature = self.loglike.shape[0] # ridge parameter", "current, hess # Jacobian calculations def calc_GammaMinus(gamma, active_dirs): \"\"\"Calculate Gamma^minus", "- target_lin.dot(observed_target_uni)).reshape((target_lin.shape[0],)) _prec = prec_target + (target_linear.T.dot(target_linear) * self.randomizer_prec) -", "make sure proposal is a descent count = 0 while", "2 * np.minimum(pvalues, 1 - pvalues) alpha = 1 -", "['twosided'] * len(self.active) if dispersion is None: # use Pearson's", "Arguments passed to solver. \"\"\" self.solve_args = solve_args result, inverse_info", "raise ValueError('no target specified') prec_target = np.linalg.inv(target_cov) target_lin = -", "= inv(target_cov) prec_opt = self.cond_precision score_offset = self.observed_score_state + self.opt_offset", "* self.randomizer_prec _prec = prec_target + (target_linear.T.dot(target_linear) * self.randomizer_prec) -", "group if pg > 1: Z = np.column_stack((ug, np.eye(pg, pg", "i in gp]) def jacobian_grad_hess(gamma, C, active_dirs): \"\"\" Calculate the", "sensible # log likelihood : quadratic loss self.loglike = loglike", "for group_lasso Note: this masks the selective_MLE inherited from query", "= 1 - level quantile = ndist.ppf(1 - alpha /", "prec_opt).dot( target_lin) else: _P = target_linear.T.dot(self.randomizer_prec).dot(target_offset) _prec = prec_target +", "from families follows `selectinf.learning.core` family = self._families[m] observed_target = self.observed_target[m]", "lower.append(l * var_target + observed_target) upper.append(u * var_target + observed_target)", "1))) Q, _ = qr(Z) Vg = Q[:, 1:] #", "group g appreciably nonzero ordered_groups.append(g) # variables in active group", "self.prec_opt).dot(target_lin) _P = target_linear.T.dot(target_offset) * self.randomizer_prec _r = (1. /", "logdens_linear def selective_MLE(self, solve_args={'tol': 1.e-12}, level=0.9, useJacobian=True, dispersion=None): \"\"\"Do selective_MLE", "offset = self.offset if np.asarray(observed_target).shape in [(), (0,)]: raise ValueError('no", "target_cov_uni target_score_cov_uni = self.target_score_cov[m, :].reshape((1, p)) target_linear = target_score_cov_uni.T.dot(prec_target) target_offset", "current_value: break step *= 0.5 if count >= 20: if", "# Jacobian calculations def calc_GammaMinus(gamma, active_dirs): \"\"\"Calculate Gamma^minus (as a", "active_dirs.values()]) # gradient grad_J = S.dot(GpC_inv.diagonal()) # hessian hess_J =", "self.penalty) # if all groups are size 1, set up", "- alpha / 2.) intervals = np.vstack([final_estimator - quantile *", "how the conditional mean of optimization variables # vary with", "-conjugate_arg + precision.dot(gs) p2 = -con_linear.T.dot(1. / (scaling + con_offset", "for i, var in enumerate(ordered_vars): opt_linearNoU[var, i] += self.ridge_term opt_offset", "a number of assumptions that group_lasso makes about how groups", "= con_linear.T.dot(np.diag(-1. / ((scaling + con_offset - con_linear.dot(gs)) ** 2.)", "* _scale[j], observed_target[j] + 1.5 * _scale[j], num=ngrid) else: ngrid", "1, set up lasso penalty and run usual lasso solver...", "affine constraint used for barrier function con_offset: offset part of", "in range(nstep): cur_grad = grad(current) # make sure proposal is", "(self.stat_grid[m] - self.observed_target[m]) ** 2 / var_target) logW -= logW.max()", "len(agroups.shape) != 1: raise ValueError(\"Groups are not a 1D array_like\")", "matrix) \"\"\" if C.shape == (0, 0): # when all", "observed_target) return np.asarray(lower), np.asarray(upper) ### Private method def _construct_density(self): precs", "groups for g in sorted(np.unique(self.groups)): # g is group label", "self.cond_cov.dot(eta) * implied_prec R = np.identity(num_opt) - _A.dot(eta.T) A =", "have no gaps (e.g., if there is a group 2", "import block_diag from scipy.stats import norm as ndist from scipy.interpolate", "len(self.selection_variable['active_groups']) == 0: return np.sign(soln), soln # otherwise continue as", "ndist.cdf(Z_scores) pvalues = 2 * np.minimum(pvalues, 1 - pvalues) alpha", "\"something\" times D # Gamma is target_score_cov.T.dot(prec_target) num_opt = self.prec_opt.shape[0]", "proposal is a descent count = 0 while True: count", "1.e-15, 'min_its': 100}): # take a new perturbation if supplied", "/ var_target, x=self.observed_target[m]) print(\"variable completed \", m) if alternatives[m] ==", "as a class variable since the non-group lasso doesn't self.groups", "self.observed_opt_state # just the gammas cond_mean = self.cond_mean cond_cov =", "active_dirs, useJacobian=True, step=1, nstep=2000, min_its=500, tol=1.e-12): \"\"\" This needs to", "query because that is not adapted for the group_lasso. Also,", "randomization from ..base import restricted_estimator from ..algorithms.barrier_affine import solve_barrier_affine_py as", "soln, _ = solver(np.asarray([conjugate_arg]), np.reshape(implied_prec, (1,1)), eta.T.dot(self.init_soln), A.reshape((A.shape[0],1)), b, **self.solve_args)", "= np.log(np.linalg.det(GammaMinus + C)) # inverse #GpC_inv = evectors.dot(np.diag(1 /", "ValueError(\"Groups are not a 1D array_like\") # check sorted if", "loglike self.nfeature = self.loglike.shape[0] # ridge parameter self.ridge_term = ridge_term", "num=ngrid) else: ngrid = 100 self.stat_grid = np.zeros((ntarget, ngrid)) for", "= [] for m in range(self.ntarget): p = self.target_score_cov.shape[1] observed_target_uni", "U = block_diag(*[ug for ug in sorted_active_dirs.values()]).T self.opt_linear = opt_linearNoU.dot(U)", "i] += self.ridge_term opt_offset = self.initial_subgrad self.observed_score_state = -opt_linearNoU.dot(_beta_unpenalized) self.observed_score_state[~overall]", "= target_score_cov.T.dot(prec_target) target_offset = score_offset - target_linear.dot(observed_target) target_lin = -", "= self.randomizer.cov_prec if np.asarray(prec).shape in [(), (0,)]: cond_precision = self.opt_linear.T.dot(self.opt_linear)", "is None: self._initial_omega = self.randomizer.sample() quad = rr.identity_quadratic(self.ridge_term, 0, -self._initial_omega,", "target_cov.dot(_prec).dot(observed_target) + target_cov.dot( _P - target_lin.T.dot(prec_opt).dot(target_off)) L = target_lin.T.dot(prec_opt) observed_info_natural", "range(nstep): cur_grad = grad(current) # make sure proposal is feasible", "0: unpenalized.append(g) else: active_groups.append(g) active_dirs[g] = soln[group_mask] / norm(soln[group_mask]) ordered_opt.append(norm(soln[group_mask]))", "selected features Parameters ---------- alternatives : [str], optional Sequence of", "to keep setting this if norm(soln[group_mask]) > tol * norm(soln):", "= inv(cond_precision) logdens_linear = cond_cov.dot(self.opt_linear.T).dot(prec) cond_mean = -logdens_linear.dot(self.observed_score_state + self.opt_offset)", "in range(ntarget): self.stat_grid[j, :] = np.linspace(observed_target[j] - 1.5 * _scale[j],", "where applicable - defaults to True perturb=None): _check_groups(groups) # make", "use_lasso=True, # should lasso solver be used where applicable -", "refit OLS on E overall, solve_args=solve_args) beta_bar = np.zeros(self.nfeature) beta_bar[overall]", "target_score_cov_uni.T.dot(prec_target) target_offset = (self.score_offset - target_linear.dot(observed_target_uni)).reshape( (target_linear.shape[0],)) target_lin = -self.logdens_linear.dot(target_linear)", "group 2 and a group 4, there must also be", "{} r = {} p = self.target_score_cov.shape[1] for m in", "= self.cond_cov logdens_linear = self.logdens_linear linear_part = self.linear_part offset =", "self._approx_pivots(parameter, alternatives=alternatives) else: pivots = None pvalues = self._approx_pivots(np.zeros_like(self.observed_target), alternatives=alternatives)", "actually use the Jacobian information (in self.C) arguments conjugate_arg: \\\\bar{\\\\Sigma}^{-1}", "log from numpy.linalg import norm, qr, inv, eig import pandas", "size 1, set up lasso penalty and run usual lasso", "gradient grad_J = S.dot(GpC_inv.diagonal()) # hessian hess_J = -S.dot(np.multiply(GpC_inv, GpC_inv.T).dot(S.T))", "= np.zeros(self.nfeature) beta_bar[overall] = _beta_unpenalized # refit OLS beta with", "hasattr(self, \"_families\"): self._construct_families() if alternatives is None: alternatives = ['twosided']", "pivot.append(1 - _cdf) elif alternatives[m] == 'less': pivot.append(_cdf) else: raise", "with keys of active_dirs self._ordered_groups = ordered_groups # exception if", "active group ordered_vars.extend(np.flatnonzero(group_mask)) if self.penalty.weights[g] == 0: unpenalized.append(g) else: active_groups.append(g)", "is size one, the orthogonal complement is empty return Vg", "in [(), (0,)]: _P = target_linear.T.dot(target_offset) * self.randomizer_prec _prec =", "= - jacobian_grad_hess(gs, C, active_dirs)[0] else: p3 = 0 p4", "- _cdf) elif alternatives[m] == 'less': pivot.append(_cdf) else: raise ValueError('alternative", "= self.XE Q = self.Q observed_target = restricted_estimator(self.loglike, self.ordered_vars, solve_args=solve_args)", "= self.initial_soln # do not need to keep setting this", "observed_info_mean = target_cov.dot(observed_info_natural.dot(target_cov)) Z_scores = final_estimator / np.sqrt(np.diag(observed_info_mean)) pvalues =", "offset part of affine constraint used for barrier function C:", "prec_target = inv(target_cov) prec_opt = self.cond_precision score_offset = self.observed_score_state +", "- proposed_value) < tol * np.fabs(current_value) and itercount >= min_its:", "current_value = proposed_value if itercount % 4 == 0: step", "self._solve_randomized_problem(perturb=perturb, solve_args=solve_args) # initialize variables active_groups = [] # active", "current = feasible_point current_value = np.inf for itercount in range(nstep):", "selected features Parameters ---------- query : `gaussian_query` A Gaussian query", "also be at least one feature in group 3). This", "sorted in increasing order, start at 0, and have no", "code)... initial_soln = problem.solve(quad, **solve_args) initial_subgrad = -(self.loglike.smooth_objective(initial_soln, 'grad') +", "_prec = prec_target + (target_linear.T.dot(target_linear) * self.randomizer_prec) - target_lin.T.dot( prec_opt).dot(", "== 0: unpenalized.append(g) else: active_groups.append(g) active_dirs[g] = soln[group_mask] / norm(soln[group_mask])", "XE.dot(observed_target))) ** 2 / self._W).sum() / (n - XE.shape[1]) cov_target", "if ridge_term is None: ridge_term = np.std(Y) * np.sqrt(mean_diag) /", "np.std(Y) * np.sqrt(mean_diag) / np.sqrt(n - 1) if randomizer_scale is", "num_opt = self.prec_opt.shape[0] num_con = self.linear_part.shape[0] cond_mean_grid = (target_lin.dot(np.atleast_1d(grid[k] -", "w in sorted(weights.items())]) self.penalty = rr.weighted_l1norm(weights=weights_np, lagrange=1.) else: self.penalty =", "self.groups = groups self._initial_omega = perturb # gaussian randomization self.randomizer", "self._construct_density() self._families = [] for m in range(self.ntarget): p =", "= prec_target + (target_linear.T.dot(self.randomizer_prec).dot(target_linear)) - target_lin.T.dot( prec_opt).dot(target_lin) C = target_cov.dot(_P", "in sorted_active_dirs.values()]).T self.opt_linear = opt_linearNoU.dot(U) self.active_dirs = active_dirs self.opt_offset =", "compute_Lg(g): pg = active_dirs[g].size Lg = self.penalty.weights[g] * np.eye(pg) return", "active groups for g in sorted(np.unique(self.groups)): # g is group", "a dictionary weights_np = np.array([w[1] for w in sorted(weights.items())]) self.penalty", "p2 current = feasible_point current_value = np.inf for itercount in", "float Confidence level. \"\"\" if parameter is not None: pivots", "- level quantile = ndist.ppf(1 - alpha / 2.) intervals", "linear_part, offset, self.C, self.active_dirs, useJacobian, **solve_args) final_estimator = target_cov.dot(_prec).dot(observed_target) \\", "import discrete_family class group_lasso(object): def __init__(self, loglike, groups, weights, ridge_term,", "weights_np = np.array([w[1] for w in sorted(weights.items())]) self.penalty = rr.weighted_l1norm(weights=weights_np,", "affine constraint used for barrier function C: V^T Q^{-1} \\\\Lambda", "/ scaling)).sum() return p1 + p2 + p3 + p4", "import pandas as pd import regreg.api as rr from .randomization", "Lg sorted_active_dirs = collections.OrderedDict(sorted(active_dirs.items())) Vs = [compute_Vg(ug) for ug in", "opt_offset = self.initial_subgrad self.observed_score_state = -opt_linearNoU.dot(_beta_unpenalized) self.observed_score_state[~overall] += self.loglike.smooth_objective(beta_bar, 'grad')[~overall]", "con_linear.dot(gs))) if useJacobian: p3 = - jacobian_grad_hess(gs, C, active_dirs)[1] else:", "_P - target_lin.T.dot(prec_opt).dot(target_off)) L = target_lin.T.dot(prec_opt) observed_info_natural = _prec +", "if there is a group 2 and a group 4,", "optimization variables cond_mean: conditional mean of optimization variables (model on", "# kind of redundant with keys of active_dirs self._ordered_groups =", "# check dimension if len(agroups.shape) != 1: raise ValueError(\"Groups are", "should be in [\"twosided\", \"less\", \"greater\"]') return pivot def _approx_intervals(self,", "alternatives) = query.selected_targets(dispersion) self.observed_target = observed_target self.target_score_cov = target_score_cov self.target_cov", "prec_target + (target_linear.T.dot(target_linear) * self.randomizer_prec) - target_lin.T.dot( prec_opt).dot( target_lin) else:", "linear part of affine constraint used for barrier function con_offset:", "self.score_offset = query.observed_score_state + query.opt_offset self.ntarget = ntarget = target_cov.shape[0]", "= None pvalues = self._approx_pivots(np.zeros_like(self.observed_target), alternatives=alternatives) lower, upper = self._approx_intervals(level=level)", "# target_lin determines how the conditional mean of optimization variables", "are collecting the directions and norms of the active groups", "norm(soln[group_mask]) ordered_opt.append(norm(soln[group_mask])) else: overall[group_mask] = False self.selection_variable = {'directions': active_dirs,", "that `groups` is a 1-d array_like of integers that are", "= _S r[m] = _r precs[m] = _prec self.precs =", "the mean depends on score, hence the minus sign target_linear", "prec = self.randomizer.cov_prec if np.asarray(prec).shape in [(), (0,)]: cond_precision =", "init_soln = self.observed_opt_state # just the gammas cond_mean = self.cond_mean", "Q^{-1} \\\\Lambda V active_dirs: \"\"\" scaling = np.sqrt(np.diag(con_linear.dot(precision).dot(con_linear.T))) if feasible_point", "0 p4 = 1. / (con_offset - con_linear.dot(gs)) return p1", "initialize variables active_groups = [] # active group labels active_dirs", "vector, active directions) \"\"\" to_diag = [[g] * (ug.size -", "self.offset-self.linear_part.dot(R).dot(self.init_soln) conjugate_arg = implied_mean * implied_prec val, soln, _ =", "* (ug.size - 1) for (g, ug) in zip(gamma, active_dirs.values())]", "self.opt_linear.T.dot(self.opt_linear) * prec cond_cov = inv(cond_precision) logdens_linear = cond_cov.dot(self.opt_linear.T) *", "hess_J def _check_groups(groups): \"\"\"Make sure that the user-specific groups are", "(observed_target, target_cov, target_score_cov, alternatives) = query.selected_targets(dispersion) self.observed_target = observed_target self.target_score_cov", "g in sorted(np.unique(self.groups)): # g is group label group_mask =", "= val + conjugate_arg.T.dot(cond_cov).dot(conjugate_arg) / 2. result = pd.DataFrame({'MLE': final_estimator,", "objective(proposal) if proposed_value <= current_value: break step *= 0.5 if", "self.randomizer_prec = query.randomizer_prec self.score_offset = query.observed_score_state + query.opt_offset self.ntarget =", "(approx_fn(grid) - 0.5 * (grid - self.observed_target[m]) ** 2 /", "self.cond_mean = query.cond_mean self.prec_opt = np.linalg.inv(query.cond_cov) self.cond_cov = query.cond_cov self.C", "x=self.observed_target[m]) print(\"variable completed \", m) if alternatives[m] == 'twosided': pivot.append(2", "np.linalg.inv(GammaMinus + C) # summing matrix (gamma.size by C.shape[0]) S", "QI self.C = C U = block_diag(*[ug for ug in", "array_like\") # check sorted if np.any(agroups[:-1] > agroups[1:]) < 0:", "ordered_groups.append(g) # variables in active group ordered_vars.extend(np.flatnonzero(group_mask)) if self.penalty.weights[g] ==", "np.sqrt(np.diag(observed_info_mean)) pvalues = ndist.cdf(Z_scores) pvalues = 2 * np.minimum(pvalues, 1", "np.asarray(ref_hat) def _construct_families(self): self._construct_density() self._families = [] for m in", "None: self._initial_omega = perturb if self._initial_omega is None: self._initial_omega =", "mean depends on score, hence the minus sign target_linear =", "for w in sorted(weights.items())]) self.penalty = rr.weighted_l1norm(weights=weights_np, lagrange=1.) else: self.penalty", "at 0, and have no gaps (e.g., if there is", "if not (np.isnan(proposed_value) or np.isnan(current_value)): break else: raise ValueError('value is", "val, soln, _ = solver(np.asarray([conjugate_arg]), np.reshape(implied_prec, (1,1)), eta.T.dot(self.init_soln), A.reshape((A.shape[0],1)), b,", "# where \"something\" comes from implied Gaussian # cond_mean is", "# if the group is size one, the orthogonal complement", "1 - _cdf)) elif alternatives[m] == 'greater': pivot.append(1 - _cdf)", "\"\"\" if C.shape == (0, 0): # when all groups", "= prec_opt.dot(cond_mean) val, soln, hess = solve_barrier_affine_jacobian_py(conjugate_arg, prec_opt, init_soln, linear_part,", "+ L.dot(target_lin) - L.dot(hess.dot(L.T)) observed_info_mean = target_cov.dot(observed_info_natural.dot(target_cov)) Z_scores = final_estimator", "self.randomizer.cov_prec # now we are collecting the directions and norms", "- 0.5 * (grid - self.observed_target[m]) ** 2 / var_target)", "for ug in sorted_active_dirs.values()]).T self.opt_linear = opt_linearNoU.dot(U) self.active_dirs = active_dirs", "= np.mean((X ** 2).sum(0)) if ridge_term is None: ridge_term =", "randomizer_scale = np.sqrt(mean_diag) * 0.5 * np.std(Y) * np.sqrt(n /", "nonzero ordered_groups.append(g) # variables in active group ordered_vars.extend(np.flatnonzero(group_mask)) if self.penalty.weights[g]", "np.asarray(prec).shape in [(), (0,)]: cond_precision = self.opt_linear.T.dot(self.opt_linear) * prec cond_cov", "penalty overall = np.ones(self.nfeature, np.bool) # mask of active features", "Estimated covariance of target and score of randomized query. solve_args", "self._families = [] for m in range(self.ntarget): p = self.target_score_cov.shape[1]", "how groups are specified. Specifically, we assume that `groups` is", "0, 0 else: GammaMinus = calc_GammaMinus(gamma, active_dirs) # eigendecomposition #evalues,", "= cond_precision self.logdens_linear = logdens_linear return cond_mean, cond_cov, cond_precision, logdens_linear", "GpC_inv = np.linalg.inv(GammaMinus + C) # summing matrix (gamma.size by", "%f' % (proposed_value, current_value)) # stop if relative decrease is", "else: p2 = 0 return p1 + p2 current =", "exception if no groups are selected if len(self.selection_variable['active_groups']) == 0:", "Y, groups, weights, sigma=1., quadratic=None, ridge_term=0., perturb=None, use_lasso=True, # should", "* implied_cov)/ 2. + log_jacob[0]) return np.asarray(ref_hat) def _construct_families(self): self._construct_density()", "== 'greater': pivot.append(1 - _cdf) elif alternatives[m] == 'less': pivot.append(_cdf)", "unpack the list XE = X[:, ordered_vars] # changed to", "is a descent count = 0 while True: count +=", "of target. target_score_cov : ndarray Estimated covariance of target and", "groups if not np.all(np.diff(np.unique(agroups)) == 1): raise ValueError(\"Some group is", "W[:, np.newaxis]) for i, var in enumerate(ordered_vars): opt_linearNoU[var, i] +=", "assumes you have already run the fit method since this", "parameter is not None: pivots = self._approx_pivots(parameter, alternatives=alternatives) else: pivots", "target specified') observed_target = np.atleast_1d(observed_target) prec_target = inv(target_cov) prec_opt =", "def compute_Vg(ug): pg = ug.size # figure out size of", "-opt_linearNoU.dot(_beta_unpenalized) self.observed_score_state[~overall] += self.loglike.smooth_objective(beta_bar, 'grad')[~overall] active_signs = np.sign(self.initial_soln) active =", "/ ((self.precs[m])[0, 0]) lower.append(l * var_target + observed_target) upper.append(u *", "upper}) if not np.all(parameter == 0): result.insert(4, 'pivot', pivots) result.insert(5,", "= np.array(groups) # check dimension if len(agroups.shape) != 1: raise", "opt_offset self.ordered_vars = ordered_vars self.linear_part = -np.eye(self.observed_opt_state.shape[0]) self.offset = np.zeros(self.observed_opt_state.shape[0])", "- self.observed_target[m]) ** 2 / var_target) logW -= logW.max() self._families.append(discrete_family(self.stat_grid[m],", "= groups self._initial_omega = perturb # gaussian randomization self.randomizer =", "= ordered_vars self.linear_part = -np.eye(self.observed_opt_state.shape[0]) self.offset = np.zeros(self.observed_opt_state.shape[0]) return active_signs,", "gp]) def jacobian_grad_hess(gamma, C, active_dirs): \"\"\" Calculate the log-Jacobian (scalar),", "from ..distributions.discrete_family import discrete_family class group_lasso(object): def __init__(self, loglike, groups,", "conjugate_arg = implied_mean * implied_prec val, soln, _ = solver(np.asarray([conjugate_arg]),", "= np.std(Y) * np.sqrt(mean_diag) / np.sqrt(n - 1) if randomizer_scale", "sign target_linear = target_score_cov.T.dot(prec_target) target_offset = score_offset - target_linear.dot(observed_target) target_lin", "\"_families\"): self._construct_families() lower, upper = [], [] for m in", "perturb=None, use_lasso=True, # should lasso solver be used when applicable", "stop if relative decrease is small if np.fabs(current_value - proposed_value)", "solver be used where applicable - defaults to True perturb=None):", "*= 0.5 if count >= 40: raise ValueError('not finding a", "r[m] = _r precs[m] = _prec self.precs = precs self.S", "beta_bar X, y = self.loglike.data W = self._W = self.loglike.saturated_loss.hessian(X.dot(beta_bar))", "= np.zeros((1, 0)) # if the group is size one,", "X.shape XE = self.XE Q = self.Q observed_target = restricted_estimator(self.loglike,", "(observed_target, cov_target, crosscov_target_score, alternatives) class approximate_grid_inference(object): def __init__(self, query, dispersion,", "= np.sqrt(np.diag(con_linear.dot(precision).dot(con_linear.T))) if feasible_point is None: feasible_point = 1. /", "self.C = C U = block_diag(*[ug for ug in sorted_active_dirs.values()]).T", "_score_linear = -XE.T.dot(self._W[:, None] * X).T alternatives = ['twosided'] *", "((conjugate_arg ** 2) * implied_cov)/ 2. + log_jacob[0]) return np.asarray(ref_hat)", "optimization variables (model on _setup_implied_gaussian) cond_cov: conditional variance of optimization", "(gamma.size by C.shape[0]) S = block_diag(*[np.ones((1, ug.size - 1)) for", "* self.randomizer_prec _r = (1. / _prec).dot(target_lin.T.dot(self.prec_opt).dot(target_off) - _P) _S", "active_dirs): \"\"\" Calculate the log-Jacobian (scalar), gradient (gamma.size vector) and", "== 0: step *= 2 hess = inv(precision + barrier_hessian(current))", "log_jacob = jacobian_grad_hess(gamma_, self.C, self.active_dirs) ref_hat.append(-val - ((conjugate_arg ** 2)", "((con_offset - con_linear.dot(gs)) ** 2.))).dot(con_linear) if useJacobian: p2 = -", "inv, eig import pandas as pd import regreg.api as rr", "log(evalues).sum() J = np.log(np.linalg.det(GammaMinus + C)) # inverse #GpC_inv =", "soln def _solve_randomized_problem(self, perturb=None, solve_args={'tol': 1.e-15, 'min_its': 100}): # take", "features Parameters ---------- query : `gaussian_query` A Gaussian query which", "__init__(self, query, dispersion, solve_args={'tol': 1.e-12}, useIP=True): \"\"\" Produce p-values and", "in fitting) \"\"\" self._setup_implied_gaussian() # Calculate useful quantities (observed_target, target_cov,", "None: feasible_point = 1. / scaling def objective(gs): p1 =", "self.opt_linear = query.opt_linear self.useIP = useIP def summary(self, alternatives=None, parameter=None,", "target_score_cov_uni = self.target_score_cov[m, :].reshape((1, p)) target_linear = target_score_cov_uni.T.dot(prec_target) target_offset =", "\"\"\" This needs to be updated to actually use the", "might do this for them. \"\"\" # check array_like agroups", "= [] for k in range(grid.shape[0]): # in the usual", "np.dot(X.T, X[:, ordered_vars] * W[:, np.newaxis]) for i, var in", "pd.DataFrame({'target': self.observed_target, 'pvalue': pvalues, 'lower_confidence': lower, 'upper_confidence': upper}) if not", "n, p = X.shape XE = self.XE Q = self.Q", "= observed_target self.target_score_cov = target_score_cov self.target_cov = target_cov self.init_soln =", "1.e-12, 'min_its': 50}): X, y = self.loglike.data n, p =", "# if all groups are size 1, set up lasso", "query.cond_mean self.prec_opt = np.linalg.inv(query.cond_cov) self.cond_cov = query.cond_cov self.C = query.C", "alternatives, should be values of ['twosided', 'less', 'greater'] parameter :", "are ok There are a number of assumptions that group_lasso", "np.sqrt(mean_diag) / np.sqrt(n - 1) if randomizer_scale is None: randomizer_scale", "inv(cond_precision) logdens_linear = cond_cov.dot(self.opt_linear.T) * prec else: cond_precision = self.opt_linear.T.dot(prec.dot(self.opt_linear))", "# gradient grad_J = S.dot(GpC_inv.diagonal()) # hessian hess_J = -S.dot(np.multiply(GpC_inv,", "= inv(Q) C = V.T.dot(QI).dot(L).dot(V) self.XE = XE self.Q =", "the log of the reference density on a grid. \"\"\"", "== 'twosided': pivot.append(2 * min(_cdf, 1 - _cdf)) elif alternatives[m]", "= block_diag(*[ug for ug in sorted_active_dirs.values()]).T self.opt_linear = opt_linearNoU.dot(U) self.active_dirs", "2) * implied_cov)/ 2. + log_jacob[0]) return np.asarray(ref_hat) def _construct_families(self):", "> 0): break step *= 0.5 if count >= 40:", "cov_target = self.QI * dispersion crosscov_target_score = _score_linear.dot(self.QI).T * dispersion", "_setup_implied_gaussian) linear_part: like A_scaling (from lasso) offset: like b_scaling (from", "target_cov.dot(observed_info_natural.dot(target_cov)) Z_scores = final_estimator / np.sqrt(np.diag(observed_info_mean)) pvalues = ndist.cdf(Z_scores) pvalues", "if useIP == False: ngrid = 1000 self.stat_grid = np.zeros((ntarget,", "1./implied_cov _A = self.cond_cov.dot(eta) * implied_prec R = np.identity(num_opt) -", "import collections import numpy as np from numpy import log", "((self.precs[m])[0, 0]) mean = self.S[m].dot(mean_parameter[m].reshape((1,))) + self.r[m] _cdf = family.cdf((mean[0]", "= implied_mean * implied_prec val, soln, _ = solver(np.asarray([conjugate_arg]), np.reshape(implied_prec,", "[compute_Lg(g) for g in sorted_active_dirs] L = block_diag(*Ls) # unpack", "_A = self.cond_cov.dot(eta) * implied_prec R = np.identity(num_opt) - _A.dot(eta.T)", "family.equal_tailed_interval(observed_target, alpha=1 - level) var_target = 1. / ((self.precs[m])[0, 0])", "on _setup_implied_gaussian) logdens_linear: (model on _setup_implied_gaussian) linear_part: like A_scaling (from", "mask of active features ordered_groups = [] # active group", "np.sqrt(np.diag(observed_info_mean))]).T log_ref = val + conjugate_arg.T.dot(cond_cov).dot(conjugate_arg) / 2. result =", "0: step *= 2 hess = inv(precision + barrier_hessian(current)) return", "logW = (log_ref - 0.5 * (self.stat_grid[m] - self.observed_target[m]) **", "self.S = S self.r = r def solve_barrier_affine_jacobian_py(conjugate_arg, precision, feasible_point,", "self._construct_families() if alternatives is None: alternatives = ['twosided'] * self.ntarget", "hasattr(self, \"_families\"): self._construct_families() lower, upper = [], [] for m", "is None: alternatives = ['twosided'] * self.ntarget pivot = []", "group 3). This function checks the user-specified group scheme and", "is group g appreciably nonzero ordered_groups.append(g) # variables in active", "for ug in active_dirs.values()]) # gradient grad_J = S.dot(GpC_inv.diagonal()) #", "groups, weights, sigma=1., quadratic=None, ridge_term=0., perturb=None, use_lasso=True, # should lasso", "size one, the orthogonal complement is empty return Vg def", "1.e-12}, level=0.9, useJacobian=True, dispersion=None): \"\"\"Do selective_MLE for group_lasso Note: this", "itercount % 4 == 0: step *= 2 hess =", "p = self.target_score_cov.shape[1] for m in range(self.ntarget): observed_target_uni = (self.observed_target[m]).reshape((1,))", "_check_groups(groups) # make sure groups looks sensible # log likelihood", "soln = self.initial_soln # do not need to keep setting", "Gamma is target_score_cov.T.dot(prec_target) num_opt = self.prec_opt.shape[0] num_con = self.linear_part.shape[0] cond_mean_grid", "gaps (e.g., if there is a group 2 and a", "raise ValueError(\"Groups are not a 1D array_like\") # check sorted", "the active groups for g in sorted(np.unique(self.groups)): # g is", "# use Pearson's X^2 dispersion = ((y - self.loglike.saturated_loss.mean_function( XE.dot(observed_target)))", "loglike, groups, weights, ridge_term, randomizer, use_lasso=True, # should lasso solver", "(0,)]: _P = target_linear.T.dot(target_offset) * self.randomizer_prec _prec = prec_target +", "depends on score, hence the minus sign target_linear = target_score_cov.T.dot(prec_target)", "1000 self.stat_grid = np.zeros((ntarget, ngrid)) for j in range(ntarget): self.stat_grid[j,", "on _setup_implied_gaussian) linear_part: like A_scaling (from lasso) offset: like b_scaling", "directions and norms of the active groups for g in", "cond_mean: conditional mean of optimization variables (model on _setup_implied_gaussian) cond_cov:", "ordered_vars] # changed to ordered_vars Q = XE.T.dot(self._W[:, None] *", "return result, observed_info_mean, log_ref def selected_targets(self, dispersion=None, solve_args={'tol': 1.e-12, 'min_its':", "numpy import log from numpy.linalg import norm, qr, inv, eig", "active = np.flatnonzero(active_signs) self.active = active def compute_Vg(ug): pg =", "j in range(ntarget): self.stat_grid[j, :] = np.linspace(observed_target[j] - 1.5 *", "= target_lin.T.dot(prec_opt) observed_info_natural = _prec + L.dot(target_lin) - L.dot(hess.dot(L.T)) observed_info_mean", "jacobian_grad_hess(gs, C, active_dirs)[0] else: p3 = 0 p4 = log(1.", "(target_linear.shape[0],)) target_lin = -self.logdens_linear.dot(target_linear) target_off = (self.cond_mean - target_lin.dot(observed_target_uni)).reshape((target_lin.shape[0],)) _prec", "# store groups as a class variable since the non-group", "randomization self.randomizer = randomizer def fit(self, solve_args={'tol': 1.e-12, 'min_its': 50},", "= proposed_value if itercount % 4 == 0: step *=", "as np from numpy import log from numpy.linalg import norm,", "con_linear, con_offset, C, active_dirs, useJacobian=True, step=1, nstep=2000, min_its=500, tol=1.e-12): \"\"\"", "must also be at least one feature in group 3).", "= {} r = {} p = self.target_score_cov.shape[1] for m", "= 1./implied_cov _A = self.cond_cov.dot(eta) * implied_prec R = np.identity(num_opt)", "= solve_args result, inverse_info = query.selective_MLE(dispersion=dispersion)[:2] self.linear_part = query.linear_part self.offset", "min(_cdf, 1 - _cdf)) elif alternatives[m] == 'greater': pivot.append(1 -", "# otherwise continue as before self.observed_opt_state = np.hstack(ordered_opt) # gammas", "0.5 * (grid - self.observed_target[m]) ** 2 / var_target) logW", "return group_lasso(loglike, groups, weights, ridge_term, randomizer, use_lasso, perturb) def _setup_implied_gaussian(self):", "group 4, there must also be at least one feature", "C, active_dirs)[2] else: p2 = 0 return p1 + p2", "up lasso penalty and run usual lasso solver... (see existing", "lasso (self.initial_soln, self.initial_subgrad) = self._solve_randomized_problem(perturb=perturb, solve_args=solve_args) # initialize variables active_groups", "confidence intervals useC: whether to use python or C solver", "= np.linalg.inv(GammaMinus + C) # summing matrix (gamma.size by C.shape[0])", "vary with target # logdens_linear determines how the argument of", "fitting) \"\"\" self._setup_implied_gaussian() # Calculate useful quantities (observed_target, target_cov, target_score_cov,", "Parameters ---------- alternatives : [str], optional Sequence of strings describing", "is group label group_mask = self.groups == g soln =", "Lg = self.penalty.weights[g] * np.eye(pg) return Lg sorted_active_dirs = collections.OrderedDict(sorted(active_dirs.items()))", "R = np.identity(num_opt) - _A.dot(eta.T) A = self.linear_part.dot(_A).reshape((-1,)) b =", "lasso penalty and run usual lasso solver... (see existing code)...", "+ query.opt_offset self.ntarget = ntarget = target_cov.shape[0] _scale = 4", "target_cov.dot( _P - target_lin.T.dot(prec_opt).dot(target_off)) L = target_lin.T.dot(prec_opt) observed_info_natural = _prec", "lasso) offset: like b_scaling (from lasso) solve_args: passed on to", "self.C) arguments conjugate_arg: \\\\bar{\\\\Sigma}^{-1} \\bar{\\\\mu} precision: \\\\bar{\\\\Sigma}^{-1} feasible_point: gamma's from", "feasible count = 0 while True: count += 1 proposal", "count = 0 while True: count += 1 proposal =", "else: raise ValueError('value is NaN: %f, %f' % (proposed_value, current_value))", "= self.target_score_cov[m, :].reshape((1, p)) target_linear = target_score_cov_uni.T.dot(prec_target) target_offset = (self.score_offset", "perturb=None): # solve the randomized version of group lasso (self.initial_soln,", "whether to use python or C solver JacobianPieces: (use self.C", "unpenalized = [] # selected groups with no penalty overall", "0 while True: count += 1 proposal = current -", "method def _construct_density(self): precs = {} S = {} r", "active_dirs = {} # dictionary: keys are group labels, values", "beta with zeros self._beta_full = beta_bar X, y = self.loglike.data", "1.5 * _scale[j], num=ngrid) self.opt_linear = query.opt_linear self.useIP = useIP", "gs.T.dot(precision).dot(gs) / 2. if useJacobian: p3 = - jacobian_grad_hess(gs, C,", "W = self._W = self.loglike.saturated_loss.hessian(X.dot(beta_bar)) # all 1's for LS", "((self.precs[m])[0, 0]) log_ref = self.log_reference(observed_target_uni, target_cov_uni, target_score_cov_uni, self.stat_grid[m]) if self.useIP", "if perturb is not None: self._initial_omega = perturb if self._initial_omega", "p3 + p4 def grad(gs): p1 = -conjugate_arg + precision.dot(gs)", "in increasing order, start at 0, and have no gaps", "= np.linalg.inv(_prec).dot(prec_target) S[m] = _S r[m] = _r precs[m] =", "useJacobian: p3 = - jacobian_grad_hess(gs, C, active_dirs)[1] else: p3 =", "- 1)) for ug in active_dirs.values()]) # gradient grad_J =", "V.T.dot(QI).dot(L).dot(V) self.XE = XE self.Q = Q self.QI = QI", "+ C) # log Jacobian #J = log(evalues).sum() J =", "rr.group_lasso(groups, weights=weights, lagrange=1.) # store groups as a class variable", "lasso solver be used when applicable - defaults to True", "---------- query : `gaussian_query` A Gaussian query which has information", "p1 + p2 + p3 + p4 def grad(gs): p1", "..distributions.discrete_family import discrete_family class group_lasso(object): def __init__(self, loglike, groups, weights,", "'min_its': 100}): # take a new perturbation if supplied if", "exception if it finds any problems. Sorting feature groups is", "= 1000 self.stat_grid = np.zeros((ntarget, ngrid)) for j in range(ntarget):", "* cur_grad if np.all(con_offset - con_linear.dot(proposal) > 0): break step", "selective_MLE for group_lasso Note: this masks the selective_MLE inherited from", "if np.asarray(observed_target).shape in [(), (0,)]: raise ValueError('no target specified') prec_target", "query : `gaussian_query` A Gaussian query which has information to", "pd.DataFrame({'MLE': final_estimator, 'SE': np.sqrt(np.diag(observed_info_mean)), 'Zvalue': Z_scores, 'pvalue': pvalues, 'lower_confidence': intervals[:,", "- defaults to True perturb=None): _check_groups(groups) # make sure groups", "alternatives : [str], optional Sequence of strings describing the alternatives,", "tol * norm(soln): # is group g appreciably nonzero ordered_groups.append(g)", "rr.simple_problem(self.loglike, self.penalty) # if all groups are size 1, set", "# Calculate useful quantities (observed_target, target_cov, target_score_cov, alternatives) = self.selected_targets(dispersion)", "* dispersion crosscov_target_score = _score_linear.dot(self.QI).T * dispersion return (observed_target, cov_target,", "target_lin.T.dot( prec_opt).dot(target_lin) C = target_cov.dot(_P - target_lin.T.dot(prec_opt).dot(target_off)) conjugate_arg = prec_opt.dot(cond_mean)", "alternatives[m] == 'twosided': pivot.append(2 * min(_cdf, 1 - _cdf)) elif", "and norms of the active groups for g in sorted(np.unique(self.groups)):", "the group is size one, the orthogonal complement is empty", "_P = target_linear.T.dot(target_offset) * self.randomizer_prec _r = (1. / _prec).dot(target_lin.T.dot(self.prec_opt).dot(target_off)", "target_off = (self.cond_mean - target_lin.dot(observed_target_uni)).reshape((target_lin.shape[0],)) _prec = prec_target + (target_linear.T.dot(target_linear)", "np.hstack(ordered_opt) # gammas as array _beta_unpenalized = restricted_estimator(self.loglike, # refit", "self.observed_opt_state = np.hstack(ordered_opt) # gammas as array _beta_unpenalized = restricted_estimator(self.loglike,", "useJacobian, **solve_args) final_estimator = target_cov.dot(_prec).dot(observed_target) \\ + target_cov.dot(target_lin.T.dot(prec_opt.dot(cond_mean - soln)))", "np.sqrt(n / (n - 1.)) randomizer = randomization.isotropic_gaussian((p,), randomizer_scale) return", "when applicable - defaults to True randomizer_scale=None): loglike = rr.glm.gaussian(X,", "'greater': pivot.append(1 - _cdf) elif alternatives[m] == 'less': pivot.append(_cdf) else:", "_scale = 4 * np.sqrt(np.diag(inverse_info)) if useIP == False: ngrid", "a 1D array_like\") # check sorted if np.any(agroups[:-1] > agroups[1:])", "= (1. / _prec).dot(target_lin.T.dot(self.prec_opt).dot(target_off) - _P) _S = np.linalg.inv(_prec).dot(prec_target) S[m]", "+ (target_linear.T.dot(self.randomizer_prec).dot(target_linear)) - target_lin.T.dot( prec_opt).dot(target_lin) C = target_cov.dot(_P - target_lin.T.dot(prec_opt).dot(target_off))", "in gp]) def jacobian_grad_hess(gamma, C, active_dirs): \"\"\" Calculate the log-Jacobian", "/ var_target) logW -= logW.max() self._families.append(discrete_family(grid, np.exp(logW))) def _approx_pivots(self, mean_parameter,", "from ..algorithms.barrier_affine import solve_barrier_affine_py as solver from ..distributions.discrete_family import discrete_family", "= query.randomizer_prec self.score_offset = query.observed_score_state + query.opt_offset self.ntarget = ntarget", "1: Z = np.column_stack((ug, np.eye(pg, pg - 1))) Q, _", "level) var_target = 1. / ((self.precs[m])[0, 0]) lower.append(l * var_target", "= rr.glm.gaussian(X, Y, coef=1. / sigma ** 2, quadratic=quadratic) n,", "= self.opt_linear.T.dot(prec.dot(self.opt_linear)) cond_cov = inv(cond_precision) logdens_linear = cond_cov.dot(self.opt_linear.T).dot(prec) cond_mean =", "jacobian_grad_hess(gs, C, active_dirs)[1] else: p3 = 0 p4 = 1.", "= query.linear_part self.offset = query.offset self.logdens_linear = query.logdens_linear self.cond_mean =", "level: level of confidence intervals useC: whether to use python", "itercount >= min_its: current = proposal current_value = proposed_value break", "+= 1 proposal = current - step * cur_grad if", "self.observed_target = observed_target self.target_score_cov = target_score_cov self.target_cov = target_cov self.init_soln", "ValueError(\"Groups are not sorted\") # check integers if not np.issubdtype(agroups.dtype,", "self.linear_part = query.linear_part self.offset = query.offset self.logdens_linear = query.logdens_linear self.cond_mean", "self.QI = QI self.C = C U = block_diag(*[ug for", "# when all groups are size one, C will be", "of optimization variables (model on _setup_implied_gaussian) cond_cov: conditional variance of", "None: self._initial_omega = self.randomizer.sample() quad = rr.identity_quadratic(self.ridge_term, 0, -self._initial_omega, 0)", "var_target, x=self.observed_target[m]) print(\"variable completed \", m) if alternatives[m] == 'twosided':", "defined in fitting) \"\"\" self._setup_implied_gaussian() # Calculate useful quantities (observed_target,", "inverse #GpC_inv = evectors.dot(np.diag(1 / evalues).dot(evectors.T)) GpC_inv = np.linalg.inv(GammaMinus +", "cond_cov.dot(self.opt_linear.T) * prec else: cond_precision = self.opt_linear.T.dot(prec.dot(self.opt_linear)) cond_cov = inv(cond_precision)", "ridge parameter self.ridge_term = ridge_term # group lasso penalty (from", "block_diag(*Vs) # unpack the list Ls = [compute_Lg(g) for g", "proposed_value break current = proposal current_value = proposed_value if itercount", "query.active_dirs (observed_target, target_cov, target_score_cov, alternatives) = query.selected_targets(dispersion) self.observed_target = observed_target", "constraint used for barrier function C: V^T Q^{-1} \\\\Lambda V", "on _setup_implied_gaussian) cond_cov: conditional variance of optimization variables (model on", "and jacobian to hessian p1 = con_linear.T.dot(np.diag(-1. / ((scaling +", "range(self.ntarget): # construction of intervals from families follows `selectinf.learning.core` family", "= - jacobian_grad_hess(gs, C, active_dirs)[1] else: p3 = 0 p4", "from implied Gaussian # cond_mean is \"something\" times D #", "nstep=2000, min_its=500, tol=1.e-12): \"\"\" This needs to be updated to", "where \"something\" comes from implied Gaussian # cond_mean is \"something\"", "numpy.linalg import norm, qr, inv, eig import pandas as pd", "# all 1's for LS opt_linearNoU = np.dot(X.T, X[:, ordered_vars]", "logdens_linear return cond_mean, cond_cov, cond_precision, logdens_linear def selective_MLE(self, solve_args={'tol': 1.e-12},", "alternatives=None): if not hasattr(self, \"_families\"): self._construct_families() if alternatives is None:", "any problems. Sorting feature groups is potentially tedious for the", "1 - level quantile = ndist.ppf(1 - alpha / 2.)", "weights an an np.array rather than a dictionary weights_np =", "coefficients unpenalized = [] # selected groups with no penalty", "Also, assumes you have already run the fit method since", "part of affine constraint used for barrier function con_offset: offset", "discrete_family class group_lasso(object): def __init__(self, loglike, groups, weights, ridge_term, randomizer,", "# exception if no groups are selected if len(self.selection_variable['active_groups']) ==", "increasing order, start at 0, and have no gaps (e.g.,", "selective_MLE(self, solve_args={'tol': 1.e-12}, level=0.9, useJacobian=True, dispersion=None): \"\"\"Do selective_MLE for group_lasso", "< tol * np.fabs(current_value) and itercount >= min_its: current =", "= self.observed_opt_state # just the gammas cond_mean = self.cond_mean cond_cov", "= inv(cond_precision) logdens_linear = cond_cov.dot(self.opt_linear.T) * prec else: cond_precision =", "- 1) if randomizer_scale is None: randomizer_scale = np.sqrt(mean_diag) *", "(n - XE.shape[1]) cov_target = self.QI * dispersion crosscov_target_score =", "inverse_info = query.selective_MLE(dispersion=dispersion)[:2] self.linear_part = query.linear_part self.offset = query.offset self.logdens_linear", "jacobian_grad_hess(gs, C, active_dirs)[2] else: p2 = 0 return p1 +", "_ = qr(Z) Vg = Q[:, 1:] # drop the", "Q self.QI = QI self.C = C U = block_diag(*[ug", "Q = self.Q observed_target = restricted_estimator(self.loglike, self.ordered_vars, solve_args=solve_args) _score_linear =", "prec_target + (target_linear.T.dot(self.randomizer_prec).dot(target_linear)) - target_lin.T.dot( prec_opt).dot(target_lin) C = target_cov.dot(_P -", "self.observed_target[m]) ** 2 / var_target) logW -= logW.max() self._families.append(discrete_family(self.stat_grid[m], np.exp(logW)))", "self.logdens_linear linear_part = self.linear_part offset = self.offset if np.asarray(observed_target).shape in", "[str], optional Sequence of strings describing the alternatives, should be", "0]) log_ref = self.log_reference(observed_target_uni, target_cov_uni, target_score_cov_uni, self.stat_grid[m]) if self.useIP ==", "from fitting con_linear: linear part of affine constraint used for", "0\") # check for no skipped groups if not np.all(np.diff(np.unique(agroups))", "are not sorted\") # check integers if not np.issubdtype(agroups.dtype, np.integer):", "should lasso solver be used when applicable - defaults to", "50}): X, y = self.loglike.data n, p = X.shape XE", "raise TypeError(\"Groups are not integers\") # check starts with 0", "labels sorted by label ordered_opt = [] # gamma's ordered", "if len(agroups.shape) != 1: raise ValueError(\"Groups are not a 1D", "cond_precision, logdens_linear def selective_MLE(self, solve_args={'tol': 1.e-12}, level=0.9, useJacobian=True, dispersion=None): \"\"\"Do", "the usual D = N + Gamma theta.hat, # target_lin", "no penalty overall = np.ones(self.nfeature, np.bool) # mask of active", "* X).T alternatives = ['twosided'] * len(self.active) if dispersion is", "weights, ridge_term, randomizer, use_lasso=True, # should lasso solver be used", "alpha = 1 - level quantile = ndist.ppf(1 - alpha", "self.penalty = rr.group_lasso(groups, weights=weights, lagrange=1.) # store groups as a", "of affine constraint used for barrier function C: V^T Q^{-1}", "self.cond_mean) #direction for decomposing o eta = -self.prec_opt.dot(self.logdens_linear.dot(target_score_cov.T)) implied_mean =", "cond_mean - target_lin.dot(observed_target) if np.asarray(self.randomizer_prec).shape in [(), (0,)]: _P =", "* np.sqrt(mean_diag) / np.sqrt(n - 1) if randomizer_scale is None:", "looks sensible # log likelihood : quadratic loss self.loglike =", "optimization variables (model on _setup_implied_gaussian) logdens_linear: (model on _setup_implied_gaussian) linear_part:", "_scale[j], num=ngrid) self.opt_linear = query.opt_linear self.useIP = useIP def summary(self,", "* (self.stat_grid[m] - self.observed_target[m]) ** 2 / var_target) logW -=", "# solve the randomized version of group lasso (self.initial_soln, self.initial_subgrad)", "return cond_mean, cond_cov, cond_precision, logdens_linear def selective_MLE(self, solve_args={'tol': 1.e-12}, level=0.9,", "is not None: pivots = self._approx_pivots(parameter, alternatives=alternatives) else: pivots =", "None pvalues = self._approx_pivots(np.zeros_like(self.observed_target), alternatives=alternatives) lower, upper = self._approx_intervals(level=level) result", "self._W = self.loglike.saturated_loss.hessian(X.dot(beta_bar)) # all 1's for LS opt_linearNoU =", "self.Q observed_target = restricted_estimator(self.loglike, self.ordered_vars, solve_args=solve_args) _score_linear = -XE.T.dot(self._W[:, None]", "- con_linear.dot(gs)) / scaling)).sum() return p1 + p2 + p3", "prec_opt).dot(target_lin) C = target_cov.dot(_P - target_lin.T.dot(prec_opt).dot(target_off)) conjugate_arg = prec_opt.dot(cond_mean) val,", "np.integer): raise TypeError(\"Groups are not integers\") # check starts with", "m) if alternatives[m] == 'twosided': pivot.append(2 * min(_cdf, 1 -", "`selectinf.learning.core` family = self._families[m] observed_target = self.observed_target[m] l, u =", "self.active_dirs = query.active_dirs (observed_target, target_cov, target_score_cov, alternatives) = query.selected_targets(dispersion) self.observed_target", "[] # active group labels active_dirs = {} # dictionary:", "['twosided', 'less', 'greater'] parameter : np.array Hypothesized value for parameter", "method. Parameters ---------- observed_target: from selected_targets target_cov: from selected_targets target_cov_score:", "**solve_args) final_estimator = target_cov.dot(_prec).dot(observed_target) \\ + target_cov.dot(target_lin.T.dot(prec_opt.dot(cond_mean - soln))) +", "prec_target = np.linalg.inv(target_cov) target_lin = - self.logdens_linear.dot(target_score_cov.T.dot(prec_target)) ref_hat = []", "self.stat_grid[m]) if self.useIP == False: logW = (log_ref - 0.5", "(1. / _prec).dot(target_lin.T.dot(self.prec_opt).dot(target_off) - _P) _S = np.linalg.inv(_prec).dot(prec_target) S[m] =", "for them. \"\"\" # check array_like agroups = np.array(groups) #", "- 1.)) randomizer = randomization.isotropic_gaussian((p,), randomizer_scale) return group_lasso(loglike, groups, weights,", "== False: ngrid = 1000 self.stat_grid = np.zeros((ntarget, ngrid)) for", "for targets of model including selected features Parameters ---------- alternatives", "target_lin determines how the conditional mean of optimization variables #", "'greater'] parameter : np.array Hypothesized value for parameter -- defaults", "(opt_state) initial (observed) value of optimization variables cond_mean: conditional mean", "ordered_opt.append(norm(soln[group_mask])) else: overall[group_mask] = False self.selection_variable = {'directions': active_dirs, 'active_groups':", "/ ((self.precs[m])[0, 0]) log_ref = self.log_reference(observed_target_uni, target_cov_uni, target_score_cov_uni, self.stat_grid[m]) if", "= query.selected_targets(dispersion) self.observed_target = observed_target self.target_score_cov = target_score_cov self.target_cov =", "not 0\") # check for no skipped groups if not", "inv(Q) C = V.T.dot(QI).dot(L).dot(V) self.XE = XE self.Q = Q", "perturb=None): _check_groups(groups) # make sure groups looks sensible # log", "Observed estimate of target. target_cov : ndarray Estimated covaraince of", "p1 = -conjugate_arg + precision.dot(gs) p2 = -con_linear.T.dot(1. / (scaling", "restricted_estimator from ..algorithms.barrier_affine import solve_barrier_affine_py as solver from ..distributions.discrete_family import", "sorting group labels tol = 1.e-20 _, self.randomizer_prec = self.randomizer.cov_prec", "con_offset - con_linear.dot(gs)) ** 2.) + 1. / ((con_offset -", "* _scale[j], num=ngrid) else: ngrid = 100 self.stat_grid = np.zeros((ntarget,", "np.asarray(observed_target).shape in [(), (0,)]: raise ValueError('no target specified') observed_target =", "m in range(self.ntarget): family = self._families[m] var_target = 1. /", "{} # dictionary: keys are group labels, values are unit-norm", "(0,)]: raise ValueError('no target specified') observed_target = np.atleast_1d(observed_target) prec_target =", "'min_its': 50}): X, y = self.loglike.data n, p = X.shape", "+ 1.5 * _scale[j], num=ngrid) else: ngrid = 100 self.stat_grid", "_setup_implied_gaussian) cond_cov: conditional variance of optimization variables (model on _setup_implied_gaussian)", "jacobian_grad_hess(gamma_, self.C, self.active_dirs) ref_hat.append(-val - ((conjugate_arg ** 2) * implied_cov)/", "_construct_families(self): self._construct_density() self._families = [] for m in range(self.ntarget): p", "self.useIP == False: logW = (log_ref - 0.5 * (self.stat_grid[m]", "_beta_unpenalized = restricted_estimator(self.loglike, # refit OLS on E overall, solve_args=solve_args)", "randomizer = randomization.isotropic_gaussian((p,), randomizer_scale) return group_lasso(loglike, groups, weights, ridge_term, randomizer,", "of randomized query. solve_args : dict, optional Arguments passed to", "_, self.randomizer_prec = self.randomizer.cov_prec # now we are collecting the", "= self.target_score_cov[m, :].reshape((1, p)) var_target = 1. / ((self.precs[m])[0, 0])", "= (log_ref - 0.5 * (self.stat_grid[m] - self.observed_target[m]) ** 2", "active def compute_Vg(ug): pg = ug.size # figure out size", "!= 1: raise ValueError(\"Groups are not a 1D array_like\") #", "- target_lin.T.dot(prec_opt).dot(target_off)) conjugate_arg = prec_opt.dot(cond_mean) val, soln, hess = solve_barrier_affine_jacobian_py(conjugate_arg,", "active group labels sorted by label ordered_opt = [] #", "qr(Z) Vg = Q[:, 1:] # drop the first column", "complement is empty return Vg def compute_Lg(g): pg = active_dirs[g].size", "in the usual D = N + Gamma theta.hat, #", "# group lasso penalty (from regreg) # use regular lasso", "1:] # drop the first column else: Vg = np.zeros((1,", "= _r precs[m] = _prec self.precs = precs self.S =", "np.column_stack((ug, np.eye(pg, pg - 1))) Q, _ = qr(Z) Vg", "not sorted\") # check integers if not np.issubdtype(agroups.dtype, np.integer): raise", "-logdens_linear.dot(self.observed_score_state + self.opt_offset) self.cond_mean = cond_mean self.cond_cov = cond_cov self.cond_precision", "\"_families\"): self._construct_families() if alternatives is None: alternatives = ['twosided'] *", "0. level : float Confidence level. \"\"\" if parameter is", "np.amin(agroups) == 0: raise ValueError(\"First group is not 0\") #", "y = self.loglike.data n, p = X.shape XE = self.XE", "- quantile * np.sqrt(np.diag(observed_info_mean)), final_estimator + quantile * np.sqrt(np.diag(observed_info_mean))]).T log_ref", "soln[group_mask] / norm(soln[group_mask]) ordered_opt.append(norm(soln[group_mask])) else: overall[group_mask] = False self.selection_variable =", "None: randomizer_scale = np.sqrt(mean_diag) * 0.5 * np.std(Y) * np.sqrt(n", "= cond_cov.dot(self.opt_linear.T).dot(prec) cond_mean = -logdens_linear.dot(self.observed_score_state + self.opt_offset) self.cond_mean = cond_mean", "result.insert(5, 'parameter', parameter) return result def log_reference(self, observed_target, target_cov, target_score_cov,", "= calc_GammaMinus(gamma, active_dirs) # eigendecomposition #evalues, evectors = eig(GammaMinus +", "- L.dot(hess.dot(L.T)) observed_info_mean = target_cov.dot(observed_info_natural.dot(target_cov)) Z_scores = final_estimator / np.sqrt(np.diag(observed_info_mean))", "is None: feasible_point = 1. / scaling def objective(gs): p1", "= query.opt_linear self.useIP = useIP def summary(self, alternatives=None, parameter=None, level=0.9):", "labels active_dirs = {} # dictionary: keys are group labels,", "loglike = rr.glm.gaussian(X, Y, coef=1. / sigma ** 2, quadratic=quadratic)", "function C: V^T Q^{-1} \\\\Lambda V active_dirs: \"\"\" scaling =", "conjugate_arg.T.dot(cond_cov).dot(conjugate_arg) / 2. result = pd.DataFrame({'MLE': final_estimator, 'SE': np.sqrt(np.diag(observed_info_mean)), 'Zvalue':", "= C U = block_diag(*[ug for ug in sorted_active_dirs.values()]).T self.opt_linear", "p2 = gs.T.dot(precision).dot(gs) / 2. if useJacobian: p3 = -", "var_target + observed_target) upper.append(u * var_target + observed_target) return np.asarray(lower),", "query.C self.active_dirs = query.active_dirs (observed_target, target_cov, target_score_cov, alternatives) = query.selected_targets(dispersion)", "of barrier and jacobian to hessian p1 = con_linear.T.dot(np.diag(-1. /", "* self.ntarget pivot = [] for m in range(self.ntarget): family", "- target_lin.T.dot( prec_opt).dot(target_lin) C = target_cov.dot(_P - target_lin.T.dot(prec_opt).dot(target_off)) conjugate_arg =", "p1 + p2 current = feasible_point current_value = np.inf for", "* len(self.active) if dispersion is None: # use Pearson's X^2", "= - jacobian_grad_hess(gs, C, active_dirs)[2] else: p2 = 0 return", "1D array_like\") # check sorted if np.any(agroups[:-1] > agroups[1:]) <", "= rr.group_lasso(groups, weights=weights, lagrange=1.) # store groups as a class", "target_score_cov_uni = self.target_score_cov[m, :].reshape((1, p)) var_target = 1. / ((self.precs[m])[0,", "return current_value, current, hess # Jacobian calculations def calc_GammaMinus(gamma, active_dirs):", "level quantile = ndist.ppf(1 - alpha / 2.) intervals =", "- _A.dot(eta.T) A = self.linear_part.dot(_A).reshape((-1,)) b = self.offset-self.linear_part.dot(R).dot(self.init_soln) conjugate_arg =", "is potentially tedious for the user and in future we", "- pvalues) alpha = 1 - level quantile = ndist.ppf(1", "pvalues, 'lower_confidence': intervals[:, 0], 'upper_confidence': intervals[:, 1], 'unbiased': unbiased_estimator}) return", "by C.shape[0]) S = block_diag(*[np.ones((1, ug.size - 1)) for ug", "array_like of integers that are sorted in increasing order, start", "= self.logdens_linear linear_part = self.linear_part offset = self.offset if np.asarray(observed_target).shape", "= -logdens_linear.dot(self.observed_score_state + self.opt_offset) self.cond_mean = cond_mean self.cond_cov = cond_cov", "# log likelihood : quadratic loss self.loglike = loglike self.nfeature", "with target # logdens_linear determines how the argument of the", "like b_scaling (from lasso) solve_args: passed on to solver level:", "user-specified group scheme and raises an exception if it finds", "how the mean depends on score, hence the minus sign", "Confidence level. \"\"\" if parameter is not None: pivots =", "we might do this for them. \"\"\" # check array_like", "= 1. / ((self.precs[m])[0, 0]) mean = self.S[m].dot(mean_parameter[m].reshape((1,))) + self.r[m]", "step=1, nstep=2000, min_its=500, tol=1.e-12): \"\"\" This needs to be updated", "score, not how the mean depends on score, hence the", "to 0. level : float Confidence level. \"\"\" if parameter", "construction of intervals from families follows `selectinf.learning.core` family = self._families[m]", "target_linear.dot(observed_target) target_lin = - logdens_linear.dot(target_linear) target_off = cond_mean - target_lin.dot(observed_target)", "passed to solver. \"\"\" self.solve_args = solve_args result, inverse_info =", "p3 + p4 def barrier_hessian(gs): # contribution of barrier and", "y = self.loglike.data W = self._W = self.loglike.saturated_loss.hessian(X.dot(beta_bar)) # all", "eig import pandas as pd import regreg.api as rr from", "def __init__(self, loglike, groups, weights, ridge_term, randomizer, use_lasso=True, # should", "'grad')) return initial_soln, initial_subgrad @staticmethod def gaussian(X, Y, groups, weights,", "def gaussian(X, Y, groups, weights, sigma=1., quadratic=None, ridge_term=0., perturb=None, use_lasso=True,", "4 * np.sqrt(np.diag(inverse_info)) if useIP == False: ngrid = 1000", "self.observed_target[m] l, u = family.equal_tailed_interval(observed_target, alpha=1 - level) var_target =", "mean of optimization variables (model on _setup_implied_gaussian) cond_cov: conditional variance", "gamma's from fitting con_linear: linear part of affine constraint used", "= proposal current_value = proposed_value break current = proposal current_value", "np.sqrt(np.diag(observed_info_mean)), final_estimator + quantile * np.sqrt(np.diag(observed_info_mean))]).T log_ref = val +", "randomized query. solve_args : dict, optional Arguments passed to solver.", "rr.glm.gaussian(X, Y, coef=1. / sigma ** 2, quadratic=quadratic) n, p", "None] * X).T alternatives = ['twosided'] * len(self.active) if dispersion", "not (np.isnan(proposed_value) or np.isnan(current_value)): break else: raise ValueError('value is NaN:", "run the fit method since this uses results from that", "0: raise ValueError(\"First group is not 0\") # check for", "parameter=None, level=0.9): \"\"\" Produce p-values and confidence intervals for targets", "alternatives = ['twosided'] * self.ntarget pivot = [] for m", "current_value = np.inf for itercount in range(nstep): cur_grad = grad(current)", "sigma=1., quadratic=None, ridge_term=0., perturb=None, use_lasso=True, # should lasso solver be", "+ R.dot(self.init_soln) log_jacob = jacobian_grad_hess(gamma_, self.C, self.active_dirs) ref_hat.append(-val - ((conjugate_arg", "the list Ls = [compute_Lg(g) for g in sorted_active_dirs] L", "constraint used for barrier function con_offset: offset part of affine", "self.initial_subgrad) = self._solve_randomized_problem(perturb=perturb, solve_args=solve_args) # initialize variables active_groups = []", "user and in future we might do this for them.", "(target_linear.T.dot(self.randomizer_prec).dot(target_linear)) - target_lin.T.dot( prec_opt).dot(target_lin) C = target_cov.dot(_P - target_lin.T.dot(prec_opt).dot(target_off)) conjugate_arg", "skipped groups if not np.all(np.diff(np.unique(agroups)) == 1): raise ValueError(\"Some group", "alternatives=alternatives) else: pivots = None pvalues = self._approx_pivots(np.zeros_like(self.observed_target), alternatives=alternatives) lower,", "in sorted(weights.items())]) self.penalty = rr.weighted_l1norm(weights=weights_np, lagrange=1.) else: self.penalty = rr.group_lasso(groups,", "0 return p1 + p2 current = feasible_point current_value =", "target_score_cov : ndarray Estimated covariance of target and score of", "num=ngrid) self.opt_linear = query.opt_linear self.useIP = useIP def summary(self, alternatives=None,", "else: raise ValueError('alternative should be in [\"twosided\", \"less\", \"greater\"]') return", "on the score, not how the mean depends on score,", "u = family.equal_tailed_interval(observed_target, alpha=1 - level) var_target = 1. /", "* np.sqrt(n / (n - 1.)) randomizer = randomization.isotropic_gaussian((p,), randomizer_scale)", "keep setting this if norm(soln[group_mask]) > tol * norm(soln): #", "np.mean((X ** 2).sum(0)) if ridge_term is None: ridge_term = np.std(Y)", "= self.initial_subgrad self.observed_score_state = -opt_linearNoU.dot(_beta_unpenalized) self.observed_score_state[~overall] += self.loglike.smooth_objective(beta_bar, 'grad')[~overall] active_signs", "if self._initial_omega is None: self._initial_omega = self.randomizer.sample() quad = rr.identity_quadratic(self.ridge_term,", "evectors.dot(np.diag(1 / evalues).dot(evectors.T)) GpC_inv = np.linalg.inv(GammaMinus + C) # summing", "'twosided': pivot.append(2 * min(_cdf, 1 - _cdf)) elif alternatives[m] ==", "Gamma^minus (as a function of gamma vector, active directions) \"\"\"", "query.linear_part self.offset = query.offset self.logdens_linear = query.logdens_linear self.cond_mean = query.cond_mean", "proposal is feasible count = 0 while True: count +=", "2.))).dot(con_linear) if useJacobian: p2 = - jacobian_grad_hess(gs, C, active_dirs)[2] else:", "..algorithms.barrier_affine import solve_barrier_affine_py as solver from ..distributions.discrete_family import discrete_family class", "ordered by group labels ordered_vars = [] # indices \"ordered\"", "query.observed_score_state + query.opt_offset self.ntarget = ntarget = target_cov.shape[0] _scale =", "np.std(Y) * np.sqrt(n / (n - 1.)) randomizer = randomization.isotropic_gaussian((p,),", "value of optimization variables cond_mean: conditional mean of optimization variables", "- _cdf)) elif alternatives[m] == 'greater': pivot.append(1 - _cdf) elif", "p3 = 0 p4 = log(1. + 1. / ((con_offset", "randomized version of group lasso (self.initial_soln, self.initial_subgrad) = self._solve_randomized_problem(perturb=perturb, solve_args=solve_args)", "((scaling + con_offset - con_linear.dot(gs)) ** 2.) + 1. /", "= [] # selected groups with no penalty overall =", "0: return np.sign(soln), soln # otherwise continue as before self.observed_opt_state", "variable since the non-group lasso doesn't self.groups = groups self._initial_omega", "score_offset = self.observed_score_state + self.opt_offset # target_lin determines how the", "used for barrier function C: V^T Q^{-1} \\\\Lambda V active_dirs:", "= active def compute_Vg(ug): pg = ug.size # figure out", "S[m] = _S r[m] = _r precs[m] = _prec self.precs", "unpack the list Ls = [compute_Lg(g) for g in sorted_active_dirs]", "p3 = - jacobian_grad_hess(gs, C, active_dirs)[1] else: p3 = 0", "that the user-specific groups are ok There are a number", "* implied_prec R = np.identity(num_opt) - _A.dot(eta.T) A = self.linear_part.dot(_A).reshape((-1,))", "# contribution of barrier and jacobian to hessian p1 =", "_cdf) elif alternatives[m] == 'less': pivot.append(_cdf) else: raise ValueError('alternative should", "penalty (from regreg) # use regular lasso penalty if all", "+ 1.5 * _scale[j], num=ngrid) self.opt_linear = query.opt_linear self.useIP =", "self.target_score_cov.shape[1] for m in range(self.ntarget): observed_target_uni = (self.observed_target[m]).reshape((1,)) target_cov_uni =", "0): # when all groups are size one, C will", "group_lasso Note: this masks the selective_MLE inherited from query because", "there is a group 2 and a group 4, there", "self._approx_intervals(level=level) result = pd.DataFrame({'target': self.observed_target, 'pvalue': pvalues, 'lower_confidence': lower, 'upper_confidence':", "updated to actually use the Jacobian information (in self.C) arguments", "-np.eye(self.observed_opt_state.shape[0]) self.offset = np.zeros(self.observed_opt_state.shape[0]) return active_signs, soln def _solve_randomized_problem(self, perturb=None,", "raise ValueError(\"Groups are not sorted\") # check integers if not", "ndarray Estimated covariance of target and score of randomized query.", "scaling = np.sqrt(np.diag(con_linear.dot(precision).dot(con_linear.T))) if feasible_point is None: feasible_point = 1.", "= active_dirs self.opt_offset = opt_offset self.ordered_vars = ordered_vars self.linear_part =", "self.observed_score_state + self.opt_offset # target_lin determines how the conditional mean", "'grad')[~overall] active_signs = np.sign(self.initial_soln) active = np.flatnonzero(active_signs) self.active = active", "unbiased_estimator}) return result, observed_info_mean, log_ref def selected_targets(self, dispersion=None, solve_args={'tol': 1.e-12,", "calc_GammaMinus(gamma, active_dirs) # eigendecomposition #evalues, evectors = eig(GammaMinus + C)", "= pd.DataFrame({'MLE': final_estimator, 'SE': np.sqrt(np.diag(observed_info_mean)), 'Zvalue': Z_scores, 'pvalue': pvalues, 'lower_confidence':", "overall = np.ones(self.nfeature, np.bool) # mask of active features ordered_groups", "in enumerate(ordered_vars): opt_linearNoU[var, i] += self.ridge_term opt_offset = self.initial_subgrad self.observed_score_state", "'unbiased': unbiased_estimator}) return result, observed_info_mean, log_ref def selected_targets(self, dispersion=None, solve_args={'tol':", "np.linalg.inv(query.cond_cov) self.cond_cov = query.cond_cov self.C = query.C self.active_dirs = query.active_dirs", "init_soln: (opt_state) initial (observed) value of optimization variables cond_mean: conditional", "S = {} r = {} p = self.target_score_cov.shape[1] for", "True: count += 1 proposal = current - step *", "use python or C solver JacobianPieces: (use self.C defined in", "p2 = - jacobian_grad_hess(gs, C, active_dirs)[2] else: p2 = 0", "\"something\" comes from implied Gaussian # cond_mean is \"something\" times", "in range(self.ntarget): observed_target_uni = (self.observed_target[m]).reshape((1,)) target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1, 1)) prec_target", "= X.shape mean_diag = np.mean((X ** 2).sum(0)) if ridge_term is", "= ((y - self.loglike.saturated_loss.mean_function( XE.dot(observed_target))) ** 2 / self._W).sum() /", "no skipped groups if not np.all(np.diff(np.unique(agroups)) == 1): raise ValueError(\"Some", "this for them. \"\"\" # check array_like agroups = np.array(groups)", "p2 + p3 + p4 def barrier_hessian(gs): # contribution of", "for ug in sorted_active_dirs.values()] V = block_diag(*Vs) # unpack the", "intervals[:, 0], 'upper_confidence': intervals[:, 1], 'unbiased': unbiased_estimator}) return result, observed_info_mean,", "Parameters ---------- query : `gaussian_query` A Gaussian query which has", "b = self.offset-self.linear_part.dot(R).dot(self.init_soln) conjugate_arg = implied_mean * implied_prec val, soln,", "= [compute_Lg(g) for g in sorted_active_dirs] L = block_diag(*Ls) #", "= np.inf for itercount in range(nstep): cur_grad = grad(current) #", "gp in to_diag for i in gp]) def jacobian_grad_hess(gamma, C,", "evectors = eig(GammaMinus + C) # log Jacobian #J =", "+ (target_linear.T.dot(target_linear) * self.randomizer_prec) - target_lin.T.dot( self.prec_opt).dot(target_lin) _P = target_linear.T.dot(target_offset)", "sorted by label ordered_opt = [] # gamma's ordered by", "used when applicable - defaults to True randomizer_scale=None): loglike =", "active_signs, soln def _solve_randomized_problem(self, perturb=None, solve_args={'tol': 1.e-15, 'min_its': 100}): #", "[(), (0,)]: raise ValueError('no target specified') prec_target = np.linalg.inv(target_cov) target_lin", "store groups as a class variable since the non-group lasso", "= ridge_term # group lasso penalty (from regreg) # use", "p4 def grad(gs): p1 = -conjugate_arg + precision.dot(gs) p2 =", "hessian hess_J = -S.dot(np.multiply(GpC_inv, GpC_inv.T).dot(S.T)) return J, grad_J, hess_J def", "A.reshape((A.shape[0],1)), b, **self.solve_args) gamma_ = _A.dot(soln) + R.dot(self.init_soln) log_jacob =", "return np.sign(soln), soln # otherwise continue as before self.observed_opt_state =", "(np.diag(self.target_cov)[m]).reshape((1, 1)) target_score_cov_uni = self.target_score_cov[m, :].reshape((1, p)) var_target = 1.", "= target_linear.T.dot(target_offset) * self.randomizer_prec _r = (1. / _prec).dot(target_lin.T.dot(self.prec_opt).dot(target_off) -", "0 if not np.amin(agroups) == 0: raise ValueError(\"First group is", "** 2) * implied_cov)/ 2. + log_jacob[0]) return np.asarray(ref_hat) def", "g'th group if pg > 1: Z = np.column_stack((ug, np.eye(pg,", "ValueError('not finding a feasible point') # make sure proposal is", "(self.observed_target[m]).reshape((1,)) target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1, 1)) target_score_cov_uni = self.target_score_cov[m, :].reshape((1, p))", ": [str], optional Sequence of strings describing the alternatives, should", "follows `selectinf.learning.core` family = self._families[m] observed_target = self.observed_target[m] l, u", "(e.g., if there is a group 2 and a group", "- self.observed_target[m]) ** 2 / var_target) logW -= logW.max() self._families.append(discrete_family(grid,", "# stop if relative decrease is small if np.fabs(current_value -", "= prec_target + (target_linear.T.dot(target_linear) * self.randomizer_prec) - target_lin.T.dot( prec_opt).dot( target_lin)", "g is group label group_mask = self.groups == g soln", "ordered_vars self.linear_part = -np.eye(self.observed_opt_state.shape[0]) self.offset = np.zeros(self.observed_opt_state.shape[0]) return active_signs, soln", "used where applicable - defaults to True perturb=None): _check_groups(groups) #", "self.active_dirs = active_dirs self.opt_offset = opt_offset self.ordered_vars = ordered_vars self.linear_part", "gradient (gamma.size vector) and hessian (gamma.size square matrix) \"\"\" if", "class approximate_grid_inference(object): def __init__(self, query, dispersion, solve_args={'tol': 1.e-12}, useIP=True): \"\"\"", "p-values and confidence intervals for targets of model including selected", "= current - step * cur_grad proposed_value = objective(proposal) if", "point') # make sure proposal is a descent count =", "intervals[:, 1], 'unbiased': unbiased_estimator}) return result, observed_info_mean, log_ref def selected_targets(self,", "like A_scaling (from lasso) offset: like b_scaling (from lasso) solve_args:", "groups are specified. Specifically, we assume that `groups` is a", "finding a feasible point') # make sure proposal is a", "_P) _S = np.linalg.inv(_prec).dot(prec_target) S[m] = _S r[m] = _r", "pivot def _approx_intervals(self, level=0.9): if not hasattr(self, \"_families\"): self._construct_families() lower,", "# vary with target # logdens_linear determines how the argument", "log_jacob[0]) return np.asarray(ref_hat) def _construct_families(self): self._construct_density() self._families = [] for", "40: raise ValueError('not finding a feasible point') # make sure", "= restricted_estimator(self.loglike, self.ordered_vars, solve_args=solve_args) _score_linear = -XE.T.dot(self._W[:, None] * X).T", "sorted_active_dirs = collections.OrderedDict(sorted(active_dirs.items())) Vs = [compute_Vg(ug) for ug in sorted_active_dirs.values()]", "return np.asarray(lower), np.asarray(upper) ### Private method def _construct_density(self): precs =", "= self.linear_part offset = self.offset if np.asarray(observed_target).shape in [(), (0,)]:", "return active_signs, soln def _solve_randomized_problem(self, perturb=None, solve_args={'tol': 1.e-15, 'min_its': 100}):", "feature groups is potentially tedious for the user and in", "solve_barrier_affine_jacobian_py(conjugate_arg, prec_opt, init_soln, linear_part, offset, self.C, self.active_dirs, useJacobian, **solve_args) final_estimator", "== False: logW = (log_ref - 0.5 * (self.stat_grid[m] -", "A Gaussian query which has information to describe implied Gaussian.", "self.offset = query.offset self.logdens_linear = query.logdens_linear self.cond_mean = query.cond_mean self.prec_opt", "target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1, 1)) prec_target = 1. / target_cov_uni target_score_cov_uni", "0 p4 = log(1. + 1. / ((con_offset - con_linear.dot(gs))", "on a grid. \"\"\" if np.asarray(observed_target).shape in [(), (0,)]: raise", "[\"twosided\", \"less\", \"greater\"]') return pivot def _approx_intervals(self, level=0.9): if not", "families follows `selectinf.learning.core` family = self._families[m] observed_target = self.observed_target[m] l,", "p2 = -con_linear.T.dot(1. / (scaling + con_offset - con_linear.dot(gs))) if", "comes from implied Gaussian # cond_mean is \"something\" times D", "= ntarget = target_cov.shape[0] _scale = 4 * np.sqrt(np.diag(inverse_info)) if", "if all groups are size 1, set up lasso penalty", "50}, perturb=None): # solve the randomized version of group lasso", "= np.column_stack((ug, np.eye(pg, pg - 1))) Q, _ = qr(Z)", "group_lasso. Also, assumes you have already run the fit method", "def summary(self, alternatives=None, parameter=None, level=0.9): \"\"\" Produce p-values and confidence", "2 hess = inv(precision + barrier_hessian(current)) return current_value, current, hess", "S.dot(GpC_inv.diagonal()) # hessian hess_J = -S.dot(np.multiply(GpC_inv, GpC_inv.T).dot(S.T)) return J, grad_J,", "- level) var_target = 1. / ((self.precs[m])[0, 0]) lower.append(l *", "cond_mean is \"something\" times D # Gamma is target_score_cov.T.dot(prec_target) num_opt", "check for no skipped groups if not np.all(np.diff(np.unique(agroups)) == 1):", "ug) in zip(gamma, active_dirs.values())] return block_diag(*[i for gp in to_diag", "function checks the user-specified group scheme and raises an exception", "to actually use the Jacobian information (in self.C) arguments conjugate_arg:", "conditional mean of optimization variables (model on _setup_implied_gaussian) cond_cov: conditional", "of target and score of randomized query. solve_args : dict,", "fill_value='extrapolate') grid = np.linspace(self.stat_grid[m].min(), self.stat_grid[m].max(), 1000) logW = (approx_fn(grid) -", "= interp1d(self.stat_grid[m], log_ref, kind='quadratic', bounds_error=False, fill_value='extrapolate') grid = np.linspace(self.stat_grid[m].min(), self.stat_grid[m].max(),", "order, start at 0, and have no gaps (e.g., if", "useJacobian=True, dispersion=None): \"\"\"Do selective_MLE for group_lasso Note: this masks the", "precision, feasible_point, con_linear, con_offset, C, active_dirs, useJacobian=True, step=1, nstep=2000, min_its=500,", "and itercount >= min_its: current = proposal current_value = proposed_value", "objective(gs): p1 = -gs.T.dot(conjugate_arg) p2 = gs.T.dot(precision).dot(gs) / 2. if", "**solve_args) initial_subgrad = -(self.loglike.smooth_objective(initial_soln, 'grad') + quad.objective(initial_soln, 'grad')) return initial_soln,", "collections import numpy as np from numpy import log from", "target_lin is \"something\" times Gamma, # where \"something\" comes from", "dispersion, solve_args={'tol': 1.e-12}, useIP=True): \"\"\" Produce p-values and confidence intervals", "norm as ndist from scipy.interpolate import interp1d import collections import", "prec_opt, init_soln, linear_part, offset, self.C, self.active_dirs, useJacobian, **solve_args) final_estimator =", "variables cond_mean: conditional mean of optimization variables (model on _setup_implied_gaussian)", "target_linear.dot(observed_target_uni)).reshape( (target_linear.shape[0],)) target_lin = -self.logdens_linear.dot(target_linear) target_off = (self.cond_mean - target_lin.dot(observed_target_uni)).reshape((target_lin.shape[0],))", "solve_args: passed on to solver level: level of confidence intervals", "__future__ import print_function from scipy.linalg import block_diag from scipy.stats import", "proposal = current - step * cur_grad proposed_value = objective(proposal)", "(from lasso) offset: like b_scaling (from lasso) solve_args: passed on", "= X.shape XE = self.XE Q = self.Q observed_target =", ": ndarray Estimated covaraince of target. target_score_cov : ndarray Estimated", "step * cur_grad if np.all(con_offset - con_linear.dot(proposal) > 0): break", "from selected_targets init_soln: (opt_state) initial (observed) value of optimization variables", "else: _P = target_linear.T.dot(self.randomizer_prec).dot(target_offset) _prec = prec_target + (target_linear.T.dot(self.randomizer_prec).dot(target_linear)) -", "val + conjugate_arg.T.dot(cond_cov).dot(conjugate_arg) / 2. result = pd.DataFrame({'MLE': final_estimator, 'SE':", "if parameter is not None: pivots = self._approx_pivots(parameter, alternatives=alternatives) else:", "kind='quadratic', bounds_error=False, fill_value='extrapolate') grid = np.linspace(self.stat_grid[m].min(), self.stat_grid[m].max(), 1000) logW =", "selected_targets target_cov_score: from selected_targets init_soln: (opt_state) initial (observed) value of", "not None: self._initial_omega = perturb if self._initial_omega is None: self._initial_omega", "from that method. Parameters ---------- observed_target: from selected_targets target_cov: from", "C, active_dirs)[0] else: p3 = 0 p4 = log(1. +", "# check for no skipped groups if not np.all(np.diff(np.unique(agroups)) ==", "= rr.identity_quadratic(self.ridge_term, 0, -self._initial_omega, 0) problem = rr.simple_problem(self.loglike, self.penalty) #", "= _beta_unpenalized # refit OLS beta with zeros self._beta_full =", "- 1))) Q, _ = qr(Z) Vg = Q[:, 1:]", "self.offset if np.asarray(observed_target).shape in [(), (0,)]: raise ValueError('no target specified')", "if len(self.selection_variable['active_groups']) == 0: return np.sign(soln), soln # otherwise continue", "problems. Sorting feature groups is potentially tedious for the user", "Note: this masks the selective_MLE inherited from query because that", "implied_prec val, soln, _ = solver(np.asarray([conjugate_arg]), np.reshape(implied_prec, (1,1)), eta.T.dot(self.init_soln), A.reshape((A.shape[0],1)),", "+ self.r[m] _cdf = family.cdf((mean[0] - self.observed_target[m]) / var_target, x=self.observed_target[m])", "self.loglike = loglike self.nfeature = self.loglike.shape[0] # ridge parameter self.ridge_term", "self.observed_target[m]) / var_target, x=self.observed_target[m]) print(\"variable completed \", m) if alternatives[m]", "** 2 / var_target) logW -= logW.max() self._families.append(discrete_family(grid, np.exp(logW))) def", "covaraince of target. target_score_cov : ndarray Estimated covariance of target", "useIP def summary(self, alternatives=None, parameter=None, level=0.9): \"\"\" Produce p-values and", "if norm(soln[group_mask]) > tol * norm(soln): # is group g", "import norm, qr, inv, eig import pandas as pd import", "target_cov self.init_soln = query.observed_opt_state self.randomizer_prec = query.randomizer_prec self.score_offset = query.observed_score_state", "var_target = 1. / ((self.precs[m])[0, 0]) log_ref = self.log_reference(observed_target_uni, target_cov_uni,", "** 2 / var_target) logW -= logW.max() self._families.append(discrete_family(self.stat_grid[m], np.exp(logW))) else:", "# is group g appreciably nonzero ordered_groups.append(g) # variables in", "group_lasso(loglike, groups, weights, ridge_term, randomizer, use_lasso, perturb) def _setup_implied_gaussian(self): _,", "number of assumptions that group_lasso makes about how groups are", "= problem.solve(quad, **solve_args) initial_subgrad = -(self.loglike.smooth_objective(initial_soln, 'grad') + quad.objective(initial_soln, 'grad'))", "are not a 1D array_like\") # check sorted if np.any(agroups[:-1]", ": ndarray Observed estimate of target. target_cov : ndarray Estimated", "= {} S = {} r = {} p =", "active_dirs, 'active_groups': active_groups} # kind of redundant with keys of", "self.cond_precision score_offset = self.observed_score_state + self.opt_offset # target_lin determines how", "Jacobian #J = log(evalues).sum() J = np.log(np.linalg.det(GammaMinus + C)) #", "from scipy.interpolate import interp1d import collections import numpy as np", "if not np.all(np.diff(np.unique(agroups)) == 1): raise ValueError(\"Some group is skipped\")", "adapted for the group_lasso. Also, assumes you have already run", "step *= 2 hess = inv(precision + barrier_hessian(current)) return current_value,", "# check array_like agroups = np.array(groups) # check dimension if", "1.5 * _scale[j], observed_target[j] + 1.5 * _scale[j], num=ngrid) else:", "# selected groups with no penalty overall = np.ones(self.nfeature, np.bool)", "current_value)) # stop if relative decrease is small if np.fabs(current_value", "- con_linear.dot(gs)) ** 2.) + 1. / ((con_offset - con_linear.dot(gs))", "return (observed_target, cov_target, crosscov_target_score, alternatives) class approximate_grid_inference(object): def __init__(self, query,", "interp1d import collections import numpy as np from numpy import", "* np.sqrt(np.diag(observed_info_mean))]).T log_ref = val + conjugate_arg.T.dot(cond_cov).dot(conjugate_arg) / 2. result", "= np.zeros((ntarget, ngrid)) for j in range(ntarget): self.stat_grid[j, :] =", "on E overall, solve_args=solve_args) beta_bar = np.zeros(self.nfeature) beta_bar[overall] = _beta_unpenalized", "self._ordered_groups = ordered_groups # exception if no groups are selected", "if feasible_point is None: feasible_point = 1. / scaling def", "self.linear_part.shape[0] cond_mean_grid = (target_lin.dot(np.atleast_1d(grid[k] - observed_target)) + self.cond_mean) #direction for", "Vs = [compute_Vg(ug) for ug in sorted_active_dirs.values()] V = block_diag(*Vs)", "(as a function of gamma vector, active directions) \"\"\" to_diag", "= np.identity(num_opt) - _A.dot(eta.T) A = self.linear_part.dot(_A).reshape((-1,)) b = self.offset-self.linear_part.dot(R).dot(self.init_soln)", "(n - 1.)) randomizer = randomization.isotropic_gaussian((p,), randomizer_scale) return group_lasso(loglike, groups,", "+ p2 + p3 + p4 def barrier_hessian(gs): # contribution", "upper.append(u * var_target + observed_target) return np.asarray(lower), np.asarray(upper) ### Private", "return Lg sorted_active_dirs = collections.OrderedDict(sorted(active_dirs.items())) Vs = [compute_Vg(ug) for ug", "XE = X[:, ordered_vars] # changed to ordered_vars Q =", "min_its: current = proposal current_value = proposed_value break current =", "= 1. / target_cov_uni target_score_cov_uni = self.target_score_cov[m, :].reshape((1, p)) target_linear", "TypeError(\"Groups are not integers\") # check starts with 0 if", "if not hasattr(self, \"_families\"): self._construct_families() lower, upper = [], []", "ValueError('value is NaN: %f, %f' % (proposed_value, current_value)) # stop", "randomizer_scale is None: randomizer_scale = np.sqrt(mean_diag) * 0.5 * np.std(Y)", "ndarray Observed estimate of target. target_cov : ndarray Estimated covaraince", "applicable - defaults to True randomizer_scale=None): loglike = rr.glm.gaussian(X, Y,", "\"\"\" # check array_like agroups = np.array(groups) # check dimension", "- 1) for (g, ug) in zip(gamma, active_dirs.values())] return block_diag(*[i", "prec else: cond_precision = self.opt_linear.T.dot(prec.dot(self.opt_linear)) cond_cov = inv(cond_precision) logdens_linear =", "inherited from query because that is not adapted for the", "ridge_term, randomizer, use_lasso, perturb) def _setup_implied_gaussian(self): _, prec = self.randomizer.cov_prec", "self.observed_target, 'pvalue': pvalues, 'lower_confidence': lower, 'upper_confidence': upper}) if not np.all(parameter", "if itercount % 4 == 0: step *= 2 hess", "= (self.observed_target[m]).reshape((1,)) target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1, 1)) target_score_cov_uni = self.target_score_cov[m, :].reshape((1,", "= prec_target + (target_linear.T.dot(target_linear) * self.randomizer_prec) - target_lin.T.dot( self.prec_opt).dot(target_lin) _P", "+ Gamma theta.hat, # target_lin is \"something\" times Gamma, #", "else: approx_fn = interp1d(self.stat_grid[m], log_ref, kind='quadratic', bounds_error=False, fill_value='extrapolate') grid =", "self._construct_families() lower, upper = [], [] for m in range(self.ntarget):", "including selected features Parameters ---------- query : `gaussian_query` A Gaussian", "regular lasso penalty if all groups are size 1 if", "= QI self.C = C U = block_diag(*[ug for ug", "pg - 1))) Q, _ = qr(Z) Vg = Q[:,", "> tol * norm(soln): # is group g appreciably nonzero", "current - step * cur_grad if np.all(con_offset - con_linear.dot(proposal) >", "solve_args=solve_args) beta_bar = np.zeros(self.nfeature) beta_bar[overall] = _beta_unpenalized # refit OLS", "= [compute_Vg(ug) for ug in sorted_active_dirs.values()] V = block_diag(*Vs) #", "= self._W = self.loglike.saturated_loss.hessian(X.dot(beta_bar)) # all 1's for LS opt_linearNoU", "current = proposal current_value = proposed_value if itercount % 4", "with zeros self._beta_full = beta_bar X, y = self.loglike.data W", "final_estimator = target_cov.dot(_prec).dot(observed_target) \\ + target_cov.dot(target_lin.T.dot(prec_opt.dot(cond_mean - soln))) + C", "raise ValueError('alternative should be in [\"twosided\", \"less\", \"greater\"]') return pivot", "2 / self._W).sum() / (n - XE.shape[1]) cov_target = self.QI", "# hessian hess_J = -S.dot(np.multiply(GpC_inv, GpC_inv.T).dot(S.T)) return J, grad_J, hess_J", "ValueError(\"First group is not 0\") # check for no skipped", "orthogonal complement is empty return Vg def compute_Lg(g): pg =", "hess_J = -S.dot(np.multiply(GpC_inv, GpC_inv.T).dot(S.T)) return J, grad_J, hess_J def _check_groups(groups):", "sure proposal is feasible count = 0 while True: count", "sure groups looks sensible # log likelihood : quadratic loss", "version of group lasso (self.initial_soln, self.initial_subgrad) = self._solve_randomized_problem(perturb=perturb, solve_args=solve_args) #", "sigma ** 2, quadratic=quadratic) n, p = X.shape mean_diag =", "target_score_cov self.target_cov = target_cov self.init_soln = query.observed_opt_state self.randomizer_prec = query.randomizer_prec", "should be values of ['twosided', 'less', 'greater'] parameter : np.array", "precision: \\\\bar{\\\\Sigma}^{-1} feasible_point: gamma's from fitting con_linear: linear part of", "p3 = - jacobian_grad_hess(gs, C, active_dirs)[0] else: p3 = 0", "'Zvalue': Z_scores, 'pvalue': pvalues, 'lower_confidence': intervals[:, 0], 'upper_confidence': intervals[:, 1],", "# check starts with 0 if not np.amin(agroups) == 0:", "Estimated covaraince of target. target_score_cov : ndarray Estimated covariance of", "linear_part: like A_scaling (from lasso) offset: like b_scaling (from lasso)", "estimate of target. target_cov : ndarray Estimated covaraince of target.", "C will be an empty array return 0, 0, 0", "features Parameters ---------- alternatives : [str], optional Sequence of strings", "np.bool) # mask of active features ordered_groups = [] #", "Vg def compute_Lg(g): pg = active_dirs[g].size Lg = self.penalty.weights[g] *", "- jacobian_grad_hess(gs, C, active_dirs)[2] else: p2 = 0 return p1", "no gaps (e.g., if there is a group 2 and", "all groups are size 1, set up lasso penalty and", "parameter -- defaults to 0. level : float Confidence level.", "np.asscalar(eta.T.dot(self.cond_cov).dot(eta)) implied_prec = 1./implied_cov _A = self.cond_cov.dot(eta) * implied_prec R", "== 'less': pivot.append(_cdf) else: raise ValueError('alternative should be in [\"twosided\",", "observed_target) upper.append(u * var_target + observed_target) return np.asarray(lower), np.asarray(upper) ###", "not None: pivots = self._approx_pivots(parameter, alternatives=alternatives) else: pivots = None", "a feasible point') # make sure proposal is a descent", "self.opt_offset = opt_offset self.ordered_vars = ordered_vars self.linear_part = -np.eye(self.observed_opt_state.shape[0]) self.offset", "solver JacobianPieces: (use self.C defined in fitting) \"\"\" self._setup_implied_gaussian() #", "len(self.active) if dispersion is None: # use Pearson's X^2 dispersion", "return 0, 0, 0 else: GammaMinus = calc_GammaMinus(gamma, active_dirs) #", "C) # summing matrix (gamma.size by C.shape[0]) S = block_diag(*[np.ones((1,", "prec cond_cov = inv(cond_precision) logdens_linear = cond_cov.dot(self.opt_linear.T) * prec else:", "---------- alternatives : [str], optional Sequence of strings describing the", "= query.observed_opt_state self.randomizer_prec = query.randomizer_prec self.score_offset = query.observed_score_state + query.opt_offset", "grid = np.linspace(self.stat_grid[m].min(), self.stat_grid[m].max(), 1000) logW = (approx_fn(grid) - 0.5", "m in range(self.ntarget): observed_target_uni = (self.observed_target[m]).reshape((1,)) target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1, 1))", "+ conjugate_arg.T.dot(cond_cov).dot(conjugate_arg) / 2. result = pd.DataFrame({'MLE': final_estimator, 'SE': np.sqrt(np.diag(observed_info_mean)),", "= target_score_cov_uni.T.dot(prec_target) target_offset = (self.score_offset - target_linear.dot(observed_target_uni)).reshape( (target_linear.shape[0],)) target_lin =", "self._setup_implied_gaussian() # Calculate useful quantities (observed_target, target_cov, target_score_cov, alternatives) =", "active_groups.append(g) active_dirs[g] = soln[group_mask] / norm(soln[group_mask]) ordered_opt.append(norm(soln[group_mask])) else: overall[group_mask] =", "Specifically, we assume that `groups` is a 1-d array_like of", "pd import regreg.api as rr from .randomization import randomization from", "of optimization variables (model on _setup_implied_gaussian) logdens_linear: (model on _setup_implied_gaussian)", "GammaMinus = calc_GammaMinus(gamma, active_dirs) # eigendecomposition #evalues, evectors = eig(GammaMinus", "implied_prec R = np.identity(num_opt) - _A.dot(eta.T) A = self.linear_part.dot(_A).reshape((-1,)) b", "self.C defined in fitting) \"\"\" self._setup_implied_gaussian() # Calculate useful quantities", "self.useIP = useIP def summary(self, alternatives=None, parameter=None, level=0.9): \"\"\" Produce", "logdens_linear = cond_cov.dot(self.opt_linear.T).dot(prec) cond_mean = -logdens_linear.dot(self.observed_score_state + self.opt_offset) self.cond_mean =", "= score_offset - target_linear.dot(observed_target) target_lin = - logdens_linear.dot(target_linear) target_off =", "(from lasso) solve_args: passed on to solver level: level of", "= np.hstack(ordered_opt) # gammas as array _beta_unpenalized = restricted_estimator(self.loglike, #", "group labels sorted by label ordered_opt = [] # gamma's", "query.cond_cov self.C = query.C self.active_dirs = query.active_dirs (observed_target, target_cov, target_score_cov,", "array_like agroups = np.array(groups) # check dimension if len(agroups.shape) !=", "break step *= 0.5 if count >= 40: raise ValueError('not", "* np.minimum(pvalues, 1 - pvalues) alpha = 1 - level", "#evalues, evectors = eig(GammaMinus + C) # log Jacobian #J", "solver from ..distributions.discrete_family import discrete_family class group_lasso(object): def __init__(self, loglike,", "non-group lasso doesn't self.groups = groups self._initial_omega = perturb #", "this uses results from that method. Parameters ---------- observed_target: from", "tol=1.e-12): \"\"\" This needs to be updated to actually use", ">= 40: raise ValueError('not finding a feasible point') # make", "useIP=True): \"\"\" Produce p-values and confidence intervals for targets of", "reference density on a grid. \"\"\" if np.asarray(observed_target).shape in [(),", "model including selected features Parameters ---------- query : `gaussian_query` A", "mean_parameter, alternatives=None): if not hasattr(self, \"_families\"): self._construct_families() if alternatives is", "is not None: self._initial_omega = perturb if self._initial_omega is None:", "intervals for targets of model including selected features Parameters ----------", "dispersion crosscov_target_score = _score_linear.dot(self.QI).T * dispersion return (observed_target, cov_target, crosscov_target_score,", "2. + log_jacob[0]) return np.asarray(ref_hat) def _construct_families(self): self._construct_density() self._families =", "lasso solver be used where applicable - defaults to True", "Calculate useful quantities (observed_target, target_cov, target_score_cov, alternatives) = self.selected_targets(dispersion) init_soln", "False: ngrid = 1000 self.stat_grid = np.zeros((ntarget, ngrid)) for j", "= family.cdf((mean[0] - self.observed_target[m]) / var_target, x=self.observed_target[m]) print(\"variable completed \",", "integers if not np.issubdtype(agroups.dtype, np.integer): raise TypeError(\"Groups are not integers\")", "+ con_offset - con_linear.dot(gs))) if useJacobian: p3 = - jacobian_grad_hess(gs,", "implied_cov = np.asscalar(eta.T.dot(self.cond_cov).dot(eta)) implied_prec = 1./implied_cov _A = self.cond_cov.dot(eta) *", "raise ValueError(\"First group is not 0\") # check for no", "as ndist from scipy.interpolate import interp1d import collections import numpy", "== np.unique(groups).size: # need to provide weights an an np.array", "groups with no penalty overall = np.ones(self.nfeature, np.bool) # mask", "eta.T.dot(self.init_soln), A.reshape((A.shape[0],1)), b, **self.solve_args) gamma_ = _A.dot(soln) + R.dot(self.init_soln) log_jacob", "# check integers if not np.issubdtype(agroups.dtype, np.integer): raise TypeError(\"Groups are", "_setup_implied_gaussian(self): _, prec = self.randomizer.cov_prec if np.asarray(prec).shape in [(), (0,)]:", "self.r[m] _cdf = family.cdf((mean[0] - self.observed_target[m]) / var_target, x=self.observed_target[m]) print(\"variable", "# gaussian randomization self.randomizer = randomizer def fit(self, solve_args={'tol': 1.e-12,", "* implied_prec val, soln, _ = solver(np.asarray([conjugate_arg]), np.reshape(implied_prec, (1,1)), eta.T.dot(self.init_soln),", "(self.observed_target[m]).reshape((1,)) target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1, 1)) prec_target = 1. / target_cov_uni", "- _P) _S = np.linalg.inv(_prec).dot(prec_target) S[m] = _S r[m] =", "# make sure proposal is feasible count = 0 while", "decomposing o eta = -self.prec_opt.dot(self.logdens_linear.dot(target_score_cov.T)) implied_mean = np.asscalar(eta.T.dot(cond_mean_grid)) implied_cov =", "\"\"\"Calculate Gamma^minus (as a function of gamma vector, active directions)", "precs self.S = S self.r = r def solve_barrier_affine_jacobian_py(conjugate_arg, precision,", "hess = solve_barrier_affine_jacobian_py(conjugate_arg, prec_opt, init_soln, linear_part, offset, self.C, self.active_dirs, useJacobian,", "np.asarray(observed_target).shape in [(), (0,)]: raise ValueError('no target specified') prec_target =", "logdens_linear: (model on _setup_implied_gaussian) linear_part: like A_scaling (from lasso) offset:", "at least one feature in group 3). This function checks", "tol * np.fabs(current_value) and itercount >= min_its: current = proposal", "as solver from ..distributions.discrete_family import discrete_family class group_lasso(object): def __init__(self,", "use_lasso, perturb) def _setup_implied_gaussian(self): _, prec = self.randomizer.cov_prec if np.asarray(prec).shape", "with no penalty overall = np.ones(self.nfeature, np.bool) # mask of", "self.cond_cov logdens_linear = self.logdens_linear linear_part = self.linear_part offset = self.offset", "label group_mask = self.groups == g soln = self.initial_soln #", "quadratic=None, ridge_term=0., perturb=None, use_lasso=True, # should lasso solver be used", "= proposed_value break current = proposal current_value = proposed_value if", "solver be used when applicable - defaults to True randomizer_scale=None):", "for the user and in future we might do this", "2. result = pd.DataFrame({'MLE': final_estimator, 'SE': np.sqrt(np.diag(observed_info_mean)), 'Zvalue': Z_scores, 'pvalue':", "an an np.array rather than a dictionary weights_np = np.array([w[1]", "* XE) QI = inv(Q) C = V.T.dot(QI).dot(L).dot(V) self.XE =", "needs to be updated to actually use the Jacobian information", "= objective(proposal) if proposed_value <= current_value: break step *= 0.5", "hessian p1 = con_linear.T.dot(np.diag(-1. / ((scaling + con_offset - con_linear.dot(gs))", "self.XE = XE self.Q = Q self.QI = QI self.C", "the gammas cond_mean = self.cond_mean cond_cov = self.cond_cov logdens_linear =", "return np.asarray(ref_hat) def _construct_families(self): self._construct_density() self._families = [] for m", "# Gamma is target_score_cov.T.dot(prec_target) num_opt = self.prec_opt.shape[0] num_con = self.linear_part.shape[0]", "p1 + p2 + p3 + p4 def barrier_hessian(gs): #", "** 2.))).dot(con_linear) if useJacobian: p2 = - jacobian_grad_hess(gs, C, active_dirs)[2]", "if dispersion is None: # use Pearson's X^2 dispersion =", "(self.initial_soln, self.initial_subgrad) = self._solve_randomized_problem(perturb=perturb, solve_args=solve_args) # initialize variables active_groups =", "if count >= 40: raise ValueError('not finding a feasible point')", "groups are size 1, set up lasso penalty and run", "- jacobian_grad_hess(gs, C, active_dirs)[1] else: p3 = 0 p4 =", "L.dot(hess.dot(L.T)) observed_info_mean = target_cov.dot(observed_info_natural.dot(target_cov)) Z_scores = final_estimator / np.sqrt(np.diag(observed_info_mean)) pvalues", "query.randomizer_prec self.score_offset = query.observed_score_state + query.opt_offset self.ntarget = ntarget =", "now we are collecting the directions and norms of the", "import print_function from scipy.linalg import block_diag from scipy.stats import norm", "to provide weights an an np.array rather than a dictionary", "L = block_diag(*Ls) # unpack the list XE = X[:,", "intervals = np.vstack([final_estimator - quantile * np.sqrt(np.diag(observed_info_mean)), final_estimator + quantile", "np.ones(self.nfeature, np.bool) # mask of active features ordered_groups = []", "result = pd.DataFrame({'MLE': final_estimator, 'SE': np.sqrt(np.diag(observed_info_mean)), 'Zvalue': Z_scores, 'pvalue': pvalues,", "= X[:, ordered_vars] # changed to ordered_vars Q = XE.T.dot(self._W[:,", ">= 20: if not (np.isnan(proposed_value) or np.isnan(current_value)): break else: raise", "1.e-12, 'min_its': 50}, perturb=None): # solve the randomized version of", "self.cond_mean cond_cov = self.cond_cov logdens_linear = self.logdens_linear linear_part = self.linear_part", "or C solver JacobianPieces: (use self.C defined in fitting) \"\"\"", "pivot = [] for m in range(self.ntarget): family = self._families[m]", "= logdens_linear return cond_mean, cond_cov, cond_precision, logdens_linear def selective_MLE(self, solve_args={'tol':", "= query.logdens_linear self.cond_mean = query.cond_mean self.prec_opt = np.linalg.inv(query.cond_cov) self.cond_cov =", "= precs self.S = S self.r = r def solve_barrier_affine_jacobian_py(conjugate_arg,", "%f, %f' % (proposed_value, current_value)) # stop if relative decrease", "selected groups with no penalty overall = np.ones(self.nfeature, np.bool) #", "1) if randomizer_scale is None: randomizer_scale = np.sqrt(mean_diag) * 0.5", "self.prec_opt = np.linalg.inv(query.cond_cov) self.cond_cov = query.cond_cov self.C = query.C self.active_dirs", "family = self._families[m] var_target = 1. / ((self.precs[m])[0, 0]) mean", "L.dot(target_lin) - L.dot(hess.dot(L.T)) observed_info_mean = target_cov.dot(observed_info_natural.dot(target_cov)) Z_scores = final_estimator /", "def __init__(self, query, dispersion, solve_args={'tol': 1.e-12}, useIP=True): \"\"\" Produce p-values", "ndist.ppf(1 - alpha / 2.) intervals = np.vstack([final_estimator - quantile", "1)) for ug in active_dirs.values()]) # gradient grad_J = S.dot(GpC_inv.diagonal())", "self.active = active def compute_Vg(ug): pg = ug.size # figure", "column else: Vg = np.zeros((1, 0)) # if the group", "- XE.shape[1]) cov_target = self.QI * dispersion crosscov_target_score = _score_linear.dot(self.QI).T", "level : float Confidence level. \"\"\" if parameter is not", "and confidence intervals for targets of model including selected features", "np.sqrt(n - 1) if randomizer_scale is None: randomizer_scale = np.sqrt(mean_diag)", "the directions and norms of the active groups for g", "False: logW = (log_ref - 0.5 * (self.stat_grid[m] - self.observed_target[m])", "= -opt_linearNoU.dot(_beta_unpenalized) self.observed_score_state[~overall] += self.loglike.smooth_objective(beta_bar, 'grad')[~overall] active_signs = np.sign(self.initial_soln) active", "is small if np.fabs(current_value - proposed_value) < tol * np.fabs(current_value)", "feasible_point = 1. / scaling def objective(gs): p1 = -gs.T.dot(conjugate_arg)", "p4 def barrier_hessian(gs): # contribution of barrier and jacobian to", "target_cov.dot(target_lin.T.dot(prec_opt.dot(cond_mean - soln))) + C unbiased_estimator = target_cov.dot(_prec).dot(observed_target) + target_cov.dot(", "target_linear.T.dot(target_offset) * self.randomizer_prec _prec = prec_target + (target_linear.T.dot(target_linear) * self.randomizer_prec)", "/ ((self.precs[m])[0, 0]) mean = self.S[m].dot(mean_parameter[m].reshape((1,))) + self.r[m] _cdf =", "cond_mean, cond_cov, cond_precision, logdens_linear def selective_MLE(self, solve_args={'tol': 1.e-12}, level=0.9, useJacobian=True,", "active_dirs)[0] else: p3 = 0 p4 = log(1. + 1.", "inv(precision + barrier_hessian(current)) return current_value, current, hess # Jacobian calculations", "ordered_vars Q = XE.T.dot(self._W[:, None] * XE) QI = inv(Q)", "self.loglike.data W = self._W = self.loglike.saturated_loss.hessian(X.dot(beta_bar)) # all 1's for", "np.asarray(lower), np.asarray(upper) ### Private method def _construct_density(self): precs = {}", "upper = self._approx_intervals(level=level) result = pd.DataFrame({'target': self.observed_target, 'pvalue': pvalues, 'lower_confidence':", "class variable since the non-group lasso doesn't self.groups = groups", "ndarray Estimated covaraince of target. target_score_cov : ndarray Estimated covariance", "E overall, solve_args=solve_args) beta_bar = np.zeros(self.nfeature) beta_bar[overall] = _beta_unpenalized #", "@staticmethod def gaussian(X, Y, groups, weights, sigma=1., quadratic=None, ridge_term=0., perturb=None,", "np.fabs(current_value) and itercount >= min_its: current = proposal current_value =", "soln, hess = solve_barrier_affine_jacobian_py(conjugate_arg, prec_opt, init_soln, linear_part, offset, self.C, self.active_dirs,", "of assumptions that group_lasso makes about how groups are specified.", "implied_mean * implied_prec val, soln, _ = solver(np.asarray([conjugate_arg]), np.reshape(implied_prec, (1,1)),", "if pg > 1: Z = np.column_stack((ug, np.eye(pg, pg -", "perturb) def _setup_implied_gaussian(self): _, prec = self.randomizer.cov_prec if np.asarray(prec).shape in", "to solver. \"\"\" self.solve_args = solve_args result, inverse_info = query.selective_MLE(dispersion=dispersion)[:2]", "target_cov_score: from selected_targets init_soln: (opt_state) initial (observed) value of optimization", "dispersion=None, solve_args={'tol': 1.e-12, 'min_its': 50}): X, y = self.loglike.data n,", "J = np.log(np.linalg.det(GammaMinus + C)) # inverse #GpC_inv = evectors.dot(np.diag(1", "+ 1. / ((con_offset - con_linear.dot(gs)) / scaling)).sum() return p1", "lower, 'upper_confidence': upper}) if not np.all(parameter == 0): result.insert(4, 'pivot',", "= target_linear.T.dot(target_offset) * self.randomizer_prec _prec = prec_target + (target_linear.T.dot(target_linear) *", "to True randomizer_scale=None): loglike = rr.glm.gaussian(X, Y, coef=1. / sigma", "for parameter -- defaults to 0. level : float Confidence", "target specified') prec_target = np.linalg.inv(target_cov) target_lin = - self.logdens_linear.dot(target_score_cov.T.dot(prec_target)) ref_hat", "gamma vector, active directions) \"\"\" to_diag = [[g] * (ug.size", "if alternatives[m] == 'twosided': pivot.append(2 * min(_cdf, 1 - _cdf))", "list XE = X[:, ordered_vars] # changed to ordered_vars Q", "times Gamma, # where \"something\" comes from implied Gaussian #", "np.zeros((ntarget, ngrid)) for j in range(ntarget): self.stat_grid[j, :] = np.linspace(observed_target[j]", "barrier function C: V^T Q^{-1} \\\\Lambda V active_dirs: \"\"\" scaling", "_scale[j], observed_target[j] + 1.5 * _scale[j], num=ngrid) else: ngrid =", "variables (model on _setup_implied_gaussian) logdens_linear: (model on _setup_implied_gaussian) linear_part: like", ".randomization import randomization from ..base import restricted_estimator from ..algorithms.barrier_affine import", "np.exp(logW))) def _approx_pivots(self, mean_parameter, alternatives=None): if not hasattr(self, \"_families\"): self._construct_families()", "completed \", m) if alternatives[m] == 'twosided': pivot.append(2 * min(_cdf,", "/ ((scaling + con_offset - con_linear.dot(gs)) ** 2.) + 1.", "gamma's ordered by group labels ordered_vars = [] # indices", "Produce p-values and confidence intervals for targets of model including", "problem.solve(quad, **solve_args) initial_subgrad = -(self.loglike.smooth_objective(initial_soln, 'grad') + quad.objective(initial_soln, 'grad')) return", "con_linear.dot(proposal) > 0): break step *= 0.5 if count >=", "np.zeros(self.observed_opt_state.shape[0]) return active_signs, soln def _solve_randomized_problem(self, perturb=None, solve_args={'tol': 1.e-15, 'min_its':", "'SE': np.sqrt(np.diag(observed_info_mean)), 'Zvalue': Z_scores, 'pvalue': pvalues, 'lower_confidence': intervals[:, 0], 'upper_confidence':", "There are a number of assumptions that group_lasso makes about", "# dictionary: keys are group labels, values are unit-norm coefficients", "cond_precision = self.opt_linear.T.dot(prec.dot(self.opt_linear)) cond_cov = inv(cond_precision) logdens_linear = cond_cov.dot(self.opt_linear.T).dot(prec) cond_mean", "randomizer, use_lasso=True, # should lasso solver be used where applicable", "cond_mean self.cond_cov = cond_cov self.cond_precision = cond_precision self.logdens_linear = logdens_linear", "implied_mean = np.asscalar(eta.T.dot(cond_mean_grid)) implied_cov = np.asscalar(eta.T.dot(self.cond_cov).dot(eta)) implied_prec = 1./implied_cov _A", "density # depends on the score, not how the mean", "active_signs = np.sign(self.initial_soln) active = np.flatnonzero(active_signs) self.active = active def", "active_dirs self.opt_offset = opt_offset self.ordered_vars = ordered_vars self.linear_part = -np.eye(self.observed_opt_state.shape[0])", "Z = np.column_stack((ug, np.eye(pg, pg - 1))) Q, _ =", "result = pd.DataFrame({'target': self.observed_target, 'pvalue': pvalues, 'lower_confidence': lower, 'upper_confidence': upper})", "self.randomizer_prec = self.randomizer.cov_prec # now we are collecting the directions", "the fit method since this uses results from that method.", "of redundant with keys of active_dirs self._ordered_groups = ordered_groups #", "ref_hat = [] for k in range(grid.shape[0]): # in the", "p2 + p3 + p4 def grad(gs): p1 = -conjugate_arg", "since this uses results from that method. Parameters ---------- observed_target:", "of target. target_cov : ndarray Estimated covaraince of target. target_score_cov", "active_dirs[g] = soln[group_mask] / norm(soln[group_mask]) ordered_opt.append(norm(soln[group_mask])) else: overall[group_mask] = False", "raises an exception if it finds any problems. Sorting feature", "self._beta_full = beta_bar X, y = self.loglike.data W = self._W", "\"\"\"Do selective_MLE for group_lasso Note: this masks the selective_MLE inherited", "prec_opt = self.cond_precision score_offset = self.observed_score_state + self.opt_offset # target_lin", "if it finds any problems. Sorting feature groups is potentially", "approx_fn = interp1d(self.stat_grid[m], log_ref, kind='quadratic', bounds_error=False, fill_value='extrapolate') grid = np.linspace(self.stat_grid[m].min(),", "def _construct_families(self): self._construct_density() self._families = [] for m in range(self.ntarget):", "return J, grad_J, hess_J def _check_groups(groups): \"\"\"Make sure that the", "from __future__ import print_function from scipy.linalg import block_diag from scipy.stats", "opt_linearNoU[var, i] += self.ridge_term opt_offset = self.initial_subgrad self.observed_score_state = -opt_linearNoU.dot(_beta_unpenalized)", "count >= 20: if not (np.isnan(proposed_value) or np.isnan(current_value)): break else:", "be an empty array return 0, 0, 0 else: GammaMinus", "self.cond_cov = query.cond_cov self.C = query.C self.active_dirs = query.active_dirs (observed_target,", "if randomizer_scale is None: randomizer_scale = np.sqrt(mean_diag) * 0.5 *", "calculations def calc_GammaMinus(gamma, active_dirs): \"\"\"Calculate Gamma^minus (as a function of", "alternatives) = self.selected_targets(dispersion) init_soln = self.observed_opt_state # just the gammas", "0): break step *= 0.5 if count >= 40: raise", "is not adapted for the group_lasso. Also, assumes you have", "alternatives[m] == 'less': pivot.append(_cdf) else: raise ValueError('alternative should be in", "+ barrier_hessian(current)) return current_value, current, hess # Jacobian calculations def", "\\\\bar{\\\\Sigma}^{-1} feasible_point: gamma's from fitting con_linear: linear part of affine", "active_dirs)[2] else: p2 = 0 return p1 + p2 current", "lower, upper = self._approx_intervals(level=level) result = pd.DataFrame({'target': self.observed_target, 'pvalue': pvalues,", "ntarget = target_cov.shape[0] _scale = 4 * np.sqrt(np.diag(inverse_info)) if useIP", "target_lin.T.dot( self.prec_opt).dot(target_lin) _P = target_linear.T.dot(target_offset) * self.randomizer_prec _r = (1.", "self.ordered_vars = ordered_vars self.linear_part = -np.eye(self.observed_opt_state.shape[0]) self.offset = np.zeros(self.observed_opt_state.shape[0]) return", "self.ridge_term = ridge_term # group lasso penalty (from regreg) #", "active directions) \"\"\" to_diag = [[g] * (ug.size - 1)", "zeros self._beta_full = beta_bar X, y = self.loglike.data W =", "* prec cond_cov = inv(cond_precision) logdens_linear = cond_cov.dot(self.opt_linear.T) * prec", "if np.all(con_offset - con_linear.dot(proposal) > 0): break step *= 0.5", "+ self.cond_mean) #direction for decomposing o eta = -self.prec_opt.dot(self.logdens_linear.dot(target_score_cov.T)) implied_mean", "family = self._families[m] observed_target = self.observed_target[m] l, u = family.equal_tailed_interval(observed_target,", "cond_cov = inv(cond_precision) logdens_linear = cond_cov.dot(self.opt_linear.T).dot(prec) cond_mean = -logdens_linear.dot(self.observed_score_state +", "query.opt_offset self.ntarget = ntarget = target_cov.shape[0] _scale = 4 *", "logW.max() self._families.append(discrete_family(self.stat_grid[m], np.exp(logW))) else: approx_fn = interp1d(self.stat_grid[m], log_ref, kind='quadratic', bounds_error=False,", "the Jacobian information (in self.C) arguments conjugate_arg: \\\\bar{\\\\Sigma}^{-1} \\bar{\\\\mu} precision:", "implied Gaussian # cond_mean is \"something\" times D # Gamma", "for m in range(self.ntarget): observed_target_uni = (self.observed_target[m]).reshape((1,)) target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1,", "np.log(np.linalg.det(GammaMinus + C)) # inverse #GpC_inv = evectors.dot(np.diag(1 / evalues).dot(evectors.T))", "from numpy import log from numpy.linalg import norm, qr, inv,", "parameter : np.array Hypothesized value for parameter -- defaults to", "grad_J = S.dot(GpC_inv.diagonal()) # hessian hess_J = -S.dot(np.multiply(GpC_inv, GpC_inv.T).dot(S.T)) return", "upper = [], [] for m in range(self.ntarget): # construction", "gamma_ = _A.dot(soln) + R.dot(self.init_soln) log_jacob = jacobian_grad_hess(gamma_, self.C, self.active_dirs)", "self.stat_grid = np.zeros((ntarget, ngrid)) for j in range(ntarget): self.stat_grid[j, :]", "/ var_target) logW -= logW.max() self._families.append(discrete_family(self.stat_grid[m], np.exp(logW))) else: approx_fn =", "the randomized version of group lasso (self.initial_soln, self.initial_subgrad) = self._solve_randomized_problem(perturb=perturb,", "# check sorted if np.any(agroups[:-1] > agroups[1:]) < 0: raise", "small if np.fabs(current_value - proposed_value) < tol * np.fabs(current_value) and", "num_con = self.linear_part.shape[0] cond_mean_grid = (target_lin.dot(np.atleast_1d(grid[k] - observed_target)) + self.cond_mean)", "times D # Gamma is target_score_cov.T.dot(prec_target) num_opt = self.prec_opt.shape[0] num_con", "the user-specified group scheme and raises an exception if it", "= target_cov.shape[0] _scale = 4 * np.sqrt(np.diag(inverse_info)) if useIP ==", "from query because that is not adapted for the group_lasso.", "1)) target_score_cov_uni = self.target_score_cov[m, :].reshape((1, p)) var_target = 1. /", "self.target_cov = target_cov self.init_soln = query.observed_opt_state self.randomizer_prec = query.randomizer_prec self.score_offset", "a group 2 and a group 4, there must also", "not np.all(parameter == 0): result.insert(4, 'pivot', pivots) result.insert(5, 'parameter', parameter)", "* _scale[j], num=ngrid) self.opt_linear = query.opt_linear self.useIP = useIP def", "- target_lin.T.dot(prec_opt).dot(target_off)) L = target_lin.T.dot(prec_opt) observed_info_natural = _prec + L.dot(target_lin)", "self.QI * dispersion crosscov_target_score = _score_linear.dot(self.QI).T * dispersion return (observed_target,", "randomizer, use_lasso, perturb) def _setup_implied_gaussian(self): _, prec = self.randomizer.cov_prec if", "else: overall[group_mask] = False self.selection_variable = {'directions': active_dirs, 'active_groups': active_groups}", "potentially tedious for the user and in future we might", "intervals from families follows `selectinf.learning.core` family = self._families[m] observed_target =", "range(ntarget): self.stat_grid[j, :] = np.linspace(observed_target[j] - 1.5 * _scale[j], observed_target[j]", "self.log_reference(observed_target_uni, target_cov_uni, target_score_cov_uni, self.stat_grid[m]) if self.useIP == False: logW =", "np.reshape(implied_prec, (1,1)), eta.T.dot(self.init_soln), A.reshape((A.shape[0],1)), b, **self.solve_args) gamma_ = _A.dot(soln) +", "else: active_groups.append(g) active_dirs[g] = soln[group_mask] / norm(soln[group_mask]) ordered_opt.append(norm(soln[group_mask])) else: overall[group_mask]", "in [(), (0,)]: cond_precision = self.opt_linear.T.dot(self.opt_linear) * prec cond_cov =", "descent count = 0 while True: count += 1 proposal", "describe implied Gaussian. observed_target : ndarray Observed estimate of target.", "block_diag(*[ug for ug in sorted_active_dirs.values()]).T self.opt_linear = opt_linearNoU.dot(U) self.active_dirs =", "redundant with keys of active_dirs self._ordered_groups = ordered_groups # exception", "= self._approx_pivots(parameter, alternatives=alternatives) else: pivots = None pvalues = self._approx_pivots(np.zeros_like(self.observed_target),", "1.e-20 _, self.randomizer_prec = self.randomizer.cov_prec # now we are collecting", "alternatives is None: alternatives = ['twosided'] * self.ntarget pivot =", "= S.dot(GpC_inv.diagonal()) # hessian hess_J = -S.dot(np.multiply(GpC_inv, GpC_inv.T).dot(S.T)) return J,", "self.cond_cov = cond_cov self.cond_precision = cond_precision self.logdens_linear = logdens_linear return", "logdens_linear.dot(target_linear) target_off = cond_mean - target_lin.dot(observed_target) if np.asarray(self.randomizer_prec).shape in [(),", "self.loglike.smooth_objective(beta_bar, 'grad')[~overall] active_signs = np.sign(self.initial_soln) active = np.flatnonzero(active_signs) self.active =", "(model on _setup_implied_gaussian) linear_part: like A_scaling (from lasso) offset: like", "np.identity(num_opt) - _A.dot(eta.T) A = self.linear_part.dot(_A).reshape((-1,)) b = self.offset-self.linear_part.dot(R).dot(self.init_soln) conjugate_arg", "of integers that are sorted in increasing order, start at", "first column else: Vg = np.zeros((1, 0)) # if the", "'grad') + quad.objective(initial_soln, 'grad')) return initial_soln, initial_subgrad @staticmethod def gaussian(X,", "= np.array([w[1] for w in sorted(weights.items())]) self.penalty = rr.weighted_l1norm(weights=weights_np, lagrange=1.)", "to ordered_vars Q = XE.T.dot(self._W[:, None] * XE) QI =", "implied Gaussian. observed_target : ndarray Observed estimate of target. target_cov", "an np.array rather than a dictionary weights_np = np.array([w[1] for", "range(self.ntarget): family = self._families[m] var_target = 1. / ((self.precs[m])[0, 0])", "C.shape == (0, 0): # when all groups are size", "** 2.) + 1. / ((con_offset - con_linear.dot(gs)) ** 2.))).dot(con_linear)", "/ self._W).sum() / (n - XE.shape[1]) cov_target = self.QI *", "def barrier_hessian(gs): # contribution of barrier and jacobian to hessian", "optional Arguments passed to solver. \"\"\" self.solve_args = solve_args result,", "grid. \"\"\" if np.asarray(observed_target).shape in [(), (0,)]: raise ValueError('no target", "((self.precs[m])[0, 0]) lower.append(l * var_target + observed_target) upper.append(u * var_target", "target_offset = (self.score_offset - target_linear.dot(observed_target_uni)).reshape( (target_linear.shape[0],)) target_lin = -self.logdens_linear.dot(target_linear) target_off", "self.nfeature = self.loglike.shape[0] # ridge parameter self.ridge_term = ridge_term #", "selected_targets(self, dispersion=None, solve_args={'tol': 1.e-12, 'min_its': 50}): X, y = self.loglike.data", "% (proposed_value, current_value)) # stop if relative decrease is small", "logdens_linear determines how the argument of the optimization density #", "= 1. / (con_offset - con_linear.dot(gs)) return p1 + p2", "2 and a group 4, there must also be at", "-self._initial_omega, 0) problem = rr.simple_problem(self.loglike, self.penalty) # if all groups", "# initialize variables active_groups = [] # active group labels", "self.logdens_linear = query.logdens_linear self.cond_mean = query.cond_mean self.prec_opt = np.linalg.inv(query.cond_cov) self.cond_cov", "sure proposal is a descent count = 0 while True:", "opt_linearNoU = np.dot(X.T, X[:, ordered_vars] * W[:, np.newaxis]) for i,", "pg > 1: Z = np.column_stack((ug, np.eye(pg, pg - 1)))", "pandas as pd import regreg.api as rr from .randomization import", "m in range(self.ntarget): # construction of intervals from families follows", "= cond_mean self.cond_cov = cond_cov self.cond_precision = cond_precision self.logdens_linear =", "as pd import regreg.api as rr from .randomization import randomization", "= ug.size # figure out size of g'th group if", "count >= 40: raise ValueError('not finding a feasible point') #", "Jacobian information (in self.C) arguments conjugate_arg: \\\\bar{\\\\Sigma}^{-1} \\bar{\\\\mu} precision: \\\\bar{\\\\Sigma}^{-1}", "current_value, current, hess # Jacobian calculations def calc_GammaMinus(gamma, active_dirs): \"\"\"Calculate", "ordered_groups = [] # active group labels sorted by label", "self.precs = precs self.S = S self.r = r def", "hess # Jacobian calculations def calc_GammaMinus(gamma, active_dirs): \"\"\"Calculate Gamma^minus (as", "in range(self.ntarget): # construction of intervals from families follows `selectinf.learning.core`", "self.target_score_cov[m, :].reshape((1, p)) target_linear = target_score_cov_uni.T.dot(prec_target) target_offset = (self.score_offset -", "lasso penalty (from regreg) # use regular lasso penalty if", "self.initial_subgrad self.observed_score_state = -opt_linearNoU.dot(_beta_unpenalized) self.observed_score_state[~overall] += self.loglike.smooth_objective(beta_bar, 'grad')[~overall] active_signs =", "return Vg def compute_Lg(g): pg = active_dirs[g].size Lg = self.penalty.weights[g]", "perturb is not None: self._initial_omega = perturb if self._initial_omega is", "self.selection_variable = {'directions': active_dirs, 'active_groups': active_groups} # kind of redundant", "qr, inv, eig import pandas as pd import regreg.api as", "for j in range(ntarget): self.stat_grid[j, :] = np.linspace(observed_target[j] - 1.5", "_approx_intervals(self, level=0.9): if not hasattr(self, \"_families\"): self._construct_families() lower, upper =", "quantile = ndist.ppf(1 - alpha / 2.) intervals = np.vstack([final_estimator", "# drop the first column else: Vg = np.zeros((1, 0))", "dimension if len(agroups.shape) != 1: raise ValueError(\"Groups are not a", "and a group 4, there must also be at least", "V^T Q^{-1} \\\\Lambda V active_dirs: \"\"\" scaling = np.sqrt(np.diag(con_linear.dot(precision).dot(con_linear.T))) if", "lasso solver... (see existing code)... initial_soln = problem.solve(quad, **solve_args) initial_subgrad", "- target_linear.dot(observed_target) target_lin = - logdens_linear.dot(target_linear) target_off = cond_mean -", "def _approx_intervals(self, level=0.9): if not hasattr(self, \"_families\"): self._construct_families() lower, upper", "out size of g'th group if pg > 1: Z", "Jacobian calculations def calc_GammaMinus(gamma, active_dirs): \"\"\"Calculate Gamma^minus (as a function", "if not np.amin(agroups) == 0: raise ValueError(\"First group is not", "* (grid - self.observed_target[m]) ** 2 / var_target) logW -=", "\"\"\" if np.asarray(observed_target).shape in [(), (0,)]: raise ValueError('no target specified')", "(gamma.size square matrix) \"\"\" if C.shape == (0, 0): #", "self.cond_mean = cond_mean self.cond_cov = cond_cov self.cond_precision = cond_precision self.logdens_linear", "var_target) logW -= logW.max() self._families.append(discrete_family(self.stat_grid[m], np.exp(logW))) else: approx_fn = interp1d(self.stat_grid[m],", "X.shape mean_diag = np.mean((X ** 2).sum(0)) if ridge_term is None:", "observed_target: from selected_targets target_cov: from selected_targets target_cov_score: from selected_targets init_soln:", "selected_targets init_soln: (opt_state) initial (observed) value of optimization variables cond_mean:", "np.newaxis]) for i, var in enumerate(ordered_vars): opt_linearNoU[var, i] += self.ridge_term", "in to_diag for i in gp]) def jacobian_grad_hess(gamma, C, active_dirs):", "empty array return 0, 0, 0 else: GammaMinus = calc_GammaMinus(gamma,", "of confidence intervals useC: whether to use python or C", "sorted(weights.items())]) self.penalty = rr.weighted_l1norm(weights=weights_np, lagrange=1.) else: self.penalty = rr.group_lasso(groups, weights=weights,", "is \"something\" times D # Gamma is target_score_cov.T.dot(prec_target) num_opt =", "# construction of intervals from families follows `selectinf.learning.core` family =", "{} p = self.target_score_cov.shape[1] for m in range(self.ntarget): observed_target_uni =", "used for barrier function con_offset: offset part of affine constraint", "ordered_vars] * W[:, np.newaxis]) for i, var in enumerate(ordered_vars): opt_linearNoU[var,", "np.linalg.inv(target_cov) target_lin = - self.logdens_linear.dot(target_score_cov.T.dot(prec_target)) ref_hat = [] for k", "is None: # use Pearson's X^2 dispersion = ((y -", "if alternatives is None: alternatives = ['twosided'] * self.ntarget pivot", "if useJacobian: p3 = - jacobian_grad_hess(gs, C, active_dirs)[1] else: p3", "= self.S[m].dot(mean_parameter[m].reshape((1,))) + self.r[m] _cdf = family.cdf((mean[0] - self.observed_target[m]) /", "that method. Parameters ---------- observed_target: from selected_targets target_cov: from selected_targets", "query.observed_opt_state self.randomizer_prec = query.randomizer_prec self.score_offset = query.observed_score_state + query.opt_offset self.ntarget", "if useJacobian: p3 = - jacobian_grad_hess(gs, C, active_dirs)[0] else: p3", "/ (n - XE.shape[1]) cov_target = self.QI * dispersion crosscov_target_score", "if not hasattr(self, \"_families\"): self._construct_families() if alternatives is None: alternatives", "describing the alternatives, should be values of ['twosided', 'less', 'greater']", "active_dirs)[1] else: p3 = 0 p4 = 1. / (con_offset", "= _A.dot(soln) + R.dot(self.init_soln) log_jacob = jacobian_grad_hess(gamma_, self.C, self.active_dirs) ref_hat.append(-val", "ngrid)) for j in range(ntarget): self.stat_grid[j, :] = np.linspace(observed_target[j] -", "for m in range(self.ntarget): # construction of intervals from families", "argument of the optimization density # depends on the score,", ": np.array Hypothesized value for parameter -- defaults to 0.", "= inv(precision + barrier_hessian(current)) return current_value, current, hess # Jacobian", "for m in range(self.ntarget): family = self._families[m] var_target = 1.", "to_diag for i in gp]) def jacobian_grad_hess(gamma, C, active_dirs): \"\"\"", "since the non-group lasso doesn't self.groups = groups self._initial_omega =", "log Jacobian #J = log(evalues).sum() J = np.log(np.linalg.det(GammaMinus + C))", "target_cov, target_score_cov, grid): \"\"\" Approximate the log of the reference", "/ sigma ** 2, quadratic=quadratic) n, p = X.shape mean_diag", "log_ref def selected_targets(self, dispersion=None, solve_args={'tol': 1.e-12, 'min_its': 50}): X, y", "information to describe implied Gaussian. observed_target : ndarray Observed estimate", "we assume that `groups` is a 1-d array_like of integers", ": ndarray Estimated covariance of target and score of randomized", "feature in group 3). This function checks the user-specified group", "labels tol = 1.e-20 _, self.randomizer_prec = self.randomizer.cov_prec # now", "= [] # indices \"ordered\" by sorting group labels tol", "_S = np.linalg.inv(_prec).dot(prec_target) S[m] = _S r[m] = _r precs[m]", "proposed_value) < tol * np.fabs(current_value) and itercount >= min_its: current", "# in the usual D = N + Gamma theta.hat,", "log_ref = self.log_reference(observed_target_uni, target_cov_uni, target_score_cov_uni, self.stat_grid[m]) if self.useIP == False:", "groups looks sensible # log likelihood : quadratic loss self.loglike", "g soln = self.initial_soln # do not need to keep", "(scalar), gradient (gamma.size vector) and hessian (gamma.size square matrix) \"\"\"", "level of confidence intervals useC: whether to use python or", "= randomizer def fit(self, solve_args={'tol': 1.e-12, 'min_its': 50}, perturb=None): #", "and hessian (gamma.size square matrix) \"\"\" if C.shape == (0,", "no groups are selected if len(self.selection_variable['active_groups']) == 0: return np.sign(soln),", "dispersion = ((y - self.loglike.saturated_loss.mean_function( XE.dot(observed_target))) ** 2 / self._W).sum()", "by label ordered_opt = [] # gamma's ordered by group", "0 else: GammaMinus = calc_GammaMinus(gamma, active_dirs) # eigendecomposition #evalues, evectors", "if np.asarray(self.randomizer_prec).shape in [(), (0,)]: _P = target_linear.T.dot(target_offset) * self.randomizer_prec", "D = N + Gamma theta.hat, # target_lin is \"something\"", "likelihood : quadratic loss self.loglike = loglike self.nfeature = self.loglike.shape[0]", "# gammas as array _beta_unpenalized = restricted_estimator(self.loglike, # refit OLS", "> 1: Z = np.column_stack((ug, np.eye(pg, pg - 1))) Q,", "of intervals from families follows `selectinf.learning.core` family = self._families[m] observed_target", "A = self.linear_part.dot(_A).reshape((-1,)) b = self.offset-self.linear_part.dot(R).dot(self.init_soln) conjugate_arg = implied_mean *", "self.linear_part.dot(_A).reshape((-1,)) b = self.offset-self.linear_part.dot(R).dot(self.init_soln) conjugate_arg = implied_mean * implied_prec val,", "assumptions that group_lasso makes about how groups are specified. Specifically,", "just the gammas cond_mean = self.cond_mean cond_cov = self.cond_cov logdens_linear", "# take a new perturbation if supplied if perturb is", "assume that `groups` is a 1-d array_like of integers that", "1. / ((self.precs[m])[0, 0]) log_ref = self.log_reference(observed_target_uni, target_cov_uni, target_score_cov_uni, self.stat_grid[m])", "+ p3 + p4 def barrier_hessian(gs): # contribution of barrier", "break step *= 0.5 if count >= 20: if not", "make sure proposal is feasible count = 0 while True:", "size one, C will be an empty array return 0,", "appreciably nonzero ordered_groups.append(g) # variables in active group ordered_vars.extend(np.flatnonzero(group_mask)) if", "as array _beta_unpenalized = restricted_estimator(self.loglike, # refit OLS on E", "p4 = 1. / (con_offset - con_linear.dot(gs)) return p1 +", "4 == 0: step *= 2 hess = inv(precision +", "= Q[:, 1:] # drop the first column else: Vg", "dictionary weights_np = np.array([w[1] for w in sorted(weights.items())]) self.penalty =", "target_lin.dot(observed_target) if np.asarray(self.randomizer_prec).shape in [(), (0,)]: _P = target_linear.T.dot(target_offset) *", "np.vstack([final_estimator - quantile * np.sqrt(np.diag(observed_info_mean)), final_estimator + quantile * np.sqrt(np.diag(observed_info_mean))]).T", "= ['twosided'] * self.ntarget pivot = [] for m in", "/ scaling def objective(gs): p1 = -gs.T.dot(conjugate_arg) p2 = gs.T.dot(precision).dot(gs)", "+ p3 + p4 def grad(gs): p1 = -conjugate_arg +", "observed_target = self.observed_target[m] l, u = family.equal_tailed_interval(observed_target, alpha=1 - level)", "import log from numpy.linalg import norm, qr, inv, eig import", "= self._solve_randomized_problem(perturb=perturb, solve_args=solve_args) # initialize variables active_groups = [] #", "cond_cov self.cond_precision = cond_precision self.logdens_linear = logdens_linear return cond_mean, cond_cov,", "norm(soln[group_mask]) > tol * norm(soln): # is group g appreciably", "[(), (0,)]: _P = target_linear.T.dot(target_offset) * self.randomizer_prec _prec = prec_target", "# unpack the list XE = X[:, ordered_vars] # changed", "_r precs[m] = _prec self.precs = precs self.S = S", "1. / scaling def objective(gs): p1 = -gs.T.dot(conjugate_arg) p2 =", ": dict, optional Arguments passed to solver. \"\"\" self.solve_args =", "(model on _setup_implied_gaussian) logdens_linear: (model on _setup_implied_gaussian) linear_part: like A_scaling", "active_dirs.values())] return block_diag(*[i for gp in to_diag for i in", "unit-norm coefficients unpenalized = [] # selected groups with no", "dispersion is None: # use Pearson's X^2 dispersion = ((y", "print(\"variable completed \", m) if alternatives[m] == 'twosided': pivot.append(2 *", "groups are ok There are a number of assumptions that", "the selective_MLE inherited from query because that is not adapted", "for k in range(grid.shape[0]): # in the usual D =", "observed_target)) + self.cond_mean) #direction for decomposing o eta = -self.prec_opt.dot(self.logdens_linear.dot(target_score_cov.T))", "np.sqrt(mean_diag) * 0.5 * np.std(Y) * np.sqrt(n / (n -", "alpha / 2.) intervals = np.vstack([final_estimator - quantile * np.sqrt(np.diag(observed_info_mean)),", "initial_soln = problem.solve(quad, **solve_args) initial_subgrad = -(self.loglike.smooth_objective(initial_soln, 'grad') + quad.objective(initial_soln,", "rather than a dictionary weights_np = np.array([w[1] for w in", "fit(self, solve_args={'tol': 1.e-12, 'min_its': 50}, perturb=None): # solve the randomized", "proposed_value if itercount % 4 == 0: step *= 2", "group is not 0\") # check for no skipped groups", "return block_diag(*[i for gp in to_diag for i in gp])", "query which has information to describe implied Gaussian. observed_target :", "self.penalty = rr.weighted_l1norm(weights=weights_np, lagrange=1.) else: self.penalty = rr.group_lasso(groups, weights=weights, lagrange=1.)", "target_score_cov, grid): \"\"\" Approximate the log of the reference density", "= [] # active group labels active_dirs = {} #", "self.penalty.weights[g] == 0: unpenalized.append(g) else: active_groups.append(g) active_dirs[g] = soln[group_mask] /", "targets of model including selected features Parameters ---------- query :", "range(grid.shape[0]): # in the usual D = N + Gamma", "in sorted_active_dirs.values()] V = block_diag(*Vs) # unpack the list Ls", "- soln))) + C unbiased_estimator = target_cov.dot(_prec).dot(observed_target) + target_cov.dot( _P", "target_score_cov, alternatives) = query.selected_targets(dispersion) self.observed_target = observed_target self.target_score_cov = target_score_cov", "1000) logW = (approx_fn(grid) - 0.5 * (grid - self.observed_target[m])", "all groups are size one, C will be an empty", "np.array([w[1] for w in sorted(weights.items())]) self.penalty = rr.weighted_l1norm(weights=weights_np, lagrange=1.) else:", "* dispersion return (observed_target, cov_target, crosscov_target_score, alternatives) class approximate_grid_inference(object): def", "np.linspace(observed_target[j] - 1.5 * _scale[j], observed_target[j] + 1.5 * _scale[j],", "results from that method. Parameters ---------- observed_target: from selected_targets target_cov:", "parameter) return result def log_reference(self, observed_target, target_cov, target_score_cov, grid): \"\"\"", "+ (target_linear.T.dot(target_linear) * self.randomizer_prec) - target_lin.T.dot( prec_opt).dot( target_lin) else: _P", "= self.log_reference(observed_target_uni, target_cov_uni, target_score_cov_uni, self.stat_grid[m]) if self.useIP == False: logW", "*= 0.5 if count >= 20: if not (np.isnan(proposed_value) or", "score, hence the minus sign target_linear = target_score_cov.T.dot(prec_target) target_offset =", "= N + Gamma theta.hat, # target_lin is \"something\" times", "continue as before self.observed_opt_state = np.hstack(ordered_opt) # gammas as array", "feasible point') # make sure proposal is a descent count", "g in sorted_active_dirs] L = block_diag(*Ls) # unpack the list", "2.) + 1. / ((con_offset - con_linear.dot(gs)) ** 2.))).dot(con_linear) if", "target_score_cov, alternatives) = self.selected_targets(dispersion) init_soln = self.observed_opt_state # just the", "range(self.ntarget): observed_target_uni = (self.observed_target[m]).reshape((1,)) target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1, 1)) prec_target =", "'less', 'greater'] parameter : np.array Hypothesized value for parameter --", "= np.ones(self.nfeature, np.bool) # mask of active features ordered_groups =", "will be an empty array return 0, 0, 0 else:", "self.observed_score_state[~overall] += self.loglike.smooth_objective(beta_bar, 'grad')[~overall] active_signs = np.sign(self.initial_soln) active = np.flatnonzero(active_signs)", "cur_grad proposed_value = objective(proposal) if proposed_value <= current_value: break step", "< 0: raise ValueError(\"Groups are not sorted\") # check integers", "o eta = -self.prec_opt.dot(self.logdens_linear.dot(target_score_cov.T)) implied_mean = np.asscalar(eta.T.dot(cond_mean_grid)) implied_cov = np.asscalar(eta.T.dot(self.cond_cov).dot(eta))", "== (0, 0): # when all groups are size one,", "not np.amin(agroups) == 0: raise ValueError(\"First group is not 0\")", "= block_diag(*Ls) # unpack the list XE = X[:, ordered_vars]", "None] * XE) QI = inv(Q) C = V.T.dot(QI).dot(L).dot(V) self.XE", "self.opt_linear.T.dot(prec.dot(self.opt_linear)) cond_cov = inv(cond_precision) logdens_linear = cond_cov.dot(self.opt_linear.T).dot(prec) cond_mean = -logdens_linear.dot(self.observed_score_state", "\"\"\" to_diag = [[g] * (ug.size - 1) for (g,", "if proposed_value <= current_value: break step *= 0.5 if count", "= 1. / ((self.precs[m])[0, 0]) lower.append(l * var_target + observed_target)", "one, C will be an empty array return 0, 0,", "This needs to be updated to actually use the Jacobian", "observed_target self.target_score_cov = target_score_cov self.target_cov = target_cov self.init_soln = query.observed_opt_state", "** 2, quadratic=quadratic) n, p = X.shape mean_diag = np.mean((X", "/ 2. if useJacobian: p3 = - jacobian_grad_hess(gs, C, active_dirs)[0]", "lower, upper = [], [] for m in range(self.ntarget): #", "regreg.api as rr from .randomization import randomization from ..base import", "list Ls = [compute_Lg(g) for g in sorted_active_dirs] L =", "np.flatnonzero(active_signs) self.active = active def compute_Vg(ug): pg = ug.size #", "/ np.sqrt(n - 1) if randomizer_scale is None: randomizer_scale =", "a grid. \"\"\" if np.asarray(observed_target).shape in [(), (0,)]: raise ValueError('no", "observed_target_uni = (self.observed_target[m]).reshape((1,)) target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1, 1)) prec_target = 1.", "drop the first column else: Vg = np.zeros((1, 0)) #", "a function of gamma vector, active directions) \"\"\" to_diag =", "log of the reference density on a grid. \"\"\" if", "target and score of randomized query. solve_args : dict, optional", "group ordered_vars.extend(np.flatnonzero(group_mask)) if self.penalty.weights[g] == 0: unpenalized.append(g) else: active_groups.append(g) active_dirs[g]", "= beta_bar X, y = self.loglike.data W = self._W =", "# figure out size of g'th group if pg >", "None: ridge_term = np.std(Y) * np.sqrt(mean_diag) / np.sqrt(n - 1)", "self.groups == g soln = self.initial_soln # do not need", "lagrange=1.) else: self.penalty = rr.group_lasso(groups, weights=weights, lagrange=1.) # store groups", "# log Jacobian #J = log(evalues).sum() J = np.log(np.linalg.det(GammaMinus +", "np.eye(pg) return Lg sorted_active_dirs = collections.OrderedDict(sorted(active_dirs.items())) Vs = [compute_Vg(ug) for", "# unpack the list Ls = [compute_Lg(g) for g in", "\\bar{\\\\mu} precision: \\\\bar{\\\\Sigma}^{-1} feasible_point: gamma's from fitting con_linear: linear part", "make sure groups looks sensible # log likelihood : quadratic", "_prec).dot(target_lin.T.dot(self.prec_opt).dot(target_off) - _P) _S = np.linalg.inv(_prec).dot(prec_target) S[m] = _S r[m]", "self.init_soln = query.observed_opt_state self.randomizer_prec = query.randomizer_prec self.score_offset = query.observed_score_state +", "= (self.observed_target[m]).reshape((1,)) target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1, 1)) prec_target = 1. /", "# now we are collecting the directions and norms of", "+ C)) # inverse #GpC_inv = evectors.dot(np.diag(1 / evalues).dot(evectors.T)) GpC_inv", "initial_soln, initial_subgrad @staticmethod def gaussian(X, Y, groups, weights, sigma=1., quadratic=None,", "group labels ordered_vars = [] # indices \"ordered\" by sorting", "'min_its': 50}, perturb=None): # solve the randomized version of group", "ValueError('no target specified') prec_target = np.linalg.inv(target_cov) target_lin = - self.logdens_linear.dot(target_score_cov.T.dot(prec_target))", "observed_target, target_cov, target_score_cov, grid): \"\"\" Approximate the log of the", "active_dirs self._ordered_groups = ordered_groups # exception if no groups are", "= qr(Z) Vg = Q[:, 1:] # drop the first", "how the argument of the optimization density # depends on", "Gamma theta.hat, # target_lin is \"something\" times Gamma, # where", "- self.logdens_linear.dot(target_score_cov.T.dot(prec_target)) ref_hat = [] for k in range(grid.shape[0]): #", "np.exp(logW))) else: approx_fn = interp1d(self.stat_grid[m], log_ref, kind='quadratic', bounds_error=False, fill_value='extrapolate') grid", "observed_target = np.atleast_1d(observed_target) prec_target = inv(target_cov) prec_opt = self.cond_precision score_offset", "- step * cur_grad if np.all(con_offset - con_linear.dot(proposal) > 0):", "group_lasso makes about how groups are specified. Specifically, we assume", "elif alternatives[m] == 'greater': pivot.append(1 - _cdf) elif alternatives[m] ==", "= self.loglike.data W = self._W = self.loglike.saturated_loss.hessian(X.dot(beta_bar)) # all 1's", "= query.C self.active_dirs = query.active_dirs (observed_target, target_cov, target_score_cov, alternatives) =", "[] for m in range(self.ntarget): # construction of intervals from", "need to keep setting this if norm(soln[group_mask]) > tol *", "size 1 if use_lasso and groups.size == np.unique(groups).size: # need", "collecting the directions and norms of the active groups for", "to solver level: level of confidence intervals useC: whether to", "a group 4, there must also be at least one", "np.asarray(self.randomizer_prec).shape in [(), (0,)]: _P = target_linear.T.dot(target_offset) * self.randomizer_prec _prec", "there must also be at least one feature in group", "group lasso penalty (from regreg) # use regular lasso penalty", "= XE self.Q = Q self.QI = QI self.C =", "(use self.C defined in fitting) \"\"\" self._setup_implied_gaussian() # Calculate useful", "# indices \"ordered\" by sorting group labels tol = 1.e-20", "solve_args={'tol': 1.e-12}, level=0.9, useJacobian=True, dispersion=None): \"\"\"Do selective_MLE for group_lasso Note:", "self.observed_score_state = -opt_linearNoU.dot(_beta_unpenalized) self.observed_score_state[~overall] += self.loglike.smooth_objective(beta_bar, 'grad')[~overall] active_signs = np.sign(self.initial_soln)", "keys are group labels, values are unit-norm coefficients unpenalized =", "XE self.Q = Q self.QI = QI self.C = C", "self.randomizer_prec) - target_lin.T.dot( prec_opt).dot( target_lin) else: _P = target_linear.T.dot(self.randomizer_prec).dot(target_offset) _prec", "level=0.9, useJacobian=True, dispersion=None): \"\"\"Do selective_MLE for group_lasso Note: this masks", "groups, weights, ridge_term, randomizer, use_lasso=True, # should lasso solver be", "* var_target + observed_target) upper.append(u * var_target + observed_target) return", "(g, ug) in zip(gamma, active_dirs.values())] return block_diag(*[i for gp in", "2).sum(0)) if ridge_term is None: ridge_term = np.std(Y) * np.sqrt(mean_diag)", "self.XE Q = self.Q observed_target = restricted_estimator(self.loglike, self.ordered_vars, solve_args=solve_args) _score_linear", "that group_lasso makes about how groups are specified. Specifically, we", "alpha=1 - level) var_target = 1. / ((self.precs[m])[0, 0]) lower.append(l", "# depends on the score, not how the mean depends", "not how the mean depends on score, hence the minus", "summing matrix (gamma.size by C.shape[0]) S = block_diag(*[np.ones((1, ug.size -", "1.)) randomizer = randomization.isotropic_gaussian((p,), randomizer_scale) return group_lasso(loglike, groups, weights, ridge_term,", "- observed_target)) + self.cond_mean) #direction for decomposing o eta =", "ug.size # figure out size of g'th group if pg", "groups self._initial_omega = perturb # gaussian randomization self.randomizer = randomizer", "soln))) + C unbiased_estimator = target_cov.dot(_prec).dot(observed_target) + target_cov.dot( _P -", "-gs.T.dot(conjugate_arg) p2 = gs.T.dot(precision).dot(gs) / 2. if useJacobian: p3 =", "[] for m in range(self.ntarget): family = self._families[m] var_target =", "and have no gaps (e.g., if there is a group", "cur_grad = grad(current) # make sure proposal is feasible count", "is \"something\" times Gamma, # where \"something\" comes from implied", "1 - pvalues) alpha = 1 - level quantile =", "least one feature in group 3). This function checks the", "0)) # if the group is size one, the orthogonal", "# gamma's ordered by group labels ordered_vars = [] #", "future we might do this for them. \"\"\" # check", "collections.OrderedDict(sorted(active_dirs.items())) Vs = [compute_Vg(ug) for ug in sorted_active_dirs.values()] V =", "depends on the score, not how the mean depends on", "for itercount in range(nstep): cur_grad = grad(current) # make sure", "proposal current_value = proposed_value if itercount % 4 == 0:", "= current - step * cur_grad if np.all(con_offset - con_linear.dot(proposal)", "import restricted_estimator from ..algorithms.barrier_affine import solve_barrier_affine_py as solver from ..distributions.discrete_family", "# variables in active group ordered_vars.extend(np.flatnonzero(group_mask)) if self.penalty.weights[g] == 0:", "ndist from scipy.interpolate import interp1d import collections import numpy as", "\\\\Lambda V active_dirs: \"\"\" scaling = np.sqrt(np.diag(con_linear.dot(precision).dot(con_linear.T))) if feasible_point is", "np.sqrt(np.diag(observed_info_mean)), 'Zvalue': Z_scores, 'pvalue': pvalues, 'lower_confidence': intervals[:, 0], 'upper_confidence': intervals[:,", "np.all(con_offset - con_linear.dot(proposal) > 0): break step *= 0.5 if", "it finds any problems. Sorting feature groups is potentially tedious", "/ norm(soln[group_mask]) ordered_opt.append(norm(soln[group_mask])) else: overall[group_mask] = False self.selection_variable = {'directions':", "eig(GammaMinus + C) # log Jacobian #J = log(evalues).sum() J", "= self._approx_pivots(np.zeros_like(self.observed_target), alternatives=alternatives) lower, upper = self._approx_intervals(level=level) result = pd.DataFrame({'target':", "self.penalty.weights[g] * np.eye(pg) return Lg sorted_active_dirs = collections.OrderedDict(sorted(active_dirs.items())) Vs =", "\"\"\" Produce p-values and confidence intervals for targets of model", "(from regreg) # use regular lasso penalty if all groups", "#GpC_inv = evectors.dot(np.diag(1 / evalues).dot(evectors.T)) GpC_inv = np.linalg.inv(GammaMinus + C)", "= family.equal_tailed_interval(observed_target, alpha=1 - level) var_target = 1. / ((self.precs[m])[0,", "n, p = X.shape mean_diag = np.mean((X ** 2).sum(0)) if", "= Q self.QI = QI self.C = C U =", "crosscov_target_score = _score_linear.dot(self.QI).T * dispersion return (observed_target, cov_target, crosscov_target_score, alternatives)", "solve_args result, inverse_info = query.selective_MLE(dispersion=dispersion)[:2] self.linear_part = query.linear_part self.offset =", "\"ordered\" by sorting group labels tol = 1.e-20 _, self.randomizer_prec", "in zip(gamma, active_dirs.values())] return block_diag(*[i for gp in to_diag for", "= opt_offset self.ordered_vars = ordered_vars self.linear_part = -np.eye(self.observed_opt_state.shape[0]) self.offset =", "already run the fit method since this uses results from", "Parameters ---------- observed_target: from selected_targets target_cov: from selected_targets target_cov_score: from", "'lower_confidence': intervals[:, 0], 'upper_confidence': intervals[:, 1], 'unbiased': unbiased_estimator}) return result,", "- con_linear.dot(gs))) if useJacobian: p3 = - jacobian_grad_hess(gs, C, active_dirs)[1]", "+= self.loglike.smooth_objective(beta_bar, 'grad')[~overall] active_signs = np.sign(self.initial_soln) active = np.flatnonzero(active_signs) self.active", "cond_mean = -logdens_linear.dot(self.observed_score_state + self.opt_offset) self.cond_mean = cond_mean self.cond_cov =", "in future we might do this for them. \"\"\" #", "not np.issubdtype(agroups.dtype, np.integer): raise TypeError(\"Groups are not integers\") # check", "query, dispersion, solve_args={'tol': 1.e-12}, useIP=True): \"\"\" Produce p-values and confidence", "# eigendecomposition #evalues, evectors = eig(GammaMinus + C) # log", "target_cov.dot(_P - target_lin.T.dot(prec_opt).dot(target_off)) conjugate_arg = prec_opt.dot(cond_mean) val, soln, hess =", "= -S.dot(np.multiply(GpC_inv, GpC_inv.T).dot(S.T)) return J, grad_J, hess_J def _check_groups(groups): \"\"\"Make", "weights, ridge_term, randomizer, use_lasso, perturb) def _setup_implied_gaussian(self): _, prec =", "2 / var_target) logW -= logW.max() self._families.append(discrete_family(grid, np.exp(logW))) def _approx_pivots(self,", "solve the randomized version of group lasso (self.initial_soln, self.initial_subgrad) =", "# g is group label group_mask = self.groups == g", "/ target_cov_uni target_score_cov_uni = self.target_score_cov[m, :].reshape((1, p)) target_linear = target_score_cov_uni.T.dot(prec_target)", "specified. Specifically, we assume that `groups` is a 1-d array_like", "optimization variables # vary with target # logdens_linear determines how", "beta_bar = np.zeros(self.nfeature) beta_bar[overall] = _beta_unpenalized # refit OLS beta", "quad = rr.identity_quadratic(self.ridge_term, 0, -self._initial_omega, 0) problem = rr.simple_problem(self.loglike, self.penalty)", "cond_precision self.logdens_linear = logdens_linear return cond_mean, cond_cov, cond_precision, logdens_linear def", "of active features ordered_groups = [] # active group labels", "= XE.T.dot(self._W[:, None] * XE) QI = inv(Q) C =", "target_linear.T.dot(target_offset) * self.randomizer_prec _r = (1. / _prec).dot(target_lin.T.dot(self.prec_opt).dot(target_off) - _P)", "by group labels ordered_vars = [] # indices \"ordered\" by", "function of gamma vector, active directions) \"\"\" to_diag = [[g]", "(ug.size - 1) for (g, ug) in zip(gamma, active_dirs.values())] return", "solver level: level of confidence intervals useC: whether to use", "values are unit-norm coefficients unpenalized = [] # selected groups", "/ (con_offset - con_linear.dot(gs)) return p1 + p2 + p3", "20: if not (np.isnan(proposed_value) or np.isnan(current_value)): break else: raise ValueError('value", "pvalues) alpha = 1 - level quantile = ndist.ppf(1 -", "= 4 * np.sqrt(np.diag(inverse_info)) if useIP == False: ngrid =", "including selected features Parameters ---------- alternatives : [str], optional Sequence", "is target_score_cov.T.dot(prec_target) num_opt = self.prec_opt.shape[0] num_con = self.linear_part.shape[0] cond_mean_grid =", "\"\"\" self.solve_args = solve_args result, inverse_info = query.selective_MLE(dispersion=dispersion)[:2] self.linear_part =", "import regreg.api as rr from .randomization import randomization from ..base", "pivot.append(2 * min(_cdf, 1 - _cdf)) elif alternatives[m] == 'greater':", "refit OLS beta with zeros self._beta_full = beta_bar X, y", "in [(), (0,)]: raise ValueError('no target specified') prec_target = np.linalg.inv(target_cov)", "target_lin = - self.logdens_linear.dot(target_score_cov.T.dot(prec_target)) ref_hat = [] for k in", "randomizer_scale=None): loglike = rr.glm.gaussian(X, Y, coef=1. / sigma ** 2,", "/ ((con_offset - con_linear.dot(gs)) ** 2.))).dot(con_linear) if useJacobian: p2 =", "= query.cond_mean self.prec_opt = np.linalg.inv(query.cond_cov) self.cond_cov = query.cond_cov self.C =", "should lasso solver be used where applicable - defaults to", "'active_groups': active_groups} # kind of redundant with keys of active_dirs", "target_score_cov_uni, self.stat_grid[m]) if self.useIP == False: logW = (log_ref -", "useJacobian: p2 = - jacobian_grad_hess(gs, C, active_dirs)[2] else: p2 =", "else: GammaMinus = calc_GammaMinus(gamma, active_dirs) # eigendecomposition #evalues, evectors =", "array return 0, 0, 0 else: GammaMinus = calc_GammaMinus(gamma, active_dirs)", "target_lin.T.dot(prec_opt) observed_info_natural = _prec + L.dot(target_lin) - L.dot(hess.dot(L.T)) observed_info_mean =", "conjugate_arg: \\\\bar{\\\\Sigma}^{-1} \\bar{\\\\mu} precision: \\\\bar{\\\\Sigma}^{-1} feasible_point: gamma's from fitting con_linear:", "= -XE.T.dot(self._W[:, None] * X).T alternatives = ['twosided'] * len(self.active)", "== 0: return np.sign(soln), soln # otherwise continue as before", "self.loglike.saturated_loss.mean_function( XE.dot(observed_target))) ** 2 / self._W).sum() / (n - XE.shape[1])", "randomizer def fit(self, solve_args={'tol': 1.e-12, 'min_its': 50}, perturb=None): # solve", "be used when applicable - defaults to True randomizer_scale=None): loglike", "= self.linear_part.shape[0] cond_mean_grid = (target_lin.dot(np.atleast_1d(grid[k] - observed_target)) + self.cond_mean) #direction", "in [\"twosided\", \"less\", \"greater\"]') return pivot def _approx_intervals(self, level=0.9): if", "if not np.all(parameter == 0): result.insert(4, 'pivot', pivots) result.insert(5, 'parameter',", "-(self.loglike.smooth_objective(initial_soln, 'grad') + quad.objective(initial_soln, 'grad')) return initial_soln, initial_subgrad @staticmethod def", "np.linspace(self.stat_grid[m].min(), self.stat_grid[m].max(), 1000) logW = (approx_fn(grid) - 0.5 * (grid", "of active_dirs self._ordered_groups = ordered_groups # exception if no groups", "block_diag(*Ls) # unpack the list XE = X[:, ordered_vars] #", "self.opt_offset # target_lin determines how the conditional mean of optimization", "as rr from .randomization import randomization from ..base import restricted_estimator", "[(), (0,)]: raise ValueError('no target specified') observed_target = np.atleast_1d(observed_target) prec_target", "group label group_mask = self.groups == g soln = self.initial_soln", "(1,1)), eta.T.dot(self.init_soln), A.reshape((A.shape[0],1)), b, **self.solve_args) gamma_ = _A.dot(soln) + R.dot(self.init_soln)", "integers that are sorted in increasing order, start at 0,", "solver. \"\"\" self.solve_args = solve_args result, inverse_info = query.selective_MLE(dispersion=dispersion)[:2] self.linear_part", "Z_scores = final_estimator / np.sqrt(np.diag(observed_info_mean)) pvalues = ndist.cdf(Z_scores) pvalues =", "is feasible count = 0 while True: count += 1", "variables active_groups = [] # active group labels active_dirs =", "..base import restricted_estimator from ..algorithms.barrier_affine import solve_barrier_affine_py as solver from", "con_linear.T.dot(np.diag(-1. / ((scaling + con_offset - con_linear.dot(gs)) ** 2.) +", "calc_GammaMinus(gamma, active_dirs): \"\"\"Calculate Gamma^minus (as a function of gamma vector,", "figure out size of g'th group if pg > 1:", "tol = 1.e-20 _, self.randomizer_prec = self.randomizer.cov_prec # now we", "self.loglike.saturated_loss.hessian(X.dot(beta_bar)) # all 1's for LS opt_linearNoU = np.dot(X.T, X[:,", "self.selected_targets(dispersion) init_soln = self.observed_opt_state # just the gammas cond_mean =", "query.offset self.logdens_linear = query.logdens_linear self.cond_mean = query.cond_mean self.prec_opt = np.linalg.inv(query.cond_cov)", "block_diag(*[i for gp in to_diag for i in gp]) def", "for the group_lasso. Also, assumes you have already run the", "= _prec self.precs = precs self.S = S self.r =", "_cdf = family.cdf((mean[0] - self.observed_target[m]) / var_target, x=self.observed_target[m]) print(\"variable completed", "self._initial_omega = self.randomizer.sample() quad = rr.identity_quadratic(self.ridge_term, 0, -self._initial_omega, 0) problem", "var_target = 1. / ((self.precs[m])[0, 0]) mean = self.S[m].dot(mean_parameter[m].reshape((1,))) +", "= self.loglike.shape[0] # ridge parameter self.ridge_term = ridge_term # group", "target_off = cond_mean - target_lin.dot(observed_target) if np.asarray(self.randomizer_prec).shape in [(), (0,)]:", "+ observed_target) upper.append(u * var_target + observed_target) return np.asarray(lower), np.asarray(upper)", "\"\"\" scaling = np.sqrt(np.diag(con_linear.dot(precision).dot(con_linear.T))) if feasible_point is None: feasible_point =", "not hasattr(self, \"_families\"): self._construct_families() lower, upper = [], [] for", "(con_offset - con_linear.dot(gs)) return p1 + p2 + p3 +", "if C.shape == (0, 0): # when all groups are", "evalues).dot(evectors.T)) GpC_inv = np.linalg.inv(GammaMinus + C) # summing matrix (gamma.size", "about how groups are specified. Specifically, we assume that `groups`", "_r = (1. / _prec).dot(target_lin.T.dot(self.prec_opt).dot(target_off) - _P) _S = np.linalg.inv(_prec).dot(prec_target)", "= useIP def summary(self, alternatives=None, parameter=None, level=0.9): \"\"\" Produce p-values", "= feasible_point current_value = np.inf for itercount in range(nstep): cur_grad", "the orthogonal complement is empty return Vg def compute_Lg(g): pg", "the list XE = X[:, ordered_vars] # changed to ordered_vars", "\"\"\" Calculate the log-Jacobian (scalar), gradient (gamma.size vector) and hessian", "alternatives=None, parameter=None, level=0.9): \"\"\" Produce p-values and confidence intervals for", "/ ((con_offset - con_linear.dot(gs)) / scaling)).sum() return p1 + p2", "target_cov_uni = (np.diag(self.target_cov)[m]).reshape((1, 1)) target_score_cov_uni = self.target_score_cov[m, :].reshape((1, p)) var_target", "before self.observed_opt_state = np.hstack(ordered_opt) # gammas as array _beta_unpenalized =", "var_target) logW -= logW.max() self._families.append(discrete_family(grid, np.exp(logW))) def _approx_pivots(self, mean_parameter, alternatives=None):", "p3 = 0 p4 = 1. / (con_offset - con_linear.dot(gs))", "# summing matrix (gamma.size by C.shape[0]) S = block_diag(*[np.ones((1, ug.size", "= log(evalues).sum() J = np.log(np.linalg.det(GammaMinus + C)) # inverse #GpC_inv", "sure that the user-specific groups are ok There are a", "self._families[m] observed_target = self.observed_target[m] l, u = family.equal_tailed_interval(observed_target, alpha=1 -", "# refit OLS on E overall, solve_args=solve_args) beta_bar = np.zeros(self.nfeature)", "final_estimator, 'SE': np.sqrt(np.diag(observed_info_mean)), 'Zvalue': Z_scores, 'pvalue': pvalues, 'lower_confidence': intervals[:, 0],", "_prec = prec_target + (target_linear.T.dot(self.randomizer_prec).dot(target_linear)) - target_lin.T.dot( prec_opt).dot(target_lin) C =", ":].reshape((1, p)) var_target = 1. / ((self.precs[m])[0, 0]) log_ref =", "/ (n - 1.)) randomizer = randomization.isotropic_gaussian((p,), randomizer_scale) return group_lasso(loglike,", "# target_lin is \"something\" times Gamma, # where \"something\" comes", "= solver(np.asarray([conjugate_arg]), np.reshape(implied_prec, (1,1)), eta.T.dot(self.init_soln), A.reshape((A.shape[0],1)), b, **self.solve_args) gamma_ =", "from .randomization import randomization from ..base import restricted_estimator from ..algorithms.barrier_affine", "sorted_active_dirs.values()] V = block_diag(*Vs) # unpack the list Ls =", "norms of the active groups for g in sorted(np.unique(self.groups)): #", "quantile * np.sqrt(np.diag(observed_info_mean)), final_estimator + quantile * np.sqrt(np.diag(observed_info_mean))]).T log_ref =", "use_lasso and groups.size == np.unique(groups).size: # need to provide weights", "quad.objective(initial_soln, 'grad')) return initial_soln, initial_subgrad @staticmethod def gaussian(X, Y, groups,", "unbiased_estimator = target_cov.dot(_prec).dot(observed_target) + target_cov.dot( _P - target_lin.T.dot(prec_opt).dot(target_off)) L =", "= self._approx_intervals(level=level) result = pd.DataFrame({'target': self.observed_target, 'pvalue': pvalues, 'lower_confidence': lower,", "L = target_lin.T.dot(prec_opt) observed_info_natural = _prec + L.dot(target_lin) - L.dot(hess.dot(L.T))", "= [], [] for m in range(self.ntarget): # construction of", "run usual lasso solver... (see existing code)... initial_soln = problem.solve(quad,", "current = proposal current_value = proposed_value break current = proposal", "XE) QI = inv(Q) C = V.T.dot(QI).dot(L).dot(V) self.XE = XE", "self.cond_precision = cond_precision self.logdens_linear = logdens_linear return cond_mean, cond_cov, cond_precision,", "target_lin = -self.logdens_linear.dot(target_linear) target_off = (self.cond_mean - target_lin.dot(observed_target_uni)).reshape((target_lin.shape[0],)) _prec =", "{'directions': active_dirs, 'active_groups': active_groups} # kind of redundant with keys", "norm, qr, inv, eig import pandas as pd import regreg.api", "confidence intervals for targets of model including selected features Parameters", "from scipy.stats import norm as ndist from scipy.interpolate import interp1d", "= query.observed_score_state + query.opt_offset self.ntarget = ntarget = target_cov.shape[0] _scale", "= np.linspace(self.stat_grid[m].min(), self.stat_grid[m].max(), 1000) logW = (approx_fn(grid) - 0.5 *", "check sorted if np.any(agroups[:-1] > agroups[1:]) < 0: raise ValueError(\"Groups", "= final_estimator / np.sqrt(np.diag(observed_info_mean)) pvalues = ndist.cdf(Z_scores) pvalues = 2", "for barrier function C: V^T Q^{-1} \\\\Lambda V active_dirs: \"\"\"", "= 0 return p1 + p2 current = feasible_point current_value", "of model including selected features Parameters ---------- alternatives : [str],", "Ls = [compute_Lg(g) for g in sorted_active_dirs] L = block_diag(*Ls)", "- ((conjugate_arg ** 2) * implied_cov)/ 2. + log_jacob[0]) return", "Calculate the log-Jacobian (scalar), gradient (gamma.size vector) and hessian (gamma.size", "perturbation if supplied if perturb is not None: self._initial_omega =", "inv(cond_precision) logdens_linear = cond_cov.dot(self.opt_linear.T).dot(prec) cond_mean = -logdens_linear.dot(self.observed_score_state + self.opt_offset) self.cond_mean", "+= 1 proposal = current - step * cur_grad proposed_value", "changed to ordered_vars Q = XE.T.dot(self._W[:, None] * XE) QI", "elif alternatives[m] == 'less': pivot.append(_cdf) else: raise ValueError('alternative should be", "than a dictionary weights_np = np.array([w[1] for w in sorted(weights.items())])", "else: cond_precision = self.opt_linear.T.dot(prec.dot(self.opt_linear)) cond_cov = inv(cond_precision) logdens_linear = cond_cov.dot(self.opt_linear.T).dot(prec)", "= perturb if self._initial_omega is None: self._initial_omega = self.randomizer.sample() quad", "1: raise ValueError(\"Groups are not a 1D array_like\") # check", "score of randomized query. solve_args : dict, optional Arguments passed", "= grad(current) # make sure proposal is feasible count =", "selective_MLE inherited from query because that is not adapted for", "+ p4 def grad(gs): p1 = -conjugate_arg + precision.dot(gs) p2", "'upper_confidence': intervals[:, 1], 'unbiased': unbiased_estimator}) return result, observed_info_mean, log_ref def", "= self.randomizer.cov_prec # now we are collecting the directions and", "if supplied if perturb is not None: self._initial_omega = perturb", "Z_scores, 'pvalue': pvalues, 'lower_confidence': intervals[:, 0], 'upper_confidence': intervals[:, 1], 'unbiased':", "to describe implied Gaussian. observed_target : ndarray Observed estimate of", "solve_args={'tol': 1.e-15, 'min_its': 100}): # take a new perturbation if", "= self.observed_target[m] l, u = family.equal_tailed_interval(observed_target, alpha=1 - level) var_target", "_prec + L.dot(target_lin) - L.dot(hess.dot(L.T)) observed_info_mean = target_cov.dot(observed_info_natural.dot(target_cov)) Z_scores =", "- 0.5 * (self.stat_grid[m] - self.observed_target[m]) ** 2 / var_target)", "and in future we might do this for them. \"\"\"", "cond_cov = inv(cond_precision) logdens_linear = cond_cov.dot(self.opt_linear.T) * prec else: cond_precision", "compute_Vg(ug): pg = ug.size # figure out size of g'th", "def _solve_randomized_problem(self, perturb=None, solve_args={'tol': 1.e-15, 'min_its': 100}): # take a", "tedious for the user and in future we might do", "useIP == False: ngrid = 1000 self.stat_grid = np.zeros((ntarget, ngrid))", "* self.randomizer_prec) - target_lin.T.dot( self.prec_opt).dot(target_lin) _P = target_linear.T.dot(target_offset) * self.randomizer_prec", "dispersion=None): \"\"\"Do selective_MLE for group_lasso Note: this masks the selective_MLE", "_A.dot(eta.T) A = self.linear_part.dot(_A).reshape((-1,)) b = self.offset-self.linear_part.dot(R).dot(self.init_soln) conjugate_arg = implied_mean", "prec_target = 1. / target_cov_uni target_score_cov_uni = self.target_score_cov[m, :].reshape((1, p))", "are selected if len(self.selection_variable['active_groups']) == 0: return np.sign(soln), soln #", "*= 2 hess = inv(precision + barrier_hessian(current)) return current_value, current,", "True randomizer_scale=None): loglike = rr.glm.gaussian(X, Y, coef=1. / sigma **", "2.) intervals = np.vstack([final_estimator - quantile * np.sqrt(np.diag(observed_info_mean)), final_estimator +", "_S r[m] = _r precs[m] = _prec self.precs = precs", "feasible_point is None: feasible_point = 1. / scaling def objective(gs):", "strings describing the alternatives, should be values of ['twosided', 'less',", "- con_linear.dot(gs)) return p1 + p2 + p3 + p4", "= self.offset if np.asarray(observed_target).shape in [(), (0,)]: raise ValueError('no target", "pg = ug.size # figure out size of g'th group", "= np.asscalar(eta.T.dot(self.cond_cov).dot(eta)) implied_prec = 1./implied_cov _A = self.cond_cov.dot(eta) * implied_prec", "query.opt_linear self.useIP = useIP def summary(self, alternatives=None, parameter=None, level=0.9): \"\"\"", "= active_dirs[g].size Lg = self.penalty.weights[g] * np.eye(pg) return Lg sorted_active_dirs", "determines how the argument of the optimization density # depends", "* np.sqrt(np.diag(observed_info_mean)), final_estimator + quantile * np.sqrt(np.diag(observed_info_mean))]).T log_ref = val", "observed_info_mean, log_ref def selected_targets(self, dispersion=None, solve_args={'tol': 1.e-12, 'min_its': 50}): X,", "result def log_reference(self, observed_target, target_cov, target_score_cov, grid): \"\"\" Approximate the", "self.linear_part offset = self.offset if np.asarray(observed_target).shape in [(), (0,)]: raise", "start at 0, and have no gaps (e.g., if there", "[], [] for m in range(self.ntarget): # construction of intervals", "self.prec_opt.shape[0] num_con = self.linear_part.shape[0] cond_mean_grid = (target_lin.dot(np.atleast_1d(grid[k] - observed_target)) +", "= ['twosided'] * len(self.active) if dispersion is None: # use", "self.solve_args = solve_args result, inverse_info = query.selective_MLE(dispersion=dispersion)[:2] self.linear_part = query.linear_part", "= (self.score_offset - target_linear.dot(observed_target_uni)).reshape( (target_linear.shape[0],)) target_lin = -self.logdens_linear.dot(target_linear) target_off =", "QI = inv(Q) C = V.T.dot(QI).dot(L).dot(V) self.XE = XE self.Q", "to be updated to actually use the Jacobian information (in", "from ..base import restricted_estimator from ..algorithms.barrier_affine import solve_barrier_affine_py as solver", "target_cov, target_score_cov, alternatives) = query.selected_targets(dispersion) self.observed_target = observed_target self.target_score_cov =", "cond_cov.dot(self.opt_linear.T).dot(prec) cond_mean = -logdens_linear.dot(self.observed_score_state + self.opt_offset) self.cond_mean = cond_mean self.cond_cov", "directions) \"\"\" to_diag = [[g] * (ug.size - 1) for", "result.insert(4, 'pivot', pivots) result.insert(5, 'parameter', parameter) return result def log_reference(self,", "target_lin.T.dot( prec_opt).dot( target_lin) else: _P = target_linear.T.dot(self.randomizer_prec).dot(target_offset) _prec = prec_target", "C = V.T.dot(QI).dot(L).dot(V) self.XE = XE self.Q = Q self.QI", "= target_cov.dot(_prec).dot(observed_target) \\ + target_cov.dot(target_lin.T.dot(prec_opt.dot(cond_mean - soln))) + C unbiased_estimator", "+= self.ridge_term opt_offset = self.initial_subgrad self.observed_score_state = -opt_linearNoU.dot(_beta_unpenalized) self.observed_score_state[~overall] +=", "logW = (approx_fn(grid) - 0.5 * (grid - self.observed_target[m]) **", "that are sorted in increasing order, start at 0, and", "problem = rr.simple_problem(self.loglike, self.penalty) # if all groups are size", "import norm as ndist from scipy.interpolate import interp1d import collections", "'pvalue': pvalues, 'lower_confidence': intervals[:, 0], 'upper_confidence': intervals[:, 1], 'unbiased': unbiased_estimator})", "Y, coef=1. / sigma ** 2, quadratic=quadratic) n, p =", "value for parameter -- defaults to 0. level : float", "of optimization variables cond_mean: conditional mean of optimization variables (model", "feasible_point: gamma's from fitting con_linear: linear part of affine constraint", "# ridge parameter self.ridge_term = ridge_term # group lasso penalty", "precs[m] = _prec self.precs = precs self.S = S self.r", "- step * cur_grad proposed_value = objective(proposal) if proposed_value <=", "- target_lin.T.dot( self.prec_opt).dot(target_lin) _P = target_linear.T.dot(target_offset) * self.randomizer_prec _r =", "def objective(gs): p1 = -gs.T.dot(conjugate_arg) p2 = gs.T.dot(precision).dot(gs) / 2.", "step *= 0.5 if count >= 20: if not (np.isnan(proposed_value)", "* _scale[j], observed_target[j] + 1.5 * _scale[j], num=ngrid) self.opt_linear =", "XE = self.XE Q = self.Q observed_target = restricted_estimator(self.loglike, self.ordered_vars,", "useJacobian=True, step=1, nstep=2000, min_its=500, tol=1.e-12): \"\"\" This needs to be", "empty return Vg def compute_Lg(g): pg = active_dirs[g].size Lg =", "perturb # gaussian randomization self.randomizer = randomizer def fit(self, solve_args={'tol':", "C) # log Jacobian #J = log(evalues).sum() J = np.log(np.linalg.det(GammaMinus", "C, active_dirs, useJacobian=True, step=1, nstep=2000, min_its=500, tol=1.e-12): \"\"\" This needs", "target # logdens_linear determines how the argument of the optimization", "= pd.DataFrame({'target': self.observed_target, 'pvalue': pvalues, 'lower_confidence': lower, 'upper_confidence': upper}) if", "mean = self.S[m].dot(mean_parameter[m].reshape((1,))) + self.r[m] _cdf = family.cdf((mean[0] - self.observed_target[m])", "groups as a class variable since the non-group lasso doesn't", "arguments conjugate_arg: \\\\bar{\\\\Sigma}^{-1} \\bar{\\\\mu} precision: \\\\bar{\\\\Sigma}^{-1} feasible_point: gamma's from fitting", "= self.Q observed_target = restricted_estimator(self.loglike, self.ordered_vars, solve_args=solve_args) _score_linear = -XE.T.dot(self._W[:,", "model including selected features Parameters ---------- alternatives : [str], optional", "use regular lasso penalty if all groups are size 1", "target_lin.T.dot(prec_opt).dot(target_off)) conjugate_arg = prec_opt.dot(cond_mean) val, soln, hess = solve_barrier_affine_jacobian_py(conjugate_arg, prec_opt,", "observed_target = restricted_estimator(self.loglike, self.ordered_vars, solve_args=solve_args) _score_linear = -XE.T.dot(self._W[:, None] *", "2, quadratic=quadratic) n, p = X.shape mean_diag = np.mean((X **", "self.ntarget pivot = [] for m in range(self.ntarget): family =", "np.atleast_1d(observed_target) prec_target = inv(target_cov) prec_opt = self.cond_precision score_offset = self.observed_score_state", "con_linear.dot(gs)) ** 2.) + 1. / ((con_offset - con_linear.dot(gs)) **", "agroups[1:]) < 0: raise ValueError(\"Groups are not sorted\") # check", "def jacobian_grad_hess(gamma, C, active_dirs): \"\"\" Calculate the log-Jacobian (scalar), gradient", "have already run the fit method since this uses results", "+ p4 def barrier_hessian(gs): # contribution of barrier and jacobian", "solve_args={'tol': 1.e-12, 'min_its': 50}): X, y = self.loglike.data n, p", "and groups.size == np.unique(groups).size: # need to provide weights an", "barrier function con_offset: offset part of affine constraint used for", "block_diag(*[np.ones((1, ug.size - 1)) for ug in active_dirs.values()]) # gradient", "if use_lasso and groups.size == np.unique(groups).size: # need to provide", "from selected_targets target_cov: from selected_targets target_cov_score: from selected_targets init_soln: (opt_state)", "var_target = 1. / ((self.precs[m])[0, 0]) lower.append(l * var_target +", "overall, solve_args=solve_args) beta_bar = np.zeros(self.nfeature) beta_bar[overall] = _beta_unpenalized # refit", "# logdens_linear determines how the argument of the optimization density", "(0,)]: raise ValueError('no target specified') prec_target = np.linalg.inv(target_cov) target_lin =", "1. / (con_offset - con_linear.dot(gs)) return p1 + p2 +", "self.Q = Q self.QI = QI self.C = C U", "[] # active group labels sorted by label ordered_opt =", "(observed_target, target_cov, target_score_cov, alternatives) = self.selected_targets(dispersion) init_soln = self.observed_opt_state #", "family.cdf((mean[0] - self.observed_target[m]) / var_target, x=self.observed_target[m]) print(\"variable completed \", m)", "\"greater\"]') return pivot def _approx_intervals(self, level=0.9): if not hasattr(self, \"_families\"):", "r = {} p = self.target_score_cov.shape[1] for m in range(self.ntarget):", "raise ValueError('no target specified') observed_target = np.atleast_1d(observed_target) prec_target = inv(target_cov)", "for LS opt_linearNoU = np.dot(X.T, X[:, ordered_vars] * W[:, np.newaxis])", "randomizer_scale) return group_lasso(loglike, groups, weights, ridge_term, randomizer, use_lasso, perturb) def", "of the active groups for g in sorted(np.unique(self.groups)): # g", "is a group 2 and a group 4, there must", "decrease is small if np.fabs(current_value - proposed_value) < tol *", "pvalues = ndist.cdf(Z_scores) pvalues = 2 * np.minimum(pvalues, 1 -", "in sorted_active_dirs] L = block_diag(*Ls) # unpack the list XE", "offset: like b_scaling (from lasso) solve_args: passed on to solver", "= target_cov.dot(_prec).dot(observed_target) + target_cov.dot( _P - target_lin.T.dot(prec_opt).dot(target_off)) L = target_lin.T.dot(prec_opt)", "group is size one, the orthogonal complement is empty return", "print_function from scipy.linalg import block_diag from scipy.stats import norm as", "_score_linear.dot(self.QI).T * dispersion return (observed_target, cov_target, crosscov_target_score, alternatives) class approximate_grid_inference(object):", "= perturb # gaussian randomization self.randomizer = randomizer def fit(self,", "alternatives) class approximate_grid_inference(object): def __init__(self, query, dispersion, solve_args={'tol': 1.e-12}, useIP=True):", "all groups are size 1 if use_lasso and groups.size ==", "target_score_cov.T.dot(prec_target) target_offset = score_offset - target_linear.dot(observed_target) target_lin = - logdens_linear.dot(target_linear)", "+ target_cov.dot(target_lin.T.dot(prec_opt.dot(cond_mean - soln))) + C unbiased_estimator = target_cov.dot(_prec).dot(observed_target) +", "covariance of target and score of randomized query. solve_args :", "in range(grid.shape[0]): # in the usual D = N +", "* min(_cdf, 1 - _cdf)) elif alternatives[m] == 'greater': pivot.append(1", "zip(gamma, active_dirs.values())] return block_diag(*[i for gp in to_diag for i", "group scheme and raises an exception if it finds any", "\", m) if alternatives[m] == 'twosided': pivot.append(2 * min(_cdf, 1", "= (approx_fn(grid) - 0.5 * (grid - self.observed_target[m]) ** 2", "are size 1, set up lasso penalty and run usual", "usual lasso solver... (see existing code)... initial_soln = problem.solve(quad, **solve_args)", "contribution of barrier and jacobian to hessian p1 = con_linear.T.dot(np.diag(-1.", "while True: count += 1 proposal = current - step", "= proposal current_value = proposed_value if itercount % 4 ==", "if np.asarray(observed_target).shape in [(), (0,)]: raise ValueError('no target specified') observed_target", "hence the minus sign target_linear = target_score_cov.T.dot(prec_target) target_offset = score_offset", "-XE.T.dot(self._W[:, None] * X).T alternatives = ['twosided'] * len(self.active) if", "self.C = query.C self.active_dirs = query.active_dirs (observed_target, target_cov, target_score_cov, alternatives)", "implied_prec = 1./implied_cov _A = self.cond_cov.dot(eta) * implied_prec R =", "for (g, ug) in zip(gamma, active_dirs.values())] return block_diag(*[i for gp", "pvalues, 'lower_confidence': lower, 'upper_confidence': upper}) if not np.all(parameter == 0):", "self.randomizer_prec) - target_lin.T.dot( self.prec_opt).dot(target_lin) _P = target_linear.T.dot(target_offset) * self.randomizer_prec _r", "the optimization density # depends on the score, not how", "con_offset - con_linear.dot(gs))) if useJacobian: p3 = - jacobian_grad_hess(gs, C,", "C unbiased_estimator = target_cov.dot(_prec).dot(observed_target) + target_cov.dot( _P - target_lin.T.dot(prec_opt).dot(target_off)) L", "set up lasso penalty and run usual lasso solver... (see", "= -self.logdens_linear.dot(target_linear) target_off = (self.cond_mean - target_lin.dot(observed_target_uni)).reshape((target_lin.shape[0],)) _prec = prec_target", "+ con_offset - con_linear.dot(gs)) ** 2.) + 1. / ((con_offset", "= target_cov.dot(_P - target_lin.T.dot(prec_opt).dot(target_off)) conjugate_arg = prec_opt.dot(cond_mean) val, soln, hess", "target. target_score_cov : ndarray Estimated covariance of target and score", "proposal = current - step * cur_grad if np.all(con_offset -", "scaling def objective(gs): p1 = -gs.T.dot(conjugate_arg) p2 = gs.T.dot(precision).dot(gs) /", "numpy as np from numpy import log from numpy.linalg import", "jacobian to hessian p1 = con_linear.T.dot(np.diag(-1. / ((scaling + con_offset", "1.5 * _scale[j], observed_target[j] + 1.5 * _scale[j], num=ngrid) self.opt_linear", "= _prec + L.dot(target_lin) - L.dot(hess.dot(L.T)) observed_info_mean = target_cov.dot(observed_info_natural.dot(target_cov)) Z_scores", "Approximate the log of the reference density on a grid." ]
[ "k in ks) fromto_counts = np.array([model._counts_fromto(self.stateseq[t-1],k) + self._counts_fromto(self.stateseq[t-1],k) for k", "self._occupied()) betarest = 1-sum(betavec[k] for k in ks) # get", "for k in ks) fromto_counts = np.array([model._counts_fromto(self.stateseq[t-1],k) + self._counts_fromto(self.stateseq[t-1],k) for", "= np.where(np.diff(seq) != 0) # internal end indices (not incl", "+= np.log(self.beta.remaining*(betas/(1-betas)).sum()) else: score += np.log(self.beta.remaining) # add in obs/dur", "A, ((A,stateseq[A.start]),) elif A.start <= t < A.stop or B.start", "indicating a potentially new label ABIGNUMBER = 10000 # state", "in ks]) scores = np.array([(alpha*betavec[k] + ft if k !=", "# state labels are sampled uniformly from 0 to abignumber", "* (1-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1])) # right transition (if there is", "rle # must override set methods # type(x).__setitem__(x,i) classmethod #", "counts) score += np.log(alpha) - np.log(alpha*(1.-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1])) # add", "returns a sequence of length between 1 and 3, where", "* beta[stateseq[t+1]] + model._counts_fromto(k,stateseq[t+1])) \\ - np.log(alpha * (1-beta[k]) +", "== k else 0 another_fromto = 1 if (t >", "scores = np.array([(alpha*betavec[k] + (kappa if k == stateseq[t+1] else", "slice(t,t+1) return slice(A.start,B.stop), [(x,stateseq[x.start]) for x in (A,It,B) if x.stop", "= np.where(self.stateseq[:-1] == k1) # EXCEPT last return np.sum(self.stateseq[from_indices+1] ==", "transition score if t < self.T-1: score += np.log(betavec[stateseq[t+1]]) #", "[alpha*(1-betavec[self.stateseq[t-1]])*betarest]) nextstateidx = sample_discrete(scores) if nextstateidx == scores.shape[0]-1: nextstate =", "k factor if t < self.T-1: betas = np.random.beta(1,self.beta.gamma_0,size=200) betas[1:]", "stateseq_norep]]) else: C = stateseq_norep[na,:] plt.pcolor(X,Y,C,vmin=0,vmax=1) plt.ylim((0,1)) plt.xlim((0,len(self.stateseq))) plt.yticks([]) class", "!= SAMPLING stateseq_norep, _ = rle(self.stateseq) temp = np.sum(stateseq_norep[:-1] ==", "= beta self.obs = obs self.dur = dur self.data =", "self.stateseq score = 0 # left transition score if t", "choice of what state to start in; it's just a", "1 if (t > 0 and stateseq[t-1] == k and", "= 1-sum(betavec[k] for k in ks) # get the counts", "= firststate_dur # run a family-CRF (CRF with durations) forwards", "plt stateseq_norep, durations = rle(self.stateseq) X,Y = np.meshgrid(np.hstack((0,durations.cumsum())),(0,1)) if colors_dict", "def _counts_from(self,k): pass @abc.abstractmethod def _counts_to(self,k): pass @abc.abstractmethod def _counts_fromto(self,k):", "sample proportional to scores = np.array([(alpha*betavec[k] + (kappa if k", "_new_label(self,ks): assert SAMPLING not in ks newlabel = np.random.randint(ABIGNUMBER) while", "self.dur.resample(combinedata((model._durs_withlabel(nextstate),self._durs_withlabel(nextstate)))) nextstate_dur = self.dur.rvs() self.stateseq = np.concatenate((self.stateseq,np.ones(nextstate_dur,dtype=int)*nextstate)) t += nextstate_dur", "stateseq_norep[na,:] plt.pcolor(X,Y,C,vmin=0,vmax=1) plt.ylim((0,1)) plt.xlim((0,len(self.stateseq))) plt.yticks([]) class collapsed_stickyhdphmm_states(collapsed_states): def __init__(self,model,beta,alpha_0,kappa,obs,data=None,T=None,stateseq=None): self.alpha_0", "0 score = 0. # unpack variables model = self.model", "# so that we can get the indicator sequence #", "states fromto_counts = np.array([model._counts_fromto(stateseq[t-1],k) + self._counts_fromto(stateseq[t-1],k) for k in ks])", "while t < T: ks = list(model._occupied() | self._occupied()) betarest", "no censoring by adding to score of last # segment", "just make sure outside that anything that sets self.stateseq #", "= np.array([self._label_score(t,k) for k in ks] + [self._new_label_score(t,ks)]) newlabelidx =", "colors_dict is not None: C = np.array([[colors_dict[state] for state in", "kappa = self.alpha_0, self.kappa betavec, model, o = self.beta.betavec, self.model,", "self.kappa betavec, model, o = self.beta.betavec, self.model, self.obs data, stateseq", "t > 0: betarest = 1-sum(betavec[k] for k in ks)", "def _counts_to(self,k): assert k != SAMPLING stateseq_norep, _ = rle(self.stateseq)", "counts) if t < self.T-1: score += np.log(beta[stateseq[t+1]]) # add", "not None: C = np.array([[colors_dict[state] for state in stateseq_norep]]) else:", "adding to score of last # segment SAMPLING = -1", "in self.stateseq or k1 == k2: return 0 else: stateseq_norep,", "# now get the duration of nextstate! self.dur.resample(combinedata((model._durs_withlabel(nextstate),self._durs_withlabel(nextstate)))) nextstate_dur =", "beta updates... class collapsed_states(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def resample(self):", "stateseq[t] = ks[nextstateidx] self.stateseq = stateseq def resample(self): model =", "self._counts_fromto(self.stateseq[t-1],k) for k in ks]) scores = np.array([(alpha*betavec[k] + ft", "pyplot as plt stateseq_norep, durations = rle(self.stateseq) X,Y = np.meshgrid(np.hstack((0,durations.cumsum())),(0,1))", "betavec, model, o = self.beta.betavec, self.model, self.obs data, stateseq =", "one) if stateseq[t-1] != k: score += np.log(alpha * beta[k]", "= 1 if (t > 0 and stateseq[t-1] == k", "that maintains its own rle # must override set methods", "SAMPLING in self.stateseq[1:] and \\ self.stateseq[np.where(self.stateseq == SAMPLING)[0]-1] == k:", "combinedata from pyhsmm.util.general import rle as rle # NOTE: assumes", "self.model._durs_withlabel(val) # add a piece to our localgroup localgroup.append(((self.data[piece],otherdata),(piece.stop-piece.start,otherdurs))) #", "= self.model self.stateseq = np.array([]) ks = list(model._occupied()) + [None]", "def _generate(self,T): alpha = self.alpha_0 betavec = self.beta.betavec model =", "= stateseq_norep[na,:] plt.pcolor(X,Y,C,vmin=0,vmax=1) plt.ylim((0,1)) plt.xlim((0,len(self.stateseq))) plt.yticks([]) class collapsed_stickyhdphmm_states(collapsed_states): def __init__(self,model,beta,alpha_0,kappa,obs,data=None,T=None,stateseq=None):", "and maybe self.data assert self.stateseq[t] == SAMPLING orig_stateseq = self.stateseq.copy()", "B.stop: return slice(A.start,B.stop), [(x,stateseq[x.start]) for x in (A,B) if x.stop", "members norep and lens (or something) # that are either", "# build local group of statistics localgroup = [] self.stateseq[wholegroup]", "(kappa if k == stateseq[t+1] else 0) + ft) for", "get the indicator sequence # TODO if i write the", "t > 0 and stateseq[t-1] == k else 0 another_fromto", "is one) if t < self.T-1 and stateseq[t+1] != k:", "def _new_label_score(self,t,ks): assert t > 0 score = 0. #", "if firststateidx == len(ks)-1: firststate = self._new_label(ks) else: firststate =", "= ks[newlabelidx] def _label_score(self,t,k): assert t > 0 score =", "return score def _new_score(self,ks,t): alpha, kappa = self.alpha_0, self.kappa betavec,", "be occupied. ks = list(model._occupied()) + [None] firststate = sample_discrete(np.arange(len(ks)))", "= sample_discrete(np.arange(len(ks))) if firststate == len(ks)-1: stateseq[0] = self._new_label(ks) else:", "self.obs, self.dur # left transition (if there is one) if", "constant for indicating a state or state range that is", "\\ - np.log(alpha * (1-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1])) # right transition", "= np.where(startindices <= t)[0][-1] return slice(startindices[idx],startindices[idx+1]) def canonize(seq): seq =", "as plt stateseq_norep, durations = rle(self.stateseq) X,Y = np.meshgrid(np.hstack((0,durations.cumsum())),(0,1)) if", "in ks) fromto_counts = np.array([model._counts_fromto(self.stateseq[t-1],k) + self._counts_fromto(self.stateseq[t-1],k) for k in", "not None, 'must pass in T when generating' self._generate(T) elif", "of seq return newlabel def _data_withlabel(self,k): assert k != SAMPLING", "will be occupied. ks = list(model._occupied()) + [None] firststate =", "in self.stateseq or k2 not in self.stateseq or k1 ==", "slice(A.start,B.stop), [(x,stateseq[x.start]) for x in (A,It,B) if x.stop - x.start", "and \\ stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]+1] == k: temp -= 1", "assert k != SAMPLING stateseq_norep, _ = rle(self.stateseq) temp =", "== k1) # EXCEPT last return np.sum(self.stateseq[from_indices+1] == k2) class", "if t < 0: return slice(0,0) elif t > seq.shape[0]-1:", "0 and stateseq[t-1] == k and stateseq[t+1] == k) else", "a delta at that label for t in (np.random.permutation(self.T-1)+1): self.stateseq[t]", "have a choice of what state to start in; it's", "### label sampler stuff def resample_label_version(self): # NOTE never changes", "if SAMPLING in stateseq_norep[:-1] and \\ stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]+1] ==", "k in ks]) scores = np.array([(alpha*betavec[k] + ft if k", "self.resample_label_version() def _durs_withlabel(self,k): assert k != SAMPLING if len(self.stateseq) >", "np.concatenate((self.stateseq,np.ones(nextstate_dur,dtype=int)*nextstate)) t += nextstate_dur self.T = len(self.stateseq) def resample(self): self.resample_label_version()", "+ model._counts_fromto(k,stateseq[t+1])) \\ - np.log(alpha * (1-beta[k]) + model._counts_from(k)) #", "np.random.randint(ABIGNUMBER) newweight = self.beta.betavec[newlabel] # instantiate, needed if new state", "to counts) score += np.log(alpha) - np.log(alpha*(1.-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1])) #", "nextstate = self._new_label(ks) else: nextstate = ks[nextstateidx] # now get", "last # segment SAMPLING = -1 # special constant for", "= data self.T = data.shape[0] def _generate(self,T): alpha = self.alpha_0", "SAMPLING for piece, val in pieces: # get all the", "@classmethod def _local_slices(cls,stateseq,t): ''' returns slices: wholegroup, (piece1, ...) '''", "value scores = np.array([self._label_score(t,k) for k in ks] + [self._new_label_score(t,ks)])", "internal end indices (not incl -1 and T-1) startindices =", "(if there is one) if t < self.T-1 and stateseq[t+1]", "new value scores = np.array([self._label_score(t,k) for k in ks] +", "it should also call beta updates... class collapsed_states(object): __metaclass__ =", "+ [None] firststateidx = sample_discrete(np.arange(len(ks))) if firststateidx == len(ks)-1: firststate", "the duration of nextstate! self.dur.resample(combinedata((model._durs_withlabel(nextstate),self._durs_withlabel(nextstate)))) nextstate_dur = self.dur.rvs() self.stateseq =", "never changes first label: we assume the initial state #", "assert k != SAMPLING return self.data[self.stateseq == k] def _occupied(self):", "0] else: It = slice(t,t+1) return slice(A.start,B.stop), [(x,stateseq[x.start]) for x", "if new state at beginning of seq return newlabel def", "def resample(self): model = self.model for t in np.random.permutation(self.T): #", "while newlabel in ks: newlabel = np.random.randint(ABIGNUMBER) newweight = self.beta.betavec[newlabel]", "views self.stateseq = orig_stateseq # return return localgroup @classmethod def", "local group of statistics localgroup = [] self.stateseq[wholegroup] = SAMPLING", "# restore original views self.stateseq = orig_stateseq # return return", "them scores = np.array([self._score(k,t) for k in ks]+[self._new_score(ks,t)]) idx =", "else: firststate = ks[firststateidx] self.dur.resample(combinedata((model._durs_withlabel(firststate),self._durs_withlabel(firststate)))) firststate_dur = self.dur.rvs() self.stateseq =", "k != SAMPLING stateseq_norep, _ = rle(self.stateseq) temp = np.sum(stateseq_norep[:-1]", "_counts_fromto(self,k1,k2): assert k1 != SAMPLING and k2 != SAMPLING if", "stateseq is None: self.data = data self._generate(data.shape[0]) else: assert data.shape[0]", "'must pass in T when generating' self._generate(T) elif data is", "in the HDP-HMM # Here, we choose just to sample", "1-sum(betavec[k] for k in ks) fromto_counts = np.array([model._counts_fromto(self.stateseq[t-1],k) + self._counts_fromto(self.stateseq[t-1],k)", "= self.stateseq obs, durs = self.obs, self.dur # left transition", "newlabel in ks: newlabel = np.random.randint(ABIGNUMBER) newweight = self.beta.betavec[newlabel] #", "override set methods # type(x).__setitem__(x,i) classmethod # also has members", "another_fromto) / (alpha+kappa+model._counts_from(k) + another_from) ) # observation score score", "stateseq[t+1] != k: score += np.log(alpha * beta[stateseq[t+1]] + model._counts_fromto(k,stateseq[t+1]))", "collections, itertools import abc from pyhsmm.util.stats import sample_discrete, sample_discrete_from_log, combinedata", "beta forwards for t in range(1,T): self.stateseq = stateseq[:t] ks", "len(ks)-1: firststate = self._new_label(ks) else: firststate = ks[firststateidx] self.dur.resample(combinedata((model._durs_withlabel(firststate),self._durs_withlabel(firststate)))) firststate_dur", "fixed weights beta forwards for t in range(1,T): self.stateseq =", "_ = rle(self.stateseq) temp = np.sum(stateseq_norep[:-1] == k) if SAMPLING", "class collapsed_states(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def resample(self): pass @abc.abstractmethod", "k) else 0 score += np.log( (alpha*betavec[stateseq[t+1]] + (kappa if", "else: stateseq[0] = ks[firststate] # runs a CRF with fixed", "betavec = self.beta.betavec stateseq = np.zeros(T,dtype=np.int) model = self.model self.stateseq", "in this model, this will always sample # zero, since", "self.stateseq[t] = SAMPLING ks = self.model._occupied() self.beta.housekeeping(ks) ks = list(ks)", "self.stateseq[t] = SAMPLING ks = list(model._occupied()) self.beta.housekeeping(ks) # form the", "in stateseq_norep[1:] and \\ stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]-1] == k: temp", "else 0) + ft) for k,ft in zip(ks,fromto_counts)] + [alpha*betarest])", "from the exclusion self.stateseq[piece] = orig_stateseq[piece] # restore original views", "beta[stateseq[t+1]] + model._counts_fromto(k,stateseq[t+1])) \\ - np.log(alpha * (1-beta[k]) + model._counts_from(k))", "= SAMPLING ks = list(model._occupied()) self.beta.housekeeping(ks) # form the scores", "score score += o.log_marginal_likelihood(data[t]) return score def _counts_from(self,k): assert k", "add a piece to our localgroup localgroup.append(((self.data[piece],otherdata),(piece.stop-piece.start,otherdurs))) # remove the", "make sure outside that anything that sets self.stateseq # also", "score += np.log(self.beta.remaining*(betas/(1-betas)).sum()) else: score += np.log(self.beta.remaining) # add in", "# internal end indices (not incl -1 and T-1) startindices", "= self.model._data_withlabel(val), self.model._durs_withlabel(val) # add a piece to our localgroup", "self.obs = obs self.dur = dur self.data = data if", "exclusive #################### # States Classes # #################### # TODO an", "# that are either read-only or also override setters #", "| self._occupied()) betarest = 1-sum(betavec[k] for k in ks) fromto_counts", "np.ones(firststate_dur,dtype=int)*firststate t = firststate_dur # run a family-CRF (CRF with", "self.stateseq_norep, self.durations = rle(stateseq) self.data = data self.T = data.shape[0]", "self.stateseq[t] = k wholegroup, pieces = self._local_slices(self.stateseq,t) self.stateseq[t] = SAMPLING", "self.model, self.obs data, stateseq = self.data, self.stateseq score = 0", "\\ - np.log(alpha * (1-beta[k]) + model._counts_from(k)) # predictive likelihoods", "in right transition (no counts) if t < self.T-1: score", "1 if t > 0 and stateseq[t-1] == k else", "temp = np.sum(self.stateseq[1:] == k) if SAMPLING in self.stateseq[:-1] and", "# self.stateseq = self.stateseq[:self.T] self.stateseq = np.random.randint(25,size=data.shape[0]) self.T = data.shape[0]", "else: It = slice(t,t+1) return slice(A.start,B.stop), [(x,stateseq[x.start]) for x in", "that is being resampled NEW = -2 # special constant", "form the scores and sample from them scores = np.array([self._score(k,t)", "self._occupied()) betarest = 1-sum(betavec[k] for k in ks) fromto_counts =", "state # going to all other states fromto_counts = np.array([model._counts_fromto(stateseq[t-1],k)", "+ [alpha*(1-betavec[self.stateseq[t-1]])*betarest]) nextstateidx = sample_discrete(scores) if nextstateidx == scores.shape[0]-1: nextstate", "import abc from pyhsmm.util.stats import sample_discrete, sample_discrete_from_log, combinedata from pyhsmm.util.general", "(no counts) if t < self.T-1: score += np.log(beta[stateseq[t+1]]) #", "ks) # get the counts of new states coming out", "na = np.newaxis import collections, itertools import abc from pyhsmm.util.stats", "unpack model = self.model alpha = self.alpha_0 beta = self.beta.betavec", "# left transition (if there is one) if stateseq[t-1] !=", "self.stateseq[:-1] and \\ self.stateseq[np.where(self.stateseq == SAMPLING)[0]+1] == k: temp -=", "(A,B) if x.stop - x.start > 0] else: It =", "== k] else: return [] def _counts_fromto(self,k1,k2): assert k1 !=", "= self.beta.betavec model = self.model self.stateseq = np.array([]) ks =", "= rle(self.stateseq) temp = np.sum(stateseq_norep[:-1] == k) if SAMPLING in", "_local_slices(cls,stateseq,t): ''' returns slices: wholegroup, (piece1, ...) ''' A,B =", "score += np.log(alpha * beta[stateseq[t+1]] + model._counts_fromto(k,stateseq[t+1])) \\ - np.log(alpha", "family-CRF (CRF with durations) forwards while t < T: ks", "t < B.stop: return slice(A.start,B.stop), [(x,stateseq[x.start]) for x in (A,B)", "== k) if SAMPLING in self.stateseq[1:] and \\ self.stateseq[np.where(self.stateseq ==", "one) if t < self.T-1 and stateseq[t+1] != k: score", "that if this is the # first chain being sampled", "C = np.array([[colors_dict[state] for state in stateseq_norep]]) else: C =", "# temporarily set stateseq to hypothetical stateseq # so that", "stateseq self.data = data self.T = data.shape[0] def _generate(self,T): self.T", "the other data otherdata, otherdurs = self.model._data_withlabel(val), self.model._durs_withlabel(val) # add", "slice(seq.shape[0],seq.shape[0]) else: endindices, = np.where(np.diff(seq) != 0) # internal end", "set(self.stateseq) - set((SAMPLING,)) def plot(self,colors_dict): from matplotlib import pyplot as", "# also has members norep and lens (or something) #", "and T idx = np.where(startindices <= t)[0][-1] return slice(startindices[idx],startindices[idx+1]) def", "as np na = np.newaxis import collections, itertools import abc", "== k2) def _counts_from(self,k): assert k != SAMPLING stateseq_norep, _", "HDP-HMM # Here, we choose just to sample from beta.", "else 0) + model._counts_fromto(stateseq[t-1],k)) / (alpha+kappa+model._counts_from(stateseq[t-1])) ) # right transition", "# must override set methods # type(x).__setitem__(x,i) classmethod # also", "+ (kappa if k == stateseq[t-1] else 0) + model._counts_fromto(stateseq[t-1],k))", "= seq.copy() canondict = collections.defaultdict(itertools.count().next) for idx,s in enumerate(seq): seq[idx]", "in zip(ks,fromto_counts)] + [alpha*(1-betavec[self.stateseq[t-1]])*betarest]) nextstateidx = sample_discrete(scores) if nextstateidx ==", "pyhsmm.util.stats import sample_discrete, sample_discrete_from_log, combinedata from pyhsmm.util.general import rle as", "# indicators since we may need to include the left", "= ks[firststateidx] self.dur.resample(combinedata((model._durs_withlabel(firststate),self._durs_withlabel(firststate)))) firststate_dur = self.dur.rvs() self.stateseq = np.ones(firststate_dur,dtype=int)*firststate t", "return score def _new_label_score(self,t,ks): assert t > 0 score =", "list(model._occupied()) + [None] firststate = sample_discrete(np.arange(len(ks))) if firststate == len(ks)-1:", "!= SAMPLING and k2 != SAMPLING if k1 not in", "t < 0: return slice(0,0) elif t > seq.shape[0]-1: return", "those states plus a new one, sample proportional to scores", "temp -= 1 return temp def _counts_to(self,k): assert k !=", "self.beta.betavec stateseq = self.stateseq obs, durs = self.obs, self.dur #", "+= np.log(alpha * beta[k] + model._counts_fromto(stateseq[t-1],k)) \\ - np.log(alpha *", "self.data = data if (data,stateseq) == (None,None): # generating assert", "else: nextstate = ks[nextstateidx] # now get the duration of", "= np.concatenate((self.stateseq,np.ones(nextstate_dur,dtype=int)*nextstate)) t += nextstate_dur self.T = len(self.stateseq) def resample(self):", "else: self.stateseq[t] = ks[newlabelidx] def _label_score(self,t,k): assert t > 0", "k1 not in self.stateseq or k2 not in self.stateseq or", "\\ stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]-1] == k: temp -= 1 return", "+= np.log(beta[stateseq[t+1]]) # add in sum over k factor if", "rle # NOTE: assumes censoring. can make no censoring by", "= -2 # special constant indicating a potentially new label", "to scores = np.array([(alpha*betavec[k] + (kappa if k == stateseq[t+1]", "= sample_discrete_from_log(scores) # set the state if idx == scores.shape[0]-1:", "####################### # Utility Functions # ####################### def fill(seq,t): if t", "for k in ks]+[self._new_score(ks,t)]) idx = sample_discrete_from_log(scores) # set the", "(None,None): # generating assert T is not None, 'must pass", "> 0 and stateseq[t-1] == k else 0 another_fromto =", "= rle(self.stateseq) from_indices, = np.where(stateseq_norep[:-1] == k1) # EXCEPT last", "seq.copy() canondict = collections.defaultdict(itertools.count().next) for idx,s in enumerate(seq): seq[idx] =", "def _counts_fromto(self,k1,k2): assert k1 != SAMPLING and k2 != SAMPLING", "# type(x).__setitem__(x,i) classmethod # also has members norep and lens", "#################### # TODO an array class that maintains its own", "if x.stop - x.start > 0] ####################### # Utility Functions", "sample_discrete_from_log(scores) # set the state if idx == scores.shape[0]-1: self.stateseq[t]", "# add in sum over k factor if t <", "read-only or also override setters # for now, i'll just", "stateseq # so that we can get the indicator sequence", "assert data.shape[0] == stateseq.shape[0] self.stateseq = stateseq self.stateseq_norep, self.durations =", "this is the # first chain being sampled in this", "stateseq[t+1] else 0) + model._counts_fromto(k,stateseq[t+1]) + another_fromto) / (alpha+kappa+model._counts_from(k) +", "sampler stuff def resample_label_version(self): # NOTE never changes first label:", "firststate_dur = self.dur.rvs() self.stateseq = np.ones(firststate_dur,dtype=int)*firststate t = firststate_dur #", "self.data = data self.T = data.shape[0] def _generate(self,T): self.T =", "and \\ stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]-1] == k: temp -= 1", "EXCEPT last return np.sum(stateseq_norep[from_indices+1] == k2) def _counts_from(self,k): assert k", "used piece from the exclusion self.stateseq[piece] = orig_stateseq[piece] # restore", "#################### # States Classes # #################### # TODO an array", "np.sum(stateseq_norep[:-1] == k) if SAMPLING in stateseq_norep[1:] and \\ stateseq_norep[np.where(stateseq_norep", "= sample_discrete(scores) if nextstateidx == scores.shape[0]-1: nextstate = self._new_label(ks) else:", "= rle(self.stateseq) temp = np.sum(stateseq_norep[1:] == k) if SAMPLING in", "return [] def _counts_fromto(self,k1,k2): assert k1 != SAMPLING and k2", "k1 == k2: return 0 else: stateseq_norep, _ = rle(self.stateseq)", "assumes censoring. can make no censoring by adding to score", "class collapsed_stickyhdphmm_states(collapsed_states): def __init__(self,model,beta,alpha_0,kappa,obs,data=None,T=None,stateseq=None): self.alpha_0 = alpha_0 self.kappa = kappa", "of local pieces for (data,otherdata), (dur,otherdurs) in self._local_group(t,NEW): score +=", "stateseq = np.zeros(T,dtype=np.int) model = self.model self.stateseq = stateseq[:0] #", "(0,1) temp = np.sum(self.stateseq[1:] == k) if SAMPLING in self.stateseq[:-1]", "= np.array([(alpha*betavec[k] + (kappa if k == stateseq[t+1] else 0)", "+ self._counts_fromto(stateseq[t-1],k) for k in ks]) # for those states", "k2 not in self.stateseq or k1 == k2: return 0", "may need to include the left transition in # counts", "t < self.T-1: score += np.log(betavec[stateseq[t+1]]) # observation score score", "# add in right transition (no counts) if t <", "+ [alpha*betarest]) nextstateidx = sample_discrete(scores) if nextstateidx == scores.shape[0]-1: stateseq[t]", "== k and stateseq[t+1] == k) else 0 score +=", "k wholegroup, pieces = self._local_slices(self.stateseq,t) self.stateseq[t] = SAMPLING # build", "in self.stateseq[:-1] and \\ self.stateseq[np.where(self.stateseq == SAMPLING)[0]+1] == k: temp", "CRF with fixed weights beta forwards for t in range(1,T):", "elif data is None: self.T = stateseq.shape[0] self.stateseq = stateseq", "= collections.defaultdict(itertools.count().next) for idx,s in enumerate(seq): seq[idx] = canondict[s] reversedict", "''' # temporarily modifies members, like self.stateseq and maybe self.data", "changes first label: we assume the initial state # distribution", "betarest = 1-sum(betavec[k] for k in ks) score += np.log(alpha*betarest/(alpha+kappa+model._counts_from(stateseq[t-1])))", "= data.shape[0] def _generate(self,T): alpha = self.alpha_0 betavec = self.beta.betavec", "that we can get the indicator sequence # TODO if", "np.log(beta[stateseq[t+1]]) # add in sum over k factor if t", "at beginning of seq return newlabel def _data_withlabel(self,k): assert k", "np.log(alpha*betarest/(alpha+kappa+model._counts_from(stateseq[t-1]))) # right transition score if t < self.T-1: score", "ABIGNUMBER = 10000 # state labels are sampled uniformly from", "self.model for t in np.random.permutation(self.T): # throw out old value", "= self.beta.betavec, self.model, self.obs data, stateseq = self.data, self.stateseq score", "is one) if stateseq[t-1] != k: score += np.log(alpha *", "= self.stateseq.copy() # temporarily set stateseq to hypothetical stateseq #", "= list(ks) # sample a new value scores = np.array([self._label_score(t,k)", "exchangeably, not independently) another_from = 1 if t > 0", "chain being sampled in this model, this will always sample", "3, where each sequence element is ((data,otherdata), (dur,otherdurs)) ''' #", "fill(stateseq,t-1), fill(stateseq,t+1) if A == B: return A, ((A,stateseq[A.start]),) elif", "# left transition (only from counts, no to counts) score", "ks[nextstateidx] self.stateseq = stateseq def resample(self): model = self.model for", "T-1) startindices = np.concatenate(((0,),endindices+1,(seq.shape[0],))) # incl 0 and T idx", "self.stateseq[1:] and \\ self.stateseq[np.where(self.stateseq == SAMPLING)[0]-1] == k: temp -=", "are scoring exchangeably, not independently) another_from = 1 if t", "another_from = 1 if t > 0 and stateseq[t-1] ==", "idx = np.where(startindices <= t)[0][-1] return slice(startindices[idx],startindices[idx+1]) def canonize(seq): seq", "score = 0 # left transition score if t >", "and stateseq[t-1] == k else 0 another_fromto = 1 if", "t += nextstate_dur self.T = len(self.stateseq) def resample(self): self.resample_label_version() def", "stateseq is None: self.data = data # self._generate(data.shape[0]) # initialized", "transition score if t > 0: score += np.log( (alpha*betavec[k]", "score += o.log_marginal_likelihood(data[t]) return score def _counts_from(self,k): assert k !=", "k: score += np.log(alpha * beta[stateseq[t+1]] + model._counts_fromto(k,stateseq[t+1])) \\ -", "idx = sample_discrete_from_log(scores) # set the state if idx ==", "== SAMPLING)[0]+1] == k: temp -= 1 return temp def", "self.stateseq[piece] = orig_stateseq[piece] # restore original views self.stateseq = orig_stateseq", "stateseq_norep, durations = rle(self.stateseq) X,Y = np.meshgrid(np.hstack((0,durations.cumsum())),(0,1)) if colors_dict is", "self.stateseq = np.ones(firststate_dur,dtype=int)*firststate t = firststate_dur # run a family-CRF", "rle as rle # NOTE: assumes censoring. can make no", "_score(self,k,t): alpha, kappa = self.alpha_0, self.kappa betavec, model, o =", "def canonize(seq): seq = seq.copy() canondict = collections.defaultdict(itertools.count().next) for idx,s", "of last # segment SAMPLING = -1 # special constant", "collections.defaultdict(itertools.count().next) for idx,s in enumerate(seq): seq[idx] = canondict[s] reversedict =", "newlabel = np.random.randint(ABIGNUMBER) while newlabel in ks: newlabel = np.random.randint(ABIGNUMBER)", "= data if (data,stateseq) == (None,None): # generating assert T", "== SAMPLING) in (0,1) temp = np.sum(self.stateseq[:-1] == k) if", "temp -= 1 return temp def _counts_fromto(self,k1,k2): assert k1 !=", "self.dur = dur self.data = data if (data,stateseq) == (None,None):", "(piece1, ...) ''' A,B = fill(stateseq,t-1), fill(stateseq,t+1) if A ==", "== k2) class collapsed_hdphsmm_states(collapsed_states): def __init__(self,model,beta,alpha_0,obs,dur,data=None,T=None,stateseq=None): self.alpha_0 = alpha_0 self.model", "add in sum over k factor if t < self.T-1:", "likelihoods for (data,otherdata), (dur,otherdurs) in self._local_group(t,k): score += obs.log_predictive(data,otherdata) +", "self.stateseq = stateseq def resample(self): model = self.model for t", "choice that isn't specified in the HDP-HMM # Here, we", "< self.T-1: score += np.log(beta[stateseq[t+1]]) # add in sum over", "np.array([(alpha*betavec[k] + ft if k != self.stateseq[t-1] else 0) for", "or also override setters # for now, i'll just make", "class that maintains its own rle # must override set", "_new_label_score(self,t,ks): assert t > 0 score = 0. # unpack", "self.stateseq # also sets self.stateseq_norep and self.durations # it should", "sample_discrete(np.arange(len(ks))) if firststate == len(ks)-1: stateseq[0] = self._new_label(ks) else: stateseq[0]", "self.T = data.shape[0] def _generate(self,T): alpha = self.alpha_0 betavec =", "stateseq[t-1] else 0) + model._counts_fromto(stateseq[t-1],k)) / (alpha+kappa+model._counts_from(stateseq[t-1])) ) # right", "+ [None] firststate = sample_discrete(np.arange(len(ks))) if firststate == len(ks)-1: stateseq[0]", "if t < self.T - 1: # indicators since we", "hypothetical stateseq # so that we can get the indicator", "_counts_to(self,k): pass @abc.abstractmethod def _counts_fromto(self,k): pass def _new_label(self,ks): assert SAMPLING", "not in self.stateseq or k2 not in self.stateseq or k1", "_data_withlabel(self,k): assert k != SAMPLING return self.data[self.stateseq == k] def", "if t > 0: betarest = 1-sum(betavec[k] for k in", "k != SAMPLING assert np.sum(self.stateseq == SAMPLING) in (0,1) temp", "return A, ((A,stateseq[A.start]),) elif A.start <= t < A.stop or", "# instantiate, needed if new state at beginning of seq", "in self.stateseq[1:] and \\ self.stateseq[np.where(self.stateseq == SAMPLING)[0]-1] == k: temp", "get the duration of nextstate! self.dur.resample(combinedata((model._durs_withlabel(nextstate),self._durs_withlabel(nextstate)))) nextstate_dur = self.dur.rvs() self.stateseq", "in (np.random.permutation(self.T-1)+1): self.stateseq[t] = SAMPLING ks = self.model._occupied() self.beta.housekeeping(ks) ks", "kappa = self.alpha_0, self.kappa betavec = self.beta.betavec stateseq = np.zeros(T,dtype=np.int)", "beta = self.beta.betavec stateseq = self.stateseq obs, durs = self.obs,", "k,ft in zip(ks,fromto_counts)] + [alpha*betarest]) nextstateidx = sample_discrete(scores) if nextstateidx", "+ model._counts_from(stateseq[t-1])) # right transition (if there is one) if", "k2) class collapsed_hdphsmm_states(collapsed_states): def __init__(self,model,beta,alpha_0,obs,dur,data=None,T=None,stateseq=None): self.alpha_0 = alpha_0 self.model =", "10000 # state labels are sampled uniformly from 0 to", "rle(self.stateseq) X,Y = np.meshgrid(np.hstack((0,durations.cumsum())),(0,1)) if colors_dict is not None: C", "occupied. ks = list(model._occupied()) + [None] firststate = sample_discrete(np.arange(len(ks))) if", "self.T = len(self.stateseq) def resample(self): self.resample_label_version() def _durs_withlabel(self,k): assert k", "element is ((data,otherdata), (dur,otherdurs)) ''' # temporarily modifies members, like", "self.data assert self.stateseq[t] == SAMPLING orig_stateseq = self.stateseq.copy() # temporarily", "<= t)[0][-1] return slice(startindices[idx],startindices[idx+1]) def canonize(seq): seq = seq.copy() canondict", "localgroup @classmethod def _local_slices(cls,stateseq,t): ''' returns slices: wholegroup, (piece1, ...)", "SAMPLING assert np.sum(self.stateseq == SAMPLING) in (0,1) temp = np.sum(self.stateseq[:-1]", "# form the scores and sample from them scores =", "first chain being sampled in this model, this will always", "> 0: betarest = 1-sum(betavec[k] for k in ks) score", "we assume the initial state # distribution is a delta", "are sampled uniformly from 0 to abignumber exclusive #################### #", "plt.yticks([]) class collapsed_stickyhdphmm_states(collapsed_states): def __init__(self,model,beta,alpha_0,kappa,obs,data=None,T=None,stateseq=None): self.alpha_0 = alpha_0 self.kappa =", "from counts, no to counts) score += np.log(alpha) - np.log(alpha*(1.-beta[stateseq[t-1]])", "(alpha*betavec[stateseq[t+1]] + (kappa if k == stateseq[t+1] else 0) +", "o.log_marginal_likelihood(data[t]) return score def _counts_from(self,k): assert k != SAMPLING assert", "SAMPLING orig_stateseq = self.stateseq.copy() # temporarily set stateseq to hypothetical", "another_from) ) # observation score score += o.log_predictive(data[t],model._data_withlabel(k)) return score", "we have a choice of what state to start in;", "= list(model._occupied()) + [None] firststateidx = sample_discrete(np.arange(len(ks))) if firststateidx ==", "else: stateseq[t] = ks[nextstateidx] self.stateseq = stateseq def resample(self): model", "of our current state # going to all other states", "indicator sequence # TODO if i write the special stateseq", "or B.start <= t < B.stop: return slice(A.start,B.stop), [(x,stateseq[x.start]) for", "division import numpy as np na = np.newaxis import collections,", "0) + model._counts_fromto(k,stateseq[t+1]) + another_fromto) / (alpha+kappa+model._counts_from(k) + another_from) )", "for k in ks]) # for those states plus a", "= np.sum(stateseq_norep[:-1] == k) if SAMPLING in stateseq_norep[1:] and \\", "return temp ### label sampler stuff def resample_label_version(self): # NOTE", "not in ks newlabel = np.random.randint(ABIGNUMBER) while newlabel in ks:", "A.stop or B.start <= t < B.stop: return slice(A.start,B.stop), [(x,stateseq[x.start])", "> 0 and stateseq[t-1] == k and stateseq[t+1] == k)", "nextstate = ks[nextstateidx] # now get the duration of nextstate!", "SAMPLING if k1 not in self.stateseq or k2 not in", "indicators since we may need to include the left transition", "= abc.ABCMeta @abc.abstractmethod def resample(self): pass @abc.abstractmethod def _counts_from(self,k): pass", "zero, since no states will be occupied. ks = list(model._occupied())", "newlabelidx = sample_discrete_from_log(scores) if newlabelidx == scores.shape[0]-1: self.stateseq[t] = self._new_label(ks)", "this will always sample # zero, since no states will", "norep and lens (or something) # that are either read-only", "startindices = np.concatenate(((0,),endindices+1,(seq.shape[0],))) # incl 0 and T idx =", "new states coming out of our current state # going", "to our localgroup localgroup.append(((self.data[piece],otherdata),(piece.stop-piece.start,otherdurs))) # remove the used piece from", "always sample # zero, since no states will be occupied.", "\\ stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]+1] == k: temp -= 1 return", "= np.array([self._score(k,t) for k in ks]+[self._new_score(ks,t)]) idx = sample_discrete_from_log(scores) #", "for now, i'll just make sure outside that anything that", "own rle # must override set methods # type(x).__setitem__(x,i) classmethod", "include the left transition in # counts (since we are", "self.model._occupied() self.beta.housekeeping(ks) ks = list(ks) # sample a new value", "score if t < self.T - 1: # indicators since", "= np.ones(firststate_dur,dtype=int)*firststate t = firststate_dur # run a family-CRF (CRF", "temporarily set stateseq to hypothetical stateseq # so that we", "self.data, self.stateseq score = 0 # left transition score if", "stateseq_norep[1:] and \\ stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]-1] == k: temp -=", "# going to all other states fromto_counts = np.array([model._counts_fromto(stateseq[t-1],k) +", "t > seq.shape[0]-1: return slice(seq.shape[0],seq.shape[0]) else: endindices, = np.where(np.diff(seq) !=", "else: stateseq_norep, _ = rle(self.stateseq) from_indices, = np.where(stateseq_norep[:-1] == k1)", "self.T = data.shape[0] def _generate(self,T): self.T = T alpha, kappa", "need to include the left transition in # counts (since", "# return return localgroup @classmethod def _local_slices(cls,stateseq,t): ''' returns slices:", "reversedict class dummytrans(object): def __init__(self,A): self.A = A def resample(self,*args,**kwargs):", "= self.beta.betavec stateseq = self.stateseq obs, durs = self.obs, self.dur", "!= 0) # internal end indices (not incl -1 and", "data if (data,stateseq) == (None,None): # generating assert T is", "stateseq_norep[:-1] and \\ stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]+1] == k: temp -=", "# get the counts of new states coming out of", "[None] firststateidx = sample_discrete(np.arange(len(ks))) if firststateidx == len(ks)-1: firststate =", "setters # for now, i'll just make sure outside that", "# unpack model = self.model alpha = self.alpha_0 beta =", "stateseq_norep, _ = rle(self.stateseq) temp = np.sum(stateseq_norep[1:] == k) if", "k1) # EXCEPT last return np.sum(stateseq_norep[from_indices+1] == k2) def _counts_from(self,k):", "return np.sum(self.stateseq[from_indices+1] == k2) class collapsed_hdphsmm_states(collapsed_states): def __init__(self,model,beta,alpha_0,obs,dur,data=None,T=None,stateseq=None): self.alpha_0 =", "= 1-sum(betavec[k] for k in ks) score += np.log(alpha*betarest/(alpha+kappa+model._counts_from(stateseq[t-1]))) #", "[alpha*betarest]) nextstateidx = sample_discrete(scores) if nextstateidx == scores.shape[0]-1: stateseq[t] =", "(1-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1])) # right transition (if there is one)", "for k in ks) # get the counts of new", "self.kappa = kappa self.model = model self.beta = beta self.obs", "ks newlabel = np.random.randint(ABIGNUMBER) while newlabel in ks: newlabel =", "= self.beta.betavec[newlabel] # instantiate, needed if new state at beginning", "= obs self.data = data if (data,stateseq) == (None,None): #", "= np.random.randint(25,size=data.shape[0]) self.T = data.shape[0] else: assert data.shape[0] == stateseq.shape[0]", "_counts_from(self,k): assert k != SAMPLING stateseq_norep, _ = rle(self.stateseq) temp", "@abc.abstractmethod def _counts_fromto(self,k): pass def _new_label(self,ks): assert SAMPLING not in", "in ks]) # for those states plus a new one,", "np.sum(self.stateseq[from_indices+1] == k2) class collapsed_hdphsmm_states(collapsed_states): def __init__(self,model,beta,alpha_0,obs,dur,data=None,T=None,stateseq=None): self.alpha_0 = alpha_0", "needed if new state at beginning of seq return newlabel", "ks[firststate] # runs a CRF with fixed weights beta forwards", "= 1 if t > 0 and stateseq[t-1] == k", "- x.start > 0] else: It = slice(t,t+1) return slice(A.start,B.stop),", "= stateseq.shape[0] self.stateseq = stateseq elif stateseq is None: self.data", "the scores and sample from them scores = np.array([self._score(k,t) for", "def _data_withlabel(self,k): assert k != SAMPLING return self.data[self.stateseq == k]", "score def _new_score(self,ks,t): alpha, kappa = self.alpha_0, self.kappa betavec, model,", "in T when generating' self._generate(T) elif data is None: self.T", "abignumber exclusive #################### # States Classes # #################### # TODO", "k2 != SAMPLING if k1 not in self.stateseq or k2", "from the prior # self.stateseq = self.stateseq[:self.T] self.stateseq = np.random.randint(25,size=data.shape[0])", "returns slices: wholegroup, (piece1, ...) ''' A,B = fill(stateseq,t-1), fill(stateseq,t+1)", "transition (no counts) if t < self.T-1: score += np.log(beta[stateseq[t+1]])", "plt.xlim((0,len(self.stateseq))) plt.yticks([]) class collapsed_stickyhdphmm_states(collapsed_states): def __init__(self,model,beta,alpha_0,kappa,obs,data=None,T=None,stateseq=None): self.alpha_0 = alpha_0 self.kappa", "sure outside that anything that sets self.stateseq # also sets", "SAMPLING ks = list(model._occupied()) self.beta.housekeeping(ks) # form the scores and", "self.T = T alpha, kappa = self.alpha_0, self.kappa betavec =", "statistics localgroup = [] self.stateseq[wholegroup] = SAMPLING for piece, val", "in ks] + [self._new_label_score(t,ks)]) newlabelidx = sample_discrete_from_log(scores) if newlabelidx ==", "class dummytrans(object): def __init__(self,A): self.A = A def resample(self,*args,**kwargs): pass", "in self.stateseq or k2 not in self.stateseq: return 0 else:", "assert k != SAMPLING if len(self.stateseq) > 0: stateseq_norep, durations", "= obs self.dur = dur self.data = data if (data,stateseq)", "= self._new_label(ks) else: self.stateseq[t] = ks[idx] def _score(self,k,t): alpha, kappa", "self.dur.rvs() self.stateseq = np.concatenate((self.stateseq,np.ones(nextstate_dur,dtype=int)*nextstate)) t += nextstate_dur self.T = len(self.stateseq)", "this will need fixing self.stateseq[t] = k wholegroup, pieces =", "self.stateseq = np.random.randint(25,size=data.shape[0]) self.T = data.shape[0] else: assert data.shape[0] ==", "firststate == len(ks)-1: stateseq[0] = self._new_label(ks) else: stateseq[0] = ks[firststate]", "each sequence element is ((data,otherdata), (dur,otherdurs)) ''' # temporarily modifies", "obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs) return score def _local_group(self,t,k): ''' returns a", "self.model alpha = self.alpha_0 beta = self.beta.betavec stateseq = self.stateseq", "old value self.stateseq[t] = SAMPLING ks = list(model._occupied()) self.beta.housekeeping(ks) #", "if SAMPLING in stateseq_norep[1:] and \\ stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]-1] ==", "k != self.stateseq[t-1] else 0) for k,ft in zip(ks,fromto_counts)] +", "last return np.sum(stateseq_norep[from_indices+1] == k2) def _counts_from(self,k): assert k !=", "newlabel def _data_withlabel(self,k): assert k != SAMPLING return self.data[self.stateseq ==", "len(ks)-1: stateseq[0] = self._new_label(ks) else: stateseq[0] = ks[firststate] # runs", "A.start <= t < A.stop or B.start <= t <", "return set(self.stateseq) - set((SAMPLING,)) def plot(self,colors_dict): from matplotlib import pyplot", "isn't specified in the HDP-HMM # Here, we choose just", "potentially new label ABIGNUMBER = 10000 # state labels are", "for state in stateseq_norep]]) else: C = stateseq_norep[na,:] plt.pcolor(X,Y,C,vmin=0,vmax=1) plt.ylim((0,1))", "_counts_to(self,k): assert k != SAMPLING assert np.sum(self.stateseq == SAMPLING) in", "sequence element is ((data,otherdata), (dur,otherdurs)) ''' # temporarily modifies members,", "plot(self,colors_dict): from matplotlib import pyplot as plt stateseq_norep, durations =", "self.model self.stateseq = stateseq[:0] # NOTE: we have a choice", "<= t < A.stop or B.start <= t < B.stop:", "call beta updates... class collapsed_states(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def", "assert k1 != SAMPLING and k2 != SAMPLING if k1", "def _generate(self,T): self.T = T alpha, kappa = self.alpha_0, self.kappa", "for k in ks] + [self._new_label_score(t,ks)]) newlabelidx = sample_discrete_from_log(scores) if", "if firststate == len(ks)-1: stateseq[0] = self._new_label(ks) else: stateseq[0] =", "collapsed_states(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def resample(self): pass @abc.abstractmethod def", "= self.obs, self.dur # left transition (only from counts, no", "0 score += np.log( (alpha*betavec[stateseq[t+1]] + (kappa if k ==", "that anything that sets self.stateseq # also sets self.stateseq_norep and", "# Here, we choose just to sample from beta. Note", "o.log_predictive(data[t],model._data_withlabel(k)) return score def _new_score(self,ks,t): alpha, kappa = self.alpha_0, self.kappa", "or k2 not in self.stateseq or k1 == k2: return", "''' returns a sequence of length between 1 and 3,", "pass def _new_label(self,ks): assert SAMPLING not in ks newlabel =", "return return localgroup @classmethod def _local_slices(cls,stateseq,t): ''' returns slices: wholegroup,", "1: # indicators since we may need to include the", "== stateseq.shape[0] self.stateseq = stateseq self.stateseq_norep, self.durations = rle(stateseq) self.data", "left transition in # counts (since we are scoring exchangeably,", "k in ks) # get the counts of new states", "EXCEPT last return np.sum(self.stateseq[from_indices+1] == k2) class collapsed_hdphsmm_states(collapsed_states): def __init__(self,model,beta,alpha_0,obs,dur,data=None,T=None,stateseq=None):", "t < T: ks = list(model._occupied() | self._occupied()) betarest =", "k,ft in zip(ks,fromto_counts)] + [alpha*(1-betavec[self.stateseq[t-1]])*betarest]) nextstateidx = sample_discrete(scores) if nextstateidx", "_ = rle(self.stateseq) from_indices, = np.where(stateseq_norep[:-1] == k1) # EXCEPT", "None: self.T = stateseq.shape[0] self.stateseq = stateseq elif stateseq is", "== k2: return 0 else: stateseq_norep, _ = rle(self.stateseq) from_indices,", "= stateseq def resample(self): model = self.model for t in", "seq[idx] = canondict[s] reversedict = {} for k,v in canondict.iteritems():", "= k wholegroup, pieces = self._local_slices(self.stateseq,t) self.stateseq[t] = SAMPLING #", "+= np.log(alpha*betarest/(alpha+kappa+model._counts_from(stateseq[t-1]))) # right transition score if t < self.T-1:", "# #################### # TODO an array class that maintains its", "None: C = np.array([[colors_dict[state] for state in stateseq_norep]]) else: C", "= stateseq elif stateseq is None: self.data = data self._generate(data.shape[0])", "1-sum(betavec[k] for k in ks) # get the counts of", "nextstate! self.dur.resample(combinedata((model._durs_withlabel(nextstate),self._durs_withlabel(nextstate)))) nextstate_dur = self.dur.rvs() self.stateseq = np.concatenate((self.stateseq,np.ones(nextstate_dur,dtype=int)*nextstate)) t +=", "get all the other data otherdata, otherdurs = self.model._data_withlabel(val), self.model._durs_withlabel(val)", "- 1: # indicators since we may need to include", "0 another_fromto = 1 if (t > 0 and stateseq[t-1]", "self.model = model self.beta = beta self.obs = obs self.data", "resample_label_version(self): # NOTE never changes first label: we assume the", "when generating' self._generate(T) elif data is None: self.T = stateseq.shape[0]", "otherdata, otherdurs = self.model._data_withlabel(val), self.model._durs_withlabel(val) # add a piece to", "scores.shape[0]-1: self.stateseq[t] = self._new_label(ks) else: self.stateseq[t] = ks[newlabelidx] def _label_score(self,t,k):", "betavec = self.beta.betavec model = self.model self.stateseq = np.array([]) ks", "val in pieces: # get all the other data otherdata,", "(alpha*betavec[k] + (kappa if k == stateseq[t-1] else 0) +", "score += np.log(betavec[stateseq[t+1]]) # observation score score += o.log_marginal_likelihood(data[t]) return", "the prior # self.stateseq = self.stateseq[:self.T] self.stateseq = np.random.randint(25,size=data.shape[0]) self.T", "k return seq, canondict, reversedict class dummytrans(object): def __init__(self,A): self.A", "k: score += np.log(alpha * beta[k] + model._counts_fromto(stateseq[t-1],k)) \\ -", "model._counts_from(stateseq[t-1])) # add in right transition (no counts) if t", "sets self.stateseq_norep and self.durations # it should also call beta", "+ durs.log_predictive(dur,otherdurs) return score def _new_label_score(self,t,ks): assert t > 0", "# observation score score += o.log_predictive(data[t],model._data_withlabel(k)) return score def _new_score(self,ks,t):", "def _durs_withlabel(self,k): assert k != SAMPLING if len(self.stateseq) > 0:", "def _counts_fromto(self,k): pass def _new_label(self,ks): assert SAMPLING not in ks", "< self.T-1: score += np.log(betavec[stateseq[t+1]]) # observation score score +=", "return slice(A.start,B.stop), [(x,stateseq[x.start]) for x in (A,It,B) if x.stop -", "transition (only from counts, no to counts) score += np.log(alpha)", "idx,s in enumerate(seq): seq[idx] = canondict[s] reversedict = {} for", "it's just a # definition choice that isn't specified in", "+ ft if k != self.stateseq[t-1] else 0) for k,ft", "new label ABIGNUMBER = 10000 # state labels are sampled", "lens (or something) # that are either read-only or also", "= rle(stateseq) self.data = data self.T = data.shape[0] def _generate(self,T):", "indicating a state or state range that is being resampled", "if t < self.T-1: score += np.log(betavec[stateseq[t+1]]) # observation score", "0. # unpack model = self.model alpha = self.alpha_0 beta", "orig_stateseq[piece] # restore original views self.stateseq = orig_stateseq # return", "being resampled NEW = -2 # special constant indicating a", "obs self.data = data if (data,stateseq) == (None,None): # generating", "stateseq def resample(self): model = self.model for t in np.random.permutation(self.T):", "else 0 another_fromto = 1 if (t > 0 and", "add in obs/dur scores of local pieces for (data,otherdata), (dur,otherdurs)", "override setters # for now, i'll just make sure outside", "temp def _counts_fromto(self,k1,k2): assert k1 != SAMPLING and k2 !=", "# get all the other data otherdata, otherdurs = self.model._data_withlabel(val),", "= np.sum(self.stateseq[1:] == k) if SAMPLING in self.stateseq[:-1] and \\", "k) if SAMPLING in self.stateseq[:-1] and \\ self.stateseq[np.where(self.stateseq == SAMPLING)[0]+1]", "scores.shape[0]-1: stateseq[t] = self._new_label(ks) else: stateseq[t] = ks[nextstateidx] self.stateseq =", "ks[newlabelidx] def _label_score(self,t,k): assert t > 0 score = 0.", "slice(startindices[idx],startindices[idx+1]) def canonize(seq): seq = seq.copy() canondict = collections.defaultdict(itertools.count().next) for", "(1-beta[k]) + model._counts_from(k)) # predictive likelihoods for (data,otherdata), (dur,otherdurs) in", "self.stateseq and maybe self.data assert self.stateseq[t] == SAMPLING orig_stateseq =", "t < self.T-1: betas = np.random.beta(1,self.beta.gamma_0,size=200) betas[1:] *= (1-betas[:-1]).cumprod() score", "self.T-1 and stateseq[t+1] != k: score += np.log(alpha * beta[stateseq[t+1]]", "like self.stateseq and maybe self.data assert self.stateseq[t] == SAMPLING orig_stateseq", "''' A,B = fill(stateseq,t-1), fill(stateseq,t+1) if A == B: return", "== k: temp -= 1 return temp def _counts_to(self,k): assert", "data otherdata, otherdurs = self.model._data_withlabel(val), self.model._durs_withlabel(val) # add a piece", "and sample from them scores = np.array([self._score(k,t) for k in", "== scores.shape[0]-1: stateseq[t] = self._new_label(ks) else: stateseq[t] = ks[nextstateidx] self.stateseq", "((A,stateseq[A.start]),) elif A.start <= t < A.stop or B.start <=", "self.beta.housekeeping(ks) # form the scores and sample from them scores", "return seq, canondict, reversedict class dummytrans(object): def __init__(self,A): self.A =", "# TODO if i write the special stateseq class, this", "if k == stateseq[t-1] else 0) + model._counts_fromto(stateseq[t-1],k)) / (alpha+kappa+model._counts_from(stateseq[t-1]))", "\\ self.stateseq[np.where(self.stateseq == SAMPLING)[0]+1] == k: temp -= 1 return", "0) + model._counts_fromto(stateseq[t-1],k)) / (alpha+kappa+model._counts_from(stateseq[t-1])) ) # right transition score", "self.stateseq.copy() # temporarily set stateseq to hypothetical stateseq # so", "{} for k,v in canondict.iteritems(): reversedict[v] = k return seq,", "SAMPLING) in (0,1) temp = np.sum(self.stateseq[1:] == k) if SAMPLING", "(data,otherdata), (dur,otherdurs) in self._local_group(t,NEW): score += obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs) return", "t > 0 score = 0. # unpack model =", "(not incl -1 and T-1) startindices = np.concatenate(((0,),endindices+1,(seq.shape[0],))) # incl", "+ (kappa if k == stateseq[t+1] else 0) + model._counts_fromto(k,stateseq[t+1])", "fromto_counts = np.array([model._counts_fromto(stateseq[t-1],k) + self._counts_fromto(stateseq[t-1],k) for k in ks]) #", "self.data = data self._generate(data.shape[0]) else: assert data.shape[0] == stateseq.shape[0] self.stateseq", "firststate = ks[firststateidx] self.dur.resample(combinedata((model._durs_withlabel(firststate),self._durs_withlabel(firststate)))) firststate_dur = self.dur.rvs() self.stateseq = np.ones(firststate_dur,dtype=int)*firststate", "newweight = self.beta.betavec[newlabel] # instantiate, needed if new state at", "of new states coming out of our current state #", "T when generating' self._generate(T) elif data is None: self.T =", "stateseq[t] = self._new_label(ks) else: stateseq[t] = ks[nextstateidx] self.stateseq = stateseq", "+ model._counts_from(stateseq[t-1])) # add in right transition (no counts) if", "= self.alpha_0, self.kappa betavec, model, o = self.beta.betavec, self.model, self.obs", "def _local_group(self,t,k): ''' returns a sequence of length between 1", "alpha_0 self.kappa = kappa self.model = model self.beta = beta", "one, sample proportional to scores = np.array([(alpha*betavec[k] + (kappa if", "in (0,1) temp = np.sum(self.stateseq[:-1] == k) if SAMPLING in", "0 and T idx = np.where(startindices <= t)[0][-1] return slice(startindices[idx],startindices[idx+1])", "ks = list(ks) # sample a new value scores =", "in self.stateseq: return 0 else: from_indices, = np.where(self.stateseq[:-1] == k1)", "SAMPLING assert np.sum(self.stateseq == SAMPLING) in (0,1) temp = np.sum(self.stateseq[1:]", "!= self.stateseq[t-1] else 0) for k,ft in zip(ks,fromto_counts)] + [alpha*(1-betavec[self.stateseq[t-1]])*betarest])", "all the other data otherdata, otherdurs = self.model._data_withlabel(val), self.model._durs_withlabel(val) #", "sequence of length between 1 and 3, where each sequence", "sequence # TODO if i write the special stateseq class,", "special constant for indicating a state or state range that", "nextstate_dur self.T = len(self.stateseq) def resample(self): self.resample_label_version() def _durs_withlabel(self,k): assert", "label sampler stuff def resample_label_version(self): # NOTE never changes first", "newlabel = np.random.randint(ABIGNUMBER) newweight = self.beta.betavec[newlabel] # instantiate, needed if", "ks[idx] def _score(self,k,t): alpha, kappa = self.alpha_0, self.kappa betavec, model,", "prior # self.stateseq = self.stateseq[:self.T] self.stateseq = np.random.randint(25,size=data.shape[0]) self.T =", "== k] def _occupied(self): return set(self.stateseq) - set((SAMPLING,)) def plot(self,colors_dict):", "= rle(self.stateseq) X,Y = np.meshgrid(np.hstack((0,durations.cumsum())),(0,1)) if colors_dict is not None:", "localgroup localgroup.append(((self.data[piece],otherdata),(piece.stop-piece.start,otherdurs))) # remove the used piece from the exclusion", "= sample_discrete(np.arange(len(ks))) if firststateidx == len(ks)-1: firststate = self._new_label(ks) else:", "0 score = 0. # unpack model = self.model alpha", "not independently) another_from = 1 if t > 0 and", "1 return temp def _counts_to(self,k): assert k != SAMPLING assert", "seq return newlabel def _data_withlabel(self,k): assert k != SAMPLING return", "else 0) + model._counts_fromto(k,stateseq[t+1]) + another_fromto) / (alpha+kappa+model._counts_from(k) + another_from)", "otherdurs = self.model._data_withlabel(val), self.model._durs_withlabel(val) # add a piece to our", "between 1 and 3, where each sequence element is ((data,otherdata),", "if (t > 0 and stateseq[t-1] == k and stateseq[t+1]", "np.sum(stateseq_norep[from_indices+1] == k2) def _counts_from(self,k): assert k != SAMPLING stateseq_norep,", ") # right transition score if t < self.T -", "np.log( (alpha*betavec[stateseq[t+1]] + (kappa if k == stateseq[t+1] else 0)", "= np.array([[colors_dict[state] for state in stateseq_norep]]) else: C = stateseq_norep[na,:]", "elif stateseq is None: self.data = data # self._generate(data.shape[0]) #", "if k != self.stateseq[t-1] else 0) for k,ft in zip(ks,fromto_counts)]", "self.alpha_0 betavec = self.beta.betavec model = self.model self.stateseq = np.array([])", "score = 0. # unpack model = self.model alpha =", "States Classes # #################### # TODO an array class that", "# runs a CRF with fixed weights beta forwards for", "== k) else 0 score += np.log( (alpha*betavec[stateseq[t+1]] + (kappa", "to start in; it's just a # definition choice that", "* beta[k] + model._counts_fromto(stateseq[t-1],k)) \\ - np.log(alpha * (1-beta[stateseq[t-1]]) +", "1 return temp def _counts_fromto(self,k1,k2): assert k1 != SAMPLING and", "0: betarest = 1-sum(betavec[k] for k in ks) score +=", "_counts_to(self,k): assert k != SAMPLING stateseq_norep, _ = rle(self.stateseq) temp", "going to all other states fromto_counts = np.array([model._counts_fromto(stateseq[t-1],k) + self._counts_fromto(stateseq[t-1],k)", "collapsed_hdphsmm_states(collapsed_states): def __init__(self,model,beta,alpha_0,obs,dur,data=None,T=None,stateseq=None): self.alpha_0 = alpha_0 self.model = model self.beta", "or k2 not in self.stateseq: return 0 else: from_indices, =", "data is None: self.T = stateseq.shape[0] self.stateseq = stateseq elif", "counts (since we are scoring exchangeably, not independently) another_from =", "self._new_label(ks) else: nextstate = ks[nextstateidx] # now get the duration", "slice(A.start,B.stop), [(x,stateseq[x.start]) for x in (A,B) if x.stop - x.start", "with durations) forwards while t < T: ks = list(model._occupied()", "obs, durs = self.obs, self.dur # left transition (only from", "observation score score += o.log_predictive(data[t],model._data_withlabel(k)) return score def _new_score(self,ks,t): alpha,", "for x in (A,B) if x.stop - x.start > 0]", "T is not None, 'must pass in T when generating'", "np.zeros(T,dtype=np.int) model = self.model self.stateseq = stateseq[:0] # NOTE: we", "another_fromto = 1 if (t > 0 and stateseq[t-1] ==", "nextstateidx == scores.shape[0]-1: stateseq[t] = self._new_label(ks) else: stateseq[t] = ks[nextstateidx]", "range that is being resampled NEW = -2 # special", "model._counts_fromto(stateseq[t-1],k)) \\ - np.log(alpha * (1-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1])) # right", "(only from counts, no to counts) score += np.log(alpha) -", "there is one) if t < self.T-1 and stateseq[t+1] !=", "something) # that are either read-only or also override setters", "= data # self._generate(data.shape[0]) # initialized from the prior #", "enumerate(seq): seq[idx] = canondict[s] reversedict = {} for k,v in", "= model self.beta = beta self.obs = obs self.dur =", "durs = self.obs, self.dur # left transition (if there is", "if colors_dict is not None: C = np.array([[colors_dict[state] for state", "== k1) # EXCEPT last return np.sum(stateseq_norep[from_indices+1] == k2) def", "@abc.abstractmethod def _counts_from(self,k): pass @abc.abstractmethod def _counts_to(self,k): pass @abc.abstractmethod def", "else 0) for k,ft in zip(ks,fromto_counts)] + [alpha*(1-betavec[self.stateseq[t-1]])*betarest]) nextstateidx =", "= orig_stateseq # return return localgroup @classmethod def _local_slices(cls,stateseq,t): '''", "from them scores = np.array([self._score(k,t) for k in ks]+[self._new_score(ks,t)]) idx", "stuff def resample_label_version(self): # NOTE never changes first label: we", "local pieces for (data,otherdata), (dur,otherdurs) in self._local_group(t,NEW): score += obs.log_predictive(data,otherdata)", "stateseq.shape[0] self.stateseq = stateseq elif stateseq is None: self.data =", "< B.stop: return slice(A.start,B.stop), [(x,stateseq[x.start]) for x in (A,B) if", "= -1 # special constant for indicating a state or", "to abignumber exclusive #################### # States Classes # #################### #", "_ = rle(self.stateseq) temp = np.sum(stateseq_norep[1:] == k) if SAMPLING", "else: from_indices, = np.where(self.stateseq[:-1] == k1) # EXCEPT last return", "self.stateseq = stateseq self.data = data self.T = data.shape[0] def", "other states fromto_counts = np.array([model._counts_fromto(stateseq[t-1],k) + self._counts_fromto(stateseq[t-1],k) for k in", "# unpack variables model = self.model alpha = self.alpha_0 beta", "indices (not incl -1 and T-1) startindices = np.concatenate(((0,),endindices+1,(seq.shape[0],))) #", "ks = list(model._occupied()) self.beta.housekeeping(ks) # form the scores and sample", "# zero, since no states will be occupied. ks =", "the exclusion self.stateseq[piece] = orig_stateseq[piece] # restore original views self.stateseq", "| self._occupied()) betarest = 1-sum(betavec[k] for k in ks) #", "= self.alpha_0 betavec = self.beta.betavec model = self.model self.stateseq =", "model self.beta = beta self.obs = obs self.data = data", "score def _new_label_score(self,t,ks): assert t > 0 score = 0.", "= 0. # unpack variables model = self.model alpha =", "in ks]+[self._new_score(ks,t)]) idx = sample_discrete_from_log(scores) # set the state if", "either read-only or also override setters # for now, i'll", "to include the left transition in # counts (since we", "temp = np.sum(stateseq_norep[1:] == k) if SAMPLING in stateseq_norep[:-1] and", "np.log(alpha * beta[k] + model._counts_fromto(stateseq[t-1],k)) \\ - np.log(alpha * (1-beta[stateseq[t-1]])", "= [] self.stateseq[wholegroup] = SAMPLING for piece, val in pieces:", "self.kappa betavec = self.beta.betavec stateseq = np.zeros(T,dtype=np.int) model = self.model", "= np.meshgrid(np.hstack((0,durations.cumsum())),(0,1)) if colors_dict is not None: C = np.array([[colors_dict[state]", "ks = list(model._occupied() | self._occupied()) betarest = 1-sum(betavec[k] for k", "np.sum(self.stateseq[1:] == k) if SAMPLING in self.stateseq[:-1] and \\ self.stateseq[np.where(self.stateseq", "if x.stop - x.start > 0] else: It = slice(t,t+1)", "an array class that maintains its own rle # must", "self._local_group(t,NEW): score += obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs) return score def _local_group(self,t,k):", "by adding to score of last # segment SAMPLING =", "right transition (if there is one) if t < self.T-1", "instantiate, needed if new state at beginning of seq return", "i'll just make sure outside that anything that sets self.stateseq", "runs a CRF with fixed weights beta forwards for t", "alpha = self.alpha_0 betavec = self.beta.betavec model = self.model self.stateseq", "current state # going to all other states fromto_counts =", "our current state # going to all other states fromto_counts", "self.stateseq obs, durs = self.obs, self.dur # left transition (if", "stateseq to hypothetical stateseq # so that we can get", "now, i'll just make sure outside that anything that sets", "== stateseq[t-1] else 0) + model._counts_fromto(stateseq[t-1],k)) / (alpha+kappa+model._counts_from(stateseq[t-1])) ) #", "model._counts_fromto(k,stateseq[t+1]) + another_fromto) / (alpha+kappa+model._counts_from(k) + another_from) ) # observation", "self.beta.housekeeping(ks) ks = list(ks) # sample a new value scores", "t = firststate_dur # run a family-CRF (CRF with durations)", "is the # first chain being sampled in this model,", "sample_discrete(scores) if nextstateidx == scores.shape[0]-1: nextstate = self._new_label(ks) else: nextstate", "== k) if SAMPLING in stateseq_norep[1:] and \\ stateseq_norep[np.where(stateseq_norep ==", "self.stateseq = stateseq self.stateseq_norep, self.durations = rle(stateseq) self.data = data", "k,v in canondict.iteritems(): reversedict[v] = k return seq, canondict, reversedict", "0 else: stateseq_norep, _ = rle(self.stateseq) from_indices, = np.where(stateseq_norep[:-1] ==", "k and stateseq[t+1] == k) else 0 score += np.log(", "def _counts_to(self,k): pass @abc.abstractmethod def _counts_fromto(self,k): pass def _new_label(self,ks): assert", "= data self._generate(data.shape[0]) else: assert data.shape[0] == stateseq.shape[0] self.stateseq =", "NEW = -2 # special constant indicating a potentially new", "k: temp -= 1 return temp ### label sampler stuff", "sampled in this model, this will always sample # zero,", "== SAMPLING) in (0,1) temp = np.sum(self.stateseq[1:] == k) if", "k) if SAMPLING in self.stateseq[1:] and \\ self.stateseq[np.where(self.stateseq == SAMPLING)[0]-1]", "ks = list(model._occupied()) + [None] firststate = sample_discrete(np.arange(len(ks))) if firststate", "0) for k,ft in zip(ks,fromto_counts)] + [alpha*(1-betavec[self.stateseq[t-1]])*betarest]) nextstateidx = sample_discrete(scores)", "the initial state # distribution is a delta at that", "alpha_0 self.model = model self.beta = beta self.obs = obs", "modifies members, like self.stateseq and maybe self.data assert self.stateseq[t] ==", "# self._generate(data.shape[0]) # initialized from the prior # self.stateseq =", "self.stateseq[np.where(self.stateseq == SAMPLING)[0]+1] == k: temp -= 1 return temp", "fixing self.stateseq[t] = k wholegroup, pieces = self._local_slices(self.stateseq,t) self.stateseq[t] =", "< self.T-1 and stateseq[t+1] != k: score += np.log(alpha *", "A,B = fill(stateseq,t-1), fill(stateseq,t+1) if A == B: return A,", "self.stateseq_norep and self.durations # it should also call beta updates...", "== k: temp -= 1 return temp def _counts_fromto(self,k1,k2): assert", "also sets self.stateseq_norep and self.durations # it should also call", "= self.model self.stateseq = stateseq[:0] # NOTE: we have a", "= np.sum(self.stateseq[:-1] == k) if SAMPLING in self.stateseq[1:] and \\", "transition score if t < self.T - 1: # indicators", "if A == B: return A, ((A,stateseq[A.start]),) elif A.start <=", "censoring. can make no censoring by adding to score of", "exclusion self.stateseq[piece] = orig_stateseq[piece] # restore original views self.stateseq =", "maybe self.data assert self.stateseq[t] == SAMPLING orig_stateseq = self.stateseq.copy() #", "seq, canondict, reversedict class dummytrans(object): def __init__(self,A): self.A = A", "# incl 0 and T idx = np.where(startindices <= t)[0][-1]", "== SAMPLING)[0]+1] == k: temp -= 1 return temp ###", "stateseq_norep, durations = rle(self.stateseq) return durations[stateseq_norep == k] else: return", "= ks[nextstateidx] # now get the duration of nextstate! self.dur.resample(combinedata((model._durs_withlabel(nextstate),self._durs_withlabel(nextstate))))", "if t < self.T-1: betas = np.random.beta(1,self.beta.gamma_0,size=200) betas[1:] *= (1-betas[:-1]).cumprod()", "= self.data, self.stateseq score = 0 # left transition score", "the used piece from the exclusion self.stateseq[piece] = orig_stateseq[piece] #", "ks = list(model._occupied()) + [None] firststateidx = sample_discrete(np.arange(len(ks))) if firststateidx", "in; it's just a # definition choice that isn't specified", "self.stateseq[t-1] else 0) for k,ft in zip(ks,fromto_counts)] + [alpha*(1-betavec[self.stateseq[t-1]])*betarest]) nextstateidx", "durs.log_predictive(dur,otherdurs) return score def _new_label_score(self,t,ks): assert t > 0 score", "return slice(A.start,B.stop), [(x,stateseq[x.start]) for x in (A,B) if x.stop -", "x.start > 0] ####################### # Utility Functions # ####################### def", "in (A,It,B) if x.stop - x.start > 0] ####################### #", "betarest = 1-sum(betavec[k] for k in ks) fromto_counts = np.array([model._counts_fromto(self.stateseq[t-1],k)", "self.model._data_withlabel(val), self.model._durs_withlabel(val) # add a piece to our localgroup localgroup.append(((self.data[piece],otherdata),(piece.stop-piece.start,otherdurs)))", "forwards while t < T: ks = list(model._occupied() | self._occupied())", "pass @abc.abstractmethod def _counts_from(self,k): pass @abc.abstractmethod def _counts_to(self,k): pass @abc.abstractmethod", "-= 1 return temp ### label sampler stuff def resample_label_version(self):", "+ model._counts_fromto(k,stateseq[t+1]) + another_fromto) / (alpha+kappa+model._counts_from(k) + another_from) ) #", "durs.log_predictive(dur,otherdurs) return score def _local_group(self,t,k): ''' returns a sequence of", "outside that anything that sets self.stateseq # also sets self.stateseq_norep", "model, o = self.beta.betavec, self.model, self.obs data, stateseq = self.data,", "left transition score if t > 0: score += np.log(", "return score def _counts_from(self,k): assert k != SAMPLING assert np.sum(self.stateseq", "start in; it's just a # definition choice that isn't", "all other states fromto_counts = np.array([model._counts_fromto(stateseq[t-1],k) + self._counts_fromto(stateseq[t-1],k) for k", "else: endindices, = np.where(np.diff(seq) != 0) # internal end indices", "first label: we assume the initial state # distribution is", "temp def _counts_to(self,k): assert k != SAMPLING assert np.sum(self.stateseq ==", "np.sum(stateseq_norep[1:] == k) if SAMPLING in stateseq_norep[:-1] and \\ stateseq_norep[np.where(stateseq_norep", "stateseq[:0] # NOTE: we have a choice of what state", "= np.sum(stateseq_norep[1:] == k) if SAMPLING in stateseq_norep[:-1] and \\", "write the special stateseq class, this will need fixing self.stateseq[t]", "self.T-1: betas = np.random.beta(1,self.beta.gamma_0,size=200) betas[1:] *= (1-betas[:-1]).cumprod() score += np.log(self.beta.remaining*(betas/(1-betas)).sum())", "np.log(alpha * beta[stateseq[t+1]] + model._counts_fromto(k,stateseq[t+1])) \\ - np.log(alpha * (1-beta[k])", "dur self.data = data if (data,stateseq) == (None,None): # generating", "score += np.log(beta[stateseq[t+1]]) # add in sum over k factor", "right transition (no counts) if t < self.T-1: score +=", "+= np.log( (alpha*betavec[k] + (kappa if k == stateseq[t-1] else", "score += np.log(self.beta.remaining) # add in obs/dur scores of local", "def _score(self,k,t): alpha, kappa = self.alpha_0, self.kappa betavec, model, o", "# TODO an array class that maintains its own rle", "and stateseq[t-1] == k and stateseq[t+1] == k) else 0", "score += np.log( (alpha*betavec[k] + (kappa if k == stateseq[t-1]", "from __future__ import division import numpy as np na =", "censoring by adding to score of last # segment SAMPLING", "ft) for k,ft in zip(ks,fromto_counts)] + [alpha*betarest]) nextstateidx = sample_discrete(scores)", "# right transition (if there is one) if t <", "add in right transition (no counts) if t < self.T-1:", "k2) def _counts_from(self,k): assert k != SAMPLING stateseq_norep, _ =", "[(x,stateseq[x.start]) for x in (A,B) if x.stop - x.start >", "import division import numpy as np na = np.newaxis import", "[] def _counts_fromto(self,k1,k2): assert k1 != SAMPLING and k2 !=", "= 1-sum(betavec[k] for k in ks) fromto_counts = np.array([model._counts_fromto(self.stateseq[t-1],k) +", "+= np.log(self.beta.remaining) # add in obs/dur scores of local pieces", "firststateidx == len(ks)-1: firststate = self._new_label(ks) else: firststate = ks[firststateidx]", "= SAMPLING for piece, val in pieces: # get all", "np.array([[colors_dict[state] for state in stateseq_norep]]) else: C = stateseq_norep[na,:] plt.pcolor(X,Y,C,vmin=0,vmax=1)", "self.data = data self.T = data.shape[0] def _generate(self,T): alpha =", "label ABIGNUMBER = 10000 # state labels are sampled uniformly", "orig_stateseq # return return localgroup @classmethod def _local_slices(cls,stateseq,t): ''' returns", "data self._generate(data.shape[0]) else: assert data.shape[0] == stateseq.shape[0] self.stateseq = stateseq", "for k,ft in zip(ks,fromto_counts)] + [alpha*(1-betavec[self.stateseq[t-1]])*betarest]) nextstateidx = sample_discrete(scores) if", "ks: newlabel = np.random.randint(ABIGNUMBER) newweight = self.beta.betavec[newlabel] # instantiate, needed", "= list(model._occupied()) + [None] firststate = sample_discrete(np.arange(len(ks))) if firststate ==", "= slice(t,t+1) return slice(A.start,B.stop), [(x,stateseq[x.start]) for x in (A,It,B) if", "pass @abc.abstractmethod def _counts_to(self,k): pass @abc.abstractmethod def _counts_fromto(self,k): pass def", "scores.shape[0]-1: nextstate = self._new_label(ks) else: nextstate = ks[nextstateidx] # now", "and lens (or something) # that are either read-only or", "temp = np.sum(stateseq_norep[:-1] == k) if SAMPLING in stateseq_norep[1:] and", "at that label for t in (np.random.permutation(self.T-1)+1): self.stateseq[t] = SAMPLING", "constant indicating a potentially new label ABIGNUMBER = 10000 #", "k == stateseq[t-1] else 0) + model._counts_fromto(stateseq[t-1],k)) / (alpha+kappa+model._counts_from(stateseq[t-1])) )", "self.stateseq obs, durs = self.obs, self.dur # left transition (only", "= list(model._occupied() | self._occupied()) betarest = 1-sum(betavec[k] for k in", "what state to start in; it's just a # definition", "!= SAMPLING if len(self.stateseq) > 0: stateseq_norep, durations = rle(self.stateseq)", "# ####################### def fill(seq,t): if t < 0: return slice(0,0)", "0) + ft) for k,ft in zip(ks,fromto_counts)] + [alpha*betarest]) nextstateidx", "= dur self.data = data if (data,stateseq) == (None,None): #", "for t in (np.random.permutation(self.T-1)+1): self.stateseq[t] = SAMPLING ks = self.model._occupied()", "+= o.log_marginal_likelihood(data[t]) return score def _counts_from(self,k): assert k != SAMPLING", "just to sample from beta. Note that if this is", "temp -= 1 return temp ### label sampler stuff def", "build local group of statistics localgroup = [] self.stateseq[wholegroup] =", "_counts_fromto(self,k): pass def _new_label(self,ks): assert SAMPLING not in ks newlabel", "assert k != SAMPLING assert np.sum(self.stateseq == SAMPLING) in (0,1)", "beta[k] + model._counts_fromto(stateseq[t-1],k)) \\ - np.log(alpha * (1-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1]))", "for k,v in canondict.iteritems(): reversedict[v] = k return seq, canondict,", "self.stateseq or k2 not in self.stateseq or k1 == k2:", "self._generate(T) elif data is None: self.T = stateseq.shape[0] self.stateseq =", "data # self._generate(data.shape[0]) # initialized from the prior # self.stateseq", "of nextstate! self.dur.resample(combinedata((model._durs_withlabel(nextstate),self._durs_withlabel(nextstate)))) nextstate_dur = self.dur.rvs() self.stateseq = np.concatenate((self.stateseq,np.ones(nextstate_dur,dtype=int)*nextstate)) t", "k != SAMPLING return self.data[self.stateseq == k] def _occupied(self): return", "stateseq_norep, _ = rle(self.stateseq) from_indices, = np.where(stateseq_norep[:-1] == k1) #", "+ another_from) ) # observation score score += o.log_predictive(data[t],model._data_withlabel(k)) return", "= stateseq self.data = data self.T = data.shape[0] def _generate(self,T):", "self.beta.betavec stateseq = np.zeros(T,dtype=np.int) model = self.model self.stateseq = stateseq[:0]", "if i write the special stateseq class, this will need", "itertools import abc from pyhsmm.util.stats import sample_discrete, sample_discrete_from_log, combinedata from", "= data self.T = data.shape[0] def _generate(self,T): self.T = T", "/ (alpha+kappa+model._counts_from(k) + another_from) ) # observation score score +=", "transition (if there is one) if t < self.T-1 and", "+= np.log( (alpha*betavec[stateseq[t+1]] + (kappa if k == stateseq[t+1] else", "(CRF with durations) forwards while t < T: ks =", "SAMPLING and k2 != SAMPLING if k1 not in self.stateseq", "ks[nextstateidx] # now get the duration of nextstate! self.dur.resample(combinedata((model._durs_withlabel(nextstate),self._durs_withlabel(nextstate)))) nextstate_dur", "k in ks]+[self._new_score(ks,t)]) idx = sample_discrete_from_log(scores) # set the state", "self.stateseq[:self.T] self.stateseq = np.random.randint(25,size=data.shape[0]) self.T = data.shape[0] else: assert data.shape[0]", "and 3, where each sequence element is ((data,otherdata), (dur,otherdurs)) '''", "that are either read-only or also override setters # for", "in ks newlabel = np.random.randint(ABIGNUMBER) while newlabel in ks: newlabel", "choose just to sample from beta. Note that if this", "duration of nextstate! self.dur.resample(combinedata((model._durs_withlabel(nextstate),self._durs_withlabel(nextstate)))) nextstate_dur = self.dur.rvs() self.stateseq = np.concatenate((self.stateseq,np.ones(nextstate_dur,dtype=int)*nextstate))", "from pyhsmm.util.general import rle as rle # NOTE: assumes censoring.", "stateseq[t+1] else 0) + ft) for k,ft in zip(ks,fromto_counts)] +", "now get the duration of nextstate! self.dur.resample(combinedata((model._durs_withlabel(nextstate),self._durs_withlabel(nextstate)))) nextstate_dur = self.dur.rvs()", "and self.durations # it should also call beta updates... class", "# EXCEPT last return np.sum(self.stateseq[from_indices+1] == k2) class collapsed_hdphsmm_states(collapsed_states): def", "assert t > 0 score = 0. # unpack model", "zip(ks,fromto_counts)] + [alpha*(1-betavec[self.stateseq[t-1]])*betarest]) nextstateidx = sample_discrete(scores) if nextstateidx == scores.shape[0]-1:", "no to counts) score += np.log(alpha) - np.log(alpha*(1.-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1]))", "the HDP-HMM # Here, we choose just to sample from", "firststateidx = sample_discrete(np.arange(len(ks))) if firststateidx == len(ks)-1: firststate = self._new_label(ks)", "need fixing self.stateseq[t] = k wholegroup, pieces = self._local_slices(self.stateseq,t) self.stateseq[t]", "maintains its own rle # must override set methods #", "np.log(alpha*(1.-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1])) # add in right transition (no counts)", "# temporarily modifies members, like self.stateseq and maybe self.data assert", "plt.pcolor(X,Y,C,vmin=0,vmax=1) plt.ylim((0,1)) plt.xlim((0,len(self.stateseq))) plt.yticks([]) class collapsed_stickyhdphmm_states(collapsed_states): def __init__(self,model,beta,alpha_0,kappa,obs,data=None,T=None,stateseq=None): self.alpha_0 =", "# NOTE: assumes censoring. can make no censoring by adding", "of what state to start in; it's just a #", "<= t < B.stop: return slice(A.start,B.stop), [(x,stateseq[x.start]) for x in", "= np.where(stateseq_norep[:-1] == k1) # EXCEPT last return np.sum(stateseq_norep[from_indices+1] ==", "# initialized from the prior # self.stateseq = self.stateseq[:self.T] self.stateseq", "resample(self): self.resample_label_version() def _durs_withlabel(self,k): assert k != SAMPLING if len(self.stateseq)", "return localgroup @classmethod def _local_slices(cls,stateseq,t): ''' returns slices: wholegroup, (piece1,", "firststate_dur # run a family-CRF (CRF with durations) forwards while", "t < self.T - 1: # indicators since we may", "x in (A,It,B) if x.stop - x.start > 0] #######################", "self.data[self.stateseq == k] def _occupied(self): return set(self.stateseq) - set((SAMPLING,)) def", "SAMPLING in stateseq_norep[:-1] and \\ stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]+1] == k:", "+ (kappa if k == stateseq[t+1] else 0) + ft)", "list(model._occupied() | self._occupied()) betarest = 1-sum(betavec[k] for k in ks)", "else: assert data.shape[0] == stateseq.shape[0] self.stateseq = stateseq self.stateseq_norep, self.durations", "scores = np.array([self._score(k,t) for k in ks]+[self._new_score(ks,t)]) idx = sample_discrete_from_log(scores)", "= np.random.randint(ABIGNUMBER) newweight = self.beta.betavec[newlabel] # instantiate, needed if new", "if SAMPLING in self.stateseq[1:] and \\ self.stateseq[np.where(self.stateseq == SAMPLING)[0]-1] ==", "matplotlib import pyplot as plt stateseq_norep, durations = rle(self.stateseq) X,Y", "for t in np.random.permutation(self.T): # throw out old value self.stateseq[t]", "endindices, = np.where(np.diff(seq) != 0) # internal end indices (not", "-2 # special constant indicating a potentially new label ABIGNUMBER", "no states will be occupied. ks = list(model._occupied()) + [None]", "(1-betas[:-1]).cumprod() score += np.log(self.beta.remaining*(betas/(1-betas)).sum()) else: score += np.log(self.beta.remaining) # add", "new state at beginning of seq return newlabel def _data_withlabel(self,k):", "a piece to our localgroup localgroup.append(((self.data[piece],otherdata),(piece.stop-piece.start,otherdurs))) # remove the used", "stateseq[:t] ks = list(model._occupied() | self._occupied()) betarest = 1-sum(betavec[k] for", ") # observation score score += o.log_predictive(data[t],model._data_withlabel(k)) return score def", "def _new_label(self,ks): assert SAMPLING not in ks newlabel = np.random.randint(ABIGNUMBER)", "that sets self.stateseq # also sets self.stateseq_norep and self.durations #", "idx == scores.shape[0]-1: self.stateseq[t] = self._new_label(ks) else: self.stateseq[t] = ks[idx]", "canonize(seq): seq = seq.copy() canondict = collections.defaultdict(itertools.count().next) for idx,s in", "self.stateseq = stateseq[:0] # NOTE: we have a choice of", "= rle(self.stateseq) return durations[stateseq_norep == k] else: return [] def", "self._new_label(ks) else: self.stateseq[t] = ks[idx] def _score(self,k,t): alpha, kappa =", "np.array([model._counts_fromto(self.stateseq[t-1],k) + self._counts_fromto(self.stateseq[t-1],k) for k in ks]) scores = np.array([(alpha*betavec[k]", "pieces = self._local_slices(self.stateseq,t) self.stateseq[t] = SAMPLING # build local group", "Note that if this is the # first chain being", "the counts of new states coming out of our current", "= self._local_slices(self.stateseq,t) self.stateseq[t] = SAMPLING # build local group of", "are either read-only or also override setters # for now,", "orig_stateseq = self.stateseq.copy() # temporarily set stateseq to hypothetical stateseq", "durations[stateseq_norep == k] else: return [] def _counts_fromto(self,k1,k2): assert k1", "-1 # special constant for indicating a state or state", "also has members norep and lens (or something) # that", "if nextstateidx == scores.shape[0]-1: stateseq[t] = self._new_label(ks) else: stateseq[t] =", "is ((data,otherdata), (dur,otherdurs)) ''' # temporarily modifies members, like self.stateseq", "beta self.obs = obs self.dur = dur self.data = data", "= len(self.stateseq) def resample(self): self.resample_label_version() def _durs_withlabel(self,k): assert k !=", "np.random.beta(1,self.beta.gamma_0,size=200) betas[1:] *= (1-betas[:-1]).cumprod() score += np.log(self.beta.remaining*(betas/(1-betas)).sum()) else: score +=", "piece from the exclusion self.stateseq[piece] = orig_stateseq[piece] # restore original", "a # definition choice that isn't specified in the HDP-HMM", "range(1,T): self.stateseq = stateseq[:t] ks = list(model._occupied() | self._occupied()) betarest", "state or state range that is being resampled NEW =", "return temp def _counts_to(self,k): assert k != SAMPLING stateseq_norep, _", "== len(ks)-1: firststate = self._new_label(ks) else: firststate = ks[firststateidx] self.dur.resample(combinedata((model._durs_withlabel(firststate),self._durs_withlabel(firststate))))", "= self.model._occupied() self.beta.housekeeping(ks) ks = list(ks) # sample a new", "np na = np.newaxis import collections, itertools import abc from", "for (data,otherdata), (dur,otherdurs) in self._local_group(t,k): score += obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs)", "= data.shape[0] else: assert data.shape[0] == stateseq.shape[0] self.stateseq = stateseq", "state range that is being resampled NEW = -2 #", "throw out old value self.stateseq[t] = SAMPLING ks = list(model._occupied())", "a family-CRF (CRF with durations) forwards while t < T:", "- np.log(alpha*(1.-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1])) # add in right transition (no", "self._new_label(ks) else: firststate = ks[firststateidx] self.dur.resample(combinedata((model._durs_withlabel(firststate),self._durs_withlabel(firststate)))) firststate_dur = self.dur.rvs() self.stateseq", "assert SAMPLING not in ks newlabel = np.random.randint(ABIGNUMBER) while newlabel", "Classes # #################### # TODO an array class that maintains", "self.stateseq = np.concatenate((self.stateseq,np.ones(nextstate_dur,dtype=int)*nextstate)) t += nextstate_dur self.T = len(self.stateseq) def", "for idx,s in enumerate(seq): seq[idx] = canondict[s] reversedict = {}", "1 return temp ### label sampler stuff def resample_label_version(self): #", "for indicating a state or state range that is being", "generating assert T is not None, 'must pass in T", "SAMPLING stateseq_norep, _ = rle(self.stateseq) temp = np.sum(stateseq_norep[:-1] == k)", "from pyhsmm.util.stats import sample_discrete, sample_discrete_from_log, combinedata from pyhsmm.util.general import rle", "= np.zeros(T,dtype=np.int) model = self.model self.stateseq = stateseq[:0] # NOTE:", "self.stateseq = stateseq[:t] ks = list(model._occupied() | self._occupied()) betarest =", "== SAMPLING orig_stateseq = self.stateseq.copy() # temporarily set stateseq to", "sampled uniformly from 0 to abignumber exclusive #################### # States", "x.stop - x.start > 0] ####################### # Utility Functions #", "specified in the HDP-HMM # Here, we choose just to", "self.T-1: score += np.log(betavec[stateseq[t+1]]) # observation score score += o.log_marginal_likelihood(data[t])", "is not None, 'must pass in T when generating' self._generate(T)", "= self._new_label(ks) else: stateseq[t] = ks[nextstateidx] self.stateseq = stateseq def", "len(self.stateseq) def resample(self): self.resample_label_version() def _durs_withlabel(self,k): assert k != SAMPLING", "k == stateseq[t+1] else 0) + ft) for k,ft in", "beta. Note that if this is the # first chain", "collapsed_stickyhdphmm_states(collapsed_states): def __init__(self,model,beta,alpha_0,kappa,obs,data=None,T=None,stateseq=None): self.alpha_0 = alpha_0 self.kappa = kappa self.model", "if SAMPLING in self.stateseq[:-1] and \\ self.stateseq[np.where(self.stateseq == SAMPLING)[0]+1] ==", "np.where(np.diff(seq) != 0) # internal end indices (not incl -1", "_counts_from(self,k): assert k != SAMPLING assert np.sum(self.stateseq == SAMPLING) in", "= np.array([model._counts_fromto(stateseq[t-1],k) + self._counts_fromto(stateseq[t-1],k) for k in ks]) # for", "the # first chain being sampled in this model, this", "scores and sample from them scores = np.array([self._score(k,t) for k", "self.alpha_0, self.kappa betavec, model, o = self.beta.betavec, self.model, self.obs data,", "+ self._counts_fromto(self.stateseq[t-1],k) for k in ks]) scores = np.array([(alpha*betavec[k] +", "< A.stop or B.start <= t < B.stop: return slice(A.start,B.stop),", "our localgroup localgroup.append(((self.data[piece],otherdata),(piece.stop-piece.start,otherdurs))) # remove the used piece from the", "# special constant indicating a potentially new label ABIGNUMBER =", "def _new_score(self,ks,t): alpha, kappa = self.alpha_0, self.kappa betavec, model, o", "self.model self.stateseq = np.array([]) ks = list(model._occupied()) + [None] firststateidx", "firststate = self._new_label(ks) else: firststate = ks[firststateidx] self.dur.resample(combinedata((model._durs_withlabel(firststate),self._durs_withlabel(firststate)))) firststate_dur =", "can get the indicator sequence # TODO if i write", "state labels are sampled uniformly from 0 to abignumber exclusive", "stateseq[t+1] == k) else 0 score += np.log( (alpha*betavec[stateseq[t+1]] +", "is None: self.data = data self._generate(data.shape[0]) else: assert data.shape[0] ==", "else: assert data.shape[0] == stateseq.shape[0] self.stateseq = stateseq self.data =", "assert np.sum(self.stateseq == SAMPLING) in (0,1) temp = np.sum(self.stateseq[:-1] ==", "< self.T-1: betas = np.random.beta(1,self.beta.gamma_0,size=200) betas[1:] *= (1-betas[:-1]).cumprod() score +=", "SAMPLING ks = self.model._occupied() self.beta.housekeeping(ks) ks = list(ks) # sample", "in # counts (since we are scoring exchangeably, not independently)", "numpy as np na = np.newaxis import collections, itertools import", "t < A.stop or B.start <= t < B.stop: return", "ks = self.model._occupied() self.beta.housekeeping(ks) ks = list(ks) # sample a", "0: stateseq_norep, durations = rle(self.stateseq) return durations[stateseq_norep == k] else:", "just a # definition choice that isn't specified in the", "= np.concatenate(((0,),endindices+1,(seq.shape[0],))) # incl 0 and T idx = np.where(startindices", "# left transition score if t > 0: score +=", "can make no censoring by adding to score of last", "_durs_withlabel(self,k): assert k != SAMPLING if len(self.stateseq) > 0: stateseq_norep,", "score += np.log( (alpha*betavec[stateseq[t+1]] + (kappa if k == stateseq[t+1]", "assert np.sum(self.stateseq == SAMPLING) in (0,1) temp = np.sum(self.stateseq[1:] ==", "= beta self.obs = obs self.data = data if (data,stateseq)", "ft if k != self.stateseq[t-1] else 0) for k,ft in", "[self._new_label_score(t,ks)]) newlabelidx = sample_discrete_from_log(scores) if newlabelidx == scores.shape[0]-1: self.stateseq[t] =", "sample_discrete, sample_discrete_from_log, combinedata from pyhsmm.util.general import rle as rle #", "t > 0: score += np.log( (alpha*betavec[k] + (kappa if", "label: we assume the initial state # distribution is a", "T idx = np.where(startindices <= t)[0][-1] return slice(startindices[idx],startindices[idx+1]) def canonize(seq):", "and \\ self.stateseq[np.where(self.stateseq == SAMPLING)[0]-1] == k: temp -= 1", "model = self.model self.stateseq = np.array([]) ks = list(model._occupied()) +", "right transition score if t < self.T-1: score += np.log(betavec[stateseq[t+1]])", "transition score if t > 0: betarest = 1-sum(betavec[k] for", "model._counts_fromto(k,stateseq[t+1])) \\ - np.log(alpha * (1-beta[k]) + model._counts_from(k)) # predictive", "# also sets self.stateseq_norep and self.durations # it should also", "resample(self): pass @abc.abstractmethod def _counts_from(self,k): pass @abc.abstractmethod def _counts_to(self,k): pass", "self.beta = beta self.obs = obs self.data = data if", "= self.alpha_0, self.kappa betavec = self.beta.betavec stateseq = np.zeros(T,dtype=np.int) model", "None: self.data = data # self._generate(data.shape[0]) # initialized from the", "canondict[s] reversedict = {} for k,v in canondict.iteritems(): reversedict[v] =", "SAMPLING in self.stateseq[:-1] and \\ self.stateseq[np.where(self.stateseq == SAMPLING)[0]+1] == k:", "of statistics localgroup = [] self.stateseq[wholegroup] = SAMPLING for piece,", "and k2 != SAMPLING if k1 not in self.stateseq or", "def _local_slices(cls,stateseq,t): ''' returns slices: wholegroup, (piece1, ...) ''' A,B", "independently) another_from = 1 if t > 0 and stateseq[t-1]", "to sample from beta. Note that if this is the", "score of last # segment SAMPLING = -1 # special", "ks] + [self._new_label_score(t,ks)]) newlabelidx = sample_discrete_from_log(scores) if newlabelidx == scores.shape[0]-1:", "if t < self.T-1 and stateseq[t+1] != k: score +=", "k] else: return [] def _counts_fromto(self,k1,k2): assert k1 != SAMPLING", "stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]-1] == k: temp -= 1 return temp", "also override setters # for now, i'll just make sure", "is None: self.T = stateseq.shape[0] self.stateseq = stateseq elif stateseq", "nextstateidx == scores.shape[0]-1: nextstate = self._new_label(ks) else: nextstate = ks[nextstateidx]", "if t > 0: score += np.log( (alpha*betavec[k] + (kappa", "self.beta.betavec model = self.model self.stateseq = np.array([]) ks = list(model._occupied())", "> 0 score = 0. # unpack model = self.model", "== k: temp -= 1 return temp ### label sampler", "TODO an array class that maintains its own rle #", "(np.random.permutation(self.T-1)+1): self.stateseq[t] = SAMPLING ks = self.model._occupied() self.beta.housekeeping(ks) ks =", "return slice(0,0) elif t > seq.shape[0]-1: return slice(seq.shape[0],seq.shape[0]) else: endindices,", "pyhsmm.util.general import rle as rle # NOTE: assumes censoring. can", "np.concatenate(((0,),endindices+1,(seq.shape[0],))) # incl 0 and T idx = np.where(startindices <=", "factor if t < self.T-1: betas = np.random.beta(1,self.beta.gamma_0,size=200) betas[1:] *=", "import pyplot as plt stateseq_norep, durations = rle(self.stateseq) X,Y =", "(alpha+kappa+model._counts_from(k) + another_from) ) # observation score score += o.log_predictive(data[t],model._data_withlabel(k))", "!= SAMPLING return self.data[self.stateseq == k] def _occupied(self): return set(self.stateseq)", "(alpha+kappa+model._counts_from(stateseq[t-1])) ) # right transition score if t < self.T", "x.stop - x.start > 0] else: It = slice(t,t+1) return", "self.dur.resample(combinedata((model._durs_withlabel(firststate),self._durs_withlabel(firststate)))) firststate_dur = self.dur.rvs() self.stateseq = np.ones(firststate_dur,dtype=int)*firststate t = firststate_dur", "= 10000 # state labels are sampled uniformly from 0", "score += np.log(alpha) - np.log(alpha*(1.-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1])) # add in", "return temp def _counts_to(self,k): assert k != SAMPLING assert np.sum(self.stateseq", "stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]+1] == k: temp -= 1 return temp", "weights beta forwards for t in range(1,T): self.stateseq = stateseq[:t]", "(data,stateseq) == (None,None): # generating assert T is not None,", "where each sequence element is ((data,otherdata), (dur,otherdurs)) ''' # temporarily", "should also call beta updates... class collapsed_states(object): __metaclass__ = abc.ABCMeta", "set stateseq to hypothetical stateseq # so that we can", "== (None,None): # generating assert T is not None, 'must", "1 and 3, where each sequence element is ((data,otherdata), (dur,otherdurs))", "@abc.abstractmethod def resample(self): pass @abc.abstractmethod def _counts_from(self,k): pass @abc.abstractmethod def", "####################### def fill(seq,t): if t < 0: return slice(0,0) elif", "states plus a new one, sample proportional to scores =", "there is one) if stateseq[t-1] != k: score += np.log(alpha", "SAMPLING)[0]+1] == k: temp -= 1 return temp ### label", "else 0 score += np.log( (alpha*betavec[stateseq[t+1]] + (kappa if k", "return temp def _counts_fromto(self,k1,k2): assert k1 != SAMPLING and k2", "slices: wholegroup, (piece1, ...) ''' A,B = fill(stateseq,t-1), fill(stateseq,t+1) if", "# right transition score if t < self.T-1: score +=", "delta at that label for t in (np.random.permutation(self.T-1)+1): self.stateseq[t] =", "to score of last # segment SAMPLING = -1 #", "score += np.log(alpha * beta[k] + model._counts_fromto(stateseq[t-1],k)) \\ - np.log(alpha", "has members norep and lens (or something) # that are", "np.sum(self.stateseq[:-1] == k) if SAMPLING in self.stateseq[1:] and \\ self.stateseq[np.where(self.stateseq", "k in ks]) # for those states plus a new", "self.stateseq[t] = ks[newlabelidx] def _label_score(self,t,k): assert t > 0 score", "in canondict.iteritems(): reversedict[v] = k return seq, canondict, reversedict class", "> 0: score += np.log( (alpha*betavec[k] + (kappa if k", "def __init__(self,model,beta,alpha_0,obs,dur,data=None,T=None,stateseq=None): self.alpha_0 = alpha_0 self.model = model self.beta =", "k) if SAMPLING in stateseq_norep[:-1] and \\ stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]+1]", "stateseq[0] = self._new_label(ks) else: stateseq[0] = ks[firststate] # runs a", "sets self.stateseq # also sets self.stateseq_norep and self.durations # it", "np.array([self._score(k,t) for k in ks]+[self._new_score(ks,t)]) idx = sample_discrete_from_log(scores) # set", "self.T = data.shape[0] else: assert data.shape[0] == stateseq.shape[0] self.stateseq =", "forwards for t in range(1,T): self.stateseq = stateseq[:t] ks =", "sample_discrete(np.arange(len(ks))) if firststateidx == len(ks)-1: firststate = self._new_label(ks) else: firststate", "= np.newaxis import collections, itertools import abc from pyhsmm.util.stats import", "# left transition score if t > 0: betarest =", "= k return seq, canondict, reversedict class dummytrans(object): def __init__(self,A):", "np.sum(self.stateseq == SAMPLING) in (0,1) temp = np.sum(self.stateseq[1:] == k)", "is a delta at that label for t in (np.random.permutation(self.T-1)+1):", "durations = rle(self.stateseq) return durations[stateseq_norep == k] else: return []", "incl 0 and T idx = np.where(startindices <= t)[0][-1] return", "stateseq[t-1] == k and stateseq[t+1] == k) else 0 score", "model = self.model alpha = self.alpha_0 beta = self.beta.betavec stateseq", "x in (A,B) if x.stop - x.start > 0] else:", "pass @abc.abstractmethod def _counts_fromto(self,k): pass def _new_label(self,ks): assert SAMPLING not", "k1) # EXCEPT last return np.sum(self.stateseq[from_indices+1] == k2) class collapsed_hdphsmm_states(collapsed_states):", "is None: self.data = data # self._generate(data.shape[0]) # initialized from", "score if t < self.T-1: score += np.log(betavec[stateseq[t+1]]) # observation", "in sum over k factor if t < self.T-1: betas", "self.beta.betavec[newlabel] # instantiate, needed if new state at beginning of", "for k in ks]) scores = np.array([(alpha*betavec[k] + ft if", "self.T - 1: # indicators since we may need to", "< 0: return slice(0,0) elif t > seq.shape[0]-1: return slice(seq.shape[0],seq.shape[0])", "NOTE: assumes censoring. can make no censoring by adding to", "= stateseq self.stateseq_norep, self.durations = rle(stateseq) self.data = data self.T", "self.dur # left transition (if there is one) if stateseq[t-1]", "def __init__(self,model,beta,alpha_0,kappa,obs,data=None,T=None,stateseq=None): self.alpha_0 = alpha_0 self.kappa = kappa self.model =", "def resample_label_version(self): # NOTE never changes first label: we assume", "len(self.stateseq) > 0: stateseq_norep, durations = rle(self.stateseq) return durations[stateseq_norep ==", "segment SAMPLING = -1 # special constant for indicating a", "= self._new_label(ks) else: self.stateseq[t] = ks[newlabelidx] def _label_score(self,t,k): assert t", "class, this will need fixing self.stateseq[t] = k wholegroup, pieces", "nextstateidx = sample_discrete(scores) if nextstateidx == scores.shape[0]-1: nextstate = self._new_label(ks)", "1-sum(betavec[k] for k in ks) score += np.log(alpha*betarest/(alpha+kappa+model._counts_from(stateseq[t-1]))) # right", "= alpha_0 self.model = model self.beta = beta self.obs =", "score += np.log(alpha*betarest/(alpha+kappa+model._counts_from(stateseq[t-1]))) # right transition score if t <", "> seq.shape[0]-1: return slice(seq.shape[0],seq.shape[0]) else: endindices, = np.where(np.diff(seq) != 0)", "coming out of our current state # going to all", "k else 0 another_fromto = 1 if (t > 0", "stateseq[0] = ks[firststate] # runs a CRF with fixed weights", "= stateseq elif stateseq is None: self.data = data #", "= self.obs, self.dur # left transition (if there is one)", "a new one, sample proportional to scores = np.array([(alpha*betavec[k] +", "counts, no to counts) score += np.log(alpha) - np.log(alpha*(1.-beta[stateseq[t-1]]) +", "left transition (only from counts, no to counts) score +=", "> 0] else: It = slice(t,t+1) return slice(A.start,B.stop), [(x,stateseq[x.start]) for", "_generate(self,T): self.T = T alpha, kappa = self.alpha_0, self.kappa betavec", "= np.array([model._counts_fromto(self.stateseq[t-1],k) + self._counts_fromto(self.stateseq[t-1],k) for k in ks]) scores =", "stateseq[t-1] == k else 0 another_fromto = 1 if (t", "for piece, val in pieces: # get all the other", "= list(model._occupied()) self.beta.housekeeping(ks) # form the scores and sample from", "k1 not in self.stateseq or k2 not in self.stateseq: return", "if t > 0 and stateseq[t-1] == k else 0", "elif A.start <= t < A.stop or B.start <= t", "and stateseq[t+1] == k) else 0 score += np.log( (alpha*betavec[stateseq[t+1]]", "or k1 == k2: return 0 else: stateseq_norep, _ =", "the indicator sequence # TODO if i write the special", "_generate(self,T): alpha = self.alpha_0 betavec = self.beta.betavec model = self.model", "# definition choice that isn't specified in the HDP-HMM #", "SAMPLING stateseq_norep, _ = rle(self.stateseq) temp = np.sum(stateseq_norep[1:] == k)", "pieces for (data,otherdata), (dur,otherdurs) in self._local_group(t,NEW): score += obs.log_predictive(data,otherdata) +", "(A,It,B) if x.stop - x.start > 0] ####################### # Utility", "state # distribution is a delta at that label for", "last return np.sum(self.stateseq[from_indices+1] == k2) class collapsed_hdphsmm_states(collapsed_states): def __init__(self,model,beta,alpha_0,obs,dur,data=None,T=None,stateseq=None): self.alpha_0", "reversedict = {} for k,v in canondict.iteritems(): reversedict[v] = k", "!= k: score += np.log(alpha * beta[stateseq[t+1]] + model._counts_fromto(k,stateseq[t+1])) \\", "localgroup.append(((self.data[piece],otherdata),(piece.stop-piece.start,otherdurs))) # remove the used piece from the exclusion self.stateseq[piece]", "# add in obs/dur scores of local pieces for (data,otherdata),", "members, like self.stateseq and maybe self.data assert self.stateseq[t] == SAMPLING", "pass in T when generating' self._generate(T) elif data is None:", "abc from pyhsmm.util.stats import sample_discrete, sample_discrete_from_log, combinedata from pyhsmm.util.general import", "SAMPLING) in (0,1) temp = np.sum(self.stateseq[:-1] == k) if SAMPLING", "else: C = stateseq_norep[na,:] plt.pcolor(X,Y,C,vmin=0,vmax=1) plt.ylim((0,1)) plt.xlim((0,len(self.stateseq))) plt.yticks([]) class collapsed_stickyhdphmm_states(collapsed_states):", "resampled NEW = -2 # special constant indicating a potentially", "+= np.log(alpha * beta[stateseq[t+1]] + model._counts_fromto(k,stateseq[t+1])) \\ - np.log(alpha *", "this model, this will always sample # zero, since no", "return 0 else: from_indices, = np.where(self.stateseq[:-1] == k1) # EXCEPT", "in obs/dur scores of local pieces for (data,otherdata), (dur,otherdurs) in", "score def _counts_from(self,k): assert k != SAMPLING assert np.sum(self.stateseq ==", "return durations[stateseq_norep == k] else: return [] def _counts_fromto(self,k1,k2): assert", "= data.shape[0] def _generate(self,T): self.T = T alpha, kappa =", "stateseq elif stateseq is None: self.data = data # self._generate(data.shape[0])", "in ks) score += np.log(alpha*betarest/(alpha+kappa+model._counts_from(stateseq[t-1]))) # right transition score if", "beta self.obs = obs self.data = data if (data,stateseq) ==", "k: temp -= 1 return temp def _counts_to(self,k): assert k", "Here, we choose just to sample from beta. Note that", "self.alpha_0, self.kappa betavec = self.beta.betavec stateseq = np.zeros(T,dtype=np.int) model =", "self.T-1: score += np.log(beta[stateseq[t+1]]) # add in sum over k", "if this is the # first chain being sampled in", "def _counts_to(self,k): assert k != SAMPLING assert np.sum(self.stateseq == SAMPLING)", "= model self.beta = beta self.obs = obs self.data =", "t < self.T-1: score += np.log(beta[stateseq[t+1]]) # add in sum", "stateseq class, this will need fixing self.stateseq[t] = k wholegroup,", "unpack variables model = self.model alpha = self.alpha_0 beta =", "if t < self.T-1: score += np.log(beta[stateseq[t+1]]) # add in", "= fill(stateseq,t-1), fill(stateseq,t+1) if A == B: return A, ((A,stateseq[A.start]),)", "in stateseq_norep[:-1] and \\ stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]+1] == k: temp", "out of our current state # going to all other", "[(x,stateseq[x.start]) for x in (A,It,B) if x.stop - x.start >", "np.array([(alpha*betavec[k] + (kappa if k == stateseq[t+1] else 0) +", "np.where(startindices <= t)[0][-1] return slice(startindices[idx],startindices[idx+1]) def canonize(seq): seq = seq.copy()", "value self.stateseq[t] = SAMPLING ks = list(model._occupied()) self.beta.housekeeping(ks) # form", "end indices (not incl -1 and T-1) startindices = np.concatenate(((0,),endindices+1,(seq.shape[0],)))", "for those states plus a new one, sample proportional to", "also call beta updates... class collapsed_states(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod", "= self._new_label(ks) else: stateseq[0] = ks[firststate] # runs a CRF", "initialized from the prior # self.stateseq = self.stateseq[:self.T] self.stateseq =", "elif t > seq.shape[0]-1: return slice(seq.shape[0],seq.shape[0]) else: endindices, = np.where(np.diff(seq)", "# predictive likelihoods for (data,otherdata), (dur,otherdurs) in self._local_group(t,k): score +=", "temp ### label sampler stuff def resample_label_version(self): # NOTE never", "model._counts_fromto(stateseq[t-1],k)) / (alpha+kappa+model._counts_from(stateseq[t-1])) ) # right transition score if t", "assume the initial state # distribution is a delta at", "durs = self.obs, self.dur # left transition (only from counts,", "run a family-CRF (CRF with durations) forwards while t <", "= self.dur.rvs() self.stateseq = np.ones(firststate_dur,dtype=int)*firststate t = firststate_dur # run", "self.T = stateseq.shape[0] self.stateseq = stateseq elif stateseq is None:", "@abc.abstractmethod def _counts_to(self,k): pass @abc.abstractmethod def _counts_fromto(self,k): pass def _new_label(self,ks):", "elif stateseq is None: self.data = data self._generate(data.shape[0]) else: assert", "assert data.shape[0] == stateseq.shape[0] self.stateseq = stateseq self.data = data", "return slice(seq.shape[0],seq.shape[0]) else: endindices, = np.where(np.diff(seq) != 0) # internal", "0: score += np.log( (alpha*betavec[k] + (kappa if k ==", "self.alpha_0 beta = self.beta.betavec stateseq = self.stateseq obs, durs =", "if k == stateseq[t+1] else 0) + model._counts_fromto(k,stateseq[t+1]) + another_fromto)", "new one, sample proportional to scores = np.array([(alpha*betavec[k] + (kappa", "+= np.log(betavec[stateseq[t+1]]) # observation score score += o.log_marginal_likelihood(data[t]) return score", "self.stateseq = np.array([]) ks = list(model._occupied()) + [None] firststateidx =", "the left transition in # counts (since we are scoring", "Utility Functions # ####################### def fill(seq,t): if t < 0:", "# observation score score += o.log_marginal_likelihood(data[t]) return score def _counts_from(self,k):", "data, stateseq = self.data, self.stateseq score = 0 # left", "+ model._counts_from(k)) # predictive likelihoods for (data,otherdata), (dur,otherdurs) in self._local_group(t,k):", "stateseq = self.data, self.stateseq score = 0 # left transition", "# Utility Functions # ####################### def fill(seq,t): if t <", "that isn't specified in the HDP-HMM # Here, we choose", "abc.ABCMeta @abc.abstractmethod def resample(self): pass @abc.abstractmethod def _counts_from(self,k): pass @abc.abstractmethod", "if len(self.stateseq) > 0: stateseq_norep, durations = rle(self.stateseq) return durations[stateseq_norep", "special stateseq class, this will need fixing self.stateseq[t] = k", "+= nextstate_dur self.T = len(self.stateseq) def resample(self): self.resample_label_version() def _durs_withlabel(self,k):", "* (1-beta[k]) + model._counts_from(k)) # predictive likelihoods for (data,otherdata), (dur,otherdurs)", "== k) if SAMPLING in self.stateseq[:-1] and \\ self.stateseq[np.where(self.stateseq ==", "is being resampled NEW = -2 # special constant indicating", "ks) fromto_counts = np.array([model._counts_fromto(self.stateseq[t-1],k) + self._counts_fromto(self.stateseq[t-1],k) for k in ks])", "# sample a new value scores = np.array([self._label_score(t,k) for k", "sample # zero, since no states will be occupied. ks", "= self.alpha_0 beta = self.beta.betavec stateseq = self.stateseq obs, durs", "a choice of what state to start in; it's just", "stateseq.shape[0] self.stateseq = stateseq self.data = data self.T = data.shape[0]", "return slice(startindices[idx],startindices[idx+1]) def canonize(seq): seq = seq.copy() canondict = collections.defaultdict(itertools.count().next)", "np.newaxis import collections, itertools import abc from pyhsmm.util.stats import sample_discrete,", "np.random.randint(25,size=data.shape[0]) self.T = data.shape[0] else: assert data.shape[0] == stateseq.shape[0] self.stateseq", "list(model._occupied()) self.beta.housekeeping(ks) # form the scores and sample from them", "= 0 # left transition score if t > 0:", "+ ft) for k,ft in zip(ks,fromto_counts)] + [alpha*betarest]) nextstateidx =", "== stateseq[t+1] else 0) + model._counts_fromto(k,stateseq[t+1]) + another_fromto) / (alpha+kappa+model._counts_from(k)", "np.log( (alpha*betavec[k] + (kappa if k == stateseq[t-1] else 0)", "self._new_label(ks) else: self.stateseq[t] = ks[newlabelidx] def _label_score(self,t,k): assert t >", "betarest = 1-sum(betavec[k] for k in ks) # get the", "for k in ks) score += np.log(alpha*betarest/(alpha+kappa+model._counts_from(stateseq[t-1]))) # right transition", "variables model = self.model alpha = self.alpha_0 beta = self.beta.betavec", "scoring exchangeably, not independently) another_from = 1 if t >", "self.beta.betavec, self.model, self.obs data, stateseq = self.data, self.stateseq score =", "so that we can get the indicator sequence # TODO", "data self.T = data.shape[0] def _generate(self,T): alpha = self.alpha_0 betavec", "self.stateseq = stateseq elif stateseq is None: self.data = data", "+ durs.log_predictive(dur,otherdurs) return score def _local_group(self,t,k): ''' returns a sequence", "== scores.shape[0]-1: self.stateseq[t] = self._new_label(ks) else: self.stateseq[t] = ks[newlabelidx] def", "resample(self): model = self.model for t in np.random.permutation(self.T): # throw", "# remove the used piece from the exclusion self.stateseq[piece] =", "we may need to include the left transition in #", "def fill(seq,t): if t < 0: return slice(0,0) elif t", "self.stateseq[np.where(self.stateseq == SAMPLING)[0]-1] == k: temp -= 1 return temp", "restore original views self.stateseq = orig_stateseq # return return localgroup", "beginning of seq return newlabel def _data_withlabel(self,k): assert k !=", "counts of new states coming out of our current state", "1 return temp def _counts_to(self,k): assert k != SAMPLING stateseq_norep,", "sample_discrete_from_log(scores) if newlabelidx == scores.shape[0]-1: self.stateseq[t] = self._new_label(ks) else: self.stateseq[t]", "temporarily modifies members, like self.stateseq and maybe self.data assert self.stateseq[t]", "state to start in; it's just a # definition choice", "seq.shape[0]-1: return slice(seq.shape[0],seq.shape[0]) else: endindices, = np.where(np.diff(seq) != 0) #", "self.obs data, stateseq = self.data, self.stateseq score = 0 #", "anything that sets self.stateseq # also sets self.stateseq_norep and self.durations", "that label for t in (np.random.permutation(self.T-1)+1): self.stateseq[t] = SAMPLING ks", "sample from them scores = np.array([self._score(k,t) for k in ks]+[self._new_score(ks,t)])", "NOTE never changes first label: we assume the initial state", "make no censoring by adding to score of last #", "__init__(self,model,beta,alpha_0,obs,dur,data=None,T=None,stateseq=None): self.alpha_0 = alpha_0 self.model = model self.beta = beta", "k2: return 0 else: stateseq_norep, _ = rle(self.stateseq) from_indices, =", "alpha, kappa = self.alpha_0, self.kappa betavec, model, o = self.beta.betavec,", "# NOTE never changes first label: we assume the initial", "model = self.model self.stateseq = stateseq[:0] # NOTE: we have", "in ks) # get the counts of new states coming", "np.log(alpha) - np.log(alpha*(1.-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1])) # add in right transition", "= orig_stateseq[piece] # restore original views self.stateseq = orig_stateseq #", "== B: return A, ((A,stateseq[A.start]),) elif A.start <= t <", "np.array([model._counts_fromto(stateseq[t-1],k) + self._counts_fromto(stateseq[t-1],k) for k in ks]) # for those", "self._new_label(ks) else: stateseq[t] = ks[nextstateidx] self.stateseq = stateseq def resample(self):", "from_indices, = np.where(stateseq_norep[:-1] == k1) # EXCEPT last return np.sum(stateseq_norep[from_indices+1]", "self.dur.rvs() self.stateseq = np.ones(firststate_dur,dtype=int)*firststate t = firststate_dur # run a", "newlabelidx == scores.shape[0]-1: self.stateseq[t] = self._new_label(ks) else: self.stateseq[t] = ks[newlabelidx]", "np.where(stateseq_norep[:-1] == k1) # EXCEPT last return np.sum(stateseq_norep[from_indices+1] == k2)", "self.stateseq: return 0 else: from_indices, = np.where(self.stateseq[:-1] == k1) #", "# right transition score if t < self.T - 1:", "# EXCEPT last return np.sum(stateseq_norep[from_indices+1] == k2) def _counts_from(self,k): assert", "> 0 score = 0. # unpack variables model =", "rle(self.stateseq) return durations[stateseq_norep == k] else: return [] def _counts_fromto(self,k1,k2):", "= {} for k,v in canondict.iteritems(): reversedict[v] = k return", "= self.model for t in np.random.permutation(self.T): # throw out old", "data.shape[0] def _generate(self,T): self.T = T alpha, kappa = self.alpha_0,", "k != SAMPLING stateseq_norep, _ = rle(self.stateseq) temp = np.sum(stateseq_norep[1:]", "set methods # type(x).__setitem__(x,i) classmethod # also has members norep", "alpha, kappa = self.alpha_0, self.kappa betavec = self.beta.betavec stateseq =", "scores.shape[0]-1: self.stateseq[t] = self._new_label(ks) else: self.stateseq[t] = ks[idx] def _score(self,k,t):", "self.dur # left transition (only from counts, no to counts)", "def _label_score(self,t,k): assert t > 0 score = 0. #", "# counts (since we are scoring exchangeably, not independently) another_from", "canondict.iteritems(): reversedict[v] = k return seq, canondict, reversedict class dummytrans(object):", "0 to abignumber exclusive #################### # States Classes # ####################", "- x.start > 0] ####################### # Utility Functions # #######################", "def plot(self,colors_dict): from matplotlib import pyplot as plt stateseq_norep, durations", "canondict = collections.defaultdict(itertools.count().next) for idx,s in enumerate(seq): seq[idx] = canondict[s]", "- set((SAMPLING,)) def plot(self,colors_dict): from matplotlib import pyplot as plt", "durations = rle(self.stateseq) X,Y = np.meshgrid(np.hstack((0,durations.cumsum())),(0,1)) if colors_dict is not", "-1 and T-1) startindices = np.concatenate(((0,),endindices+1,(seq.shape[0],))) # incl 0 and", "= alpha_0 self.kappa = kappa self.model = model self.beta =", "labels are sampled uniformly from 0 to abignumber exclusive ####################", "self._counts_fromto(stateseq[t-1],k) for k in ks]) # for those states plus", "left transition (if there is one) if stateseq[t-1] != k:", "== stateseq[t+1] else 0) + ft) for k,ft in zip(ks,fromto_counts)]", "else: self.stateseq[t] = ks[idx] def _score(self,k,t): alpha, kappa = self.alpha_0,", "assert t > 0 score = 0. # unpack variables", "/ (alpha+kappa+model._counts_from(stateseq[t-1])) ) # right transition score if t <", "import rle as rle # NOTE: assumes censoring. can make", "0: return slice(0,0) elif t > seq.shape[0]-1: return slice(seq.shape[0],seq.shape[0]) else:", "classmethod # also has members norep and lens (or something)", "ks]+[self._new_score(ks,t)]) idx = sample_discrete_from_log(scores) # set the state if idx", "assert T is not None, 'must pass in T when", "<reponame>mattjj/pyhsmm-collapsedinfinite from __future__ import division import numpy as np na", "score += obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs) return score def _local_group(self,t,k): '''", "+ model._counts_fromto(stateseq[t-1],k)) \\ - np.log(alpha * (1-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1])) #", "wholegroup, pieces = self._local_slices(self.stateseq,t) self.stateseq[t] = SAMPLING # build local", "obs, durs = self.obs, self.dur # left transition (if there", "sum over k factor if t < self.T-1: betas =", "> 0] ####################### # Utility Functions # ####################### def fill(seq,t):", "self.stateseq or k1 == k2: return 0 else: stateseq_norep, _", "(since we are scoring exchangeably, not independently) another_from = 1", "import numpy as np na = np.newaxis import collections, itertools", "score if t > 0: score += np.log( (alpha*betavec[k] +", "< T: ks = list(model._occupied() | self._occupied()) betarest = 1-sum(betavec[k]", "- np.log(alpha * (1-beta[k]) + model._counts_from(k)) # predictive likelihoods for", "is not None: C = np.array([[colors_dict[state] for state in stateseq_norep]])", "self.alpha_0 = alpha_0 self.kappa = kappa self.model = model self.beta", "k in ks] + [self._new_label_score(t,ks)]) newlabelidx = sample_discrete_from_log(scores) if newlabelidx", "None, 'must pass in T when generating' self._generate(T) elif data", "obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs) return score def _new_label_score(self,t,ks): assert t >", "in ks: newlabel = np.random.randint(ABIGNUMBER) newweight = self.beta.betavec[newlabel] # instantiate,", "t < self.T-1 and stateseq[t+1] != k: score += np.log(alpha", "# NOTE: we have a choice of what state to", "# generating assert T is not None, 'must pass in", "k1 != SAMPLING and k2 != SAMPLING if k1 not", "self.durations # it should also call beta updates... class collapsed_states(object):", "ks[firststateidx] self.dur.resample(combinedata((model._durs_withlabel(firststate),self._durs_withlabel(firststate)))) firststate_dur = self.dur.rvs() self.stateseq = np.ones(firststate_dur,dtype=int)*firststate t =", "type(x).__setitem__(x,i) classmethod # also has members norep and lens (or", "self.model = model self.beta = beta self.obs = obs self.dur", "score = 0. # unpack variables model = self.model alpha", "to all other states fromto_counts = np.array([model._counts_fromto(stateseq[t-1],k) + self._counts_fromto(stateseq[t-1],k) for", "t in range(1,T): self.stateseq = stateseq[:t] ks = list(model._occupied() |", "in zip(ks,fromto_counts)] + [alpha*betarest]) nextstateidx = sample_discrete(scores) if nextstateidx ==", "state if idx == scores.shape[0]-1: self.stateseq[t] = self._new_label(ks) else: self.stateseq[t]", "a sequence of length between 1 and 3, where each", "states coming out of our current state # going to", "== k) if SAMPLING in stateseq_norep[:-1] and \\ stateseq_norep[np.where(stateseq_norep ==", "def resample(self): pass @abc.abstractmethod def _counts_from(self,k): pass @abc.abstractmethod def _counts_to(self,k):", "self.stateseq or k2 not in self.stateseq: return 0 else: from_indices,", "stateseq self.stateseq_norep, self.durations = rle(stateseq) self.data = data self.T =", "= self.stateseq[:self.T] self.stateseq = np.random.randint(25,size=data.shape[0]) self.T = data.shape[0] else: assert", "self._generate(data.shape[0]) # initialized from the prior # self.stateseq = self.stateseq[:self.T]", "!= SAMPLING if k1 not in self.stateseq or k2 not", "+ another_fromto) / (alpha+kappa+model._counts_from(k) + another_from) ) # observation score", "data.shape[0] == stateseq.shape[0] self.stateseq = stateseq self.data = data self.T", "model = self.model for t in np.random.permutation(self.T): # throw out", "fromto_counts = np.array([model._counts_fromto(self.stateseq[t-1],k) + self._counts_fromto(self.stateseq[t-1],k) for k in ks]) scores", "transition (if there is one) if stateseq[t-1] != k: score", "self._new_label(ks) else: stateseq[0] = ks[firststate] # runs a CRF with", "pieces: # get all the other data otherdata, otherdurs =", "its own rle # must override set methods # type(x).__setitem__(x,i)", "np.meshgrid(np.hstack((0,durations.cumsum())),(0,1)) if colors_dict is not None: C = np.array([[colors_dict[state] for", "uniformly from 0 to abignumber exclusive #################### # States Classes", "a CRF with fixed weights beta forwards for t in", "SAMPLING)[0]+1] == k: temp -= 1 return temp def _counts_fromto(self,k1,k2):", "score += o.log_predictive(data[t],model._data_withlabel(k)) return score def _new_score(self,ks,t): alpha, kappa =", "score def _local_group(self,t,k): ''' returns a sequence of length between", "(or something) # that are either read-only or also override", "updates... class collapsed_states(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def resample(self): pass", "= SAMPLING ks = self.model._occupied() self.beta.housekeeping(ks) ks = list(ks) #", "+= obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs) return score def _new_label_score(self,t,ks): assert t", "(data,otherdata), (dur,otherdurs) in self._local_group(t,k): score += obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs) return", "list(ks) # sample a new value scores = np.array([self._label_score(t,k) for", "we choose just to sample from beta. Note that if", "(dur,otherdurs) in self._local_group(t,NEW): score += obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs) return score", "special constant indicating a potentially new label ABIGNUMBER = 10000", "plt.ylim((0,1)) plt.xlim((0,len(self.stateseq))) plt.yticks([]) class collapsed_stickyhdphmm_states(collapsed_states): def __init__(self,model,beta,alpha_0,kappa,obs,data=None,T=None,stateseq=None): self.alpha_0 = alpha_0", "alpha = self.alpha_0 beta = self.beta.betavec stateseq = self.stateseq obs,", "(kappa if k == stateseq[t+1] else 0) + model._counts_fromto(k,stateseq[t+1]) +", "temp def _counts_to(self,k): assert k != SAMPLING stateseq_norep, _ =", "SAMPLING not in ks newlabel = np.random.randint(ABIGNUMBER) while newlabel in", "not in self.stateseq: return 0 else: from_indices, = np.where(self.stateseq[:-1] ==", "over k factor if t < self.T-1: betas = np.random.beta(1,self.beta.gamma_0,size=200)", "from beta. Note that if this is the # first", "def _occupied(self): return set(self.stateseq) - set((SAMPLING,)) def plot(self,colors_dict): from matplotlib", "t in (np.random.permutation(self.T-1)+1): self.stateseq[t] = SAMPLING ks = self.model._occupied() self.beta.housekeeping(ks)", "self.obs = obs self.data = data if (data,stateseq) == (None,None):", "np.random.permutation(self.T): # throw out old value self.stateseq[t] = SAMPLING ks", "(kappa if k == stateseq[t-1] else 0) + model._counts_fromto(stateseq[t-1],k)) /", "piece, val in pieces: # get all the other data", "kappa self.model = model self.beta = beta self.obs = obs", "observation score score += o.log_marginal_likelihood(data[t]) return score def _counts_from(self,k): assert", "!= k: score += np.log(alpha * beta[k] + model._counts_fromto(stateseq[t-1],k)) \\", "group of statistics localgroup = [] self.stateseq[wholegroup] = SAMPLING for", "0] ####################### # Utility Functions # ####################### def fill(seq,t): if", "k == stateseq[t+1] else 0) + model._counts_fromto(k,stateseq[t+1]) + another_fromto) /", "k] def _occupied(self): return set(self.stateseq) - set((SAMPLING,)) def plot(self,colors_dict): from", "0 and stateseq[t-1] == k else 0 another_fromto = 1", "zip(ks,fromto_counts)] + [alpha*betarest]) nextstateidx = sample_discrete(scores) if nextstateidx == scores.shape[0]-1:", "left transition score if t > 0: betarest = 1-sum(betavec[k]", "ks]) scores = np.array([(alpha*betavec[k] + ft if k != self.stateseq[t-1]", "+ model._counts_fromto(stateseq[t-1],k)) / (alpha+kappa+model._counts_from(stateseq[t-1])) ) # right transition score if", "_counts_from(self,k): pass @abc.abstractmethod def _counts_to(self,k): pass @abc.abstractmethod def _counts_fromto(self,k): pass", "obs self.dur = dur self.data = data if (data,stateseq) ==", "t)[0][-1] return slice(startindices[idx],startindices[idx+1]) def canonize(seq): seq = seq.copy() canondict =", "np.log(alpha * (1-beta[k]) + model._counts_from(k)) # predictive likelihoods for (data,otherdata),", "# special constant for indicating a state or state range", "= np.array([]) ks = list(model._occupied()) + [None] firststateidx = sample_discrete(np.arange(len(ks)))", "for t in range(1,T): self.stateseq = stateseq[:t] ks = list(model._occupied()", "else: return [] def _counts_fromto(self,k1,k2): assert k1 != SAMPLING and", "not in self.stateseq or k1 == k2: return 0 else:", "== scores.shape[0]-1: nextstate = self._new_label(ks) else: nextstate = ks[nextstateidx] #", "= sample_discrete(scores) if nextstateidx == scores.shape[0]-1: stateseq[t] = self._new_label(ks) else:", "# segment SAMPLING = -1 # special constant for indicating", "for (data,otherdata), (dur,otherdurs) in self._local_group(t,NEW): score += obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs)", "the state if idx == scores.shape[0]-1: self.stateseq[t] = self._new_label(ks) else:", "SAMPLING # build local group of statistics localgroup = []", "self.stateseq[t] = ks[idx] def _score(self,k,t): alpha, kappa = self.alpha_0, self.kappa", "self.obs, self.dur # left transition (only from counts, no to", "= ks[idx] def _score(self,k,t): alpha, kappa = self.alpha_0, self.kappa betavec,", "import collections, itertools import abc from pyhsmm.util.stats import sample_discrete, sample_discrete_from_log,", "predictive likelihoods for (data,otherdata), (dur,otherdurs) in self._local_group(t,k): score += obs.log_predictive(data,otherdata)", "a new value scores = np.array([self._label_score(t,k) for k in ks]", "+= o.log_predictive(data[t],model._data_withlabel(k)) return score def _new_score(self,ks,t): alpha, kappa = self.alpha_0,", "0) # internal end indices (not incl -1 and T-1)", "with fixed weights beta forwards for t in range(1,T): self.stateseq", "= sample_discrete_from_log(scores) if newlabelidx == scores.shape[0]-1: self.stateseq[t] = self._new_label(ks) else:", "stateseq.shape[0] self.stateseq = stateseq self.stateseq_norep, self.durations = rle(stateseq) self.data =", "self._local_slices(self.stateseq,t) self.stateseq[t] = SAMPLING # build local group of statistics", "if k == stateseq[t+1] else 0) + ft) for k,ft", "o = self.beta.betavec, self.model, self.obs data, stateseq = self.data, self.stateseq", "np.log(alpha * (1-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1])) # right transition (if there", "*= (1-betas[:-1]).cumprod() score += np.log(self.beta.remaining*(betas/(1-betas)).sum()) else: score += np.log(self.beta.remaining) #", "Functions # ####################### def fill(seq,t): if t < 0: return", "''' returns slices: wholegroup, (piece1, ...) ''' A,B = fill(stateseq,t-1),", "0 # left transition score if t > 0: betarest", "# run a family-CRF (CRF with durations) forwards while t", "assert self.stateseq[t] == SAMPLING orig_stateseq = self.stateseq.copy() # temporarily set", "# first chain being sampled in this model, this will", "+ [self._new_label_score(t,ks)]) newlabelidx = sample_discrete_from_log(scores) if newlabelidx == scores.shape[0]-1: self.stateseq[t]", "reversedict[v] = k return seq, canondict, reversedict class dummytrans(object): def", "sample_discrete(scores) if nextstateidx == scores.shape[0]-1: stateseq[t] = self._new_label(ks) else: stateseq[t]", "in self._local_group(t,NEW): score += obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs) return score def", "incl -1 and T-1) startindices = np.concatenate(((0,),endindices+1,(seq.shape[0],))) # incl 0", "= self.beta.betavec stateseq = np.zeros(T,dtype=np.int) model = self.model self.stateseq =", "+= obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs) return score def _local_group(self,t,k): ''' returns", "self._local_group(t,k): score += obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs) return score def _new_label_score(self,t,ks):", "score score += o.log_predictive(data[t],model._data_withlabel(k)) return score def _new_score(self,ks,t): alpha, kappa", "other data otherdata, otherdurs = self.model._data_withlabel(val), self.model._durs_withlabel(val) # add a", "self.stateseq = self.stateseq[:self.T] self.stateseq = np.random.randint(25,size=data.shape[0]) self.T = data.shape[0] else:", "if (data,stateseq) == (None,None): # generating assert T is not", "score += obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs) return score def _new_label_score(self,t,ks): assert", "nextstateidx = sample_discrete(scores) if nextstateidx == scores.shape[0]-1: stateseq[t] = self._new_label(ks)", "state in stateseq_norep]]) else: C = stateseq_norep[na,:] plt.pcolor(X,Y,C,vmin=0,vmax=1) plt.ylim((0,1)) plt.xlim((0,len(self.stateseq)))", "# States Classes # #################### # TODO an array class", "scores = np.array([self._label_score(t,k) for k in ks] + [self._new_label_score(t,ks)]) newlabelidx", "and stateseq[t+1] != k: score += np.log(alpha * beta[stateseq[t+1]] +", "in range(1,T): self.stateseq = stateseq[:t] ks = list(model._occupied() | self._occupied())", "in np.random.permutation(self.T): # throw out old value self.stateseq[t] = SAMPLING", "B.start <= t < B.stop: return slice(A.start,B.stop), [(x,stateseq[x.start]) for x", "= self._new_label(ks) else: firststate = ks[firststateidx] self.dur.resample(combinedata((model._durs_withlabel(firststate),self._durs_withlabel(firststate)))) firststate_dur = self.dur.rvs()", "stateseq = self.stateseq obs, durs = self.obs, self.dur # left", "betas[1:] *= (1-betas[:-1]).cumprod() score += np.log(self.beta.remaining*(betas/(1-betas)).sum()) else: score += np.log(self.beta.remaining)", "k != SAMPLING if len(self.stateseq) > 0: stateseq_norep, durations =", "fill(stateseq,t+1) if A == B: return A, ((A,stateseq[A.start]),) elif A.start", "distribution is a delta at that label for t in", "< self.T - 1: # indicators since we may need", "piece to our localgroup localgroup.append(((self.data[piece],otherdata),(piece.stop-piece.start,otherdurs))) # remove the used piece", "B: return A, ((A,stateseq[A.start]),) elif A.start <= t < A.stop", "in (A,B) if x.stop - x.start > 0] else: It", "model self.beta = beta self.obs = obs self.dur = dur", "[None] firststate = sample_discrete(np.arange(len(ks))) if firststate == len(ks)-1: stateseq[0] =", "= self.model alpha = self.alpha_0 beta = self.beta.betavec stateseq =", "must override set methods # type(x).__setitem__(x,i) classmethod # also has", "def resample(self): self.resample_label_version() def _durs_withlabel(self,k): assert k != SAMPLING if", "def _counts_from(self,k): assert k != SAMPLING stateseq_norep, _ = rle(self.stateseq)", "((data,otherdata), (dur,otherdurs)) ''' # temporarily modifies members, like self.stateseq and", "out old value self.stateseq[t] = SAMPLING ks = list(model._occupied()) self.beta.housekeeping(ks)", "A == B: return A, ((A,stateseq[A.start]),) elif A.start <= t", "canondict, reversedict class dummytrans(object): def __init__(self,A): self.A = A def", "X,Y = np.meshgrid(np.hstack((0,durations.cumsum())),(0,1)) if colors_dict is not None: C =", "= T alpha, kappa = self.alpha_0, self.kappa betavec = self.beta.betavec", "== len(ks)-1: stateseq[0] = self._new_label(ks) else: stateseq[0] = ks[firststate] #", "data self.T = data.shape[0] def _generate(self,T): self.T = T alpha,", "seq = seq.copy() canondict = collections.defaultdict(itertools.count().next) for idx,s in enumerate(seq):", "we are scoring exchangeably, not independently) another_from = 1 if", "self.stateseq[t] == SAMPLING orig_stateseq = self.stateseq.copy() # temporarily set stateseq", "__future__ import division import numpy as np na = np.newaxis", "x.start > 0] else: It = slice(t,t+1) return slice(A.start,B.stop), [(x,stateseq[x.start])", "self.stateseq[t] = self._new_label(ks) else: self.stateseq[t] = ks[newlabelidx] def _label_score(self,t,k): assert", "right transition score if t < self.T - 1: #", "== SAMPLING)[0]-1] == k: temp -= 1 return temp def", "data.shape[0] else: assert data.shape[0] == stateseq.shape[0] self.stateseq = stateseq self.stateseq_norep,", "a state or state range that is being resampled NEW", "+= np.log(alpha) - np.log(alpha*(1.-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1])) # add in right", "label for t in (np.random.permutation(self.T-1)+1): self.stateseq[t] = SAMPLING ks =", "localgroup = [] self.stateseq[wholegroup] = SAMPLING for piece, val in", "rle(self.stateseq) temp = np.sum(stateseq_norep[:-1] == k) if SAMPLING in stateseq_norep[1:]", "from 0 to abignumber exclusive #################### # States Classes #", "model, this will always sample # zero, since no states", "# it should also call beta updates... class collapsed_states(object): __metaclass__", "and \\ self.stateseq[np.where(self.stateseq == SAMPLING)[0]+1] == k: temp -= 1", "return score def _local_group(self,t,k): ''' returns a sequence of length", "array class that maintains its own rle # must override", "i write the special stateseq class, this will need fixing", "np.array([]) ks = list(model._occupied()) + [None] firststateidx = sample_discrete(np.arange(len(ks))) if", "rle(stateseq) self.data = data self.T = data.shape[0] def _generate(self,T): alpha", "self.stateseq[t] = SAMPLING # build local group of statistics localgroup", "from_indices, = np.where(self.stateseq[:-1] == k1) # EXCEPT last return np.sum(self.stateseq[from_indices+1]", "or state range that is being resampled NEW = -2", "return 0 else: stateseq_norep, _ = rle(self.stateseq) from_indices, = np.where(stateseq_norep[:-1]", "else: score += np.log(self.beta.remaining) # add in obs/dur scores of", "self.data = data # self._generate(data.shape[0]) # initialized from the prior", "data.shape[0] def _generate(self,T): alpha = self.alpha_0 betavec = self.beta.betavec model", "sample from beta. Note that if this is the #", "set the state if idx == scores.shape[0]-1: self.stateseq[t] = self._new_label(ks)", "= np.random.beta(1,self.beta.gamma_0,size=200) betas[1:] *= (1-betas[:-1]).cumprod() score += np.log(self.beta.remaining*(betas/(1-betas)).sum()) else: score", "_new_score(self,ks,t): alpha, kappa = self.alpha_0, self.kappa betavec, model, o =", "# distribution is a delta at that label for t", "self._generate(data.shape[0]) else: assert data.shape[0] == stateseq.shape[0] self.stateseq = stateseq self.data", "k in ks) score += np.log(alpha*betarest/(alpha+kappa+model._counts_from(stateseq[t-1]))) # right transition score", "being sampled in this model, this will always sample #", "transition in # counts (since we are scoring exchangeably, not", "self.stateseq[t] = self._new_label(ks) else: self.stateseq[t] = ks[idx] def _score(self,k,t): alpha,", "model._counts_from(k)) # predictive likelihoods for (data,otherdata), (dur,otherdurs) in self._local_group(t,k): score", "sample_discrete_from_log, combinedata from pyhsmm.util.general import rle as rle # NOTE:", "= np.array([(alpha*betavec[k] + ft if k != self.stateseq[t-1] else 0)", "_occupied(self): return set(self.stateseq) - set((SAMPLING,)) def plot(self,colors_dict): from matplotlib import", "obs/dur scores of local pieces for (data,otherdata), (dur,otherdurs) in self._local_group(t,NEW):", "...) ''' A,B = fill(stateseq,t-1), fill(stateseq,t+1) if A == B:", "np.where(self.stateseq[:-1] == k1) # EXCEPT last return np.sum(self.stateseq[from_indices+1] == k2)", "in stateseq_norep]]) else: C = stateseq_norep[na,:] plt.pcolor(X,Y,C,vmin=0,vmax=1) plt.ylim((0,1)) plt.xlim((0,len(self.stateseq))) plt.yticks([])", "states will be occupied. ks = list(model._occupied()) + [None] firststate", "np.random.randint(ABIGNUMBER) while newlabel in ks: newlabel = np.random.randint(ABIGNUMBER) newweight =", "SAMPLING)[0]-1] == k: temp -= 1 return temp def _counts_to(self,k):", "set((SAMPLING,)) def plot(self,colors_dict): from matplotlib import pyplot as plt stateseq_norep,", "not in self.stateseq or k2 not in self.stateseq: return 0", "= ks[nextstateidx] self.stateseq = stateseq def resample(self): model = self.model", "(if there is one) if stateseq[t-1] != k: score +=", "np.log(self.beta.remaining) # add in obs/dur scores of local pieces for", "from matplotlib import pyplot as plt stateseq_norep, durations = rle(self.stateseq)", "(t > 0 and stateseq[t-1] == k and stateseq[t+1] ==", "wholegroup, (piece1, ...) ''' A,B = fill(stateseq,t-1), fill(stateseq,t+1) if A", "# throw out old value self.stateseq[t] = SAMPLING ks =", "ks) score += np.log(alpha*betarest/(alpha+kappa+model._counts_from(stateseq[t-1]))) # right transition score if t", "plus a new one, sample proportional to scores = np.array([(alpha*betavec[k]", "of length between 1 and 3, where each sequence element", "if k1 not in self.stateseq or k2 not in self.stateseq", "will always sample # zero, since no states will be", "k) if SAMPLING in stateseq_norep[1:] and \\ stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]-1]", "== stateseq.shape[0] self.stateseq = stateseq self.data = data self.T =", "self.alpha_0 = alpha_0 self.model = model self.beta = beta self.obs", "0 # left transition score if t > 0: score", "== scores.shape[0]-1: self.stateseq[t] = self._new_label(ks) else: self.stateseq[t] = ks[idx] def", "> 0: stateseq_norep, durations = rle(self.stateseq) return durations[stateseq_norep == k]", "-= 1 return temp def _counts_fromto(self,k1,k2): assert k1 != SAMPLING", "NOTE: we have a choice of what state to start", "since we may need to include the left transition in", "for x in (A,It,B) if x.stop - x.start > 0]", "since no states will be occupied. ks = list(model._occupied()) +", "TODO if i write the special stateseq class, this will", "and T-1) startindices = np.concatenate(((0,),endindices+1,(seq.shape[0],))) # incl 0 and T", "data.shape[0] == stateseq.shape[0] self.stateseq = stateseq self.stateseq_norep, self.durations = rle(stateseq)", "betas = np.random.beta(1,self.beta.gamma_0,size=200) betas[1:] *= (1-betas[:-1]).cumprod() score += np.log(self.beta.remaining*(betas/(1-betas)).sum()) else:", "the special stateseq class, this will need fixing self.stateseq[t] =", "self.stateseq[wholegroup] = SAMPLING for piece, val in pieces: # get", "SAMPLING = -1 # special constant for indicating a state", "= 0. # unpack model = self.model alpha = self.alpha_0", "methods # type(x).__setitem__(x,i) classmethod # also has members norep and", "= ks[firststate] # runs a CRF with fixed weights beta", "None: self.data = data self._generate(data.shape[0]) else: assert data.shape[0] == stateseq.shape[0]", "in enumerate(seq): seq[idx] = canondict[s] reversedict = {} for k,v", "!= SAMPLING assert np.sum(self.stateseq == SAMPLING) in (0,1) temp =", "if k1 not in self.stateseq or k2 not in self.stateseq:", "T alpha, kappa = self.alpha_0, self.kappa betavec = self.beta.betavec stateseq", "0 else: from_indices, = np.where(self.stateseq[:-1] == k1) # EXCEPT last", "initial state # distribution is a delta at that label", "stateseq_norep, _ = rle(self.stateseq) temp = np.sum(stateseq_norep[:-1] == k) if", "if idx == scores.shape[0]-1: self.stateseq[t] = self._new_label(ks) else: self.stateseq[t] =", "[] self.stateseq[wholegroup] = SAMPLING for piece, val in pieces: #", "= stateseq[:0] # NOTE: we have a choice of what", "# for those states plus a new one, sample proportional", "def _counts_from(self,k): assert k != SAMPLING assert np.sum(self.stateseq == SAMPLING)", "state at beginning of seq return newlabel def _data_withlabel(self,k): assert", "score if t > 0: betarest = 1-sum(betavec[k] for k", "self.beta = beta self.obs = obs self.dur = dur self.data", "scores of local pieces for (data,otherdata), (dur,otherdurs) in self._local_group(t,NEW): score", "self.stateseq = orig_stateseq # return return localgroup @classmethod def _local_slices(cls,stateseq,t):", "if nextstateidx == scores.shape[0]-1: nextstate = self._new_label(ks) else: nextstate =", "stateseq[t-1] != k: score += np.log(alpha * beta[k] + model._counts_fromto(stateseq[t-1],k))", "_local_group(self,t,k): ''' returns a sequence of length between 1 and", "firststate = sample_discrete(np.arange(len(ks))) if firststate == len(ks)-1: stateseq[0] = self._new_label(ks)", "model._counts_from(stateseq[t-1])) # right transition (if there is one) if t", "# add a piece to our localgroup localgroup.append(((self.data[piece],otherdata),(piece.stop-piece.start,otherdurs))) # remove", "np.array([self._label_score(t,k) for k in ks] + [self._new_label_score(t,ks)]) newlabelidx = sample_discrete_from_log(scores)", "proportional to scores = np.array([(alpha*betavec[k] + (kappa if k ==", "= stateseq[:t] ks = list(model._occupied() | self._occupied()) betarest = 1-sum(betavec[k]", "ks]) # for those states plus a new one, sample", "nextstate_dur = self.dur.rvs() self.stateseq = np.concatenate((self.stateseq,np.ones(nextstate_dur,dtype=int)*nextstate)) t += nextstate_dur self.T", "-= 1 return temp def _counts_to(self,k): assert k != SAMPLING", "# for now, i'll just make sure outside that anything", "return self.data[self.stateseq == k] def _occupied(self): return set(self.stateseq) - set((SAMPLING,))", "scores = np.array([(alpha*betavec[k] + ft if k != self.stateseq[t-1] else", "C = stateseq_norep[na,:] plt.pcolor(X,Y,C,vmin=0,vmax=1) plt.ylim((0,1)) plt.xlim((0,len(self.stateseq))) plt.yticks([]) class collapsed_stickyhdphmm_states(collapsed_states): def", "rle(self.stateseq) from_indices, = np.where(stateseq_norep[:-1] == k1) # EXCEPT last return", "we can get the indicator sequence # TODO if i", "generating' self._generate(T) elif data is None: self.T = stateseq.shape[0] self.stateseq", "durations) forwards while t < T: ks = list(model._occupied() |", "stateseq elif stateseq is None: self.data = data self._generate(data.shape[0]) else:", "0. # unpack variables model = self.model alpha = self.alpha_0", "remove the used piece from the exclusion self.stateseq[piece] = orig_stateseq[piece]", "length between 1 and 3, where each sequence element is", "!= SAMPLING stateseq_norep, _ = rle(self.stateseq) temp = np.sum(stateseq_norep[1:] ==", "to hypothetical stateseq # so that we can get the", "np.log(betavec[stateseq[t+1]]) # observation score score += o.log_marginal_likelihood(data[t]) return score def", "class collapsed_hdphsmm_states(collapsed_states): def __init__(self,model,beta,alpha_0,obs,dur,data=None,T=None,stateseq=None): self.alpha_0 = alpha_0 self.model = model", "rle(self.stateseq) temp = np.sum(stateseq_norep[1:] == k) if SAMPLING in stateseq_norep[:-1]", "a potentially new label ABIGNUMBER = 10000 # state labels", "if newlabelidx == scores.shape[0]-1: self.stateseq[t] = self._new_label(ks) else: self.stateseq[t] =", "= SAMPLING # build local group of statistics localgroup =", "in (0,1) temp = np.sum(self.stateseq[1:] == k) if SAMPLING in", "SAMPLING return self.data[self.stateseq == k] def _occupied(self): return set(self.stateseq) -", "in self._local_group(t,k): score += obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs) return score def", "(dur,otherdurs)) ''' # temporarily modifies members, like self.stateseq and maybe", "original views self.stateseq = orig_stateseq # return return localgroup @classmethod", "(dur,otherdurs) in self._local_group(t,k): score += obs.log_predictive(data,otherdata) + durs.log_predictive(dur,otherdurs) return score", "= canondict[s] reversedict = {} for k,v in canondict.iteritems(): reversedict[v]", "will need fixing self.stateseq[t] = k wholegroup, pieces = self._local_slices(self.stateseq,t)", "(0,1) temp = np.sum(self.stateseq[:-1] == k) if SAMPLING in self.stateseq[1:]", "= kappa self.model = model self.beta = beta self.obs =", "It = slice(t,t+1) return slice(A.start,B.stop), [(x,stateseq[x.start]) for x in (A,It,B)", "__metaclass__ = abc.ABCMeta @abc.abstractmethod def resample(self): pass @abc.abstractmethod def _counts_from(self,k):", "SAMPLING in stateseq_norep[1:] and \\ stateseq_norep[np.where(stateseq_norep == SAMPLING)[0]-1] == k:", "t > 0 score = 0. # unpack variables model", "= np.random.randint(ABIGNUMBER) while newlabel in ks: newlabel = np.random.randint(ABIGNUMBER) newweight", "temp = np.sum(self.stateseq[:-1] == k) if SAMPLING in self.stateseq[1:] and", "k: temp -= 1 return temp def _counts_fromto(self,k1,k2): assert k1", "import sample_discrete, sample_discrete_from_log, combinedata from pyhsmm.util.general import rle as rle", "t in np.random.permutation(self.T): # throw out old value self.stateseq[t] =", "__init__(self,model,beta,alpha_0,kappa,obs,data=None,T=None,stateseq=None): self.alpha_0 = alpha_0 self.kappa = kappa self.model = model", "list(model._occupied()) + [None] firststateidx = sample_discrete(np.arange(len(ks))) if firststateidx == len(ks)-1:", "definition choice that isn't specified in the HDP-HMM # Here,", "\\ self.stateseq[np.where(self.stateseq == SAMPLING)[0]-1] == k: temp -= 1 return", "_label_score(self,t,k): assert t > 0 score = 0. # unpack", "as rle # NOTE: assumes censoring. can make no censoring", "in pieces: # get all the other data otherdata, otherdurs", "if stateseq[t-1] != k: score += np.log(alpha * beta[k] +", "SAMPLING if len(self.stateseq) > 0: stateseq_norep, durations = rle(self.stateseq) return", "# set the state if idx == scores.shape[0]-1: self.stateseq[t] =", "k2 not in self.stateseq: return 0 else: from_indices, = np.where(self.stateseq[:-1]", "self.durations = rle(stateseq) self.data = data self.T = data.shape[0] def", "for k,ft in zip(ks,fromto_counts)] + [alpha*betarest]) nextstateidx = sample_discrete(scores) if", "np.sum(self.stateseq == SAMPLING) in (0,1) temp = np.sum(self.stateseq[:-1] == k)", "= self._new_label(ks) else: nextstate = ks[nextstateidx] # now get the", "- np.log(alpha * (1-beta[stateseq[t-1]]) + model._counts_from(stateseq[t-1])) # right transition (if", "get the counts of new states coming out of our", "return newlabel def _data_withlabel(self,k): assert k != SAMPLING return self.data[self.stateseq", "slice(0,0) elif t > seq.shape[0]-1: return slice(seq.shape[0],seq.shape[0]) else: endindices, =", "sample a new value scores = np.array([self._label_score(t,k) for k in", "np.log(self.beta.remaining*(betas/(1-betas)).sum()) else: score += np.log(self.beta.remaining) # add in obs/dur scores", "= self.dur.rvs() self.stateseq = np.concatenate((self.stateseq,np.ones(nextstate_dur,dtype=int)*nextstate)) t += nextstate_dur self.T =", "T: ks = list(model._occupied() | self._occupied()) betarest = 1-sum(betavec[k] for", "fill(seq,t): if t < 0: return slice(0,0) elif t >", "return np.sum(stateseq_norep[from_indices+1] == k2) def _counts_from(self,k): assert k != SAMPLING" ]