repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
Dark-Bob/mro | routine_test.py | <gh_stars>1-10
import pytest
import json
import mro
import mro.helpers
import connection as con
def print_table(command, connection):
cursor = connection.cursor()
cursor.execute(command)
cim = mro.helpers.create_column_name_index_map(cursor)
print(cim)
for row in cursor:
print(row)
@pytest.fixture
def connection_function(request):
connection = con.connect()
request.addfinalizer(mro.disconnect)
cursor = connection.cursor()
con.drop_tables()
cursor.execute("create table table1 (created_datetime timestamp not null default current_timestamp, created_time time not null default current_time, column1 varchar(20) default 'ABC DEF', column2 integer, column3 jsonb, column4 bool)")
cursor.execute("""
create procedure insert_row_table1(
_column1 varchar(20) = 'default',
_column2 integer = 0,
_column3 jsonb = '{}'::jsonb,
_column4 bool = true,
_created_datetime timestamp = current_timestamp,
_created_time time = current_time)
language sql
as $$
insert into table1 (created_datetime, created_time, column1, column2, column3, column4) values (_created_datetime, _created_time, _column1, _column2, _column3, _column4)
$$""")
connection.commit()
connection.close()
return lambda: con.connect()
class TestRoutines(object):
def test_in_parameters_with_defaults(self, connection_function):
mro.load_database(connection_function)
tables = mro.table1.select()
assert len(tables) == 0
mro.insert_row_table1()
mro.insert_row_table1('test', 2, json.dumps({'some': 'thing'}), _column4=False)
t = mro.table1.select()
assert len(t) == 2
assert t[0].column1 == 'default'
assert t[0].column2 == 0
assert t[0].column3 == '{}'
assert t[0].column4 is True
assert t[1].column1 == 'test'
assert t[1].column2 == 2
assert t[1].column3 == '{"some": "thing"}'
assert t[1].column4 is False
def test_returns_table(self, connection_function):
mro.connection.set_connection_function(connection_function)
connection = mro.connection.connection
cursor = connection.cursor()
cursor.execute("""
create or replace function select_table1() returns table(col1 varchar(20), col2 integer)
language sql
immutable
as $$
select column1, column2 from table1
$$;""")
connection.commit()
mro.load_database(connection_function)
mro.insert_row_table1()
mro.insert_row_table1('test', 2, json.dumps({'some': 'thing'}), _column4=False)
t = mro.select_table1()
assert len(t) == 2
assert t[0].col1 == 'default'
assert t[0].col2 == 0
assert t[1].col1 == 'test'
assert t[1].col2 == 2
def test_returns_scalar(self, connection_function):
mro.connection.set_connection_function(connection_function)
connection = mro.connection.connection
cursor = connection.cursor()
cursor.execute("""
create or replace function count_table1() returns integer
language sql
immutable
as $$
select count(column1) from table1
$$;""")
connection.commit()
mro.load_database(connection_function)
mro.insert_row_table1()
mro.insert_row_table1('test', 2, json.dumps({'some': 'thing'}), _column4=False)
t = mro.table1.select()
assert len(t) == mro.count_table1()
def test_out_parameters(self, connection_function):
mro.connection.set_connection_function(connection_function)
connection = mro.connection.connection
cursor = connection.cursor()
cursor.execute("""
create or replace procedure one_two_three(in one integer, in two integer, inout three integer)
language plpgsql
as
$$
begin
three:=one+two;
end
$$""")
connection.commit()
mro.load_database(connection_function)
result = mro.one_two_three(1, 2, None)
assert result[0].three == 3 |
Dark-Bob/mro | custom_type_test.py | import pytest
import mro
import connection as con
from datetime import datetime, date
@pytest.fixture
def connection_function(request):
connection = con.connect()
request.addfinalizer(mro.disconnect)
cursor = connection.cursor()
con.drop_tables()
cursor.execute("""DROP TYPE IF EXISTS custom_type""")
cursor.execute("""DROP TYPE IF EXISTS custom_type2""")
cursor.execute("""CREATE TYPE custom_type AS (custom_field_1 float,
custom_field_2 float,
custom_field_3 float,
custom_field_4 timestamp,
custom_field_5 oid)""")
cursor.execute("""CREATE TYPE custom_type2 AS (custom_field_1 bool,
custom_field_2 int)""")
cursor.execute("create table table1 (id serial primary key,"
"created_date date not null default current_date,"
"column1 integer default 1,"
"column2 varchar(20),"
"column3 custom_type,"
"column4 custom_type2)")
cursor.execute("insert into table1 (column1, column2, column3, column4) values (%s, %s, %s, %s)", (1, 'Hello World!', (1.2345, 2.3456, 3.4567, datetime.now(), 1000), (False, 10)))
cursor.execute("insert into table1 (column1, column2, column3, column4) values (%s, %s, %s, %s)", (2, 'Hello World2!', (12.345, 23.456, 34.567, datetime.now(), 9999), (True, 11)))
cursor.execute("insert into table1 (column1, column2, column3, column4) values (%s, %s, %s, %s)", (3, 'Hello World3!', (12.345, None, 34.567, datetime.now(), None), (True, 11)))
connection.commit()
connection.close()
return lambda: con.connect()
class TestTable(object):
def test_table_reflection(self, connection_function):
mro.load_database(connection_function)
tables = mro.table1.select()
assert len(tables) == 3
assert isinstance(tables[0].created_date, date)
assert tables[0].column1 == 1
assert tables[0].column2 == 'Hello World!'
assert tables[0].column3.custom_field_1 == 1.2345
assert tables[0].column3.custom_field_2 == 2.3456
assert tables[0].column3.custom_field_3 == 3.4567
assert tables[0].column3.custom_field_5 == 1000
assert isinstance(tables[0].column3, mro.custom_types.custom_type)
assert isinstance(tables[0].column4, mro.custom_types.custom_type2)
assert tables[1].column1 == 2
assert tables[1].column2 == 'Hello World2!'
assert tables[1].column3.custom_field_1 == 12.345
assert tables[1].column3.custom_field_2 == 23.456
assert tables[1].column3.custom_field_3 == 34.567
assert tables[1].column3.custom_field_5 == 9999
assert isinstance(tables[1].column3, mro.custom_types.custom_type)
assert tables[2].column1 == 3
assert tables[2].column2 == 'Hello World3!'
assert tables[2].column3.custom_field_1 == 12.345
assert tables[2].column3.custom_field_2 is None
assert tables[2].column3.custom_field_3 == 34.567
assert tables[2].column3.custom_field_5 is None
assert isinstance(tables[2].column3, mro.custom_types.custom_type)
def test_table_select_filter(self, connection_function):
mro.load_database(connection_function)
tables = mro.table1.select('column1 = %d' % 2)
assert len(tables) == 1
assert tables[0].column1 == 2
assert tables[0].column2 == 'Hello World2!'
assert tables[0].column3.custom_field_1 == 12.345
assert tables[0].column3.custom_field_2 == 23.456
assert tables[0].column3.custom_field_3 == 34.567
assert tables[0].column3.custom_field_5 == 9999
assert isinstance(tables[0].column3, mro.custom_types.custom_type)
assert isinstance(tables[0].column4, mro.custom_types.custom_type2)
def test_table_delete_filter(self, connection_function):
mro.load_database(connection_function)
table_count = mro.table1.select_count()
tables = mro.table1.select('column1 = %d' % 2)
assert len(tables) == 1
assert tables[0].column1 == 2
assert tables[0].column2 == 'Hello World2!'
assert tables[0].column3.custom_field_1 == 12.345
assert tables[0].column3.custom_field_2 == 23.456
assert tables[0].column3.custom_field_3 == 34.567
assert tables[0].column3.custom_field_5 == 9999
mro.table1.delete('column1 = %d' % 2)
assert table_count - 1 == mro.table1.select_count()
def test_create_object(self, connection_function):
mro.load_database(connection_function)
table_count = mro.table1.select_count()
dt = datetime.now()
table = mro.table1(column1=3, column2='Hi!', column3=mro.custom_types.custom_type(custom_field_1=1.2345,
custom_field_2=2.3456,
custom_field_3=3.4567,
custom_field_4=dt,
custom_field_5=77777))
assert table.column1 == 3
assert table.column2 == 'Hi!'
assert table.column3.custom_field_1 == 1.2345
assert table.column3.custom_field_2 == 2.3456
assert table.column3.custom_field_3 == 3.4567
assert table.column3.custom_field_4 == dt
assert table.column3.custom_field_5 == 77777
table = mro.table1(column2='Hi2!')
assert table.column1 == 1
assert table.column2 == 'Hi2!'
assert table.column3 is None
kwargs = {'column1': 5, 'column2': 'Hi3!', 'column3': {"custom_field_1": 1.2345,
"custom_field_2": 2.3456,
"custom_field_3": 3.4567,
"custom_field_4": dt,
"custom_field_5": 77777}}
table = mro.table1(**kwargs)
assert table.column1 == 5
assert table.column2 == 'Hi3!'
assert table.column3.custom_field_1 == 1.2345
assert table.column3.custom_field_2 == 2.3456
assert table.column3.custom_field_3 == 3.4567
assert table.column3.custom_field_4 == dt
assert table.column3.custom_field_5 == 77777
tables = mro.table1.select()
assert table_count + 3 == len(tables)
assert tables[5].column1 == 5
assert tables[5].column2 == 'Hi3!'
assert tables[5].column3.custom_field_1 == 1.2345
assert tables[5].column3.custom_field_2 == 2.3456
assert tables[5].column3.custom_field_3 == 3.4567
assert tables[5].column3.custom_field_4 == dt
assert tables[5].column3.custom_field_5 == 77777
def test_insert_check_default_values(self, connection_function):
mro.load_database(connection_function)
table = mro.table1(column1=3,
column2='Hi!',
column3=mro.custom_types.custom_type(custom_field_1=1.2345,
custom_field_2=2.3456,
custom_field_3=3.4567,
custom_field_4=datetime.now(),
custom_field_5=5000),
created_date=datetime.now().date())
tables = mro.table1.select()
tables.append(table)
for table in tables:
assert isinstance(table.id, int)
assert table.id is not None
assert isinstance(table.created_date, date)
assert table.created_date is not None
assert isinstance(table.column1, int)
assert table.column1 is not None
assert isinstance(table.column2, str)
assert table.column2 is not None
assert table.column3 is None or isinstance(table.column3, mro.custom_types.custom_type)
def test_insert_many(self, connection_function):
mro.load_database(connection_function)
mro.table1.delete()
dt = datetime.now()
table = mro.table1.insert_many(
['column1', 'column2', 'column3'],
[
[1, 'Hi!', mro.custom_types.custom_type(custom_field_1=10.2, custom_field_2=20.1, custom_field_3=30.4, custom_field_4=dt, custom_field_5=11)],
[2, 'Hi2!', mro.custom_types.custom_type(custom_field_1=30.3, custom_field_2=20.2, custom_field_3=10.1, custom_field_4=dt, custom_field_5=22)],
[3, 'Hi3!', mro.custom_types.custom_type(custom_field_1=40.1, custom_field_2=40.2, custom_field_3=40.3, custom_field_4=dt, custom_field_5=33)]
])
tables = mro.table1.select()
assert 3 == len(tables)
assert tables[0].column1 == 1
assert tables[0].column2 == 'Hi!'
assert tables[0].column3.custom_field_1 == 10.2
assert tables[0].column3.custom_field_2 == 20.1
assert tables[0].column3.custom_field_3 == 30.4
assert tables[0].column3.custom_field_4 == dt
assert tables[0].column3.custom_field_5 == 11
assert tables[1].column1 == 2
assert tables[1].column2 == 'Hi2!'
assert tables[1].column3.custom_field_1 == 30.3
assert tables[1].column3.custom_field_2 == 20.2
assert tables[1].column3.custom_field_3 == 10.1
assert tables[1].column3.custom_field_4 == dt
assert tables[1].column3.custom_field_5 == 22
assert tables[2].column1 == 3
assert tables[2].column2 == 'Hi3!'
assert tables[2].column3.custom_field_1 == 40.1
assert tables[2].column3.custom_field_2 == 40.2
assert tables[2].column3.custom_field_3 == 40.3
assert tables[2].column3.custom_field_4 == dt
assert tables[2].column3.custom_field_5 == 33
def test_update_value(self, connection_function):
mro.load_database(connection_function)
table = mro.table1.select_one("column1 = 1")
assert table.column3.custom_field_1 == 1.2345
# Test we can assign a dictionary to the field
table.column3 = {"custom_field_1": 10.2, "custom_field_2": 10.2, "custom_field_3": 10.2, "custom_field_4": datetime.now(), "custom_field_5": 1}
table = mro.table1.select_one("column1 = 1")
# Check we updated the existing field and it was propagated to the db
assert table.column3.custom_field_1 == 10.2
# Check nothing else changed unexpectedly
assert isinstance(table.created_date, date)
assert table.column1 == 1
assert table.column2 == 'Hello World!'
table.column1 = 10
with pytest.raises(NotImplementedError) as excinfo:
table.column3.custom_field_1 = 1.5
assert excinfo.value.args[0] == "You cannot set custom type internal attributes"
assert len(mro.table1.select()) == 3
if __name__ == '__main__':
#pytest.main([__file__])
pytest.main([__file__ + '::TestTable::test_insert_with_only_primary_key_no_kwargs']) |
Dark-Bob/mro | mro/connection.py | import atexit
connection = None
connection_function = None
reconnect_function = None
hooks = None
def set_connection_function(_connection_function):
global connection
global connection_function
connection_function = _connection_function
connection = connection_function()
def disconnect():
global connection
try:
connection.close()
except:
pass
def set_on_reconnect(_reconnect_function):
global reconnect_function
reconnect_function = _reconnect_function
def set_hooks(_hooks):
global hooks
hooks = _hooks
def reconnect():
global connection
global connection_function
global reconnect_function
connection = connection_function()
print("***********RECONNECTING DATABASE************")
reconnect_function(connection)
if hooks is not None:
for hook in hooks:
hook()
atexit.register(disconnect) |
Dark-Bob/mro | mro/data_types.py |
import psycopg2.extras
import datetime
import uuid as _uuid
# Create data type functions
def defaultColumnToDataType(column, code_start, code_end):
return code_start + code_end
def varcharColumnToDataType(column, code_start, code_end):
character_maximum_length = column[8]
return f'{code_start}{character_maximum_length}, {code_end}'
# Create transform functions
def default_transform(column_default, data_type):
if column_default.endswith('::' + data_type):
column_default = f'{column_default[1:-(len(data_type)+3)]}'
return column_default, False
def float_transform(column_default, data_type):
return float(column_default), False
def integer_transform(column_default, data_type):
if column_default.endswith('::regclass)'):
return None, True
return int(column_default), False
def boolean_transform(column_default, data_type):
def str2bool(value: str):
return {'true': True,
'false': False
}.get(value.lower(), None)
result = str2bool(column_default)
return result, False
def none_transform(column_default, data_type):
return None, True
type_map = {
'character varying': ['varchar', varcharColumnToDataType, default_transform],
'integer': ['integer', defaultColumnToDataType, integer_transform],
'timestamp without time zone': ['timestamp', defaultColumnToDataType, none_transform],
'time without time zone': ['time', defaultColumnToDataType, none_transform],
'date': ['date', defaultColumnToDataType, none_transform],
'boolean': ['boolean', defaultColumnToDataType, boolean_transform],
'bool': ['boolean', defaultColumnToDataType, boolean_transform],
'text': ['text', defaultColumnToDataType, default_transform],
'double precision': ['double', defaultColumnToDataType, float_transform],
'real': ['real', defaultColumnToDataType, float_transform],
'json': ['json', defaultColumnToDataType, default_transform],
'jsonb': ['json', defaultColumnToDataType, default_transform],
'uuid': ['uuid', defaultColumnToDataType, default_transform],
'bytea': ['bytea', defaultColumnToDataType, default_transform],
'oid': ['oid', defaultColumnToDataType, integer_transform],
}
def convert_numpy_to_python(value):
if hasattr(value, 'dtype'):
value = value.item()
return value
class database_type(object):
def __init__(self, name, python_type, column_index, not_null, is_updateable, get_value_on_insert, is_primary_key):
self.name = name
self.python_type = python_type
self.column_index = column_index
self.not_null = not_null
self.is_updateable = is_updateable
self.get_value_on_insert = get_value_on_insert
self.is_primary_key = is_primary_key
def __get__(self, instance, instance_type):
if instance is None:
return self
if self.name in instance.__dict__:
return instance.__dict__[self.name]
return None
def __set__(self, instance, value):
value = convert_numpy_to_python(value)
if not self.is_updateable:
raise PermissionError(f'The value of [{self.name}] is not updateable.')
if value is None:
if self.not_null:
raise ValueError(f'The value of [{self.name}] cannot be null.')
else:
# may need to move out into derived class or ceate another layer for basic types
if type(value) is not self.python_type:
raise TypeError(f'Value should be of type [{self.python_type.__name__}] not [{value.__class__.__name__}]')
self.validate_set(value)
instance.__dict__[self.name] = value
instance.update(**{self.name: value})
def validate_set(self, value):
pass
class varchar(database_type):
def __init__(self, name, column_index, length, **kwargs):
super().__init__(name, str, column_index, **kwargs)
self.length = length
def validate_set(self, value):
if len(value) > self.length:
raise ValueError(f'Value length [{len(value)}] should not exceed [{self.length}]')
class integer(database_type):
def __init__(self, name, column_index, **kwargs):
super().__init__(name, int, column_index, **kwargs)
class timestamp(database_type):
def __init__(self, name, column_index, **kwargs):
super().__init__(name, datetime.datetime, column_index, **kwargs)
class date(database_type):
def __init__(self, name, column_index, **kwargs):
super().__init__(name, datetime.date, column_index, **kwargs)
class time(database_type):
def __init__(self, name, column_index, **kwargs):
super().__init__(name, datetime.time, column_index, **kwargs)
class boolean(database_type):
def __init__(self, name, column_index, **kwargs):
super().__init__(name, bool, column_index, **kwargs)
class text(database_type):
def __init__(self, name, column_index, **kwargs):
super().__init__(name, str, column_index, **kwargs)
# stop automatic conversion of json into a dictionary type
psycopg2.extras.register_default_json(loads=lambda x: x)
psycopg2.extras.register_default_jsonb(loads=lambda x: x)
class json(database_type):
def __init__(self, name, column_index, **kwargs):
super().__init__(name, str, column_index, **kwargs)
class double(database_type):
def __init__(self, name, column_index, **kwargs):
super().__init__(name, float, column_index, **kwargs)
class real(database_type):
def __init__(self, name, column_index, **kwargs):
super().__init__(name, float, column_index, **kwargs)
class uuid(database_type):
def __init__(self, name, column_index, **kwargs):
super().__init__(name, _uuid.UUID, column_index, **kwargs)
class bytea(database_type):
def __init__(self, name, column_index, **kwargs):
super().__init__(name, bytes, column_index, **kwargs)
class oid(database_type):
def __init__(self, name, column_index, **kwargs):
super().__init__(name, int, column_index, **kwargs) |
Dark-Bob/mro | numpy_types_test.py | import pytest
import mro
import connection as con
import pandas as pd
@pytest.fixture
def connection_function(request):
connection = con.connect()
request.addfinalizer(mro.disconnect)
cursor = connection.cursor()
con.drop_tables()
cursor.execute("create table table1 (id serial primary key, column1 integer default 1, column2 varchar(20), column3 float, column4 boolean)")
connection.commit()
connection.close()
return lambda: con.connect()
def test_numpy_type_insertion_with_col_names(connection_function):
mro.load_database(connection_function)
df = pd.DataFrame(data={'column1': [1, 2, 3], 'column2': ['abc', 'bcd', 'cde'], 'column3': [0.0, 0.1, 0.2], 'column4': [True, False, True]})
for i in range(df.shape[0]):
d = {k: v for k, v in zip(df.columns, df.iloc[i].values)}
mro.table1.insert(**d)
def test_numpy_type_update(connection_function):
mro.load_database(connection_function)
df = pd.DataFrame(data={'column1': [1, 2, 3], 'column2': ['abc', 'bcd', 'cde'], 'column3': [0.0, 0.1, 0.2], 'column4': [True, False, True]})
for i in range(df.shape[0]):
d = {k: v for k, v in zip(df.columns, df.iloc[i].values)}
mro.table1.insert(**d)
t = mro.table1.select_one()
t.column1 = df.iloc[i].values[0]
t.column2 = df.iloc[i].values[1]
t.column3 = df.iloc[i].values[2]
t.column4 = df.iloc[i].values[3]
|
Dark-Bob/mro | operational_test.py | <filename>operational_test.py
import pytest
import mro
import mro.foreign_keys
import connection as con
@pytest.fixture()
def connection(request):
connection = con.connect()
request.addfinalizer(mro.disconnect)
cursor = connection.cursor()
con.drop_tables()
cursor.execute("""create table table1 (
id serial unique,
name varchar(20) not null,
value varchar(20),
primary key (id, name)
);""")
cursor.execute("""create table table2 (
id serial,
name varchar(20) not null,
table1_id integer,
primary key (id),
foreign key (table1_id) references table1(id)
);""")
cursor.execute("""create table table3 (
value varchar(20) not null
);""")
cursor.execute("""create table table4 (
my_bool bool default False,
my_boolean boolean default True
);""")
connection.commit()
create_test_data(connection)
connection.close()
mro.load_database(lambda: con.connect())
return connection
def create_test_data(connection):
cursor = connection.cursor()
num_table1 = 2
for i in range(1,num_table1+1):
cursor.execute("insert into table1 (name) values (%s)", ('table1_{}'.format(i),))
for j in range(1,4):
cursor.execute("insert into table2 (name, table1_id) values (%s,%s)", ('table2_{}_{}'.format(i, j), i))
# edge cases
cursor.execute("insert into table2 (name, table1_id) values (%s,%s)", ('table2_None', None))
cursor.execute("insert into table1 (name) values (%s)", ('table1_None',))
connection.commit()
def test_execute_sql(connection):
cursor = mro.execute_sql('select * from table1')
row_count = 0
for row in cursor:
row_count += 1
assert row_count == 3
def test_execute_sql_disconnected(connection):
mro.disconnect()
cursor = mro.execute_sql('select * from table1')
row_count = 0
for row in cursor:
row_count += 1
assert row_count == 3
if __name__ == '__main__':
pytest.main([__file__])
#pytest.main([__file__ + '::test_update_multiple_values']) |
Dark-Bob/mro | mro/version.py | <reponame>Dark-Bob/mro
__version__ = '1.0.0dev1' |
Dark-Bob/mro | foreign_key_test.py | <reponame>Dark-Bob/mro
import os
import json
import pytest
import mro
import mro.foreign_keys
import connection as con
@pytest.fixture(scope="module")
def connection(request):
connection = con.connect()
if request:
request.addfinalizer(mro.disconnect)
cursor = connection.cursor()
con.drop_tables()
cursor.execute("""create table table1 (
id serial,
name varchar(20) not null,
primary key (id)
);""")
cursor.execute("""create table table2 (
id serial,
name varchar(20) not null,
table1_id integer,
primary key (id),
foreign key (table1_id) references table1(id)
);""")
cursor.execute("""create table table3 (
id serial,
name varchar(20) not null,
table4s varchar(20),
primary key (id)
);""")
cursor.execute("""create table table4 (
id serial,
name varchar(20) not null,
table3_id integer,
primary key (id),
foreign key (table3_id) references table3(id)
);""")
connection.commit()
create_test_data(connection)
connection.close()
mro.load_database(lambda: con.connect())
return connection
def create_test_data(connection):
cursor = connection.cursor()
num_table1 = 2
for i in range(1,num_table1+1):
cursor.execute("insert into table1 (name) values (%s)", ('table1_{}'.format(i),))
for j in range(1,4):
cursor.execute("insert into table2 (name, table1_id) values (%s,%s)", ('table2_{}_{}'.format(i, j), i))
# edge cases
cursor.execute("insert into table2 (name, table1_id) values (%s,%s)", ('table2_None', None))
cursor.execute("insert into table1 (name) values (%s)", ('table1_None',))
connection.commit()
class TestForeignKeys(object):
def test_read_foreign_key(self, connection):
table = mro.table2.select_one('table1_id is not null')
assert isinstance(table.table1_id.value, int)
assert table.table1_id.value != None
assert isinstance(table.table1_id.object, mro.table1)
assert table.table1_id.object != None
# check the _i matches up for both tables
assert table.name.startswith(table.table1_id.object.name.replace("table1", "table2"))
def test_null_foreign_key(self, connection):
table = mro.table2.select_one('table1_id is null')
assert table.table1_id.value == None
assert table.table1_id.object == None
def test_read_foreign_keys_reverse(self, connection):
name = None
table2s = mro.table2.select()
table1_refs = [str(x.table1_id.value) for x in table2s if x.table1_id.value is not None]
table = mro.table1.select_one('id in (' + ','.join(table1_refs) + ')')
assert table.name != None
assert table.table2s != None
assert len(table.table2s) > 1
assert table.table2s[0].name == 'table2_1_1'
num_table2s = len(table.table2s)
mro.table2(name = 'table2_added', table1_id = table.id)
assert len(table.table2s) == num_table2s
table.table2s() # updates the reference list
assert len(table.table2s) == num_table2s + 1
num_table2s = len(table.table2s)
table2 = mro.table2(name = 'table2_added2', table1_id = None)
assert len(table.table2s) == num_table2s
with pytest.raises(PermissionError) as excinfo:
table.table2s[0] = table2
assert excinfo.value.args[0] == "Cannot set specific value on foreign key reference list."
table.table2s.append(table2)
assert len(table.table2s) == num_table2s + 1
# make sure the change is reflected in the database
table.table2s() # updates the reference list
assert len(table.table2s) == num_table2s + 1
def test_read_foreign_keys_reverse_no_data(self, connection):
table2s = mro.table2.select()
table1_refs = [str(x.table1_id.value) for x in table2s if x.table1_id.value is not None]
table = mro.table1.select_one('id not in (' + ','.join(table1_refs) + ')')
assert table.name != None
table2s = table.table2s
assert not table2s
def test_insert_class_that_has_foreign_references(self, connection):
mro.table1(name = 'Bob')
table = mro.table3(name = 'Bob2')
# test that it's a varchar not a foreign key reference
table.table4s = 'test string'
def test_write_foreign_keys(self, connection):
table1 = mro.table1.select_one()
table2sCount = len(table1.table2s)
table2 = mro.table2(name = 'table2_added2', table1_id = None)
table3 = mro.table2(name='table2_added3', table1_id=None)
table2.table1_id = table1
table3.table1_id = table1.id
assert table2.table1_id.value == table1.id
assert table2sCount == len(table1.table2s)
table1.table2s()
assert table2sCount + 2 == len(table1.table2s)
def test_foreign_keys_shortcuts(self, connection):
table1 = mro.table1.select_one()
table2sCount = len(table1.table2s)
table2 = mro.table2(name = 'table2_added2', table1_id = None)
table2.table1_id = table1
table3 = mro.table2(name='table2_added3', table1_id=table1.id)
assert table2.table1_id == table1.id
assert (table2.table1_id != table1.id) == False
assert table2.table1_id == table3.table1_id
assert table2sCount == len(table1.table2s)
table1.table2s()
assert table2sCount + 2 == len(table1.table2s)
def test_foreign_keys_to_json(self, connection):
table1 = mro.table1.select_one()
table2 = mro.table2(name='table2_added2', table1_id=table1.id)
table3 = mro.table2(name='table2_added3', table1_id=None)
serialised = json.dumps({"foreign_key": table2.table1_id, "foreign_key2": table3.table1_id})
assert serialised == '{"foreign_key": 1, "foreign_key2": null}' or serialised == '{"foreign_key2": null, "foreign_key": 1}'
if __name__ == '__main__':
#pytest.main([__file__])
#pytest.main([__file__ + '::TestForeignKeys::test_foreign_keys_shortcuts'])
t = TestForeignKeys()
t.test_foreign_keys_to_json(connection(None)) |
Dark-Bob/mro | mro/routine.py | import mro.connection
import mro.helpers
import collections
class RoutineParameter:
def __init__(self, name, data_type, mode):
self.name = name
self.data_type = data_type
self.mode = mode
def __repr__(self):
return f"RoutineParameter({self.name}, {self.data_type}, {self.mode})"
class Routine:
def __init__(self, name, in_parameters, out_parameters, return_type, routine_type):
self.name = name
self.in_parameters = in_parameters
self.out_parameters = out_parameters
self.return_type = return_type
self.execute = 'call' if routine_type == 'PROCEDURE' else 'select * from'
self.base_command = f"{self.execute} {self.name}({{}})"
if return_type == 'void':
self.return_function = self._return_void
elif return_type == 'record':
self.return_function = self._return_record
self.out_type = collections.namedtuple(f"{name}_out", ' '.join([p.name for p in self.out_parameters]))
else:
self.return_function = self._return_scalar
def __call__(self, *args, **kwargs):
parameter_format = ', '.join(['%s' for x in args])
if len(kwargs) > 0:
parameter_format += ', ' + ', '.join([f"{k} := %s" for k in kwargs.keys()])
parameters = args + tuple(kwargs.values())
command = self.base_command.format(parameter_format)
connection = mro.connection.connection
cursor = connection.cursor()
cursor.execute(command, parameters)
connection.commit()
return self.return_function(cursor)
def _return_void(self, cursor):
return None
def _return_scalar(self, cursor):
return next(cursor)[0]
def _return_record(self, cursor):
objs = []
for row in cursor:
objs.append(self.out_type(*row))
return objs
def _create_routines(connection):
cursor = connection.cursor()
cursor.execute("select * from information_schema.routines where routine_type in ('PROCEDURE', 'FUNCTION') and routine_schema = 'public'")
connection.commit()
column_name_index_map = mro.helpers.create_column_name_index_map(cursor)
for routine in cursor:
routine_name = routine[column_name_index_map['routine_name']]
routine_type = routine[column_name_index_map['routine_type']]
specific_name = routine[column_name_index_map['specific_name']]
cursor2 = connection.cursor()
cursor2.execute(f"select * from information_schema.parameters where specific_name='{specific_name}' and parameter_mode <> 'OUT' order by ordinal_position;")
connection.commit()
in_parameters = []
cim = mro.helpers.create_column_name_index_map(cursor2)
for parameter in cursor2:
in_parameters.append(RoutineParameter(parameter[cim['parameter_name']], parameter[cim['data_type']], parameter[cim['parameter_mode']]))
# Using postgres specific tables because this information is not available in the information schema
command = """
with r as (
select proallargtypes, proargnames, proargmodes, prorettype from pg_proc where proname='{}'
), proallargtypes_expanded as (
select a.index, a.t as oid from r, unnest(proallargtypes) with ordinality as a(t, index)
), proargnames_expanded as (
select a.index, a.n as name from r, unnest(proargnames) with ordinality as a(n, index)
), proargmodes_expanded as (
select a.index, a.m as mode from r, unnest(proargmodes) with ordinality as a(m, index)
), p as (
select proallargtypes_expanded.index, oid, name, mode from proallargtypes_expanded join proargnames_expanded on proallargtypes_expanded.index = proargnames_expanded.index join proargmodes_expanded on proallargtypes_expanded.index = proargmodes_expanded.index
), params as (
select p.index, p.oid, p.name, typname as data_type, p.mode from p join pg_type t on p.oid = t.oid
), outputs as (
select index, oid, name, data_type, 'OUT' as mode from params where mode in ('o', 'b', 't')
)
select * from outputs order by index""".format(routine[column_name_index_map['routine_name']])
cursor2 = connection.cursor()
cursor2.execute(command)
connection.commit()
out_parameters = []
cim = mro.helpers.create_column_name_index_map(cursor2)
for parameter in cursor2:
out_parameters.append(RoutineParameter(parameter[cim['name']], parameter[cim['data_type']], parameter[cim['mode']]))
command = """
with r as (
select prorettype from pg_proc where proname='{}'
)
select typname from pg_type t join r on t.oid = r.prorettype""".format(routine[column_name_index_map['routine_name']])
cursor2 = connection.cursor()
cursor2.execute(command)
connection.commit()
return_type = next(cursor2)[0]
routine = Routine(routine_name, in_parameters, out_parameters, return_type, routine_type)
setattr(mro, routine_name, routine) |
Dark-Bob/mro | sql_injection_test.py | # reminder to add tests for this and fix |
karush17/esac | parser.py | <gh_stars>10-100
import os, sys
import argparse
def build_parser():
parser = argparse.ArgumentParser(description='PyTorch Soft Actor-Critic Args')
parser.add_argument('--env', default="HalfCheetah-v2",
help='Mujoco Gym environment (default: HalfCheetah-v2)')
parser.add_argument('--policy', default="Gaussian",
help='Policy Type: Gaussian | Deterministic (default: Gaussian)')
parser.add_argument('--eval', type=bool, default=True,
help='Evaluates a policy a policy every 10 episode (default: True)')
parser.add_argument('--gamma', type=float, default=0.99, metavar='G',
help='discount factor for reward (default: 0.99)')
parser.add_argument('--tau', type=float, default=0.005, metavar='G',
help='target smoothing coefficient(τ) (default: 0.005)')
parser.add_argument('--lr', type=float, default=0.0003, metavar='G',
help='learning rate of SAC (default: 0.0003)')
parser.add_argument('--lr_es', type=float, default=0.005, metavar='G',
help='learning rate of ES (default: 0.005)')
parser.add_argument('--alpha', type=float, default=0.2, metavar='G',
help='Temperature parameter α determines the relative importance of the entropy\
term against the reward (default: 0.2)')
parser.add_argument('--automatic_entropy_tuning', type=bool, default=False, metavar='G',
help='Automaically adjust α (default: False)')
parser.add_argument('--seed', type=int, default=123456, metavar='N',
help='random seed (default: 123456)')
parser.add_argument('--batch_size', type=int, default=256, metavar='N',
help='batch size (default: 256)')
parser.add_argument('--num_steps', type=float, default=1000001, metavar='N',
help='maximum number of steps (default: 1000000)')
parser.add_argument('--hidden_size', type=int, default=256, metavar='N',
help='hidden size (default: 256)')
parser.add_argument('--elite_rate', type=float, default=0.4, metavar='N',
help='Fraction of elites (default: 0.4)')
parser.add_argument('--mutation', type=float, default=0.005, metavar='N',
help='Standard deviation of perturbations (default: 0.005)')
parser.add_argument('--pop', type=int, default=10, metavar='N',
help='ES Population size (default: 10)')
parser.add_argument('--grad_models', type=int, default=4, metavar='N',
help='Number of gradient model injections in population (default: 4)')
parser.add_argument('--updates_per_step', type=int, default=1, metavar='N',
help='model updates per simulator step (default: 1)')
parser.add_argument('--start_steps', type=int, default=10000, metavar='N',
help='Steps sampling random actions (default: 10000)')
parser.add_argument('--target_update_interval', type=int, default=1, metavar='N',
help='Value target update per no. of updates per step (default: 1)')
parser.add_argument('--replay_size', type=int, default=1000000, metavar='N',
help='size of replay buffer (default: 10000000)')
parser.add_argument('--workers', type=int, default=4, metavar='N',
help='number of workers (default: 4)')
parser.add_argument('--clip', type=float, default=1e-4, metavar='N',
help='clip parameter for AMT update (default: 1e-4)')
parser.add_argument('--log_interval', type=int, default=20000, metavar='N',
help='save model and results every xth step (default: 20000)')
parser.add_argument('--sac_episodes', type=int, default=5, metavar='N',
help='number of episodes played by the sac agent (default: 5)')
return parser
|
karush17/esac | ES.py | import os
import numpy as np
import sys, copy
import time
import datetime
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.multiprocessing as mp
from torch import optim
from model import NeuralNetwork
import pickle as pkl
import scipy.stats as ss
import gym
import random
from utils import dm_wrap
checkpoint_name = './Checkpoint/'
use_cuda = torch.cuda.is_available()
device = torch.device('cuda' if use_cuda else 'cpu')
def crossover(args, STATE_DIM, ACTION_DIM, gene1, gene2):
actor_1 = NeuralNetwork(STATE_DIM, ACTION_DIM.shape[0], args.hidden_size)
actor_1.load_state_dict(gene1)
actor_2 = NeuralNetwork(STATE_DIM, ACTION_DIM.shape[0], args.hidden_size)
actor_2.load_state_dict(gene2)
for param1, param2 in zip(actor_1.parameters(), actor_2.parameters()):
# References to the variable tensors
W1 = param1.data
W2 = param2.data
if len(W1.shape) == 2: #Weights no bias
num_variables = W1.shape[0]
# Crossover opertation [Indexed by row]
num_cross_overs = random.randrange(num_variables*2) # Lower bounded on full swaps
for i in range(num_cross_overs):
receiver_choice = random.random() # Choose which gene to receive the perturbation
if receiver_choice < 0.5:
ind_cr = random.randrange(W1.shape[0]) #
W1[ind_cr, :] = W2[ind_cr, :]
else:
ind_cr = random.randrange(W1.shape[0]) #
W2[ind_cr, :] = W1[ind_cr, :]
elif len(W1.shape) == 1: #Bias
num_variables = W1.shape[0]
# Crossover opertation [Indexed by row]
num_cross_overs = random.randrange(num_variables) # Lower bounded on full swaps
for i in range(num_cross_overs):
receiver_choice = random.random() # Choose which gene to receive the perturbation
if receiver_choice < 0.5:
ind_cr = random.randrange(W1.shape[0]) #
W1[ind_cr] = W2[ind_cr]
else:
ind_cr = random.randrange(W1.shape[0]) #
W2[ind_cr] = W1[ind_cr]
def sample_noise(neural_net):
# Sample noise for each parameter of the neural net
nn_noise = []
for n in neural_net.parameters():
noise = np.random.normal(size=n.cpu().data.numpy().shape)
nn_noise.append(noise)
return np.array(nn_noise)
def evaluate_neuralnet(nn, env, wrap):
# Evaluate an agent running it in the environment and computing the total reward
obs = dm_wrap(env.reset(), wrap=wrap)
game_reward = 0
reward = 0
done = False
while True:
# Output of the neural net
obs = torch.FloatTensor(obs)
action = nn(obs)
action = np.clip(action.data.cpu().numpy().squeeze(), -1, 1)
# action = action.data.numpy().argmax()
# action = np.asarray([action])
new_obs, reward, done, _ = env.step(action)
obs = dm_wrap(new_obs, wrap=wrap)
game_reward += reward
if done:
break
return game_reward
def evaluate_noisy_net(STD_NOISE, noise, neural_net, env, elite_queue, wrap):
# Evaluate a noisy agent by adding the noise to the plain agent
old_dict = neural_net.state_dict()
# add the noise to each parameter of the NN
for n, p in zip(noise, neural_net.parameters()):
p.data += torch.FloatTensor(n * STD_NOISE)
elite_queue.put(neural_net.state_dict())
# evaluate the agent with the noise
reward = evaluate_neuralnet(neural_net, env, wrap)
# load the previous paramater (the ones without the noise)
neural_net.load_state_dict(old_dict)
return reward
def worker(args, STD_NOISE, STATE_DIM, ACTION_DIM, params_queue, output_queue, elite_queue):
# Function execute by each worker: get the agent' NN, sample noise and evaluate the agent adding the noise. Then return the seed and the rewards to the central unit
if 'dm2gym' in args.env:
env = gym.make(args.env, environment_kwargs={'flat_observation': True})
wrap = True
else:
env = gym.make(args.env)
wrap = False
# env = CyclicMDP()
actor = NeuralNetwork(STATE_DIM, ACTION_DIM.shape[0], args.hidden_size)
while True:
# get the new actor's params
act_params = params_queue.get()
if act_params != None:
# load the actor params
actor.load_state_dict(act_params)
# get a random seed
seed = np.random.randint(1e6)
# set the new seed
np.random.seed(seed)
noise = sample_noise(actor)
pos_rew = evaluate_noisy_net(STD_NOISE, noise, actor, env, elite_queue, wrap)
# Mirrored sampling
neg_rew = evaluate_noisy_net(STD_NOISE, -noise, actor, env, elite_queue, wrap)
output_queue.put([[pos_rew, neg_rew], seed])
else:
break
def normalized_rank(rewards):
'''
Rank the rewards and normalize them.
'''
ranked = ss.rankdata(rewards)
norm = (ranked - 1) / (len(ranked) - 1)
norm -= 0.5
return norm
def save_results(env, seed, time_list, max_rewards, min_rewards, avg_rewards, total_start_time, updates, noise_mut):
data_save = {}
data_save['time'] = time_list
data_save['max_rewards'] = max_rewards
data_save['min_reward'] = min_rewards
data_save['avg_reward'] = avg_rewards
data_save['total_time'] = total_start_time - time.time()
data_save['SAC_updates'] = updates
data_save['noise'] = noise_mut
with open(checkpoint_name+'data_'+str(env)+'_'+str(seed)+'.pkl', 'wb') as f:
pkl.dump(data_save, f)
def eval(env, agent):
avg_reward = 0.
episodes = 10
for _ in range(episodes):
state = env.reset()
episode_reward = 0
done = False
while not done:
action = agent.select_action(state) #.select_action #torch.Tensor(state)
# action = action.detach().cpu().numpy()
next_state, reward, done, _ = env.step(action)
episode_reward += reward
state = next_state
avg_reward += episode_reward
avg_reward /= episodes
print("----------------------------------------")
print("Test Episodes: {}, Avg. Reward: {}".format(episodes, round(avg_reward, 2)))
print("----------------------------------------")
|
karush17/esac | main.py | import os
os.environ['OMP_NUM_THREADS'] = '1'
import argparse, sys
import datetime, copy
import gym
import numpy as np
import random
import itertools, time, math
import torch
import pickle as pkl
from sac import SAC
from utils import dm_wrap
from model import NeuralNetwork
from parser import build_parser
from ES import crossover, sample_noise, evaluate_neuralnet, evaluate_noisy_net, worker, normalized_rank, save_results, eval
from replay_memory import ReplayMemory
from torch import optim
import torch.multiprocessing as mp
mp.set_start_method('spawn',force=True)
torch.autograd.set_detect_anomaly(True)
os.sched_setaffinity(os.getpid(), {0})
os.system("taskset -p 0xffffffffffffffffffffffff %d" % os.getpid())
if __name__ == "__main__":
use_cuda = torch.cuda.is_available()
device = torch.device('cuda' if use_cuda else 'cpu')
checkpoint_name = './Checkpoint/'
if not os.path.exists(checkpoint_name):
os.makedirs(checkpoint_name)
######################################### INITIALIZE SETUP #############################################
# Parse Arguments
parser = build_parser()
args = parser.parse_args()
if 'dm2gym' in args.env:
env = gym.make(args.env, environment_kwargs={'flat_observation': True})
STATE_DIM = env.observation_space["observations"].shape[0]
wrap = True
else:
env = gym.make(args.env)
STATE_DIM = env.observation_space.shape[0]
wrap = False
# Environment
torch.manual_seed(args.seed)
np.random.seed(args.seed)
env.seed(args.seed)
ACTION_DIM = env.action_space
NUM_WINNERS = int(args.elite_rate*args.pop)
BATCH_SIZE = args.pop
STD_NOISE = args.mutation
NUM_GRAD_MODELS = args.grad_models
l1_loss = torch.nn.SmoothL1Loss()
total_start_time = time.time()
# Handle exceptions
if NUM_GRAD_MODELS > BATCH_SIZE:
print("Grad Models cannot be greater than Population size")
quit()
elif args.elite_rate > 1:
print('Elite rate cannot be greater than 1')
quit()
# Initialize the ES mother paramters and optimizer
actor = NeuralNetwork(STATE_DIM, ACTION_DIM.shape[0], args.hidden_size)
optimizer = optim.Adam(actor.parameters(), lr=args.lr_es)
torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.999, last_epoch=-1)
epsilon_start = 1.0
epsilon_final = 0.1
epsilon_decay = 1200000
epsilon_by_frame = lambda frame_idx: epsilon_final + (epsilon_start - epsilon_final) * math.exp(-1. * frame_idx / epsilon_decay)
# Worker Process Queues
output_queue = mp.Queue(maxsize=args.pop)
params_queue = mp.Queue(maxsize=args.pop)
elite_queue = mp.Queue(maxsize=int(2*args.pop))
# Agent
agent = SAC(STATE_DIM, ACTION_DIM, args)
sac_episodes = args.sac_episodes
# Memory
memory = ReplayMemory(args.replay_size)
processes = []
elite_list = []
# Training Loop
total_numsteps = 0
updates = 0
time_list = []
max_rewards = []
min_rewards = []
avg_rewards = []
noise_mut = []
total_time = 0
critic_loss = 0
# Create and start the processes
for _ in range(args.workers):
p = mp.Process(target=worker, args=(args, STD_NOISE, STATE_DIM, ACTION_DIM, params_queue, output_queue, elite_queue))
p.start()
processes.append(p)
# Initialize Elite list
for _ in range(0,NUM_WINNERS):
elite_list.append(actor.state_dict())
######################################### TRAINING LOOP #############################################
# Execute the main loop
for n_iter in range(1,int(args.num_steps)):
it_time = time.time()
total_numsteps += env._max_episode_steps
if total_numsteps > args.num_steps:
break
batch_noise = []
batch_reward = []
batch_loss = []
batch_ratio = []
# Crossover between Winners and Population Actors
for h in range(0,int(NUM_WINNERS)):
dict_copy = copy.deepcopy(actor.state_dict())
crossover(args, STATE_DIM, ACTION_DIM, elite_list[h], dict_copy)
params_queue.put(dict_copy)
# Standard Population actors
for h in range(NUM_WINNERS,BATCH_SIZE-NUM_GRAD_MODELS):
params_queue.put(actor.state_dict())
# Crossover between Grad models and Population Actors
for _ in range(int(NUM_GRAD_MODELS)):
# dict_copy = copy.deepcopy(actor.state_dict())
agent_copy = copy.deepcopy(agent.policy.state_dict())
# crossover(args, STATE_DIM, ACTION_DIM, agent_copy, dict_copy)
params_queue.put(agent_copy)
######################################### SAC UPDATE #############################################
if total_numsteps % int(5*env._max_episode_steps) == 0 and random.random() < epsilon_by_frame(total_numsteps):
# total_numsteps += int(sac_episodes*env._max_episode_steps)
for i_episode in range(sac_episodes):
episode_reward = 0
episode_steps = 0
done = False
state = dm_wrap(env.reset(),wrap=wrap)
while not done:
if args.start_steps > total_numsteps:
action = env.action_space.sample()
else:
action = agent.select_action(state) # Sample action from policy
if len(memory) > args.batch_size:
# Number of updates per step in environment
for i in range(args.updates_per_step):
# Update parameters of all the networks
critic_loss, qf_2_loss, policy_loss, ent_loss, alpha = agent.update_parameters(memory, args.batch_size, updates)
updates += 1
next_state, reward, done, _ = env.step(action) # Step
episode_reward += reward
episode_steps += 1
next_state = dm_wrap(next_state, wrap=wrap)
# Ignore the "done" signal if it comes from hitting the time horizon.
# (https://github.com/openai/spinningup/blob/master/spinup/algos/sac/sac.py)
mask = 1 if episode_steps == env._max_episode_steps else float(not done)
memory.push(state, action, reward, next_state, mask) # Append transition to memory
state = next_state
######################################### COLLECT DATA FROM QUEUE #############################################
# receive from each worker the results (the seed and the rewards)
for i in range(BATCH_SIZE):
p_rews, p_seed = output_queue.get()
np.random.seed(p_seed)
noise = sample_noise(actor)
batch_noise.append(noise)
batch_noise.append(-noise)
batch_reward.append(p_rews[0]) # reward of the positive noise
batch_reward.append(p_rews[1]) # reward of the negative noise
elite_array = [] # only a placeholder for getting parameters from queue
elite_list = [] # stores weights of winners
for _ in range(int(2*BATCH_SIZE)):
elite_array.append(elite_queue.get())
elite_list = [x for _,x in sorted(zip(batch_reward,elite_array),reverse=True)]
######################################### ES UPDATE #############################################
max_rewards.append(max(batch_reward))
min_rewards.append(min(batch_reward))
avg_rewards.append(np.mean(batch_reward))
time_list.append(time.time() - it_time)
print("Episode: {}, total numsteps: {}, reward: {}, time taken: {}".format(int(total_numsteps/env._max_episode_steps), total_numsteps, round(max_rewards[-1], 2), round(time_list[-1], 2)))
# Rank the reward and normalize it
batch_reward = torch.FloatTensor(normalized_rank(batch_reward))
th_update = []
optimizer.zero_grad()
# for each actor's parameter, and for each noise in the batch, update it by the reward * the noise value
for idx, p in enumerate(actor.parameters()):
upd_weights = torch.zeros(p.data.shape)
for n,r in zip(batch_noise, batch_reward):
upd_weights += r * torch.Tensor(n[idx])
upd_weights = upd_weights / (BATCH_SIZE*STD_NOISE)
# put the updated weight on the gradient variable so that afterwards the optimizer will use it
p.grad = torch.FloatTensor(-upd_weights).clone()
# Optimize the actor's NN
optimizer.step()
if total_numsteps % args.log_interval == 0:
save_results(args.env, args.seed, time_list, max_rewards, min_rewards, avg_rewards, total_start_time, updates, noise_mut)
torch.save({'model_state_dict': agent.policy.state_dict(), 'optimizer_state_dict': optimizer.state_dict()},
checkpoint_name+'/actor_'+str(args.env)+'_'+str(args.seed)+'.pth.tar')
if args.eval == True:
eval(env, agent)
# Anneal mutation in population
std_loss = l1_loss(max(batch_reward).unsqueeze(0),torch.mean(batch_reward).unsqueeze(0)).unsqueeze(0)
STD_NOISE = STD_NOISE + torch.clamp((args.lr_es / (BATCH_SIZE*STD_NOISE))*std_loss,0,args.clip)
STD_NOISE = STD_NOISE[0]
print(STD_NOISE)
noise_mut.append(STD_NOISE)
######################################### TERMINATE #############################################
# quit the processes
for _ in range(args.workers):
params_queue.put(None)
for p in processes:
p.join()
#-------------------------------------------------------------------------------------------------------------------------------------------------------#
|
jeffs/py-kart | yesterday/main.py | <reponame>jeffs/py-kart
#!/usr/bin/env python3
#
# Prints yesterday's date, formatted for use as a filesystem relative path.
from datetime import date, timedelta
yesterday = date.today() - timedelta(days=1)
print(yesterday.strftime('%Y/%m/%d'))
|
jeffs/py-kart | pangram/main.py | <reponame>jeffs/py-kart
#!/usr/bin/env python3
from dataclasses import dataclass
import argparse
import sys
from typing import Callable, Set
DEFAULT_MIN_LENGTH = 4
DEFAULT_WORDS_FILE = "/usr/share/dict/words"
@dataclass
class Command:
mandatory_letters: Set[str]
available_letters: Set[str]
min_length: int
words_file: str
def parse_args() -> Command:
parser = argparse.ArgumentParser(description="Find Spelling Bee answers.")
parser.add_argument(
"-m",
"--min-length",
default=DEFAULT_MIN_LENGTH,
help="omit words shorter than N characters",
metavar="N",
type=int,
)
parser.add_argument(
"letters",
help="available letters, capitalized if manadatory",
type=str,
)
parser.add_argument(
"words_file",
default=DEFAULT_WORDS_FILE,
help="available words, one per line",
metavar="words-file",
nargs="?",
type=str,
)
args = parser.parse_args()
return Command(
mandatory_letters=set(c.lower() for c in args.letters if c.isupper()),
available_letters=set(args.letters.lower()),
min_length=args.min_length,
words_file=args.words_file,
)
def make_validator(command: Command) -> Callable[[str], bool]:
def is_valid_char(c: str) -> bool:
return c in command.available_letters or not c.isalpha()
def is_valid_word(word: str) -> bool:
return (
len(word) >= command.min_length
and all(c in word for c in command.mandatory_letters)
and all(map(is_valid_char, word))
)
return is_valid_word
def main() -> None:
command = parse_args()
with open(command.words_file) as lines:
words = tuple(line.strip() for line in lines)
is_valid_word = make_validator(command)
valid_words = sorted(filter(is_valid_word, words), key=len)
for word in valid_words:
is_pangram = all(c in word for c in command.available_letters)
prefix = " *" if is_pangram else " "
print(prefix, word)
if __name__ == "__main__":
main()
|
jeffs/py-kart | words/main.py | <reponame>jeffs/py-kart
#!/usr/bin/env python3
#
# Prints the number of alphanumeric words in stdin or specified files.
# Markdown links are heuristically recognized and removed automatically.
import re
import sys
from typing import Iterable
# We care only about links that include whitespace, thus affecting word count.
# Such links are generally either inline: [text]( http://... )
# Or on separate lines, like footnotes: [tag]: http://...
LINK_RE = re.compile('(?:]\([^)]*)|(?:^\[.*]:.*)')
def is_word(s: str) -> bool:
"""Return true if s contains any alphanumeric characters."""
return any(c.isalnum() for c in s)
def count_words(line: str) -> int:
"""Return the number of words in the specified line. """
return sum(1 for s in line.split() if is_word(s))
def count_markdown_words(lines: Iterable[str]) -> int:
"""
Return the total number of words on all of the specified lines, excluding
(most) Markdown links.
"""
# Python's re.sub method, unlike equivalent functions in other mainstream
# languages, and unlike Python's own str.replace, expects the replacement
# text before the subject text. 🤦 The type system can't catch incorrect
# ordering, even at runtime, because both parameters are strings.
return sum(count_words(LINK_RE.sub('', line)) for line in lines)
def main():
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
with open(arg) as lines:
total = count_markdown_words(lines)
print('{:8} {}'.format(total, arg))
else:
print(count_markdown_words(sys.stdin))
if __name__ == '__main__':
main()
|
jeffs/py-kart | vimod/main.py | <filename>vimod/main.py
#!/usr/bin/env python3
"""This script opens (in Vim) any modified files in the current Git working copy."""
import subprocess as _subprocess, sys as _sys
def main():
status = _subprocess.run(
("git", "status"), capture_output=True, check=True, encoding="utf-8"
).stdout
files = tuple(
line.split(maxsplit=1)[1]
for line in status.splitlines()
if line.startswith("\tmodified:")
)
if files:
_sys.exit(_subprocess.run(("vim", *files)).returncode)
print("no modified files", file=_sys.stderr)
if __name__ == "__main__":
main()
|
jeffs/py-kart | len/test/wide.py | <reponame>jeffs/py-kart<filename>len/test/wide.py
len('piñata') # 6
len('piñata') # 7
len('🚀') # 1 (code point), though JS returns 2 (code units)
''.join(map(chr, (0x63, 0x328))) # 'c̨'; length 2 in both Python and JS
|
jeffs/py-kart | len/main.py | <reponame>jeffs/py-kart<filename>len/main.py
#!/usr/bin/env python3
#
# Prints line lengths from stdin or specified files.
from argparse import ArgumentParser
from itertools import islice
from os import walk
from os.path import isdir, join
from sys import stderr, stdin
def chomp_dir(dir):
for d, _, fs in walk(dir):
yield from chomp_files(join(d, f) for f in fs)
# TODO: Inject warning log, or return monads.
def chomp_file(file):
with open(file) as istream:
try:
for line in chomp_lines(istream):
yield line
except UnicodeDecodeError:
print('warning:', file + ':', 'binary file', file=stderr)
def chomp_files(files):
for file in files:
yield from chomp_dir(file) if isdir(file) else chomp_file(file)
def chomp_lines(istream):
"""
Returns a lazy generator of lines without trailing newline characters from
the specified input stream.
"""
return (line.rstrip('\n\r') for line in istream)
def main():
args = parse_args()
lines = chomp_files(args.files) if args.files else chomp_lines(stdin)
# Never do a full sort if we only want one line.
if args.__dict__['1']:
if args.r:
lines = (max(lines, default=None, key=len),)
elif args.s:
lines = (min(lines, default=None, key=len),)
else:
lines = islice(lines, 1)
elif args.r:
lines = sorted(lines, key=len, reverse=True)
elif args.s:
lines = sorted(lines, key=len)
print_lines(lines)
def parse_args():
parser = ArgumentParser(
description='Print line lengths.',
usage='%(prog)s [-h] [-1rs] [FILE...]')
parser.add_argument(
'-1',
action='store_true',
help='print only the first line of output')
parser.add_argument(
'-r',
action='store_true',
help='sort lines by decreasing length')
parser.add_argument(
'-s',
action='store_true',
help='sort lines by increasing length')
parser.add_argument(
'files',
help='file(s) to parse instead of stdin',
metavar='FILE',
nargs='*')
return parser.parse_args()
def print_lines(lines):
for line in lines:
print(len(line), line, sep=':')
if __name__ == '__main__':
main()
|
jeffs/py-kart | url/main.py | <reponame>jeffs/py-kart<filename>url/main.py<gh_stars>0
#!/usr/bin/env python3
#
# This script %-encodes or %-decodes a given URL. Inspired by:
# https://unix.stackexchange.com/a/159254/49952
from sys import argv, exit, stderr
from urllib.parse import quote_plus, unquote_plus
if len(argv) != 3 or argv[1] not in ['encode', 'decode']:
print('usage: url {encode|decode} <url>', file=stderr)
exit(2)
command, url = argv[1:]
op = quote_plus if command == 'encode' else unquote_plus
print(op(url))
|
jeffs/py-kart | smarten/main.py | #!/usr/bin/env python3
#
# Replaces ordinary quotation marks with smart quotes.
#
# ## Quality
# TODO: Add formal test suite
# TODO: Rewrite in Rust
#
# ### Bugs
# TODO: Correctly support quote followed by punctuation (')' or '—')
#
# ## Features
# TODO: Support -i flag to process files in-place.
import re
import sys
# The look-behind for single close quotes lets us use them as apostrophes.
SINGLE_CLOSE = re.compile(r"(?<=\S)'|'(?=\s|$)")
SINGLE_OPEN = re.compile(r"'(?=\S)")
DOUBLE_CLOSE = re.compile(r'"(?=\s|$)')
DOUBLE_OPEN = re.compile(r'"(?=\S)')
def smarten(line):
line = SINGLE_OPEN.sub('‘', SINGLE_CLOSE.sub('’', line))
line = DOUBLE_OPEN.sub('“', DOUBLE_CLOSE.sub('”', line))
return line
def print_smart(lines):
for line in lines:
print(smarten(line), end='')
def main():
if len(sys.argv) > 1:
for arg in sys.argv[1:]:
with open(arg) as lines:
print_smart(lines)
else:
print_smart(sys.stdin)
if __name__ == '__main__':
main()
|
SHREEOM0611/S4DS-Bot | src/cogs/kaggleAPI.py | <filename>src/cogs/kaggleAPI.py
import discord
from discord import colour
from discord.ext import commands
from kaggle.api.kaggle_api_extended import KaggleApi
api = KaggleApi()
api.authenticate()
class KaggleAPI(commands.Cog):
def __init__(self, client):
self.client = client
#Gets the entire list of competitions from Kaggle API and displays each competition including respective details
@commands.command()
async def list(self, ctx):
listcomp = api.competitions_list_with_http_info(async_req = True)
tup = listcomp.get()
c = 0
for submission in tup[0]:
c += 1
title = submission.get('title')
url = submission.get('url')
category = submission.get('category')
description = submission.get('description')
organizationName = submission.get('organizationName')
reward = submission.get('reward')
deadline = submission.get('deadline')
teamCount = submission.get('teamCount')
embed=discord.Embed(title = f'{title}', description = f'{description}', colour = discord.Colour.purple())
embed.add_field(name = 'Category: ', value = category, inline = True)
embed.add_field(name = 'Organisation: ', value = organizationName, inline = True)
embed.add_field(name = 'Reward: ', value = reward, inline = False)
embed.add_field(name = 'Deadline: ', value = deadline, inline = True)
embed.add_field(name = 'Team Count: ', value=teamCount, inline = True)
embed.add_field(name = 'Link: ', value = url, inline = False)
await ctx.send(embed = embed)
await ctx.send('.................................................................................................................................................')
embed=discord.Embed(title = f'Displaying {c} search results for Kaggle Competitions.', colour = discord.Colour.gold())
await ctx.send(embed = embed)
def setup(client):
client.add_cog(KaggleAPI(client))
|
SHREEOM0611/S4DS-Bot | src/cogs/games.py | <gh_stars>1-10
# Imports
import discord
import random
from discord.ext import commands
# Create a class `games` which inherits from the `commands.Cog` class
class games(commands.Cog):
def __init__(self, client):
self.client = client
# Command for `coinflip`
@commands.command(aliases = ['cf', 'tosscoin', 'tc'])
async def coinflip(self, ctx):
cf_res = ['Heads', 'Tails']
res = random.choice(cf_res)
embed = discord.Embed(title = "Coinflip", description = f'Result = {res}!',
color = discord.Color.gold())
await ctx.send(embed = embed)
# Command for `die toss`
@commands.command(aliases = ['die', '6face'])
async def tossdie(self, ctx):
td_res = [int(i) for i in range(1,7)]
res = random.choice(td_res)
embed = discord.Embed(title = "Toss A Die", description = f'Result = {res}!',
color = discord.Color.magenta())
await ctx.send(embed = embed)
# Setup cogs `games`
def setup(client):
client.add_cog(games(client)) |
SHREEOM0611/S4DS-Bot | src/cogs/arxivAPI.py | import discord
import urllib, urllib.request
from xml.dom import minidom
from discord.ext import commands
class ArxivAPI(commands.Cog):
def __init__(self, client):
self.client = client
#Gets the top search result from arXiv API and displays the paper along with related details (including summary) in an embed
@commands.command()
async def arxivshow(self, ctx, *, search):
query = search.replace(" ", "+")
url = f'http://export.arxiv.org/api/query?search_query=all:{query}&start=0&max_results=1'
data = urllib.request.urlopen(url)
mytree = minidom.parseString(data.read().decode('utf-8'))
entry = mytree.getElementsByTagName('entry')
for y in entry:
published = y.getElementsByTagName('published')[0]
title = y.getElementsByTagName('title')[0]
summary = y.getElementsByTagName('summary')[0]
author = y.getElementsByTagName('author')
authors = ''
for x in author:
a_name = x.getElementsByTagName('name')[0]
authors = authors + (a_name.firstChild.data) + ', '
authors = authors[:-2]
link = y.getElementsByTagName('link')[0]
link1 = link.attributes['href'].value
link2 = y.getElementsByTagName('link')[1]
link3 = link2.attributes['href'].value
embed = discord.Embed(title = f'Title: {title.firstChild.data}', description = f'Published on: {published.firstChild.data}', color = discord.Colour.blue())
embed.set_author(name = f'{authors}')
await ctx.send(embed = embed)
embed = discord.Embed(title = 'Summary: ', description = f'{summary.firstChild.data}', color = discord.Colour.green())
embed.add_field(name = 'Link: ', value = f'{link1}', inline = False)
embed.add_field(name = 'Download link: ', value = f'{link3}', inline = False)
await ctx.send(embed = embed)
await ctx.send('.................................................................................................................................................')
#Gets the top 5 search results (sorted as last updated) from arXiv API and displays respective papers along with related details (excluding summary) in succesive embeds
@commands.command()
async def arxivshowlud(self, ctx, *, search):
query = search.replace(" ", "+")
url = f'http://export.arxiv.org/api/query?search_query=all:{query}&start=0&max_results=5&sortBy=lastUpdatedDate&sortOrder=ascending'
data = urllib.request.urlopen(url)
mytree = minidom.parseString(data.read().decode('utf-8'))
entry = mytree.getElementsByTagName('entry')
for y in entry:
published = y.getElementsByTagName('published')[0]
title = y.getElementsByTagName('title')[0]
author = y.getElementsByTagName('author')
authors = ''
for x in author:
a_name = x.getElementsByTagName('name')[0]
authors = authors + (a_name.firstChild.data) + ', '
authors = authors[:-2]
link = y.getElementsByTagName('link')[0]
link1 = link.attributes['href'].value
link2 = y.getElementsByTagName('link')[1]
link3 = link2.attributes['href'].value
embed = discord.Embed(title = f'Title: {title.firstChild.data}', description = f'Published on: {published.firstChild.data}', color = discord.Colour.blue())
embed.set_author(name = f'{authors}')
embed.add_field(name = 'Link: ', value = f'{link1}', inline = False)
embed.add_field(name = 'Download link: ', value = f'{link3}', inline = False)
await ctx.send(embed = embed)
await ctx.send('.................................................................................................................................................')
#Gets the top 5 search results (sorted as relevance) from arXiv API and displays respective papers along with related details (excluding summary) in succesive embeds
@commands.command()
async def arxivshowr(self, ctx, *, search):
query = search.replace(" ", "+")
url = f'http://export.arxiv.org/api/query?search_query=all:{query}&start=0&max_results=5&sortBy=relevance&sortOrder=ascending'
data = urllib.request.urlopen(url)
mytree = minidom.parseString(data.read().decode('utf-8'))
entry = mytree.getElementsByTagName('entry')
for y in entry:
published = y.getElementsByTagName('published')[0]
title = y.getElementsByTagName('title')[0]
author = y.getElementsByTagName('author')
authors = ''
for x in author:
a_name = x.getElementsByTagName('name')[0]
authors = authors+(a_name.firstChild.data) + ', '
authors = authors[:-2]
link = y.getElementsByTagName('link')[0]
link1 = link.attributes['href'].value
link2 = y.getElementsByTagName('link')[1]
link3 = link2.attributes['href'].value
embed = discord.Embed(title = f'Title: {title.firstChild.data}', description = f'Published on: {published.firstChild.data}', color = discord.Colour.blue())
embed.set_author(name = f'{authors}')
embed.add_field(name = 'Link: ', value = f'{link1}', inline = False)
embed.add_field(name = 'Download link: ', value = f'{link3}', inline = False)
await ctx.send(embed = embed)
await ctx.send('.................................................................................................................................................')
#Gets the top 5 search results (sorted as submitted date) from arXiv API and displays respective papers along with related details (excluding summary) in succesive embeds
@commands.command()
async def arxivshowsd(self, ctx, *, search):
query = search.replace(" ", "+")
url = f'http://export.arxiv.org/api/query?search_query=all:{query}&start=0&max_results=5&sortBy=submittedDate&sortOrder=ascending'
data = urllib.request.urlopen(url)
mytree = minidom.parseString(data.read().decode('utf-8'))
entry = mytree.getElementsByTagName('entry')
for y in entry:
published = y.getElementsByTagName('published')[0]
title = y.getElementsByTagName('title')[0]
author = y.getElementsByTagName('author')
authors = ''
for x in author:
a_name = x.getElementsByTagName('name')[0]
authors = authors + (a_name.firstChild.data) + ', '
authors = authors[:-2]
link = y.getElementsByTagName('link')[0]
link1 = link.attributes['href'].value
link2 = y.getElementsByTagName('link')[1]
link3 = link2.attributes['href'].value
embed = discord.Embed(title = f'Title: {title.firstChild.data}', description = f'Published on: {published.firstChild.data}', color = discord.Colour.blue())
embed.set_author(name = f'{authors}')
embed.add_field(name = 'Link: ', value = f'{link1}', inline = False)
embed.add_field(name = 'Download link: ', value = f'{link3}', inline = False)
await ctx.send(embed = embed)
await ctx.send('.................................................................................................................................................')
#Gets the top 5 search results from arXiv API and displays respective papers along with related details (including summary) in succesive embeds
@commands.command()
async def arxivshowsumm(self, ctx, *, search):
query = search.replace(" ", "+")
url = f'http://export.arxiv.org/api/query?search_query=all:{query}&start=0&max_results=5'
data = urllib.request.urlopen(url)
mytree = minidom.parseString(data.read().decode('utf-8'))
entry = mytree.getElementsByTagName('entry')
for y in entry:
published = y.getElementsByTagName('published')[0]
title = y.getElementsByTagName('title')[0]
author = y.getElementsByTagName('author')
authors = ''
for x in author:
a_name = x.getElementsByTagName('name')[0]
authors = authors + (a_name.firstChild.data) + ', '
authors = authors[:-2]
summary = y.getElementsByTagName('summary')[0]
link = y.getElementsByTagName('link')[0]
link1 = link.attributes['href'].value
link2 = y.getElementsByTagName('link')[1]
link3 = link2.attributes['href'].value
embed = discord.Embed(title = f'Title: {title.firstChild.data}', description = f'Published on: {published.firstChild.data}', color = discord.Colour.blue())
embed.set_author(name = f'{authors}')
await ctx.send(embed = embed)
embed = discord.Embed(title = 'Summary: ', description = f'{summary.firstChild.data}', color = discord.Colour.green())
embed.add_field(name = 'Link: ', value = f'{link1}', inline = False)
embed.add_field(name = 'Download link: ', value = f'{link3}', inline = False)
await ctx.send(embed = embed)
await ctx.send('.................................................................................................................................................')
def setup(client):
client.add_cog(ArxivAPI(client)) |
wrs28/safe_extubation | src/PressorGauge.py | <filename>src/PressorGauge.py
import streamlit as st
import os
import numpy as np
import pandas as pd
import pickle
from modeling.feature_definitions import features_to_keep
import shap
import copy
import statistics
import altair as alt
# block for AWS SQL-access
# # DB_USER = os.environ.get("DB_USER")
# # DB_PASSWORD = <PASSWORD>("DB_PASSWORD")
# # DB_HOST = os.environ.get("DB_HOST")
# # DB_NAME = os.environ.get("DB_NAME")
# # engine = sqlalchemy.create_engine('postgres://postgres:postgres@host.docker.internal/PressorGauge')
# # engine = sqlalchemy.create_engine("postgres://" + DB_USER + ":" + DB_PASSWORD + "@" + DB_HOST + "/" + DB_NAME)
#header
"""
# Pressor Gauge
### Predicting the need for life-saving blood-pressure medication (pressor) in the next 12 hours
-----
"""
with open(os.path.join("modeling","test_set.p"),"rb") as file:
test_set = pickle.load(file)
agree = st.sidebar.checkbox('show ground truth?')
X, y, subjects = test_set["X"], test_set["y"], test_set["cv_groups"]
#ids = np.random.choice(subjects,size=10,replace=False)
ids = [23262,5199,89402,6558,10780,8992,17551,16646,21015,20083,24616,77484,99863,15659,91222,57764,9808,63987]
id_ind = st.sidebar.selectbox(
'select a patient',
range(len(ids))
)
st.sidebar.markdown("Patient Information & Labs:")
subject_id = ids[id_ind]
with open(os.path.join("modeling","test_set.p"),"rb") as file:
test_set = pickle.load(file)
hadm_id = X[X.SUBJECT_ID==subject_id].HADM_ID.unique()[0];
inds = (X.SUBJECT_ID==subject_id) & (X.HADM_ID==hadm_id).values
y = y[inds]
X = X[inds]
X.pop("HADM_ID")
X.pop("SUBJECT_ID");
times = X.pop("EPOCH");
X.pop("PRESSOR_AT_ALL");
y[times > 2] = False
Q = X.copy()
Q = pd.DataFrame(Q.iloc[0,:]).T
# load up trained models
with open(os.path.join("modeling","random_forest_calibrated.p"),"rb") as file:
model = pickle.load(file)
y_pred = model.predict(X)
p_pred = model.predict_proba(X)[:,1]
X["Probability of pressor need"] = p_pred
X["Hours since hospital admission"] = 6*times[::-1]
X["PRESSORS LIKELY"] = p_pred>.5
c1 = alt.Chart(X).mark_circle(size=100, color="gray").encode(
x=alt.X('Hours since hospital admission:Q', scale=alt.Scale(domain=(6*times.values[0]-1,6*times.values[-1]+1))),
y=alt.Y('Probability of pressor need:Q', scale=alt.Scale(domain=(-.1,1.1))),
)
if y_pred[0]:
color="red"
else:
color="steelblue"
c2 = alt.Chart(pd.DataFrame(X.iloc[0,:]).T).mark_circle(size=200, color=color, opacity=.7).encode(
x=alt.X('Hours since hospital admission:Q', scale=alt.Scale(domain=(6*times.values[0]-1,6*times.values[-1]+1))),
y=alt.Y('Probability of pressor need:Q', scale=alt.Scale(domain=(-.1,1.1))),
)
st.altair_chart(c1 + c2)
with open(os.path.join("modeling","random_forest_test_shapley_values.p"),"rb") as file:
dict = pickle.load(file)
explainer = dict["explainer"]
shap_values = dict["shap_values"]
# following block repeats lab values in sidebar and enables them to be updated
if True:
age = st.sidebar.number_input("age", value=Q["AGE"].values[0])
Q["AGE"] = age
if Q.GENDER.values[0]==1:
sex_value = "F"
else:
sex_value = "M"
sex = st.sidebar.radio("sex", ["M","F"], index=int(Q.GENDER.values[0]))
if sex == "F":
sex_value = 1
else:
sex_value = 0
Q["GENDER"] = sex_value
weight = st.sidebar.number_input("weight (kg)", value=Q["WEIGHT_KG"].values[0])
Q["WEIGHT_KG"] = weight
ptt = st.sidebar.number_input("PTT", value=Q["ptt_LAST"].values[0])
Q["ptt_LAST"] = ptt
po2 = st.sidebar.number_input("pO2", value=Q["pO2_LAST"].values[0])
Q["pO2_LAST"] = po2
lc = st.sidebar.checkbox("abnormal lactate?", value=Q["lactate_FLAG_COUNT"].values[0])
Q["lactate_FLAG_COUNT"] = lc
wbc = st.sidebar.checkbox("abnormal white blood cell count?", value=Q["wbc_FLAG_COUNT"].values[0])
Q["wbc_FLAG_COUNT"] = wbc
ph = st.sidebar.number_input("pH", value=Q["pH_LAST"].values[0])
Q["pH_LAST"] = ph
bun = st.sidebar.number_input("BUN", value=Q["bun_LAST"].values[0])
Q["bun_LAST"] = bun
cr = st.sidebar.number_input("Cr", value=Q["creatinine_LAST"].values[0])
Q["creatinine_LAST"] = cr
ag = st.sidebar.number_input("anion gap", value=Q["anion_gap_LAST"].values[0])
Q["anion_gap_LAST"] = ag
pco2 = st.sidebar.number_input("pCO2", value=Q["pCO2_LAST"].values[0])
Q["pCO2_LAST"] = pco2
pc = st.sidebar.number_input("platelet count", value=Q["platelet_count_LAST"].values[0])
Q["platelet_count_LAST"] = pc
hg = st.sidebar.number_input("hemoglobin", value=Q["hemoglobin_LAST"].values[0])
Q["hemoglobin_LAST"] = hg
hc = st.sidebar.number_input("hematocrit", value=Q["hematocrit_LAST"].values[0])
Q["hematocrit_LAST"] = hc
sodium = st.sidebar.number_input("Na+", value=Q["sodium_LAST"].values[0])
Q["sodium_LAST"] = sodium
chloride = st.sidebar.number_input("Cl-", value=Q["chloride_LAST"].values[0])
Q["chloride_LAST"] = chloride
pot = st.sidebar.number_input("K+", value=Q["potassium_LAST"].values[0])
Q["potassium_LAST"] = pot
bcb = st.sidebar.number_input("HCO3", value=Q["hcO3_LAST"].values[0])
Q["hcO3_LAST"] = bcb
alb = st.sidebar.checkbox("abnormal albumin?", value=Q["albumin_FLAG_COUNT"].values[0])
Q["albumin_FLAG_COUNT"] = alb
ap = st.sidebar.checkbox("abnormal alkaline phosphatase?", value=Q["alkaline_phosphatase_FLAG_COUNT"].values[0])
Q["alkaline_phosphatase_FLAG_COUNT"] = ap
ast = st.sidebar.checkbox("abnormal AST?", value=Q["AST_FLAG_COUNT"].values[0])
Q["AST_FLAG_COUNT"] = ast
ALT = st.sidebar.checkbox("abnormal ALT?", value=Q["ALT_FLAG_COUNT"].values[0])
Q["ALT_FLAG_COUNT"] = ALT
new_pred = model.predict(Q)
new_prob = model.predict_proba(Q)[0,1]
f"""
Current probability of needing pressors in the next 12 hours: **{"%2i%%" % (100*new_prob)}**
"""
shap_values = explainer.shap_values(Q, approximate=False, check_additivity=False)
shapvals = shap_values[1][0,:]
a = np.argsort(shapvals)[::-1]
b = np.argsort(shapvals)
top_factors = Q.columns[a[0:3]]
bot_factors = Q.columns[b[0:3]]
tot_shap = sum(np.abs(shapvals))
x = Q.iloc[0,:]
# show top three influential lab results as markdown table
if new_pred:
f"""
Factors making pressors **likely** (ranked from most to least influential)
| | lab | result | importance (scale of 0-100) |
|- |- |- |
| 1 | {top_factors[0]} | {x[a[0]]} | {"%2i" % (100*shapvals[a[0]]/tot_shap)}
| 2 | {top_factors[1]} | {x[a[1]]} | {"%2i" % (100*shapvals[a[1]]/tot_shap)}
| 3 | {top_factors[2]} | {x[a[2]]} | {"%2i" % (100*shapvals[a[2]]/tot_shap)}
"""
else:
f"""
Factors making pressors ** *un*likely** (ranked from most to least influential)
| | lab | result | importance (scale of 0-100) |
|- |- |- |
| 1 | {bot_factors[0]} | {x[b[0]]} | {"%2i" % (-100*shapvals[b[0]]/tot_shap)}
| 2 | {bot_factors[1]} | {x[b[1]]} | {"%2i" % (-100*shapvals[b[1]]/tot_shap)}
| 3 | {bot_factors[2]} | {x[b[2]]} | {"%2i" % (-100*shapvals[b[2]]/tot_shap)}
"""
"""
----
"""
# Show historical outcome vs predicted outcome
if agree:
X["Predicted (purple)"] = y_pred
X["Ground Truth (gray)"] = y
c3 = alt.Chart(X).mark_circle(size=100, color="gray").encode(
x=alt.X('Hours since hospital admission:Q', scale=alt.Scale(domain=(6*times.values[0]-1,6*times.values[-1]+1))),
y=alt.Y('Ground Truth (gray):Q', scale=alt.Scale(domain=(-.1,1.1)), axis=alt.Axis(title="Classification (1 = pressor, 0 = none)")),
)
c4 = alt.Chart(X).mark_circle(size=50, color="#7D3C98").encode(
x=alt.X('Hours since hospital admission:Q', scale=alt.Scale(domain=(6*times.values[0]-1,6*times.values[-1]+1))),
y=alt.Y('Predicted (purple):Q', scale=alt.Scale(domain=(-.1,1.1))),
).interactive().properties(title="Pred. (purple) vs Truth (gray)")#, color=alt.Color('y', scale=alt.Scale(scheme='blueorange')))
c = c3 + c4
c.configure_title(
fontSize=30,
font='Courier',
anchor='start',
color='gray',
)
c.configure_axis(
labelFontSize=20
)
st.altair_chart(c)
"""
-----
"""
# Footer
"""
Created by <NAME>, Data Science Insight Fellow 2020
[github](https://github.com/wrs28/PressorGauge) |
[slides](https://docs.google.com/presentation/d/1O2QuISdaB0OOj7BF372qH_N30NvK4DMR628YFlL2-XE/edit?usp=sharing)
| [linkedin](https://www.linkedin.com/in/wrsweeney2/)
"""
|
wrs28/safe_extubation | src/building_database/build_pressor_database.py | <reponame>wrs28/safe_extubation<filename>src/building_database/build_pressor_database.py
import pandas as pd
import os
import numpy as np
import sqlalchemy
import pickle
from sklearn.neighbors import KernelDensity
import directories
RND_SEED = 1729
MINIMUM_TIME_TO_PRESSOR_HOURS = 12
MAXIMUM_TIME_TO_PRESSOR_DAYS = 50.
MINIMUM_PRESSOR_DURATION_MINUTES = 15.
MINIMUM_AGE = 18.
MAXIMUM_WEIGHT_KG = 350
MINIMUM_WEIGHT_KG = 25
## load in icustay data
def load_icustay():
path = os.path.join(directories.mimic_dir, "ICUSTAYS.csv")
dtypes = {
"ICUSTAY_ID" : pd.Int32Dtype(),
"SUBJECT_ID" : pd.Int32Dtype(),
"HADM_ID" : pd.Int32Dtype(),
}
cols = [
"ICUSTAY_ID",
"INTIME",
"OUTTIME",
"SUBJECT_ID",
"HADM_ID"
]
date_cols = ["INTIME","OUTTIME"]
icustays = pd.read_csv(path, usecols=cols, parse_dates=date_cols, dtype=dtypes)
return icustays
## append admission data
def load_admissions(icustays):
path = os.path.join(directories.mimic_dir, "ADMISSIONS.csv")
date_cols = [
"ADMITTIME",
"DISCHTIME",
"DEATHTIME",
"EDREGTIME",
"EDOUTTIME"
]
adm = pd.read_csv(path, parse_dates=date_cols)
icustays = icustays.join(adm[["HADM_ID","ADMITTIME","ADMISSION_TYPE","ETHNICITY"]].set_index("HADM_ID"),on="HADM_ID", how="left")
return icustays
## append patient data
def load_patients(icustays):
path = os.path.join(directories.mimic_dir, "PATIENTS.csv")
date_cols = [
"DOB",
"DOD",
"DOD_HOSP",
"DOD_SSN"
]
pat = pd.read_csv(path, parse_dates=date_cols)
icustays = icustays.join(pat[["SUBJECT_ID","GENDER","DOB"]].set_index("SUBJECT_ID"),on="SUBJECT_ID", how="left")
# for patients older than 89, age is shifted to 300, which is too big for nanosecond integer representation, so pick Jan 1, 2000 as intermediate
admittime = icustays.ADMITTIME - pd.to_datetime("2000-1-1")
dob = pd.to_datetime("2000-1-1") - icustays.DOB
icustays["AGE"] = round((admittime.dt.days + dob.dt.days)/365).astype(int)
return icustays
## append weight
def load_weights(icustays):
path = os.path.join(directories.mimic_dir, "heightweight.csv")
heightweight = pd.read_csv(path, dtype={"icustay_id": pd.Int32Dtype()}, usecols=["icustay_id", "weight_min"])
heightweight.rename(inplace=True, columns={"icustay_id": "ICUSTAY_ID", "weight_min": "WEIGHT_KG"})
# print num rows dropped b/c of weight
length_before_drop = len(heightweight)
heightweight = heightweight[(MINIMUM_WEIGHT_KG < heightweight.WEIGHT_KG) & \
(heightweight.WEIGHT_KG < MAXIMUM_WEIGHT_KG)]
length_after_drop = len(heightweight)
directories.print_log("\t",length_before_drop-length_after_drop, "icustays w/ weight greater than",\
MAXIMUM_WEIGHT_KG, "kg (likely mislabeled)")
icustays = icustays.join(heightweight.set_index("ICUSTAY_ID"), on="ICUSTAY_ID", how="left")
return icustays
## append LODS (logistic organ dysfunction score)
def load_LODS(icustays):
path = os.path.join(directories.mimic_dir, "lods.csv")
dtypes = {
"icustay_id" : pd.Int32Dtype(),
"LODS" : pd.Int16Dtype(),
"pulmonary" : pd.Int16Dtype(),
"cardiovascular" : pd.Int16Dtype(),
}
lods = pd.read_csv(path, dtype=dtypes)
lods.rename(
inplace=True,
columns = {
"icustay_id" : "ICUSTAY_ID",
"pulmonary" : "PULMONARY_LODS",
"cardiovascular" : "CARDIOVASCULAR_LODS"
}
)
# print number of icustays dropped from missing LODS
length_before_drop = len(lods)
lods.dropna(axis=0,inplace=True) # 2482 na icustays
length_after_drop = len(lods)
directories.print_log("\t",length_before_drop-length_after_drop,"icustays w/o LODS")
# interpret LODS scores as ints
lods.ICUSTAY_ID = lods.ICUSTAY_ID.astype(int)
lods.LODS = lods.LODS.astype(int)
lods.PULMONARY_LODS = lods.PULMONARY_LODS.astype(int)
lods.CARDIOVASCULAR_LODS = lods.CARDIOVASCULAR_LODS.astype(int)
icustays = icustays.join(lods.set_index("ICUSTAY_ID"), on="ICUSTAY_ID", how="left")
return icustays
## append OASIS (Oxford Acute Severity of Illness Score)
def load_OASIS(icustays):
path = os.path.join(directories.mimic_dir, "oasis.csv")
dtypes = {
"icustay_id" : pd.Int32Dtype(),
"OASIS" : pd.Int16Dtype(),
}
oasis = pd.read_csv(path, dtype=dtypes)
oasis.rename(
inplace=True,
columns = {
"icustay_id": "ICUSTAY_ID",
}
)
# print number of icustays dropped from missing OASIS
length_before_drop = len(oasis)
oasis.dropna(axis=0,inplace=True) # 0 na icustays
length_after_drop = len(oasis)
directories.print_log("\t",length_before_drop-length_after_drop,"icustays w/o OASIS")
# interpret OASIS scores as int
oasis.ICUSTAY_ID = oasis.ICUSTAY_ID.astype(int)
oasis.OASIS = oasis.OASIS.astype(int)
icustays = icustays.join(oasis.set_index("ICUSTAY_ID"), on="ICUSTAY_ID", how="left")
return icustays
## append APACHE scores (acute and chronic health evaluation)
def load_APACHE(icustays):
path = os.path.join(directories.mimic_dir, "apache.csv")
dtypes = {
"icustay_id": pd.Int32Dtype(),
"APSIII": pd.Int16Dtype(),
}
apache = pd.read_csv(path, dtype=dtypes)
apache.rename(
inplace=True,
columns = {
"icustay_id" : "ICUSTAY_ID",
"APSIII" : "APACHE"
}
)
# print number of icustays dropped from missing APACHE
length_before_drop = len(apache)
apache.dropna(axis=0,inplace=True) # 34 na icustays
length_after_drop = len(apache)
directories.print_log("\t",length_before_drop-length_after_drop,"icustays w/o APACHE")
# interpret APACHE score as int
apache.ICUSTAY_ID = apache.ICUSTAY_ID.astype(int)
apache.APACHE = apache.APACHE.astype(int)
icustays = icustays.join(apache.set_index("ICUSTAY_ID"), on="ICUSTAY_ID", how="left")
return icustays
## load in vasopressor durations
def load_vasopressor_durations():
path = os.path.join(directories.mimic_dir, "vasopressordurations.csv")
dtypes = {
"icustay_id" : pd.Int32Dtype(),
"vasonum" : pd.Int16Dtype(),
"duration_hours" : float,
}
date_cols = ["starttime", "endtime"]
vaso_episodes = pd.read_csv(path, dtype=dtypes, parse_dates=date_cols)
vaso_episodes.rename(
inplace=True,
columns = {
"icustay_id" : "ICUSTAY_ID",
"vasonum" : "EPISODE",
"starttime" : "STARTTIME",
"endtime" : "ENDTIME",
"duration_hours" : "DURATION_HOURS"
}
)
# vaso_episodes_orig.dropna(axis=0,inplace=True) # just in case
return vaso_episodes
## add total number of episodes and format dates, keep only the first episode
def clean_vaso_episodes_1(vaso_episodes):
number_of_episodes = vaso_episodes[["ICUSTAY_ID"]].groupby(["ICUSTAY_ID"]).size().to_frame("NUMBER_OF_EPISODES").reset_index()
vaso_episodes = vaso_episodes.join(number_of_episodes.set_index("ICUSTAY_ID"), on="ICUSTAY_ID", how="left")
vaso_episodes = vaso_episodes[vaso_episodes.EPISODE == 1]
icustays_bool = (vaso_episodes.groupby("ICUSTAY_ID").size() == 1).values
unique_icustays = vaso_episodes.groupby("ICUSTAY_ID").size().index.values[icustays_bool]
vaso_episodes = vaso_episodes[vaso_episodes.ICUSTAY_ID.isin(unique_icustays)]
vaso_episodes.STARTTIME = vaso_episodes.STARTTIME.dt.tz_localize(None)
vaso_episodes.ENDTIME = vaso_episodes.ENDTIME.dt.tz_localize(None)
return vaso_episodes
## pair episode data with icustay data
def pair_episodes_and_stays(vaso_episodes, icustays):
vaso_episodes = vaso_episodes.join(icustays.set_index("ICUSTAY_ID"), on="ICUSTAY_ID", how="right")
# for patients with no pressor episodes, set EPISODE, NUMBER_OF_EPISODES, DURATION_HOURS to 0
vaso_episodes.loc[pd.isna(vaso_episodes.EPISODE),["EPISODE","NUMBER_OF_EPISODES","DURATION_HOURS"]] = 0
return vaso_episodes
## compute how long after beginning of ICU stay pressor was administered
def compute_hours_to_pressor(vaso_episodes):
vaso_episodes["EPISODE_START_POST_TRANSFER"] = vaso_episodes.STARTTIME - vaso_episodes.ADMITTIME
rows_to_remove = vaso_episodes.EPISODE_START_POST_TRANSFER > pd.Timedelta(days=MAXIMUM_TIME_TO_PRESSOR_DAYS)
directories.print_log("\tdropping", sum(rows_to_remove), "icustays with first pressor episode occurring more than", "%2i"% MAXIMUM_TIME_TO_PRESSOR_DAYS, "days after admission")
vaso_episodes = vaso_episodes[~rows_to_remove]
return vaso_episodes
## clean up
def clean_vaso_episodes_2(vaso_episodes):
vaso_episodes.reset_index(inplace=True)
vaso_episodes.ICUSTAY_ID = vaso_episodes.ICUSTAY_ID.astype(int)
vaso_episodes.EPISODE = vaso_episodes.EPISODE.astype(int)
vaso_episodes.NUMBER_OF_EPISODES = vaso_episodes.NUMBER_OF_EPISODES.astype(int)
vaso_episodes.loc[vaso_episodes.EPISODE==0,"EPISODE_START_POST_TRANSFER"] = (vaso_episodes.OUTTIME - vaso_episodes.ADMITTIME)[vaso_episodes.EPISODE==0]
vaso_episodes.loc[vaso_episodes.EPISODE==0,"STARTTIME"] = vaso_episodes.OUTTIME[vaso_episodes.EPISODE==0]
# remove episodes that start in the first day
sum(vaso_episodes.EPISODE_START_POST_TRANSFER < pd.Timedelta(hours=MINIMUM_TIME_TO_PRESSOR_HOURS))
rows_to_remove = vaso_episodes.EPISODE_START_POST_TRANSFER < pd.Timedelta(hours=MINIMUM_TIME_TO_PRESSOR_HOURS)
directories.print_log("\tdropping",sum(rows_to_remove),"icustays with first pressor episode occurring less than", "%2i"% MINIMUM_TIME_TO_PRESSOR_HOURS,"hours after hospital admission")
vaso_episodes = vaso_episodes[~rows_to_remove].copy()
len(vaso_episodes)
## clean up ICU stays
rows_to_replace = vaso_episodes.AGE > 150
directories.print_log("\treplacing age of",sum(rows_to_replace),"patients over 89 with age 91")
vaso_episodes.loc[rows_to_replace, "AGE"] = 91
rows_to_remove = vaso_episodes.AGE < MINIMUM_AGE
directories.print_log("\tdropping",sum(rows_to_remove),"icustays with age less than", MINIMUM_AGE)
vaso_episodes = vaso_episodes[~rows_to_remove]
rows_to_remove = (vaso_episodes.DURATION_HOURS < MINIMUM_PRESSOR_DURATION_MINUTES/60) & (vaso_episodes.EPISODE==1)
directories.print_log("\tdropping",sum(rows_to_remove),"pressor episodes with vaso durations less than", MINIMUM_PRESSOR_DURATION_MINUTES,"minutes")
vaso_episodes = vaso_episodes[~rows_to_remove]
vaso_episodes.set_index("ICUSTAY_ID", inplace=True)
# compute pressor time distribution
kde_true = KernelDensity(kernel="tophat")
kde_true.fit(np.reshape(vaso_episodes[vaso_episodes.EPISODE==1]["EPISODE_START_POST_TRANSFER"].values.astype(int)/10**9/60/60,(-1,1))) # in hours
kde_false = KernelDensity(kernel="tophat")
kde_false.fit(np.reshape(vaso_episodes[vaso_episodes.EPISODE==0]["EPISODE_START_POST_TRANSFER"].values.astype(int)/10**9/60/60,(-1,1))) # in hours
with open(os.path.join(directories.model_dir,"time_distributions.p"),"wb") as file:
pickle.dump({"kde_true" : kde_true, "kde_false" : kde_false},file)
# vaso_episodes.reset_index(inplace=True)
vaso_episodes["PRESSOR_START_SEC"] = vaso_episodes.STARTTIME - vaso_episodes.ADMITTIME
vaso_episodes = vaso_episodes[~vaso_episodes.PRESSOR_START_SEC.isna()]
vaso_episodes.PRESSOR_START_SEC = (vaso_episodes.PRESSOR_START_SEC.astype(int)/10**9).apply(np.int32)
labels = [
"index",
"ENDTIME",
"DURATION_HOURS",
"NUMBER_OF_EPISODES",
"INTIME",
"OUTTIME",
"EPISODE_START_POST_TRANSFER",
"STARTTIME",
"DOB"
]
vaso_episodes.drop(axis=1,labels=labels, inplace=True)
len1 = len(vaso_episodes)
vaso_episodes.dropna(inplace=True)
len2 = len(vaso_episodes)
directories.print_log("\tdropping",len1-len2,"icustays with missing values")
directories.print_log("\tdropping",len(vaso_episodes) - len(vaso_episodes.HADM_ID.unique()),"multiple ICU stays in same hospital visit")
vaso_episodes.drop_duplicates("HADM_ID", inplace=True)
return vaso_episodes
def compute_pressor_time_distribution(vaso_episodes):
kde_true = KernelDensity(kernel="tophat")
kde_true.fit(np.reshape(vaso_episodes[vaso_episodes.EPISODE==1]["EPISODE_START_POST_TRANSFER"].values.astype(int)/10**9/60/60,(-1,1))) # in hours
kde_false = KernelDensity(kernel="tophat")
kde_false.fit(np.reshape(vaso_episodes[vaso_episodes.EPISODE==0]["EPISODE_START_POST_TRANSFER"].values.astype(int)/10**9/60/60,(-1,1))) # in hours
with open(os.path.join(directories.model_dir,"time_distributions.p"),"wb") as file:
pickle.dump({"kde_true" : kde_true, "kde_false" : kde_false},file)
def main():
directories.print_log("building pressor database",mode="w")
icustays = load_icustay()
icustays = load_admissions(icustays)
icustays = load_patients(icustays)
icustays = load_weights(icustays)
icustays = load_LODS(icustays)
icustays = load_OASIS(icustays)
icustays = load_APACHE(icustays)
vaso_episodes = load_vasopressor_durations()
vaso_episodes = clean_vaso_episodes_1(vaso_episodes)
vaso_episodes = pair_episodes_and_stays(vaso_episodes, icustays)
vaso_episodes = compute_hours_to_pressor(vaso_episodes)
vaso_episodes = clean_vaso_episodes_2(vaso_episodes)
directories.print_log("\tsaving to SQL database `PressorGauge`, table `pressors_by_icustay`")
with directories.engine.connect() as connection:
vaso_episodes.to_sql("pressors_by_icustay", con=connection, if_exists="replace", index_label="ICUSTAY_ID")
directories.print_log("\ttotal of",len(vaso_episodes),"icustays, of which",sum(vaso_episodes.EPISODE>0),"have a pressor episode")
check = 100*float(sum(vaso_episodes.EPISODE==1))/len(vaso_episodes)
directories.print_log("\tsanity check: %2.0f%%" % check,"have pressors, ideally in range 1/4 to 1/3")
directories.print_log("Done building pressor database!")
directories.print_log()
# execute only if run as a script
if __name__ == "__main__":
main()
|
wrs28/safe_extubation | src/modeling/build_features.py | <filename>src/modeling/build_features.py
import pandas as pd
import os
import sqlalchemy
import sklearn
import pickle
import numpy as np
import directories
import directories
import feature_definitions
RECORD_LENGTH_HOURS = 12 # how many hours the lab data is accumulated over
RECORD_LENGTH_SHIFT = 6 # how many hours each window is shifted by
def extract_lab_records():
directories.print_log("\textracting lab records for", RECORD_LENGTH_HOURS,\
"hr windows, with a shift of", RECORD_LENGTH_SHIFT, "hrs")
labs = []
with directories.engine.connect() as connection:
for k in range(int(48/RECORD_LENGTH_SHIFT)):
directories.print_log("\t\tloading epoch",k)
temp = []
for i in range(RECORD_LENGTH_HOURS):
QUERY = f"""
select *
from lab_events
where "HOURS_BEFORE_PRESSOR"={RECORD_LENGTH_SHIFT*k + 1 +i}
order by "HOURS_BEFORE_PRESSOR"
"""
temp.append(pd.read_sql_query(QUERY, con=connection))
labs.append(pd.concat(temp))
return labs
def build_features(labs, pressors_by_icustay):
directories.print_log("\tbuilding features")
data = []
for i in range(len(labs)):
directories.print_log("\t\tfor epoch", i)
temp = feature_definitions.attach_lab_features(pressors_by_icustay, labs[i])
temp["LABEL"] = (temp.EPISODE==1) & (RECORD_LENGTH_SHIFT*i <= 24) # positive detection is 12 hours or less
temp["EPOCH"] = i
data.append(temp)
return pd.concat(data)
def extract_training_inputs(cleaned_data):
with open(os.path.join(directories.model_dir,"training_subjects.p"),"rb") as file:
training_subjects = pickle.load(file).values
training_subjects = training_subjects.reshape(-1,)
training_inputs = cleaned_data[cleaned_data.SUBJECT_ID.isin(training_subjects)]
training_inputs = training_inputs[["LABEL","SUBJECT_ID","EPISODE","EPOCH","HADM_ID"] + feature_definitions.features_to_keep]
ratio = 100.*sum(training_inputs.LABEL.values)/len(training_inputs)
directories.print_log("\t\t",len(training_inputs),"training samples before dropping na,","%2.0f%%"% ratio,"are positive)")
training_inputs = training_inputs.dropna()
training_inputs = training_inputs[training_inputs.EPOCH.isin([0,2,4,6,8])]
ratio = 100.*sum(training_inputs.LABEL.values)/len(training_inputs)
directories.print_log("\t\t",len(training_inputs),"training samples after dropping na,","%2.0f%%"% ratio,"are positive)")
print("\t%2.0f%% of training subjects will need pressors" % (100*sum(training_inputs.EPISODE==1)/len(training_inputs)))
print("\t%2.0f%% of training subjects won't need pressors at all" % (100*sum(training_inputs.EPISODE==0)/len(training_inputs)))
directories.print_log("\tsaving features")
with open(os.path.join(directories.model_dir,"training_features.p"),"wb") as file:
pickle.dump(training_inputs, file)
def extract_test_inputs(cleaned_data):
with open(os.path.join(directories.model_dir,"test_subjects.p"),"rb") as file:
test_subjects = pickle.load(file).values
test_subjects = test_subjects.reshape(-1,)
test_inputs = cleaned_data[cleaned_data.SUBJECT_ID.isin(test_subjects)]
test_inputs = test_inputs[["LABEL","SUBJECT_ID","EPISODE","EPOCH","HADM_ID"] + feature_definitions.features_to_keep]
ratio = 100.*sum(test_inputs.LABEL.values)/len(test_inputs)
directories.print_log("\t\t",len(test_inputs),"test samples before dropping na,","%2.0f%%"% ratio,"are positive)")
test_inputs = test_inputs.dropna()
ratio = 100.*sum(test_inputs.LABEL.values)/len(test_inputs)
directories.print_log("\t\t",len(test_inputs),"test samples after dropping na,","%2.0f%%"% ratio,"are positive)")
print("\t%2.0f%% of test subjects will need pressors" % (100*sum(test_inputs.EPISODE==1)/len(test_inputs)))
print("\t%2.0f%% of test subjects won't need pressors at all" % (100*sum(test_inputs.EPISODE==0)/len(test_inputs)))
with open(os.path.join(directories.model_dir,"test_features.p"),"wb") as file:
pickle.dump(test_inputs, file)
def main():
directories.print_log("building features")
labs = extract_lab_records()
with directories.engine.connect() as connection:
pressors_by_icustay = pd.read_sql("pressors_by_icustay", con=connection)
data = build_features(labs, pressors_by_icustay)
directories.print_log("\tcleaning features")
cleaned_data = feature_definitions.clean_data(data)
# set nan flags to zero, since there were no lab results at all in those windows
cleaned_data.TOTAL_FLAG_COUNT.fillna(0,inplace=True)
for feature in feature_definitions.features:
cleaned_data[feature_definitions.features[feature]["ab"]+"_FLAG_COUNT"].fillna(0,inplace=True)
extract_training_inputs(cleaned_data)
extract_test_inputs(cleaned_data)
directories.print_log("done building features!")
directories.print_log()
# execute only if run as a script
if __name__ == "__main__":
main()
|
wrs28/safe_extubation | src/building_database/build_lab_database.py | <gh_stars>1-10
import numpy as np
import pandas as pd
import os
import math
import sqlalchemy
import directories
# number of rows in LABEVENTS to read in at a time (there are 27_854_055 lines in LABEVENTS)
CHUNK_SIZE = 10**6
NUM_CHUNKS = np.inf
def find_first(arr):
idx = arr.argmax()
if arr[idx]:
return idx
else:
return None
def extract_lab_events(vaso_episodes, interval_splits):
# initialize chartevents dataframe
columns = [
"SUBJECT_ID",
"ITEMID",
"CHARTTIME",
"VALUENUM",
"FLAG",
"HADM_ID"
]
dtypes = {
"VALUENUM" : float,
"FLAG" : str,
"SUBJECT_ID" : pd.Int32Dtype(),
"HADM_ID" : pd.Int32Dtype()
}
date_cols = ["CHARTTIME"]
directories.print_log("extracting relevent lab events")
path = os.path.join(directories.mimic_dir, "LABEVENTS.csv")
count = 0
replace_flag = True
for chunk in pd.read_csv(path, chunksize=CHUNK_SIZE, usecols=columns, dtype=dtypes, parse_dates=date_cols):
# add columns to keep track of whether or not 24 hours from pressor (PRESSOR_LABEL)
# and which hour before pressor event it it (HOURS_BEFORE_PRESSOR)
chunk = chunk[~pd.isna(chunk.HADM_ID)] # throwing away about 25% of labs from outpatient settings b/c hard to attach them to an admission nubmer
chunk["HOURS_BEFORE_PRESSOR"] = 0
temp = chunk.join(vaso_episodes[["HADM_ID","ADMITTIME"]].set_index("HADM_ID"),on="HADM_ID")
chunk.CHARTTIME = np.int32((chunk.CHARTTIME - temp.ADMITTIME).values/10**9)
count += 1
if count > NUM_CHUNKS:
break
else:
directories.print_log("\tprocessing LABEVENTS chunk:",count, "of", math.ceil(27_854_055/CHUNK_SIZE))
# loop through all the times in a given hospital admission (HADM_ID), recall we keep only hospital admissions with 1 icustay
for (time, hadm), time_group in chunk[chunk.HADM_ID.isin(vaso_episodes.HADM_ID)].groupby(["CHARTTIME","HADM_ID"]):
# only extract lab data if it falls in the interval i
splits = interval_splits.loc[hadm]
i = find_first((splits[1:-1].values < time) & (time <= splits[:-2].values))
if i:
time_group = time_group.copy()
time_group.HOURS_BEFORE_PRESSOR = i
# if within one day of pressor event, lable true if episode==1
# if first entry to be added, replace table, otherwise add to it
if replace_flag:
mode = "replace"
replace_flag = False
else:
mode = "append"
with directories.engine.connect() as connection:
time_group.to_sql("lab_events", con=connection, if_exists=mode, index=False)
def main():
# load in ventilation times
with directories.engine.connect() as connection:
vaso_episodes = pd.read_sql("pressors_by_icustay", con=connection, index_col="ICUSTAY_ID")
with directories.engine.connect() as connection:
interval_splits = pd.read_sql("interval_splits", con=connection, index_col="ICUSTAY_ID")
interval_splits.set_index("HADM_ID", inplace=True)
extract_lab_events(vaso_episodes, interval_splits)
directories.print_log("Done processing lab events!")
directories.print_log()
# execute only if run as a script
if __name__ == "__main__":
main()
|
wrs28/safe_extubation | src/building_database/directories.py | <reponame>wrs28/safe_extubation
import os
import sqlalchemy
# directory where project lives
project_dir = "/Users/wrs/Documents/insight/PressorGauge"
# directory where model lives
model_dir = "/Users/wrs/Documents/insight/PressorGauge/src/modeling"
# directory where mimic data lives
mimic_dir = "/Volumes/gaia/mimic"
# directory for logs
logs_dir = "/Users/wrs/Documents/insight/PressorGauge/logs"
# sql access
engine = sqlalchemy.create_engine('postgres://postgres:postgres@localhost/PressorGauge')
# print to screen and to log
def print_log(*message, mode="a"):
message = [str(sub) for sub in message]
print(*message)
with open(os.path.join(logs_dir,"build.log"),mode) as f:
f.write(" ".join(message) + "\n")
|
wrs28/safe_extubation | src/building_database/build_intervals.py | import pandas as pd
import sqlalchemy
from directories import print_log, engine
N_WINDOWS = 48
def main():
with engine.connect() as connection:
vaso_episodes = pd.read_sql("pressors_by_icustay", con=connection, index_col="ICUSTAY_ID")
print_log("building hour-long intervals for each icustay")
interval_splits = [pd.Series(vaso_episodes.PRESSOR_START_SEC - i*60*60, name=i, dtype=pd.Int32Dtype()) for i in range(N_WINDOWS+1)]
interval_splits = pd.concat(interval_splits, axis=1)
interval_splits = interval_splits.join(vaso_episodes[["SUBJECT_ID","HADM_ID"]])
print_log("\tsaving intervals to database `PressorGauge` in table `intervals`")
with engine.connect() as connection:
interval_splits.to_sql("interval_splits", con=connection, if_exists="replace", index_label="ICUSTAY_ID")
print_log("Done computing intervals!")
print_log()
# execute only if run as a script
if __name__ == "__main__":
main()
|
wrs28/safe_extubation | src/modeling/preprocess_data.py | import os
import pandas as pd
import pickle
import numpy as np
from sklearn import preprocessing, impute
import directories
RND_SEED = 1729
def preprocess_training_inputs():
with open(os.path.join(directories.model_dir,"training_features.p"),"rb") as file:
training_inputs = pickle.load(file)
# ground truth
training_outputs = training_inputs.pop("LABEL")
# encode F/M as 1/0
enc = preprocessing.OrdinalEncoder().fit(pd.DataFrame(training_inputs.GENDER))
training_inputs.GENDER = enc.transform(pd.DataFrame(training_inputs.GENDER))
# extract epoch (number of 6-hr windows away from pressor event)
# and patient-tag indicating pressor nor not (observed label)
# and subject ID
training_times = training_inputs.pop("EPOCH")
pressor_at_all = training_inputs.pop("EPISODE")
pressor_at_all = pressor_at_all==1
training_groups = training_inputs.pop("SUBJECT_ID").values
hadm_id = training_inputs.pop("HADM_ID")
scaler = preprocessing.StandardScaler().fit(training_inputs)
with open(os.path.join(directories.model_dir,"scaler_encoder.p"), "wb") as file:
pickle.dump({"scaler": scaler,"encoder": enc}, file)
X = training_inputs
X = pd.DataFrame(X,columns=training_inputs.columns)
X["EPOCH"] = training_times.values
X["PRESSOR_AT_ALL"] = pressor_at_all.values
X["SUBJECT_ID"] = training_groups
X["HADM_ID"] = hadm_id.values
y = training_outputs.values.astype(int)
with open(os.path.join(directories.model_dir,"training_set.p"),"wb") as file:
pickle.dump({"X": X, "y": y, "cv_groups": training_groups}, file)
def preprocess_test_inputs():
with open(os.path.join(directories.model_dir, "test_features.p"), "rb") as file:
test_inputs = pickle.load(file)
# ground truth
test_outputs = test_inputs.pop("LABEL")
# encode F/M as 1/0
with open(os.path.join(directories.model_dir, "scaler_encoder.p"), "rb") as file:
dict = pickle.load(file)
enc = dict["encoder"]
test_inputs.GENDER = enc.transform(pd.DataFrame(test_inputs.GENDER))
# extract epoch (number of 6-hr windows away from pressor event)
# and patient-tag indicating pressor nor not (observed label)
# and subject ID
test_times = test_inputs.pop("EPOCH")
pressor_at_all = test_inputs.pop("EPISODE")
pressor_at_all = pressor_at_all==1
test_groups = test_inputs.pop("SUBJECT_ID").values
hadm_id = test_inputs.pop("HADM_ID")
X = test_inputs
X = pd.DataFrame(X,columns=test_inputs.columns)
X["EPOCH"] = test_times.values
X["PRESSOR_AT_ALL"] = pressor_at_all.values
X["SUBJECT_ID"] = test_groups
X["HADM_ID"] = hadm_id.values
y = test_outputs.values.astype(int)
with open(os.path.join(directories.model_dir,"test_set.p"),"wb") as file:
pickle.dump({"X": X, "y": y, "cv_groups": test_groups}, file)
def main():
directories.print_log("preprocessing data")
directories.print_log("\tpreparing training set")
preprocess_training_inputs()
directories.print_log("\tpreparing test set")
preprocess_test_inputs()
directories.print_log("done preprocessing data!")
directories.print_log()
# execute only if run as a script
if __name__ == "__main__":
main()
|
wrs28/safe_extubation | src/modeling/feature_definitions.py | <reponame>wrs28/safe_extubation
import numpy as np
import pandas as pd
features_to_keep = [
# # "LODS",
#
# # "OASIS",
#
# # "APACHE",
#
# # "CARDIOVASCULAR_LODS",
#
# # "PULMONARY_LODS",
#
"AGE",
#
"TOTAL_FLAG_COUNT",
#
"GENDER", # really sex
#
"WEIGHT_KG",
#
# # "lc_MIN",
# # "lc_MAX",
# # "lc_MEAN",
"lactate_FLAG_COUNT",
#
# "pCO2_MIN",
# "pCO2_MAX",
"pCO2_LAST",
# # "pCO2_MEAN",
# "pCO2_FLAG_COUNT",
# "pCO2_RHO",
#
# "pH_MIN",
"pH_LAST",
# "pH_MAX",
# # "pH_MEAN",
# "pH_FLAG_COUNT",
# "pH_RHO",
#
# "pO2_MIN",
# "pO2_MAX",
"pO2_LAST",
# # "pO2_MEAN",
# "pO2_FLAG_COUNT",
# "pO2_RHO",
#
# # "pO2_MIN",
# # "gc_MAX",
# # "pO2_MEAN",
# "glucose_FLAG_COUNT",
# "lipase_FLAG_COUNT",
# "troponin_FLAG_COUNT",
# "bilirubin_direct_FLAG_COUNT",
# "bilirubin_total_FLAG_COUNT",
#
# # "alt_MIN",
# # "alt_MAX",
# # "alt_MEAN",
"ALT_FLAG_COUNT",
#
# # "ast_MIN",
# # "ast_MAX",
# # "ast_MEAN",
"AST_FLAG_COUNT",
#
# # "alb_MIN",
# # "alb_MAX",
# # "alb_MEAN",
"albumin_FLAG_COUNT",
#
# # "ap_MIN",
# # "ap_MAX",
# # "ap_MEAN",
"alkaline_phosphatase_FLAG_COUNT",
#
# # "ag_MIN",
# "ag_MAX",
"anion_gap_LAST",
# # "ag_MEAN",
# "ag_FLAG_COUNT",
# "ag_RHO",
#
# "ct_MIN",
# "ct_MAX",
"creatinine_LAST",
# # "ct_MEAN",
# "ct_FLAG_COUNT",
# "ct_RHO",
#
"chloride_LAST",
# # "chl_MAX",
# "cl_MEAN",
# "cl_FLAG_COUNT",
# "cl_RHO",
#
"sodium_LAST",
# # "sod_MAX",
# # "sod_MEAN",
# "na_FLAG_COUNT",
# "na_RHO",
#
"potassium_LAST",
# # "pot_MAX",
# # "pot_MEAN",
# "k_FLAG_COUNT",
# "k_RHO",
#
# "pc_MIN",
"platelet_count_LAST",
# # "pc_MAX",
# # "pc_MEAN",
# "pc_FLAG_COUNT",
# "pc_RHO",
#
# # "un_MIN",
# "bun_MAX",
"bun_LAST",
# # "un_MEAN",
# "bun_FLAG_COUNT",
# "bun_RHO",
#
# # "bcb_MIN",
# "hcO3_MAX",
"hcO3_LAST",
# "hcO3_FLAG_COUNT",
# "hcO3_RHO",
#
# # "pt_MIN",
# # "pt_MAX",
# # "pt_MEAN",
# "pt_FLAG_COUNT",
#
# # "inrpt_MIN",
# # "inrpt_MAX",
# # "inrpt_MEAN",
# "inrpt_FLAG_COUNT",
#
# # "ptt_MIN",
# "ptt_MAX",
"ptt_LAST",
# # "ptt_MEAN",
# "ptt_FLAG_COUNT",
# "ptt_RHO",
#
# "wbc_MIN",
# "wbc_MAX",
# # "wbc_MEAN",
"wbc_FLAG_COUNT",
# "wbc_RHO",
#
# "hg_MIN",
"hemoglobin_LAST",
# # "hg_MAX",
# # "hg_MEAN",
# "hg_FLAG_COUNT",
# "hg_RHO",
#
# "hmc_MIN",
"hematocrit_LAST",
# # "hmc_MAX",
# "hmc_MEAN",
# "hmc_FLAG_COUNT",
]
def find_first(row):
arr = row.values
idx = arr.argmax()
if arr[idx]:
return idx
else:
return None#len(arr) - 1
def find_last(row):
arr = row.values
return find_first(pd.Series(arr[::-1]))
def first(arr):
return find_first(~arr.isna())
def last(arr):
return arr.iloc[-1]#find_last(~arr.isna())
def attach_lab_features(data, lab):
group = lab.groupby("HADM_ID")
df_tot_flag_count = (group.FLAG.value_counts()/group.HADM_ID.size()).unstack().fillna(0).abnormal
df_tot_flag_count.name = "TOTAL_FLAG_COUNT"
df_tot_flag_count = df_tot_flag_count.reset_index()
# df_tot_flag_count.rename({"FLAG": "TOTAL_FLAG_COUNT"}, inplace=True, axis=1)
data = data.join(df_tot_flag_count.set_index("HADM_ID"), on="HADM_ID", how="left")
df_last_time = group.HOURS_BEFORE_PRESSOR.min()
df_last_time = df_last_time.reset_index()
df_last_time.rename({"HOURS_BEFORE_PRESSOR": "LAST_LAB_TIME"}, inplace=True, axis=1)
data = data.join(df_last_time.set_index("HADM_ID"), on="HADM_ID", how="left")
# df_pressor_at_all = group.PRESSOR_AT_ALL.any()
# df_pressor_at_all = df_pressor_at_all.reset_index()
# data = data.join(df_pressor_at_all.set_index("HADM_ID"), on="HADM_ID", how="left")
for feature in features:
ident = "HADM_ID"
chartlab = lab
ab = features[feature]["ab"]
group = chartlab.groupby(ident)
if len(group)>0:
df_flag_count = (group.FLAG.value_counts()).unstack().fillna(0).abnormal
df_flag_count.name = "FLAG"
df_flag_count = (df_flag_count>0).astype(int)
df_flag_count = df_flag_count.reset_index()
df_flag_count.rename({"FLAG": ab + "_FLAG_COUNT"}, inplace=True, axis=1)
group = chartlab.loc[chartlab.ITEMID.isin(features[feature]["V"])].groupby(ident)
if len(group)>0:
# df_flag_count = (group.FLAG.value_counts()/group.size()).unstack().fillna(0).abnormal
df_flag_count = (group.FLAG.value_counts()).unstack().fillna(0).abnormal
df_flag_count.name = "FLAG"
df_flag_count = (df_flag_count>0).astype(int)
df_flag_count = df_flag_count.reset_index()
df_flag_count.rename({"FLAG": ab + "_FLAG_COUNT"}, inplace=True, axis=1)
# df_flag_count = pd.DataFrame{}
# df_first = group.agg({"VALUENUM" : first, "CHARTTIME" : first})
# df_first.rename(columns={"VALUENUM" : ab + "_FIRST", "CHARTTIME" : ab + "_FIRST_TIME"}, inplace=True)
# df_first.reset_index(inplace=True)
df_last = group.agg({"VALUENUM" : last})#, "CHARTTIME" : last})
# df_last.rename(columns={"VALUENUM" : ab + "_LAST" , "CHARTTIME" : ab + "_LAST_TIME"}, inplace=True)
df_last.rename(columns={"VALUENUM" : ab + "_LAST"}, inplace=True)
df_last.reset_index(inplace=True)
df_mean = group.agg({"VALUENUM" : np.mean})
df_mean.rename(columns={"VALUENUM" : ab + "_MEAN"}, inplace=True)
df_mean.reset_index(inplace=True)
# df_std = group.agg({"VALUENUM" : np.std})
# df_std.rename(columns={"VALUENUM" : ab + "_STD"}, inplace=True)
# df_std.reset_index(inplace=True)
df_min = group.agg({"VALUENUM" : np.min})
df_min.rename(columns={"VALUENUM" : ab + "_MIN"}, inplace=True)
df_min.reset_index(inplace=True)
df_max = group.agg({"VALUENUM" : np.max})
df_max.rename(columns={"VALUENUM" : ab + "_MAX"}, inplace=True)
df_max.reset_index(inplace=True)
# df_first = group.agg({"VALUENUM" : first})
# df_last = group.agg({"VALUENUM" : last})
# df_rho = df_first-df_last
# df_rho.rename(columns={"VALUENUM" : ab + "_RHO"}, inplace=True)
# df_rho.reset_index(inplace=True)
data = data.join(df_flag_count.set_index(ident), on=ident, how="left")
data = data.join(df_last.set_index(ident), on=ident, how="left")
data = data.join(df_mean.set_index(ident) , on=ident, how="left")
# data = data.join(df_std.set_index(ident) , on=ident, how="left")
data = data.join(df_min.set_index(ident) , on=ident, how="left")
data = data.join(df_max.set_index(ident) , on=ident, how="left")
# data = data.join(df_rho.set_index(ident) , on=ident, how="left")
# data[ab + "_RATE"] = 60*(data[ab + "_LAST"] - data[ab + "_FIRST"])/((data[ab + "_LAST_TIME"] - data[ab + "_FIRST_TIME"]))
return data
def clean_data(data):
data = data.copy()
data.loc[data.WEIGHT_KG<25, "WEIGHT_KG"] = np.nan
for key in features:
feature = features[key]
ab = feature["ab"]
for suffix in ["MIN","MAX","MEAN","LAST"]: #,"RHO","STD","RATE"]:
col_name = ab + "_" + suffix
data.loc[data[ab + "_MIN"] <= feature["min"],col_name] = np.nan
data.loc[data[ab + "_MAX"] >= feature["max"],col_name] = np.nan
# data.loc[data[ab + "_RHO"] >= 1000, col_name] = np.nan
# clean_data.loc[clean_data[ab + "_RATE"] == np.inf,col_name] = np.nan
# clean_data.loc[clean_data[ab + "_RATE"] == -np.inf,col_name] = np.nan
return data
features = {
"lactate" : {
"ab": "lactate",
"S" : "L",
"V" : [50813],
"min" : 0,
"max" : 50
},
"pCO2" : {
"ab": "pCO2",
"S" : "L",
"V" : [50818],
"min" : 0,
"max" : np.inf
},
"pH" : { # *
"ab": "pH",
"S" : "L",
"V" : [50820],
"min" : 6,
"max" : 8
},
"pO2" : {
"ab": "pO2",
"S" : "L",
"V" : [50821],
"min" : 0,
"max" : 800
},
"ALT" : {
"ab": "ALT",
"S" : "L",
"V" : [50861],
"min" : 0,
"max" : np.inf
},
"albumin" : {
"ab" : "albumin",
"S" : "L",
"V" : [50862],
"min" : 0,
"max" : 10
},
"alkaline phosphatase" : {
"ab": "alkaline_phosphatase",
"S" : "L",
"V" : [50863],
"min" : 0,
"max" : np.inf
},
"anion gap" : {
"ab": "anion_gap",
"S" : "L",
"V" : [50868],
"min" : 0,
"max" : 10000
},
"AST" : {
"ab": "AST",
"S" : "L",
"V" : [50878],
"min" : 0,
"max" : np.inf
},
"bicarbonate" : {
"ab": "hcO3",
"S" : "L",
"V" : [50882],
"min" : 0,
"max" : 10000
},
"bilirubin direct" : {
"ab": "bilirubin_direct",
"S" : "L",
"V" : [50883],
"min": 0,
"max": 150
},
"bilirubin total" : {
"ab": "bilirubin_total",
"S" : "L",
"V" : [50885],
"min": 0,
"max": 150
},
"chloride" : {
"ab": "chloride",
"S" : "L",
"V" : [50902],
"min" : 0,
"max" : 10000
},
"creatinine" : { # *
"ab": "creatinine",
"S" : "L",
"V" : [50912],
"min" : 0,
"max" : 150
},
# "estimated GFR" : {
# "ab": "gfr",
# "S" : "L",
# "V" : [50920]
# },
"lipase" : {
"ab" : "lipase",
"S" : "L",
"V" : [50956],
"min" : 0,
"max" : np.inf
},
"glucose" : {
"ab" : "glucose",
"S" : "L",
"V" : [50931],
"min" : 0,
"max" : np.inf
},
"potassium" : {
"ab" : "potassium",
"S" : "L",
"V" : [50971],
"min" : 0,
"max" : 30
},
"sodium" : {
"ab": "sodium",
"S" : "L",
"V" : [50824, 50983],
"min" : 0,
"max" : 200
},
"troponin I" : {
"ab" : "troponin",
"S" : "L",
"V" : [51002],
"min" : 0,
"max" : np.inf
},
"urea nitrogen" : {
"ab": "bun",
"S" : "L",
"V" : [51006],
"min" : 0,
"max" : 300
},
"INR PT" : {
"ab" : "inrpt",
"S" : "L",
"V" : [51237],
"min" : 0,
"max" : np.inf
},
"PT" : {
"ab" : "pt",
"S" : "L",
"V" : [51274],
"min" : 0,
"max" : np.inf
},
"hematocrit" : {
"ab": "hematocrit",
"S" : "L",
"V" : [51221],
"min" : 0,
"max" : 100
},
"hemoglobin" : { # *
"ab": "hemoglobin",
"S" : "L",
"V" : [50811,51222],
"min" : 0,
"max" : 150
},
"platelet count" : {
"ab": "platelet_count",
"S" : "L",
"V" : [51265],
"min" : 0,
"max" : 10000
},
"PTT" : {
"ab": "ptt",
"S" : "L",
"V" : [51275],
"min" : 0,
"max" : 150
},
"wbc" : {
"ab": "wbc",
"S" : "L",
"V" : [51300,51301],
"min" : 0,
"max" : 1000
},
# "systolic blood pressure" : {
# "ab": "sbp",
# "S" : "C",
# "V" : [51,442,455,6701,220179,220050],
# "min" : 0,
# "max" : 400
# },
#
# "diastolic blood pressure" : {
# "ab": "dbp",
# "S" : "C",
# "V" : [8368,8440,8441,8555,220180,220051],
# "min" : 0,
# "max" : 300
# },
#
# "mean blood pressure" : {
# "ab": "mbp",
# "S" : "C",
# "V" : [456,52,6702,443,220052,220181,225312],
# "min" : 0,
# "max" : 400
# },
#
# "heart rate" : {
# "ab": "hr",
# "S" : "C",
# "V" : [211,220045],
# "min" : 0,
# "max" : 300
# },
#
# "respiratory rate" : {
# "ab": "rr",
# "S" : "C",
# "V" : [615,618,220210,224690],
# "min" : 0,
# "max" : 70
# },
#
# "glucose" : {
# "ab": "gc",
# "S" : "L",
# "V" : [50931],
# "min" : 0,
# "max" : 10000
# },
#
# "spO2" : {
# "ab": "spO2",
# "S" : "C",
# "V" : [646, 220277],
# "min" : 0,
# "max" : 100
# },
}
|
wrs28/safe_extubation | src/modeling/split_data.py | <filename>src/modeling/split_data.py
import pandas as pd
import pickle
import os
from sklearn import model_selection
import directories
RND_SEED = 2 # random seed used throughout
TEST_SIZE_FRACTION = .1 # fraction of data is set aside for testing
def main():
with directories.engine.connect() as connection:
pressors_by_icustay = pd.read_sql("pressors_by_icustay", con=connection, index_col="ICUSTAY_ID")
X = pressors_by_icustay.groupby("SUBJECT_ID").agg({"EPISODE": "max"}).reset_index()
y = X.pop("EPISODE")
directories.print_log("splitting train, validation, and test sets", mode="w")
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=TEST_SIZE_FRACTION, random_state=RND_SEED, stratify=y)
directories.print_log("\t",len(X_train),"training samples")
directories.print_log("\t",len(X_test),"testing samples")
directories.print_log("\t saving train and test set identifiers")
with open(os.path.join(directories.model_dir,"training_subjects.p"), "wb") as file:
pickle.dump(X_train, file)
with open(os.path.join(directories.model_dir,"test_subjects.p"), "wb") as file:
pickle.dump(X_test, file)
directories.print_log("done splitting data!")
directories.print_log()
# execute only if run as a script
if __name__ == "__main__":
main()
|
wrs28/safe_extubation | src/modeling/lab_explorer.py | import os
import pandas as pd
import sys
mimic_dir = "/Volumes/gaia/mimic"
d_items = pd.read_csv(os.path.join(mimic_dir,"D_LABITEMS.csv"))
def find_label(label, category=None):
if not category:
return d_items[d_items.LABEL.str.contains(label,na=False)]
else:
return d_items[d_items.LABEL.str.contains(label,na=False) & d_items.CATEGORY.str.contains(category,na=False)]
def main():
label = sys.argv[0]
if len(sys.argv) < 3:
category = sys.argv[2]
else:
category = None
print(find_label(label, category))
# execute only if run as a script
if __name__ == "__main__":
main()
|
lengthmin/multi-user-git-hook | pre-commit.py | <filename>pre-commit.py
#!/usr/bin/env python
import os
from configparser import ConfigParser
from pathlib import Path
exit_code = os.system("git config --local user.email >/dev/null")
if (exit_code >> 8) == 0:
exit(0)
config = ConfigParser()
config.read(Path("~/.gitconfig").expanduser())
section_name = "multi"
sections = config.sections()
pwd = str(Path(".").absolute())
print("pwd: ", pwd)
for section in sections:
if section.startswith(section_name):
dct = dict(config[section].items())
to_set = {}
part = dct.pop("has", "")
flag = part in pwd
for key, value in dct.items():
command = ".".join(key.split("-"))
to_set[command] = value
if flag:
for k, v in to_set.items():
cmd = f"git config --local {k} {v}"
os.system(cmd)
print(cmd)
print(
"Setting local info\n",
"Commit again if these are correct.",
)
exit(1)
|
CovidZero/Crawler | app.py | <reponame>CovidZero/Crawler<gh_stars>1-10
#!/usr/bin/env python
# coding: utf-8
# In[12]:
import urllib3
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import datetime
import os
import subprocess as cmd
import argparse
from config import BUCKET_NAME, LINKS_REPO, PROG_NAME, VERSION, PASTA_RESULTADO, REPO_URL, ESTADOS
import sys
import boto3
import aiohttp
import asyncio
import time
#Projeto https://covidzero.com.br/
SITES_COM_PROBLEMAS = []
SITES_VERIFICADOS = []
start_time = time.time()
def LerArquivo(subdiretorio):
x = datetime.datetime.now()
data = x.strftime("%Y%m%d")
arq = open(subdiretorio,'r', encoding='utf-8')
#print(arq.read())
lista = []
for item in arq:
#print(item)
lista.append(str(item).strip())
print(lista)
arq.close()
return lista
def gravarNoArquivoUrl(n1,n2,diretorio):
x = datetime.datetime.now()
data = x.strftime('%d-%m-%Y_%H')
create_directory(diretorio)
arquivo = open(diretorio+'\\covidZero_resultado_'+ data+'.csv', 'a',encoding='utf-8')
arquivo.write('%s;%s\n' %(n1,n2))
arquivo.flush()
arquivo.close()
def create_directory(dirName):
if not os.path.exists(dirName):
os.makedirs(dirName)
async def fetch(pagina, novas_paginas, diretorio, estado):
async with aiohttp.ClientSession() as session:
async with session.get(pagina) as resp:
if (resp.status == 200 and ('text/html' in resp.headers.get('content-type'))):
data = (await resp.read()).decode('utf-8', 'replace')
SITES_VERIFICADOS.append(pagina)
return varrendo_pagina(data, pagina, novas_paginas, diretorio, estado)
def varrendo_pagina(data, pagina, novas_paginas, diretorio, estado):
sopa = BeautifulSoup(data,'lxml')
print('\n**** Crawling noticias de {} ******\n'.format(estado))
print('Url utilizada {}'.format(pagina))
bolsolinks = set()
links = sopa.find_all('a')
contador = 1
for link in links:
if ('title' in link.attrs):
title = str(link.get('title').lower())
url = urljoin(pagina, str(link.get('href')))
if title.__contains__('coronavirus') or title.__contains__('COVID-19') or title.__contains__('covid'):
if url[-1] == '/':
tamanho = len(url)
url = url[:tamanho-1]
bolsolinks.add(url)
if ('href' in link.attrs):
url = urljoin(pagina, str(link.get('href')))
if url.find("'") != -1:
continue
url = url.split('#')[0]
if url[0:4] == 'http' or url[0:5] == 'https':
novas_paginas.add(url)
if url.__contains__('coronavirus') or url.__contains__('COVID-19') or url.__contains__('covid'):
if url[-1] == '/':
tamanho = len(url)
url = url[:tamanho-1]
bolsolinks.add(url)
contador = contador + 1
for bolso in bolsolinks:
gravarNoArquivoUrl(pagina,bolso,diretorio)
async def crawl(estado, paginas, profundidade, diretorio):
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
for i in range(profundidade):
novas_paginas = set()
for pagina in paginas:
try:
await fetch(pagina, novas_paginas, diretorio, estado)
except Exception as exc:
print('Erro ao abrir a página ' + pagina)
print (exc)
SITES_COM_PROBLEMAS.append(pagina)
continue
def parse_argumentos(args):
formatter_class = argparse.RawDescriptionHelpFormatter
parser = argparse.ArgumentParser(prog=PROG_NAME,formatter_class=formatter_class)
parser.add_argument("--version", action="version", version="%(prog)s {}".format(VERSION))
parser.add_argument('--salvar', action='store_true', default=False,
help="Indica se o resultado da execução deve ser salvo no respositorio de Arquivos")
parser.add_argument('--salvars3', action='store_true', default=False,
help="Indica se o resultado da execução deve ser salvo no respositorio de Arquivos") #Refatorar para o salvar ser uma lista de opções
parser.add_argument('--links', action='store', default=PASTA_RESULTADO,
help="define o caminho para carregar os links por estado")
return parser.parse_args(args)
def salvar_resultado(url):
#Importante adicionar [O upstream] git remote add upstream {reposiorio de Arquivos}
#Commit no Git upstream
cp = cmd.run("git remote add upstream {}".format(url), check=True, shell=True)
cp = cmd.run("git init", check=True, shell=True)
cp = cmd.run("git add Estados", check=True, shell=True)
cp = cmd.run(f'git commit -m "Atualizando"', check=True, shell=True)
cp = cmd.run(f"git push upstream master -f", check=True, shell=True)
def get_url_estado(estado):
return LINKS_REPO.format(estado)
def salvar_no_S3(caminho_arquivos):
try:
s3_resource = boto3.resource('s3')
for root, estados, arquivos in os.walk(caminho_arquivos, topdown=True):
for arquivo in arquivos:
(base, ext) = os.path.splitext(arquivo)
if ext == '.csv':
nome_arquivo = os.path.join(root, arquivo)
key = os.path.join(root.replace('.', ''), arquivo).replace('\\', '/')[1:]
print ("Salvando arquivo {} no S3".format(nome_arquivo))
s3_resource.Bucket(BUCKET_NAME).upload_file(Filename=nome_arquivo, Key=key)
os.remove(nome_arquivo)
except Exception as exc:
print("Erro ao salvar no S3")
print(exc)
def get_sites_por_estado(url_estado, estado):
print('Buscando urls para o estado {}'.format(estado))
http = urllib3.PoolManager()
r = http.request('GET', url_estado)
if (r.status == 200):
return str(r.data.decode('utf-8')).split('\n')
def executa_crawler(args):
path = args.links
tasks = []
loop = asyncio.get_event_loop()
for estado in ESTADOS:
url = get_url_estado(estado)
sites = get_sites_por_estado(url, estado)
pathSub = path + '\\'+ estado
tasks.append(loop.create_task(crawl(estado, sites, 1, pathSub)))
loop.run_until_complete(asyncio.wait(tasks))
print('Lista de sites com problemas')
print('\n'.join(map(str, SITES_COM_PROBLEMAS)))
print('*** Total de sites com verificados {}'.format(len(SITES_VERIFICADOS)))
print('*** Total de sites com problemas {}'.format(len(SITES_COM_PROBLEMAS)))
if __name__ == '__main__':
##Obs se for necessario podemos fazer pela rede tor, para nao entrarmos na black list dos sites
try:
print('*** iniciando processo de crawler noticias...\n')
args = arguments = parse_argumentos(sys.argv[1:])
executa_crawler(args)
if (args.salvars3):
salvar_no_S3(PASTA_RESULTADO)
if (args.salvar):
salvar_resultado(REPO_URL)
tempo_total = (time.time() - start_time) / 60
print('*** Tempo total de execução {:d} minutos'.format(int(tempo_total)))
except Exception as exc:
print(exc)
|
CovidZero/Crawler | config.py | <filename>config.py
#!/usr/bin/env python
# coding: utf-8
import os
PROG_NAME = 'Crawler_COVID'
VERSION = '1.0.0.0'
PASTA_RESULTADO = '.\Estados'
REPO_URL = os.getenv('REPO_URL','https://github.com/CovidZero/Arquivo.git')
LINKS_REPO = os.getenv('LINKS_REPO','https://raw.githubusercontent.com/CovidZero/Arquivo/master/Estados/{}/lista_sites.txt')
ESTADOS = ['AC', 'AL', 'AM', 'AP', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MG', 'MS', 'MT',
'PA', 'PB', 'PE', 'PI', 'PR', 'RJ', 'RN', 'RO', 'RR', 'RS', 'SC', 'SE', 'SP', 'TO']
BUCKET_NAME = os.getenv('BUCKET_NAME','crawler-engdados')
AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID', '')
AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY', '')
|
Pangoraw/pointnet2 | models/pointnet2_part_seg.py | import os
import sys
BASE_DIR = os.path.dirname(__file__)
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, '../utils'))
import tensorflow as tf
import numpy as np
import tf_util
from pointnet_util import pointnet_sa_module, pointnet_fp_module
def placeholder_inputs(batch_size, num_point):
pointclouds_pl = tf.placeholder(tf.float32, shape=(batch_size, num_point, 3))
labels_pl = tf.placeholder(tf.int32, shape=(batch_size, num_point))
return pointclouds_pl, labels_pl
def get_model(point_cloud, is_training, bn_decay=None):
""" Part segmentation PointNet, input is BxNx6 (XYZ NormalX NormalY NormalZ), output Bx50 """
batch_size = point_cloud.get_shape()[0].value
num_point = point_cloud.get_shape()[1].value
end_points = {}
l0_xyz = tf.slice(point_cloud, [0,0,0], [-1,-1,3])
# l0_points = tf.slice(point_cloud, [0,0,3], [-1,-1,3])
l0_points = None
# Set Abstraction layers
l1_xyz, l1_points, l1_indices = pointnet_sa_module(l0_xyz, l0_points, npoint=512, radius=0.2, nsample=64, mlp=[64,64,128], mlp2=None, group_all=False, is_training=is_training, bn_decay=bn_decay, scope='layer1')
l2_xyz, l2_points, l2_indices = pointnet_sa_module(l1_xyz, l1_points, npoint=128, radius=0.4, nsample=64, mlp=[128,128,256], mlp2=None, group_all=False, is_training=is_training, bn_decay=bn_decay, scope='layer2')
l3_xyz, l3_points, l3_indices = pointnet_sa_module(l2_xyz, l2_points, npoint=None, radius=None, nsample=None, mlp=[256,512,1024], mlp2=None, group_all=True, is_training=is_training, bn_decay=bn_decay, scope='layer3')
# Feature Propagation layers
l2_points = pointnet_fp_module(l2_xyz, l3_xyz, l2_points, l3_points, [256,256], is_training, bn_decay, scope='fa_layer1')
l1_points = pointnet_fp_module(l1_xyz, l2_xyz, l1_points, l2_points, [256,128], is_training, bn_decay, scope='fa_layer2')
# l0_points = pointnet_fp_module(l0_xyz, l1_xyz, tf.concat([l0_xyz,l0_points],axis=-1), l1_points, [128,128,128], is_training, bn_decay, scope='fa_layer3')
l0_points = pointnet_fp_module(l0_xyz, l1_xyz, l0_xyz, l1_points, [128,128,128], is_training, bn_decay, scope='fa_layer3')
# FC layers
net = tf_util.conv1d(l0_points, 128, 1, padding='VALID', bn=True, is_training=is_training, scope='fc1', bn_decay=bn_decay)
end_points['feats'] = net
net = tf_util.dropout(net, keep_prob=0.5, is_training=is_training, scope='dp1')
net = tf_util.conv1d(net, 5, 1, padding='VALID', activation_fn=None, scope='fc2')
return net, end_points
def get_loss(pred, label):
""" pred: BxNxC,
label: BxN, """
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=pred, labels=label)
classify_loss = tf.reduce_mean(loss)
tf.summary.scalar('classify loss', classify_loss)
tf.add_to_collection('losses', classify_loss)
return classify_loss
if __name__=='__main__':
with tf.Graph().as_default():
inputs = tf.zeros((32,2048,3))
net, _ = get_model(inputs, tf.constant(True))
print(net)
|
Pangoraw/pointnet2 | part_seg/face_dataset.py | """
Face dataset
"""
import os
import os.path
import h5py
import numpy as np
class FaceDataset():
def get_data_file(self):
file = os.path.join(self.root, "{}_hdf5_file_list.txt".format(self.split))
with open(file, "r") as f:
files = [ls.rstrip() for ls in f]
return files
def __init__(self, root, npoints=2048, classification=False, split='train', normalize=True, return_cls_label=False):
self.npoints = npoints
self.root = root
self.split = split
self.catfile = os.path.join(self.root, 'all_object_categories.txt')
self.cat = {}
self.classification = classification
self.return_cls_label = return_cls_label
with open(self.catfile, 'r') as f:
for line in f:
ls = line.strip().split()
self.cat[ls[0]] = ls[1]
self.cat = {k: v for k, v in self.cat.items()}
data_files = self.get_data_file()
file_path = os.path.join(self.root, data_files[0])
store = h5py.File(file_path, 'r')
samples = store['data'].value
labels = store['label'].value
segs = store['pid'].value
self.samples = samples
self.labels = labels
self.segs = segs
classes = np.unique(segs.reshape(-1, ))
self.seg_classes = {0: classes}
self.n_classes = classes.shape[0]
self.classes = {0: 'face'}
def __getitem__(self, index):
if self.classification:
return self.samples[index], self.labels[index]
elif self.return_cls_label:
return self.samples[index], self.segs[index], self.labels[index]
else:
return self.samples[index], self.segs[index]
def __len__(self):
return self.samples.shape[0]
|
zhutchens1/g3groups | create_ecoresolve_stellarmassselgroups.py | """
<NAME> - November 2020
This program creates stellar mass-selected group catalogs for ECO/RESOLVE-G3 using the new algorithm, described in the readme markdown.
The outline of this code is:
(1) Read in observational data from RESOLVE-B and ECO (the latter includes RESOLVE-A).
(2) Prepare arrays of input parameters and for storing results.
(3) Perform FoF only for giants in ECO, using an adaptive linking strategy.
(a) Get the adaptive links for every ECO galaxy.
(b) Fit those adaptive links for use in RESOLVE-B.
(c) Perform giant-only FoF for ECO
(d) Perform giant-only FoF for RESOLVE-B, by interpolating the fit to obtain separations for RESOLVE-B.
(4) From giant-only groups, fit model for individual giant projected radii and peculiar velocites, to use for association.
(5) Associate dwarf galaxies to giant-only FoF groups for ECO and RESOLVE-B (note different selection floors for dwarfs).
(6) Based on giant+dwarf groups, calibrate boundaries (as function of giant+dwarf integrated stellar mass) for iterative combination
(7) Iterative combination on remaining ungrouped dwarf galaxies
(8) halo mass assignment
(9) Finalize arrays + output
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from scipy.optimize import curve_fit
from center_binned_stats import center_binned_stats
import foftools as fof
import iterativecombination as ic
import virtools as vz
from smoothedbootstrap import smoothedbootstrap as sbs
import sys
from scipy.interpolate import UnivariateSpline
import virtools as vz
from lss_dens import lss_dens_by_galaxy
#def giantmodel(x, a, b, c, d):
# return a*np.log(np.abs(b)*x+c)+d
def giantmodel(x, a, b):
return np.abs(a)*np.log(np.abs(b)*x+1)
def exp(x, a, b, c):
return np.abs(a)*np.exp(1*np.abs(b)*(x) + c)
#return a*np.exp(b*(x**2) + c*(x) + d)+np.abs(e)
def sepmodel(x, a, b, c, d, e):
#return np.abs(a)*np.exp(-1*np.abs(b)*x + c)+d
#return a*(x**3)+b*(x**2)+c*x
return a*(x**4)+b*(x**3)+c*(x**2)+(d*x)+e
def sigmarange(x):
q84, q16 = np.percentile(x, [84 ,16])
return (q84-q16)/2.
if __name__=='__main__':
####################################
# Step 1: Read in obs data
####################################
ecodata = pd.read_csv("ECOdata_022521.csv")
resolvedata = pd.read_csv("RESOLVEdata_022521.csv")
resolvebdata = resolvedata[resolvedata.f_b==1]
####################################
# Step 2: Prepare arrays
####################################
ecosz = len(ecodata)
econame = np.array(ecodata.name)
ecoresname = np.array(ecodata.resname)
ecoradeg = np.array(ecodata.radeg)
ecodedeg = np.array(ecodata.dedeg)
ecocz = np.array(ecodata.cz)
ecologmstar = np.array(ecodata.logmstar)
ecologmgas = np.array(ecodata.logmgas)
ecourcolor = np.array(ecodata.modelu_rcorr)
ecog3grp = np.full(ecosz, -99.) # id number of g3 group
ecog3grpn = np.full(ecosz, -99.) # multiplicity of g3 group
ecog3grpradeg = np.full(ecosz,-99.) # ra of group center
ecog3grpdedeg = np.full(ecosz,-99.) # dec of group center
ecog3grpcz = np.full(ecosz,-99.) # cz of group center
ecog3logmh = np.full(ecosz,-99.) # abundance-matched halo mass
ecog3intmstar = np.full(ecosz,-99.) # group-integrated stellar mass
resbana_g3grp = np.full(ecosz,-99.) # for RESOLVE-B analogue dataset
resbsz = int(len(resolvebdata))
resbname = np.array(resolvebdata.name)
resbradeg = np.array(resolvebdata.radeg)
resbdedeg = np.array(resolvebdata.dedeg)
resbcz = np.array(resolvebdata.cz)
resblogmstar = np.array(resolvebdata.logmstar)
resblogmgas = np.array(resolvebdata.logmgas)
resburcolor = np.array(resolvebdata.modelu_rcorr)
resbg3grp = np.full(resbsz, -99.)
resbg3grpn = np.full(resbsz, -99.)
resbg3grpradeg = np.full(resbsz, -99.)
resbg3grpdedeg = np.full(resbsz, -99.)
resbg3grpcz = np.full(resbsz, -99.)
resbg3logmh = np.full(resbsz, -99.)
resbg3intmstar = np.full(resbsz, -99.)
####################################
# Step 3: Giant-Only FOF
####################################
ecogiantsel = (ecologmstar>=9.5) & (ecocz>2530.) & (ecocz<8000.)
# (a) compute sep values for eco giants
ecovolume = 192351.36 # Mpc^3 with h=1 **
meansep0 = (ecovolume/len(ecologmstar[ecogiantsel]))**(1/3.)
# (b) make an interpolation function use this for RESOLVE-B
# (c) perform giant-only FoF on ECO
blos = 1.1
bperp = 0.07 # from Duarte & Mamon 2014
ecogiantfofid = fof.fast_fof(ecoradeg[ecogiantsel], ecodedeg[ecogiantsel], ecocz[ecogiantsel], bperp, blos, meansep0) # meansep0 if fixed LL
ecog3grp[ecogiantsel] = ecogiantfofid
resbana_g3grp[ecogiantsel] = ecogiantfofid # RESOLVE-B analogue dataset
# (d) perform giant-only FoF on RESOLVE-B
resbgiantsel = (resblogmstar>=9.5) & (resbcz>4250) & (resbcz<7300)
resbgiantfofid = fof.fast_fof(resbradeg[resbgiantsel], resbdedeg[resbgiantsel], resbcz[resbgiantsel], bperp, blos, meansep0)
resbg3grp[resbgiantsel] = resbgiantfofid
# (e) check the FOF results
plt.figure()
binv = np.arange(0.5,3000.5,3)
plt.hist(fof.multiplicity_function(ecog3grp[ecog3grp!=-99.], return_by_galaxy=False), bins=binv, histtype='step', linewidth=3, label='ECO Giant-Only FoF Groups')
plt.hist(fof.multiplicity_function(resbg3grp[resbg3grp!=-99.], return_by_galaxy=False), bins=binv, histtype='step', linewidth=1.5, hatch='\\', label='RESOLVE-B Giant-Only FoF Groups')
plt.xlabel("Number of Giant Galaxies per Group")
plt.ylabel("Number of Giant-Only FoF Groups")
plt.yscale('log')
plt.legend(loc='best')
plt.xlim(0,80)
plt.show()
##########################################
# Step 4: Compute Association Boundaries
##########################################
ecogiantgrpra, ecogiantgrpdec, ecogiantgrpcz = fof.group_skycoords(ecoradeg[ecogiantsel], ecodedeg[ecogiantsel], ecocz[ecogiantsel], ecogiantfofid)
relvel = np.abs(ecogiantgrpcz - ecocz[ecogiantsel])
relprojdist = (ecogiantgrpcz + ecocz[ecogiantsel])/100. * ic.angular_separation(ecogiantgrpra, ecogiantgrpdec, ecoradeg[ecogiantsel], ecodedeg[ecogiantsel])/2.0
ecogiantgrpn = fof.multiplicity_function(ecogiantfofid, return_by_galaxy=True)
uniqecogiantgrpn, uniqindex = np.unique(ecogiantgrpn, return_index=True)
keepcalsel = np.where(uniqecogiantgrpn>1)
median_relprojdist = np.array([np.median(relprojdist[np.where(ecogiantgrpn==sz)]) for sz in uniqecogiantgrpn[keepcalsel]])
median_relvel = np.array([np.median(relvel[np.where(ecogiantgrpn==sz)]) for sz in uniqecogiantgrpn[keepcalsel]])
rproj_median_error = np.std(np.array([sbs(relprojdist[np.where(ecogiantgrpn==sz)], 10000, np.median, kwargs=dict({'axis':1 })) for sz in uniqecogiantgrpn[keepcalsel]]), axis=1)
dvproj_median_error = np.std(np.array([sbs(relvel[np.where(ecogiantgrpn==sz)], 10000, np.median, kwargs=dict({'axis':1})) for sz in uniqecogiantgrpn[keepcalsel]]), axis=1)
#rprojslope, rprojint = np.polyfit(uniqecogiantgrpn[keepcalsel], median_relprojdist, deg=1, w=1/rproj_median_error)
#dvprojslope, dvprojint = np.polyfit(uniqecogiantgrpn[keepcalsel], median_relvel, deg=1, w=1/dvproj_median_error)
poptrproj, jk = curve_fit(giantmodel, uniqecogiantgrpn[keepcalsel], median_relprojdist, sigma=rproj_median_error)#, p0=[0.1, -2, 3, -0.1])
poptdvproj,jk = curve_fit(giantmodel, uniqecogiantgrpn[keepcalsel], median_relvel, sigma=dvproj_median_error)#, p0=[160,6.5,45,-600])
rproj_boundary = lambda N: 3*giantmodel(N, *poptrproj) #3*(rprojslope*N+rprojint)
vproj_boundary = lambda N: 4.5*giantmodel(N, *poptdvproj) #4.5*(dvprojslope*N+dvprojint)
assert ((rproj_boundary(1)>0) and (vproj_boundary(1)>0)), "Cannot extrapolate Rproj_fit or dv_proj_fit to N=1"
# get virial radii from abundance matching to giant-only groups
gihaloid, gilogmh, gir280, gihalovdisp = ic.HAMwrapper(ecoradeg[ecogiantsel], ecodedeg[ecogiantsel], ecocz[ecogiantsel], ecologmstar[ecogiantsel], ecog3grp[ecogiantsel],\
ecovolume, inputfilename=None, outputfilename=None)
gilogmh = np.log10(10**gilogmh)# no longer need 7/29: /fof.getmhoffset(280,337,1,1,6))
gihalorvir = (3*(10**gilogmh) / (4*np.pi*337*0.3*2.77e11) )**(1/3.)
gihalon = fof.multiplicity_function(np.sort(ecog3grp[ecogiantsel]), return_by_galaxy=False)
plt.figure()
plt.plot(gihalon, gihalorvir, 'k.')
plt.show()
plt.figure()
sel = (ecogiantgrpn>1)
plt.scatter(gihalon, gihalovdisp, marker='D', color='purple', label=r'ECO HAM Velocity Dispersion')
plt.plot(ecogiantgrpn[sel], relvel[sel], 'r.', alpha=0.2, label='ECO Giant Galaxies')
plt.errorbar(uniqecogiantgrpn[keepcalsel], median_relvel, fmt='k^', label=r'$\Delta v_{\rm proj}$ (Median of $\Delta v_{\rm proj,\, gal}$)',yerr=dvproj_median_error)
tx = np.linspace(1,max(ecogiantgrpn),1000)
plt.plot(tx, giantmodel(tx, *poptdvproj), label=r'$1\Delta v_{\rm proj}^{\rm fit}$')
plt.plot(tx, 4.5*giantmodel(tx, *poptdvproj), 'g', label=r'$4.5\Delta v_{\rm proj}^{\rm fit}$', linestyle='-.')
plt.xlabel("Number of Giant Members")
plt.ylabel("Relative Velocity to Group Center [km/s]")
plt.legend(loc='best')
plt.show()
plt.clf()
plt.scatter(gihalon, gihalorvir, marker='D', color='purple', label=r'ECO Group Virial Radii')
plt.plot(ecogiantgrpn[sel], relprojdist[sel], 'r.', alpha=0.2, label='ECO Giant Galaxies')
plt.errorbar(uniqecogiantgrpn[keepcalsel], median_relprojdist, fmt='k^', label=r'$R_{\rm proj}$ (Median of $R_{\rm proj,\, gal}$)',yerr=rproj_median_error)
plt.plot(tx, giantmodel(tx, *poptrproj), label=r'$1R_{\rm proj}^{\rm fit}$')
plt.plot(tx, 3*giantmodel(tx, *poptrproj), 'g', label=r'$3R_{\rm proj}^{\rm fit}$', linestyle='-.')
plt.xlabel("Number of Giant Members in Galaxy's Group")
plt.ylabel("Projected Distance from Giant to Group Center [Mpc/h]")
plt.legend(loc='best')
#plt.xlim(0,20)
#plt.ylim(0,2.5)
#plt.xticks(np.arange(0,22,2))
plt.show()
####################################
# Step 5: Association of Dwarfs
####################################
ecodwarfsel = (ecologmstar<9.5) & (ecologmstar>=8.9) & (ecocz>2530) & (ecocz<8000)
resbdwarfsel = (resblogmstar<9.5) & (resblogmstar>=8.7) & (resbcz>4250) & (resbcz<7300)
resbana_dwarfsel = (ecologmstar<9.5) & (ecologmstar>=8.7) & (ecocz>2530) & (ecocz<8000)
resbgiantgrpra, resbgiantgrpdec, resbgiantgrpcz = fof.group_skycoords(resbradeg[resbgiantsel], resbdedeg[resbgiantsel], resbcz[resbgiantsel], resbgiantfofid)
resbgiantgrpn = fof.multiplicity_function(resbgiantfofid, return_by_galaxy=True)
ecodwarfassocid, junk = fof.fast_faint_assoc(ecoradeg[ecodwarfsel],ecodedeg[ecodwarfsel],ecocz[ecodwarfsel],ecogiantgrpra,ecogiantgrpdec,ecogiantgrpcz,ecogiantfofid,\
rproj_boundary(ecogiantgrpn),vproj_boundary(ecogiantgrpn))
resbdwarfassocid, junk = fof.fast_faint_assoc(resbradeg[resbdwarfsel],resbdedeg[resbdwarfsel],resbcz[resbdwarfsel],resbgiantgrpra,resbgiantgrpdec,resbgiantgrpcz,resbgiantfofid,\
rproj_boundary(resbgiantgrpn),vproj_boundary(resbgiantgrpn))
resbana_dwarfassocid, jk = fof.fast_faint_assoc(ecoradeg[resbana_dwarfsel], ecodedeg[resbana_dwarfsel], ecocz[resbana_dwarfsel], ecogiantgrpra, ecogiantgrpdec, ecogiantgrpcz, ecogiantfofid,\
rproj_boundary(ecogiantgrpn), vproj_boundary(ecogiantgrpn))
ecog3grp[ecodwarfsel] = ecodwarfassocid
resbg3grp[resbdwarfsel] = resbdwarfassocid
resbana_g3grp[resbana_dwarfsel] = resbana_dwarfassocid
###############################################
# Step 6: Calibration for Iter. Combination
###############################################
ecogdgrpn = fof.multiplicity_function(ecog3grp, return_by_galaxy=True)
#ecogdsel = np.logical_not((ecogdgrpn==1) & (ecologmstar<9.5) & (ecog3grp>0)) # select galaxies that AREN'T ungrouped dwarfs
ecogdsel = np.logical_and(np.logical_not(np.logical_or(ecog3grp==-99., ((ecogdgrpn==1) & (ecologmstar<9.5) & (ecologmstar>=8.9)))), (ecogdgrpn>1))
ecogdgrpra, ecogdgrpdec, ecogdgrpcz = fof.group_skycoords(ecoradeg[ecogdsel], ecodedeg[ecogdsel], ecocz[ecogdsel], ecog3grp[ecogdsel])
ecogdrelvel = np.abs(ecogdgrpcz - ecocz[ecogdsel])
ecogdrelprojdist = (ecogdgrpcz + ecocz[ecogdsel])/100. * ic.angular_separation(ecogdgrpra, ecogdgrpdec, ecoradeg[ecogdsel], ecodedeg[ecogdsel])/2.0
ecogdn = ecogdgrpn[ecogdsel]
ecogdtotalmass = ic.get_int_mass(ecologmstar[ecogdsel], ecog3grp[ecogdsel])
massbins=np.arange(9.75,14,0.15)
binsel = np.where(np.logical_and(ecogdn>1, ecogdtotalmass<14))
gdmedianrproj, massbincenters, massbinedges, jk = center_binned_stats(ecogdtotalmass[binsel], ecogdrelprojdist[binsel], np.median, bins=massbins)
#gdmedianrproj_err = np.std(np.array([sbs(ecogdrelprojdist[binsel][np.where(np.logical_and(ecogdtotalmass[binsel]>massbinedges[i-1], ecogdtotalmass[binsel]<=massbinedges[i]))],\
# 10000, np.median) for i in range(1,len(massbinedges))]), axis=1)
gdmedianrelvel, jk, jk, jk = center_binned_stats(ecogdtotalmass[binsel], ecogdrelvel[binsel], np.median, bins=massbins)
#gdmedianrelvel_err = np.std(np.array([sbs(ecogdrelvel[binsel][np.where(np.logical_and(ecogdtotalmass[binsel]>massbinedges[i-1], ecogdtotalmass[binsel]<=massbinedges[i]))],\
# 10000, np.median) for i in range(1,len(massbinedges))]), axis=1)
gdmedianrproj_err, jk, jk, jk = center_binned_stats(ecogdtotalmass[binsel], ecogdrelprojdist[binsel], sigmarange, bins=massbins)
gdmedianrelvel, jk, jk, jk = center_binned_stats(ecogdtotalmass[binsel], ecogdrelvel[binsel], np.median, bins=massbins)
gdmedianrelvel_err, jk, jk, jk = center_binned_stats(ecogdtotalmass[binsel], ecogdrelvel[binsel], sigmarange, bins=massbins)
nansel = np.isnan(gdmedianrproj)
if 0:
#guess=None
#guess=[-1,0.01,0.05,-6,0.01]
guess=[-1,0.01,0.05]
else:
guess= [-1,0.01,0.05]#None#[1e-5, 0.4, 0.2, 1]
poptr, pcovr = curve_fit(exp, massbincenters[~nansel], gdmedianrproj[~nansel], p0=guess, maxfev=5000, sigma=gdmedianrproj_err[~nansel])#30**massbincenters[~nansel])
poptv, pcovv = curve_fit(exp, massbincenters[~nansel], gdmedianrelvel[~nansel], p0=[3e-5,4e-1,5e-03], maxfev=5000)#, sigma=gdmedianrelvel_err[~nansel])
print(poptr, poptv)
tx = np.linspace(7,15,100)
plt.figure()
plt.axhline(0)
plt.plot(ecogdtotalmass[binsel], ecogdrelprojdist[binsel], 'k.', alpha=0.2, label='ECO Galaxies in N>1 Giant+Dwarf Groups')
#plt.plot(massbincenters, gdmedianrproj, 'r^', label='Median')
plt.errorbar(massbincenters, gdmedianrproj, yerr=gdmedianrproj_err, fmt='r^', label='Median')
plt.plot(tx, exp(tx,*poptr), label='Fit to Medians')
plt.plot(tx, 3*exp(tx,*poptr), label='3 times Fit to Medians')
plt.xlabel(r"Integrated Stellar Mass of Giant + Dwarf Members")
plt.ylabel("Projected Distance from Galaxy to Group Center [Mpc/h]")
plt.legend(loc='best')
plt.xlim(9.5,13.2)
plt.ylim(0,3)
#plt.yscale('log')
plt.show()
plt.figure()
plt.plot(ecogdtotalmass[binsel], ecogdrelvel[binsel], 'k.', alpha=0.2, label='Mock Galaxies in N=2 Giant+Dwarf Groups')
#plt.plot(massbincenters, gdmedianrelvel, 'r^',label='Medians')
plt.errorbar(massbincenters, gdmedianrelvel, yerr=gdmedianrelvel_err, fmt='r^', label='Median')
plt.plot(tx, exp(tx, *poptv), label='Fit to Medians')
plt.plot(tx, 4.5*exp(tx, *poptv), label='4.5 times Fit to Medians')
plt.ylabel("Relative Velocity between Galaxy and Group Center")
plt.xlabel(r"Integrated Stellar Mass of Giant + Dwarf Members")
plt.xlim(9.5,13)
plt.ylim(0,2000)
plt.legend(loc='best')
plt.show()
rproj_for_iteration = lambda M: 3*exp(M, *poptr)
vproj_for_iteration = lambda M: 4.5*exp(M, *poptv)
# --------------- now need to do this calibration for the RESOLVE-B analogue dataset, down to 8.7 stellar mass) -------------$
resbana_gdgrpn = fof.multiplicity_function(resbana_g3grp, return_by_galaxy=True)
#resbana_gdsel = np.logical_not((resbana_gdgrpn==1) & (ecologmstar>-19.4) & (resbana_g3grp!=-99.) & (resbana_g3grp>0)) # select galaxies that AREN'T ungrouped dwarfs
resbana_gdsel = np.logical_and(np.logical_not(np.logical_or(resbana_g3grp==-99., ((resbana_gdgrpn==1) & (ecologmstar<9.5) & (ecologmstar>=8.7)))), (resbana_gdgrpn>2))
resbana_gdgrpra, resbana_gdgrpdec, resbana_gdgrpcz = fof.group_skycoords(ecoradeg[resbana_gdsel], ecodedeg[resbana_gdsel], ecocz[resbana_gdsel], resbana_g3grp[resbana_gdsel])
resbana_gdrelvel = np.abs(resbana_gdgrpcz - ecocz[resbana_gdsel])
resbana_gdrelprojdist = (resbana_gdgrpcz + ecocz[resbana_gdsel])/100. * ic.angular_separation(resbana_gdgrpra, resbana_gdgrpdec, ecoradeg[resbana_gdsel], ecodedeg[resbana_gdsel])/2.0
resbana_gdn = resbana_gdgrpn[resbana_gdsel]
resbana_gdtotalmass = ic.get_int_mass(ecologmstar[resbana_gdsel], resbana_g3grp[resbana_gdsel])
massbins2=np.arange(9.75,14,0.15)
binsel2 = np.where(np.logical_and(resbana_gdn>1, resbana_gdtotalmass>-24))
gdmedianrproj, massbincenters, massbinedges, jk = center_binned_stats(resbana_gdtotalmass[binsel2], resbana_gdrelprojdist[binsel2], np.median, bins=massbins2)
gdmedianrproj_err, jk, jk, jk = center_binned_stats(resbana_gdtotalmass[binsel2], resbana_gdrelprojdist[binsel2], sigmarange, bins=massbins2)
gdmedianrelvel, jk, jk, jk = center_binned_stats(resbana_gdtotalmass[binsel2], resbana_gdrelvel[binsel2], np.median, bins=massbins2)
gdmedianrelvel_err, jk, jk, jk = center_binned_stats(resbana_gdtotalmass[binsel2], resbana_gdrelvel[binsel2], sigmarange, bins=massbins2)
nansel = np.isnan(gdmedianrproj)
poptr_resbana, jk = curve_fit(exp, massbincenters[~nansel], gdmedianrproj[~nansel], p0=poptr, sigma=gdmedianrproj_err[~nansel])#10**massbincenters[~nansel])
poptv_resbana, jk = curve_fit(exp, massbincenters[~nansel], gdmedianrelvel[~nansel], p0=poptv, sigma=gdmedianrelvel_err[~nansel])#[3e-5,4e-1,5e-03,1])
tx = np.linspace(7,15)
plt.figure()
plt.plot(resbana_gdtotalmass[binsel2], resbana_gdrelprojdist[binsel2], 'k.', alpha=0.2, label='Mock Galaxies in N>1 Giant+Dwarf Groups')
plt.errorbar(massbincenters, gdmedianrproj, gdmedianrproj_err, fmt='r^', label='Median')
plt.plot(tx, exp(tx,*poptr_resbana), label='Fit to Medians')
plt.plot(tx, 3*exp(tx,*poptr_resbana), label='3 times Fit to Medians')
plt.xlabel(r"Integrated Stellar Mass of Giant + Dwarf Members")
plt.ylabel("Projected Distance from Galaxy to Group Center [Mpc/h]")
plt.legend(loc='best')
plt.xlim(9.5,13)
plt.ylim(0,3)
plt.show()
plt.figure()
plt.plot(resbana_gdtotalmass[binsel2], resbana_gdrelvel[binsel2], 'k.', alpha=0.2, label='Mock Galaxies in N=2 Giant+Dwarf Groups')
plt.errorbar(massbincenters, gdmedianrelvel, yerr=gdmedianrelvel_err, fmt='r^',label='Medians')
plt.plot(tx, exp(tx, *poptv_resbana), label='Fit to Medians')
plt.plot(tx, 4.5*exp(tx, *poptv_resbana), label='4.5 times Fit to Medians')
plt.ylabel("Relative Velocity between Galaxy and Group Center")
plt.xlabel(r"Integrated Stellar Mass of Giant + Dwarf Members")
plt.xlim(9.5,13)
plt.ylim(0,2000)
plt.legend(loc='best')
plt.show()
rproj_for_iteration_resbana = lambda M: 3*exp(M, *poptr_resbana)
vproj_for_iteration_resbana = lambda M: 4.5*exp(M, *poptv_resbana)
###########################################################
# Step 7: Iterative Combination of Dwarf Galaxies
###########################################################
assert (ecog3grp[(ecologmstar>9.5) & (ecocz<8000) & (ecocz>2530)]!=-99.).all(), "Not all giants are grouped."
ecogrpnafterassoc = fof.multiplicity_function(ecog3grp, return_by_galaxy=True)
resbgrpnafterassoc = fof.multiplicity_function(resbg3grp, return_by_galaxy=True)
resbana_grpnafterassoc = fof.multiplicity_function(resbana_g3grp, return_by_galaxy=True)
eco_ungroupeddwarf_sel = (ecologmstar<9.5) & (ecologmstar>=8.9) & (ecocz<8000) & (ecocz>2530) & (ecogrpnafterassoc==1)
ecoitassocid = ic.iterative_combination(ecoradeg[eco_ungroupeddwarf_sel], ecodedeg[eco_ungroupeddwarf_sel], ecocz[eco_ungroupeddwarf_sel], ecologmstar[eco_ungroupeddwarf_sel],\
rproj_for_iteration, vproj_for_iteration, starting_id=np.max(ecog3grp)+1, centermethod='arithmetic')
resb_ungroupeddwarf_sel = (resblogmstar<9.5) & (resblogmstar>=8.7) & (resbcz<7300) & (resbcz>4250) & (resbgrpnafterassoc==1)
resbitassocid = ic.iterative_combination(resbradeg[resb_ungroupeddwarf_sel], resbdedeg[resb_ungroupeddwarf_sel], resbcz[resb_ungroupeddwarf_sel], resblogmstar[resb_ungroupeddwarf_sel],\
rproj_for_iteration, vproj_for_iteration, starting_id=np.max(resbg3grp)+1, centermethod='arithmetic')
resbana_ungroupeddwarf_sel = (ecologmstar<9.5) & (ecologmstar>=8.7) & (ecocz<8000) & (ecocz>2530) & (resbana_grpnafterassoc==1)
resbana_itassocid = ic.iterative_combination(ecoradeg[resbana_ungroupeddwarf_sel], ecodedeg[resbana_ungroupeddwarf_sel], ecocz[resbana_ungroupeddwarf_sel], ecologmstar[resbana_ungroupeddwarf_sel],\
rproj_for_iteration_resbana, vproj_for_iteration_resbana, starting_id=np.max(resbana_g3grp)+1, centermethod='arithmetic')
ecog3grp[eco_ungroupeddwarf_sel] = ecoitassocid
resbg3grp[resb_ungroupeddwarf_sel] = resbitassocid
resbana_g3grp[resbana_ungroupeddwarf_sel] = resbana_itassocid
#plt.figure()
#plt.hist(fof.multiplicity_function(ecoitassocid, return_by_galaxy=False), log=True)
#plt.hist(fof.multiplicity_function(resbitassocid, return_by_galaxy=False), log=True, histtype='step')
#plt.show()
plt.figure()
binv = np.arange(0.5,1200.5,3)
plt.hist(fof.multiplicity_function(ecog3grp[ecog3grp!=-99.], return_by_galaxy=False), bins=binv, log=True, label='ECO Groups', histtype='step', linewidth=3)
plt.hist(fof.multiplicity_function(resbg3grp[resbg3grp!=-99.], return_by_galaxy=False), bins=binv, log=True, label='RESOLVE-B Groups', histtype='step', hatch='\\')
plt.xlabel("Number of Giant + Dwarf Group Members")
plt.ylabel("Number of Groups")
plt.legend(loc='best')
plt.xlim(0,100)
plt.show()
############################################################
# Step 8: Halo Abundance Matching
###########################################################
# --- for RESOLVE-B analogue ----#
resbana_hamsel = (resbana_g3grp!=-99.)
resbana_haloid, resbana_halomass, jk, jk = ic.HAMwrapper(ecoradeg[resbana_hamsel], ecodedeg[resbana_hamsel], ecocz[resbana_hamsel], ecologmstar[resbana_hamsel], resbana_g3grp[resbana_hamsel],\
ecovolume, inputfilename=None, outputfilename=None)
resbana_halomass = np.log10(10**resbana_halomass)# no longer needed as of 7/29: /fof.getmhoffset(280,337,1,1,6))
junk, uniqindex = np.unique(resbana_g3grp[resbana_hamsel], return_index=True)
resbana_intmass = ic.get_int_mass(ecologmstar[resbana_hamsel], resbana_g3grp[resbana_hamsel])[uniqindex]
sortind = np.argsort(resbana_intmass)
sortedmass = resbana_intmass[sortind]
resbcubicspline = interp1d(sortedmass, resbana_halomass[sortind], fill_value='extrapolate')
resbintmass = ic.get_int_mass(resblogmstar[resbg3grp!=-99.], resbg3grp[resbg3grp!=-99.])
resbg3logmh[resbg3grp!=-99.] = resbcubicspline(resbintmass)-np.log10(0.7)
# ---- for ECO ----- #
ecohamsel = (ecog3grp!=-99.)
haloid, halomass, junk, junk = ic.HAMwrapper(ecoradeg[ecohamsel], ecodedeg[ecohamsel], ecocz[ecohamsel], ecologmstar[ecohamsel], ecog3grp[ecohamsel],\
ecovolume, inputfilename=None, outputfilename=None)
junk, uniqindex = np.unique(ecog3grp[ecohamsel], return_index=True)
halomass = halomass-np.log10(0.7)
for i,idv in enumerate(haloid):
sel = np.where(ecog3grp==idv)
ecog3logmh[sel] = halomass[i] # m337b
# calculate Rvir in arcsec
ecog3rvir = (3*(10**ecog3logmh) / (4*np.pi*337*0.3*1.36e11) )**(1/3.)
resbg3rvir = (3*(10**resbg3logmh ) / (4*np.pi*337*0.3*1.36e11))**(1/3.)
ecointmass = ic.get_int_mass(ecologmstar[ecohamsel], ecog3grp[ecohamsel])
plt.figure()
plt.plot(ecointmass, ecog3logmh[ecog3grp!=-99.], '.', color='palegreen', alpha=0.6, label='ECO', markersize=11)
plt.plot(resbintmass, resbg3logmh[resbg3grp!=-99.], 'k.', alpha=1, label='RESOLVE-B', markersize=3)
plt.plot
plt.xlabel("group-integrated log stellar mass")
plt.ylabel(r"group halo mass (log$M_\odot$)")
plt.legend(loc='best')
plt.show()
########################################
# (9) Output arrays
########################################
# ---- first get the quantities for ECO ---- #
#eco_in_gf = np.where(ecog3grp!=-99.)
ecog3grpn = fof.multiplicity_function(ecog3grp, return_by_galaxy=True)
ecog3grpngi = np.zeros(len(ecog3grpn))
ecog3grpndw = np.zeros(len(ecog3grpn))
for uid in np.unique(ecog3grp):
grpsel = np.where(ecog3grp==uid)
gisel = np.where(np.logical_and((ecog3grp==uid),(ecologmstar>=9.5)))
dwsel = np.where(np.logical_and((ecog3grp==uid), (ecologmstar<9.5)))
if len(gisel[0])>0.:
ecog3grpngi[grpsel] = len(gisel[0])
if len(dwsel[0])>0.:
ecog3grpndw[grpsel] = len(dwsel[0])
ecog3grpradeg, ecog3grpdedeg, ecog3grpcz = fof.group_skycoords(ecoradeg, ecodedeg, ecocz, ecog3grp)
ecog3rproj = fof.get_grprproj_e17(ecoradeg, ecodedeg, ecocz, ecog3grp, h=0.7) / (ecog3grpcz/70.) * 206265 # in arcsec
ecog3fc = fof.get_central_flag(ecologmstar, ecog3grp)
ecog3router = fof.get_outermost_galradius(ecoradeg, ecodedeg, ecocz, ecog3grp) # in arcsec
ecog3router[(ecog3grpngi+ecog3grpndw)==1] = 0.
junk, ecog3vdisp = fof.get_rproj_czdisp(ecoradeg, ecodedeg, ecocz, ecog3grp)
ecog3rvir = ecog3rvir*206265/(ecog3grpcz/70.)
ecog3grpgas = ic.get_int_mass(ecologmgas, ecog3grp)
ecog3grpstars = ic.get_int_mass(ecologmstar, ecog3grp)
ecog3ADtest = vz.AD_test(ecocz, ecog3grp)
ecog3tcross = vz.group_crossing_time(ecoradeg, ecodedeg, ecocz, ecog3grp)
ecog3colorgap = vz.group_color_gap(ecog3grp, ecologmstar, ecourcolor)
ecog3dsprob = vz.fast_DS_test(ecoradeg,ecodedeg,ecocz,ecog3grp,niter=2500)
ecog3nndens, ecog3edgeflag, ecog3nndens2d, ecog3edgeflag2d, ecog3edgescale2d = lss_dens_by_galaxy(ecog3grp,\
ecoradeg, ecodedeg, ecocz, ecog3logmh, Nnn=3, rarange=(130.05,237.45), decrange=(-1,50), czrange=(2530,7470))
outofsample = (ecog3grp==-99.)
ecog3grpn[outofsample]=-99.
ecog3grpngi[outofsample]=-99.
ecog3grpndw[outofsample]=-99.
ecog3grpradeg[outofsample]=-99.
ecog3grpdedeg[outofsample]=-99.
ecog3grpcz[outofsample]=-99.
ecog3logmh[outofsample]=-99.
ecog3rvir[outofsample]=-99.
ecog3rproj[outofsample]=-99.
ecog3fc[outofsample]=-99.
ecog3router[outofsample]=-99.
ecog3vdisp[outofsample]=-99.
ecog3grpgas[outofsample]=-99.
ecog3grpstars[outofsample]=-99.
ecog3ADtest[outofsample]=-99.
ecog3tcross[outofsample]=-99.
ecog3colorgap[outofsample]=-99.
ecog3dsprob[outofsample]=-99.
ecog3nndens[outofsample]=-99.
ecog3edgeflag[outofsample]=-99.
ecog3nndens2d[outofsample]=-99.
ecog3edgeflag2d[outofsample]=-99.
ecog3edgescale2d[outofsample]=-99.
insample = ecog3grpn!=-99.
ecodata['g3grp_s'] = ecog3grp
ecodata['g3grpradeg_s'] = ecog3grpradeg
ecodata['g3grpdedeg_s'] = ecog3grpdedeg
ecodata['g3grpcz_s'] = ecog3grpcz
ecodata['g3grpndw_s'] = ecog3grpndw
ecodata['g3grpngi_s'] = ecog3grpngi
ecodata['g3logmh_s'] = ecog3logmh
ecodata['g3r337_s'] = ecog3rvir
ecodata['g3rproj_s'] = ecog3rproj
ecodata['g3router_s'] = ecog3router
ecodata['g3fc_s'] = ecog3fc
ecodata['g3vdisp_s'] = ecog3vdisp
ecodata['g3grplogG_s'] = ecog3grpgas
ecodata['g3grplogS_s'] = ecog3grpstars
ecodata['g3grpadAlpha_s'] = ecog3ADtest
ecodata['g3grptcross_s'] = ecog3tcross
ecodata['g3grpcolorgap_s'] = ecog3colorgap
ecodata['g3grpcolorgap_s'] = ecog3colorgap
ecodata['g3grpdsProb_s'] = ecog3dsprob
ecodata['g3grpnndens_s'] = ecog3nndens
ecodata['g3grpedgeflag_s'] = ecog3edgeflag
ecodata['g3grpnndens2d_s'] = ecog3nndens2d
ecodata['g3grpedgeflag2d_s'] = ecog3edgeflag2d
ecodata['g3grpedgescale2d_s'] = ecog3edgescale2d
ecodata.to_csv("ECOdata_G3catalog_stellar.csv", index=False)
# ------ now do RESOLVE
sz = len(resolvedata)
resolvename = np.array(resolvedata.name)
resolveg3grp = np.full(sz, -99.)
resolveg3grpngi = np.full(sz, -99.)
resolveg3grpndw = np.full(sz, -99.)
resolveg3grpradeg = np.full(sz, -99.)
resolveg3grpdedeg = np.full(sz, -99.)
resolveg3grpcz = np.full(sz, -99.)
resolveg3intmstar = np.full(sz, -99.)
resolveg3logmh = np.full(sz, -99.)
resolveg3rvir = np.full(sz, -99.)
resolveg3rproj = np.full(sz,-99.)
resolveg3fc = np.full(sz,-99.)
resolveg3router = np.full(sz,-99.)
resolveg3vdisp = np.full(sz,-99.)
resolveg3grpgas = np.full(sz, -99.)
resolveg3grpstars = np.full(sz, -99.)
resolveg3ADtest = np.full(sz, -99.)
resolveg3tcross = np.full(sz, -99.)
resolveg3colorgap = np.full(sz, -99.)
resolveg3dsprob = np.full(sz,-99.)
resolveg3nndens = np.full(sz, -99.)
resolveg3edgeflag = np.full(sz, -99.)
resolveg3nndens2d = np.full(sz, -99.)
resolveg3edgeflag2d = np.full(sz, -99.)
resolveg3edgescale2d = np.full(sz, -99.)
resbg3grpngi = np.full(len(resbg3grp), 0)
resbg3grpndw = np.full(len(resbg3grp), 0)
for uid in np.unique(resbg3grp):
grpsel = np.where(resbg3grp==uid)
gisel = np.where(np.logical_and((resbg3grp==uid),(resblogmstar>=9.5)))
dwsel = np.where(np.logical_and((resbg3grp==uid), (resblogmstar<9.5)))
if len(gisel[0])>0.:
resbg3grpngi[grpsel] = len(gisel[0])
if len(dwsel[0])>0.:
resbg3grpndw[grpsel] = len(dwsel[0])
resbg3grpradeg, resbg3grpdedeg, resbg3grpcz = fof.group_skycoords(resbradeg, resbdedeg, resbcz, resbg3grp)
resbg3intmstar = ic.get_int_mass(resblogmstar, resbg3grp)
resbg3rproj = fof.get_grprproj_e17(resbradeg, resbdedeg, resbcz, resbg3grp, h=0.7) / (resbg3grpcz/70.) * 206265 # in arcsec
resbg3fc = fof.get_central_flag(resblogmstar, resbg3grp)
resbg3router = fof.get_outermost_galradius(resbradeg, resbdedeg, resbcz, resbg3grp) # in arcsec
resbg3router[(resbg3grpngi+resbg3grpndw)==1] = 0.
junk, resbg3vdisp = fof.get_rproj_czdisp(resbradeg, resbdedeg, resbcz, resbg3grp)
resbg3rvir = resbg3rvir*206265/(resbg3grpcz/70.)
resbg3grpgas = ic.get_int_mass(resblogmgas, resbg3grp)
resbg3grpstars = ic.get_int_mass(resblogmstar, resbg3grp)
resbg3ADtest = vz.AD_test(resbcz, resbg3grp)
resbg3tcross = vz.group_crossing_time(resbradeg, resbdedeg, resbcz, resbg3grp)
resbg3colorgap = vz.group_color_gap(resbg3grp, resblogmstar, resburcolor)
resbg3dsprob = vz.fast_DS_test(resbradeg,resbdedeg,resbcz,resbg3grp,niter=2500)
RESB_RADEG_REMAPPED = np.copy(resbradeg)
REMAPSEL = np.where(resbradeg>18*15.)
RESB_RADEG_REMAPPED[REMAPSEL] = resbradeg[REMAPSEL]-360.
resbg3nndens, resbg3edgeflag, resbg3nndens2d, resbg3edgeflag2d, resbg3edgescale2d = lss_dens_by_galaxy(resbg3grp,\
RESB_RADEG_REMAPPED, resbdedeg, resbcz, resbg3logmh, Nnn=3, rarange=(-2*15.,3*15.), decrange=(-1.25,1.25),\
czrange=(4250,7250)) # must use remapped RESOLVE-B RA because of 0/360 wraparound
outofsample = (resbg3grp==-99.)
resbg3grpngi[outofsample]=-99.
resbg3grpndw[outofsample]=-99.
resbg3grpradeg[outofsample]=-99.
resbg3grpdedeg[outofsample]=-99.
resbg3grpcz[outofsample]=-99.
resbg3intmstar[outofsample]=-99.
resbg3logmh[outofsample]=-99.
resbg3rvir[outofsample]=-99.
resbg3rproj[outofsample]=-99.
resbg3router[outofsample]=-99.
resbg3fc[outofsample]=-99.
resbg3vdisp[outofsample]=-99.
resbg3grpgas[outofsample]=-99.
resbg3grpstars[outofsample]=-99.
resbg3ADtest[outofsample]=-99.
resbg3tcross[outofsample]=-99.
resbg3colorgap[outofsample]=-99.
resbg3dsprob[outofsample]=-99.
resbg3nndens[outofsample]=-99.
resbg3edgeflag[outofsample]=-99.
resbg3nndens2d[outofsample]=-99.
resbg3edgeflag2d[outofsample]=-99.
resbg3edgescale2d[outofsample]=-99.
for i,nm in enumerate(resolvename):
if nm.startswith('rs'):
sel_in_eco = np.where(ecoresname==nm)
resolveg3grp[i] = ecog3grp[sel_in_eco]
resolveg3grpngi[i] = ecog3grpngi[sel_in_eco]
resolveg3grpndw[i] = ecog3grpndw[sel_in_eco]
resolveg3grpradeg[i] = ecog3grpradeg[sel_in_eco]
resolveg3grpdedeg[i] = ecog3grpdedeg[sel_in_eco]
resolveg3grpcz[i] = ecog3grpcz[sel_in_eco]
resolveg3intmstar[i] = ecog3intmstar[sel_in_eco]
resolveg3logmh[i] = ecog3logmh[sel_in_eco]
resolveg3rvir[i] = ecog3rvir[sel_in_eco]
resolveg3rproj[i] = ecog3rproj[sel_in_eco]
resolveg3fc[i] = ecog3fc[sel_in_eco]
resolveg3router[i]=ecog3router[sel_in_eco]
resolveg3vdisp[i]=ecog3vdisp[sel_in_eco]
resolveg3grpstars[i] = ecog3grpstars[sel_in_eco]
resolveg3grpgas[i] = ecog3grpgas[sel_in_eco]
resolveg3ADtest[i] = ecog3ADtest[sel_in_eco]
resolveg3tcross[i] = ecog3tcross[sel_in_eco]
resolveg3colorgap[i] = ecog3colorgap[sel_in_eco]
resolveg3dsprob[i] = ecog3dsprob[sel_in_eco]
resolveg3nndens[i] = ecog3nndens[sel_in_eco]
resolveg3edgeflag[i] = ecog3edgeflag[sel_in_eco]
resolveg3nndens2d[i] = ecog3nndens2d[sel_in_eco]
resolveg3edgeflag2d[i] = ecog3edgeflag2d[sel_in_eco]
resolveg3edgescale2d[i] = ecog3edgescale2d[sel_in_eco]
elif nm.startswith('rf'):
sel_in_resb = np.where(resbname==nm)
resolveg3grp[i] = resbg3grp[sel_in_resb]
resolveg3grpngi[i] = resbg3grpngi[sel_in_resb]
resolveg3grpndw[i] = resbg3grpndw[sel_in_resb]
resolveg3grpradeg[i] = resbg3grpradeg[sel_in_resb]
resolveg3grpdedeg[i] = resbg3grpdedeg[sel_in_resb]
resolveg3grpcz[i] = resbg3grpcz[sel_in_resb]
resolveg3intmstar[i] = resbg3intmstar[sel_in_resb]
resolveg3logmh[i] = resbg3logmh[sel_in_resb]
resolveg3rvir[i] = resbg3rvir[sel_in_resb]
resolveg3rproj[i] = resbg3rproj[sel_in_resb]
resolveg3fc[i] = resbg3fc[sel_in_resb]
resolveg3router[i] = resbg3router[sel_in_resb]
resolveg3vdisp[i] = resbg3vdisp[sel_in_resb]
resolveg3grpgas[i] = resbg3grpgas[sel_in_resb]
resolveg3grpstars[i] = resbg3grpstars[sel_in_resb]
resolveg3ADtest[i] = resbg3ADtest[sel_in_resb]
resolveg3tcross[i] = resbg3tcross[sel_in_resb]
resolveg3colorgap[i] = resbg3colorgap[sel_in_resb]
resolveg3dsprob[i] = resbg3dsprob[sel_in_resb]
resolveg3nndens[i] = resbg3nndens[sel_in_resb]
resolveg3edgeflag[i] = resbg3edgeflag[sel_in_resb]
resolveg3nndens2d[i] = resbg3nndens2d[sel_in_resb]
resolveg3edgeflag2d[i] = resbg3edgeflag2d[sel_in_resb]
resolveg3edgescale2d[i] = resbg3edgescale2d[sel_in_resb]
else:
assert False, nm+" not in RESOLVE"
resolvedata['g3grp_s'] = resolveg3grp
resolvedata['g3grpngi_s'] = resolveg3grpngi
resolvedata['g3grpndw_s'] = resolveg3grpndw
resolvedata['g3grpradeg_s'] = resolveg3grpradeg
resolvedata['g3grpdedeg_s'] = resolveg3grpdedeg
resolvedata['g3grpcz_s'] = resolveg3grpcz
resolvedata['g3logmh_s'] = resolveg3logmh
resolvedata['g3r337_s'] = resolveg3rvir
resolvedata['g3rproj_s'] = resolveg3rproj
resolvedata['g3router_s'] = resolveg3router
resolvedata['g3fc_s'] = resolveg3fc
resolvedata['g3vdisp_s'] = resolveg3vdisp
resolvedata['g3grplogG_s'] = resolveg3grpgas
resolvedata['g3grplogS_s'] = resolveg3grpstars
resolvedata['g3grpadAlpha_s'] = resolveg3ADtest
resolvedata['g3grptcross_s'] = resolveg3tcross
resolvedata['g3grpcolorgap_s'] = resolveg3colorgap
resolvedata['g3grpdsProb_s'] = resolveg3dsprob
resolvedata['g3grpnndens_s'] = resolveg3nndens
resolvedata['g3grpedgeflag_s'] = resolveg3edgeflag
resolvedata['g3grpnndens2d_s'] = resolveg3nndens2d
resolvedata['g3grpedgeflag2d_s'] = resolveg3edgeflag2d
resolvedata['g3grpedgescale2d_s'] = resolveg3edgescale2d
resolvedata.to_csv("RESOLVEdata_G3catalog_stellar.csv", index=False)
|
zhutchens1/g3groups | smoothedbootstrap.py | <gh_stars>0
"""
Smoothed Bootstrap Function
Author: <NAME>
adapted from astroML.resample.bootstrap September 2016
"""
import numpy as np
import numpy.random as npr
from astroML.utils import check_random_state
def smoothedbootstrap(data, n_bootstraps, user_statistic, kwargs=None,
random_state=None):
"""Compute smoothed bootstrapped statistics of a data set.
Parameters
----------
data : array_like
A 1-dimensional data array of size n_samples
n_bootstraps : integer
the number of bootstrap samples to compute. Note that internally,
two arrays of size (n_bootstraps, n_samples) will be allocated.
For very large numbers of bootstraps, this can cause memory issues.
user_statistic : function
The statistic to be computed. This should take an array of data
of size (n_bootstraps, n_samples) and return the row-wise statistics
of the data.
kwargs : dictionary (optional)
A dictionary of keyword arguments to be passed to the
user_statistic function.
random_state: RandomState or an int seed (0 by default)
A random number generator instance
Returns
-------
distribution : ndarray
the bootstrapped distribution of statistics (length = n_bootstraps)
"""
# we don't set kwargs={} by default in the argument list, because using
# a mutable type as a default argument can lead to strange results
if kwargs is None:
kwargs = {}
rng = check_random_state(random_state)
data = np.asarray(data)
n_datapts = data.size
if data.ndim != 1:
raise ValueError("bootstrap expects 1-dimensional data")
# Generate random indices with repetition
ind = rng.randint(n_datapts, size=(n_bootstraps, n_datapts))
# smoothing noise
noisemean = 0.
noisesigma = np.std(data,ddof=1) / np.sqrt(n_datapts)
noise = npr.normal(noisemean,noisesigma,(n_bootstraps, n_datapts))
databroadcast = data[ind] + noise
# Call the function
stat_bootstrap = user_statistic(databroadcast, **kwargs)
# compute the statistic on the data
return stat_bootstrap
|
zhutchens1/g3groups | mergegroupcatalogs.py | <filename>mergegroupcatalogs.py<gh_stars>0
import pandas as pd
lumgrps = pd.read_csv("ECOdata_G3catalog_luminosity.csv")
lumgrps = lumgrps.set_index('name')
stellargrps = pd.read_csv("ECOdata_G3catalog_stellar.csv")
stellargrps = stellargrps.set_index('name')
stellargrps = stellargrps[['g3grp_s', 'g3grpngi_s', 'g3grpndw_s', 'g3grpradeg_s', 'g3grpdedeg_s', 'g3grpcz_s', 'g3logmh_s', 'g3r337_s', 'g3rproj_s', 'g3router_s', 'g3fc_s',\
'g3grplogG_s', 'g3grplogS_s', 'g3grpadAlpha_s', 'g3grptcross_s', 'g3grpcolorgap_s', 'g3grpdsProb_s', 'g3grpnndens_s', 'g3grpedgeflag_s', 'g3grpnndens2d_s',\
'g3grpedgeflag2d_s', 'g3grpedgescale2d_s']]
barygrps = pd.read_csv("ECOdata_G3catalog_baryonic.csv")
barygrps = barygrps.set_index('name')
barygrps = barygrps[['g3grp_b', 'g3grpngi_b', 'g3grpndw_b', 'g3grpradeg_b', 'g3grpdedeg_b', 'g3grpcz_b', 'g3logmh_b', 'g3r337_b', 'g3rproj_b', 'g3router_b', 'g3fc_b',\
'g3grplogG_b', 'g3grplogS_b', 'g3grpadAlpha_b', 'g3grptcross_b', 'g3grpcolorgap_b','g3grpdsProb_b', 'g3grpnndens_b', 'g3grpedgeflag_b', 'g3grpnndens2d_b',\
'g3grpedgeflag2d_b', 'g3grpedgescale2d_b']]
eco = lumgrps.join(stellargrps)
eco = eco.join(barygrps)
eco=eco[['radeg','dedeg','cz','absrmag','logmstar','dup','resname',\
'g3grp_l', 'g3grpngi_l', 'g3grpndw_l', 'g3grpradeg_l', 'g3grpdedeg_l', 'g3grpcz_l', 'g3logmh_l', 'g3r337_l',\
'g3rproj_l', 'g3router_l', 'g3fc_l', 'g3grplogG_l', 'g3grplogS_l', 'g3grpadAlpha_l', 'g3grptcross_l', 'g3grpcolorgap_l',\
'g3grpdsProb_l', 'g3grpnndens_l', 'g3grpedgeflag_l', 'g3grpnndens2d_l','g3grpedgeflag2d_l', 'g3grpedgescale2d_l',\
'g3grp_s', 'g3grpngi_s', 'g3grpndw_s', 'g3grpradeg_s', 'g3grpdedeg_s', 'g3grpcz_s', 'g3logmh_s', 'g3r337_s',\
'g3rproj_s', 'g3router_s', 'g3fc_s', 'g3grplogG_s', 'g3grplogS_s', 'g3grpadAlpha_s', 'g3grptcross_s', 'g3grpcolorgap_s',\
'g3grpdsProb_s', 'g3grpnndens_s', 'g3grpedgeflag_s', 'g3grpnndens2d_s','g3grpedgeflag2d_s', 'g3grpedgescale2d_s',\
'g3grp_b', 'g3grpngi_b', 'g3grpndw_b', 'g3grpradeg_b', 'g3grpdedeg_b', 'g3grpcz_b', 'g3logmh_b', 'g3r337_b',\
'g3rproj_b', 'g3router_b', 'g3fc_b','g3grplogG_b', 'g3grplogS_b', 'g3grpadAlpha_b', 'g3grptcross_b', 'g3grpcolorgap_b',\
'g3grpdsProb_b', 'g3grpnndens_b', 'g3grpedgeflag_b', 'g3grpnndens2d_b','g3grpedgeflag2d_b', 'g3grpedgescale2d_b',\
'grp', 'grpn', 'logmh', 'grpsig', 'grprproj','grpcz','fc',\
'mhidet_a100', 'emhidet_a100', 'confused_a100', 'mhilim_a100', 'limflag_a100', 'w20_a100', 'w50_a100',\
'ew50_a100', 'peaksnhi_a100','logmgas_a100','agcnr_a100',\
'mhidet', 'emhidet', 'confused', 'mhilim', 'limflag', 'limsigma', 'limmult', 'w20', 'w50', 'ew50',\
'peaksnhi', 'logmgas','hitelescope','mhi_corr','emhi_corr_rand', 'emhi_corr_sys',\
'mhidet_e16', 'emhidet_e16', 'mhilim_e16', 'limflag_e16', 'hitelescope_e16', 'confused_e16','logmgas_e16']]
eco.to_csv("ECO_G3galaxycatalog_090921.csv")
eco.index.rename('central_name', inplace=True)
# output just groups (luminosity)
eco[(eco.g3fc_l==1)][['g3grp_l', 'g3grpngi_l', 'g3grpndw_l', 'g3grpradeg_l', 'g3grpdedeg_l', 'g3grpcz_l', 'g3logmh_l', 'g3r337_l', 'g3rproj_l',\
'g3router_l','g3grplogG_l', 'g3grplogS_l', 'g3grpadAlpha_l', 'g3grptcross_l', 'g3grpcolorgap_l', 'g3grpdsProb_l', 'g3grpnndens_l',\
'g3grpedgeflag_l', 'g3grpnndens2d_l','g3grpedgeflag2d_l', 'g3grpedgescale2d_l']].to_csv("ECO_G3groupcatalog_luminosity_090921.csv")
# output just groups (stellar mass)
eco[(eco.g3fc_s==1)][['g3grp_s', 'g3grpngi_s', 'g3grpndw_s', 'g3grpradeg_s', 'g3grpdedeg_s', 'g3grpcz_s', 'g3logmh_s', 'g3r337_s', 'g3rproj_s',\
'g3router_s', 'g3grplogG_s', 'g3grplogS_s', 'g3grpadAlpha_s', 'g3grptcross_s', 'g3grpcolorgap_s','g3grpdsProb_s', 'g3grpnndens_s',
'g3grpedgeflag_s', 'g3grpnndens2d_s','g3grpedgeflag2d_s', 'g3grpedgescale2d_s']].to_csv("ECO_G3groupcatalog_stellar_090921.csv")
# output just groups (baryonic mass)
eco[(eco.g3fc_b==1)][['g3grp_b', 'g3grpngi_b', 'g3grpndw_b', 'g3grpradeg_b', 'g3grpdedeg_b', 'g3grpcz_b', 'g3logmh_b', 'g3r337_b', 'g3rproj_b',\
'g3router_b', 'g3grplogG_b', 'g3grplogS_b', 'g3grpadAlpha_b', 'g3grptcross_b', 'g3grpcolorgap_b','g3grpdsProb_b', 'g3grpnndens_b',\
'g3grpedgeflag_b', 'g3grpnndens2d_b','g3grpedgeflag2d_b', 'g3grpedgescale2d_b']].to_csv("ECO_G3groupcatalog_baryonic_090921.csv")
###############################################################################
# output RESOLVE
lumgrps = pd.read_csv("RESOLVEdata_G3catalog_luminosity.csv")
lumgrps = lumgrps.set_index('name')
stellargrps = pd.read_csv("RESOLVEdata_G3catalog_stellar.csv")
stellargrps = stellargrps.set_index('name')
stellargrps = stellargrps[['g3grp_s', 'g3grpngi_s', 'g3grpndw_s', 'g3grpradeg_s', 'g3grpdedeg_s', 'g3grpcz_s', 'g3logmh_s', 'g3r337_s', 'g3rproj_s', 'g3router_s', 'g3fc_s',\
'g3grplogG_s', 'g3grplogS_s', 'g3grpadAlpha_s', 'g3grptcross_s', 'g3grpcolorgap_s', 'g3grpdsProb_s', 'g3grpnndens_s', 'g3grpedgeflag_s', 'g3grpnndens2d_s',\
'g3grpedgeflag2d_s', 'g3grpedgescale2d_s']]
barygrps = pd.read_csv("RESOLVEdata_G3catalog_baryonic.csv")
barygrps = barygrps.set_index('name')
barygrps = barygrps[['g3grp_b', 'g3grpngi_b', 'g3grpndw_b', 'g3grpradeg_b', 'g3grpdedeg_b', 'g3grpcz_b', 'g3logmh_b', 'g3r337_b', 'g3rproj_b', 'g3router_b', 'g3fc_b',\
'g3grplogG_b', 'g3grplogS_b', 'g3grpadAlpha_b', 'g3grptcross_b', 'g3grpcolorgap_b','g3grpdsProb_b', 'g3grpnndens_b', 'g3grpedgeflag_b', 'g3grpnndens2d_b',\
'g3grpedgeflag2d_b', 'g3grpedgescale2d_b']]
resolve = lumgrps.join(stellargrps)
resolve = resolve.join(barygrps)
resolve=resolve[['radeg','dedeg','cz','absrmag','logmstar','f_a','f_b','fl_insample','econame',\
'g3grp_l', 'g3grpngi_l', 'g3grpndw_l', 'g3grpradeg_l', 'g3grpdedeg_l', 'g3grpcz_l', 'g3logmh_l', 'g3r337_l',\
'g3rproj_l', 'g3router_l', 'g3fc_l', 'g3grplogG_l', 'g3grplogS_l', 'g3grpadAlpha_l', 'g3grptcross_l', 'g3grpcolorgap_l',\
'g3grpdsProb_l', 'g3grpnndens_l', 'g3grpedgeflag_l', 'g3grpnndens2d_l','g3grpedgeflag2d_l', 'g3grpedgescale2d_l',\
'g3grp_s', 'g3grpngi_s', 'g3grpndw_s', 'g3grpradeg_s', 'g3grpdedeg_s', 'g3grpcz_s', 'g3logmh_s', 'g3r337_s',\
'g3rproj_s', 'g3router_s', 'g3fc_s', 'g3grplogG_s', 'g3grplogS_s', 'g3grpadAlpha_s', 'g3grptcross_s', 'g3grpcolorgap_s',\
'g3grpdsProb_s', 'g3grpnndens_s', 'g3grpedgeflag_s', 'g3grpnndens2d_s','g3grpedgeflag2d_s', 'g3grpedgescale2d_s',\
'g3grp_b', 'g3grpngi_b', 'g3grpndw_b', 'g3grpradeg_b', 'g3grpdedeg_b', 'g3grpcz_b', 'g3logmh_b', 'g3r337_b',\
'g3rproj_b', 'g3router_b', 'g3fc_b','g3grplogG_b', 'g3grplogS_b', 'g3grpadAlpha_b', 'g3grptcross_b', 'g3grpcolorgap_b',\
'g3grpdsProb_b', 'g3grpnndens_b', 'g3grpedgeflag_b', 'g3grpnndens2d_b','g3grpedgeflag2d_b', 'g3grpedgescale2d_b',\
'grp', 'grpn', 'logmh', 'grpsig', 'grprproj','grpcz','fc',\
'mhidet', 'emhidet', 'confused', 'mhilim', 'limflag', 'w20', 'w50', 'ew50','mhi_corr','emhi_corr_rand','emhi_corr_sys',\
'peaksnhi', 'logmgas','hitelescope','logmgas_e16']]
resolve.to_csv("RESOLVE_G3galaxycatalog_090921.csv")
resolve.index.rename('central_name', inplace=True)
# output just groups (luminosity)
resolve[(resolve.g3fc_l==1)][['g3grp_l', 'g3grpngi_l', 'g3grpndw_l', 'g3grpradeg_l', 'g3grpdedeg_l', 'g3grpcz_l', 'g3logmh_l', 'g3r337_l', 'g3rproj_l',\
'g3router_l','g3grplogG_l', 'g3grplogS_l', 'g3grpadAlpha_l', 'g3grptcross_l', 'g3grpcolorgap_l', 'g3grpdsProb_l', 'g3grpnndens_l',\
'g3grpedgeflag_l', 'g3grpnndens2d_l','g3grpedgeflag2d_l', 'g3grpedgescale2d_l']].to_csv("RESOLVE_G3groupcatalog_luminosity_090921.csv")
# output just groups (stellar mass)
resolve[(resolve.g3fc_s==1)][['g3grp_s', 'g3grpngi_s', 'g3grpndw_s', 'g3grpradeg_s', 'g3grpdedeg_s', 'g3grpcz_s', 'g3logmh_s', 'g3r337_s', 'g3rproj_s',\
'g3router_s', 'g3grplogG_s', 'g3grplogS_s', 'g3grpadAlpha_s', 'g3grptcross_s', 'g3grpcolorgap_s','g3grpdsProb_s', 'g3grpnndens_s',\
'g3grpedgeflag_s', 'g3grpnndens2d_s','g3grpedgeflag2d_s', 'g3grpedgescale2d_s']].to_csv("RESOLVE_G3groupcatalog_stellar_090921.csv")
# output just groups (baryonic mass)
resolve[(resolve.g3fc_b==1)][['g3grp_b', 'g3grpngi_b', 'g3grpndw_b', 'g3grpradeg_b', 'g3grpdedeg_b', 'g3grpcz_b', 'g3logmh_b', 'g3r337_b', 'g3rproj_b',\
'g3router_b', 'g3grplogG_b', 'g3grplogS_b', 'g3grpadAlpha_b', 'g3grptcross_b', 'g3grpcolorgap_b','g3grpdsProb_b', 'g3grpnndens_b',\
'g3grpedgeflag_b', 'g3grpnndens2d_b','g3grpedgeflag2d_b', 'g3grpedgescale2d_b']].to_csv("RESOLVE_G3groupcatalog_baryonic_090921.csv")
|
zhutchens1/g3groups | iterativecombination.py | <reponame>zhutchens1/g3groups
import numpy as np
import pandas as pd
import pickle
from scipy.spatial import cKDTree
from copy import deepcopy
import matplotlib.pyplot as plt
import time
import os
import subprocess
from IPython import get_ipython
ipython = get_ipython()
HUBBLE_CONST = 100.
"""
<NAME> - zhutchen [at] live.unc.edu
University of North Carolina at Chapel Hill
"""
def iterative_combination(galaxyra, galaxydec, galaxycz, galaxymag, rprojboundary, vprojboundary, centermethod, starting_id=1):
"""
Perform iterative combination on a list of input galaxies.
Parameters
------------
galaxyra, galaxydec : iterable
Right-ascension and declination of the input galaxies in decimal degrees.
galaxycz : iterable
Redshift velocity (corrected for Local Group motion) of input galaxies in km/s.
galaxymag : iterable
M_r absolute magnitudes of input galaxies, or galaxy stellar/baryonic masses (the code will be able to differentiate.)
rprojboundary : callable
Search boundary to apply in projection on the sky for grouping input galaxies, function of group-integrated M_r, in units Mpc/h.
vprojboundary : callable
Search boundary to apply in velocity on the sky for grouping input galaxies, function of group-integrated M_r or mass, in units km/s.
centermethod : str
'arithmetic' or 'luminosity'. Specifies how to propose group centers during the combination process.
starting_id : int, default 1
Base ID number to assign to identified groups (all group IDs will be >= starting_id).
Returns
-----------
itassocid: Group ID numbers for every input galaxy. Shape matches `galaxyra`.
"""
print("Beginning iterative combination...")
# Check user input
assert (callable(rprojboundary) and callable(vprojboundary)),"Inputs `rprojboundary` and `vprojboundary` must be callable."
assert (len(galaxyra)==len(galaxydec) and len(galaxydec)==len(galaxycz)),"RA/Dec/cz inputs must have same shape."
# Convert everything to numpy + create ID array (assuming for now all galaxies are isolated)
galaxyra = np.array(galaxyra)
galaxydec = np.array(galaxydec)
galaxycz = np.array(galaxycz)
galaxymag = np.array(galaxymag)
itassocid = np.arange(starting_id, starting_id+len(galaxyra))
# Begin algorithm.
converged=False
niter=0
while (not converged):
print("iteration {} in progress...".format(niter))
# Compute based on updated ID number
olditassocid = itassocid
itassocid = nearest_neighbor_assign(galaxyra, galaxydec, galaxycz, galaxymag, olditassocid, rprojboundary, vprojboundary, centermethod)
# check for convergence
converged = np.array_equal(olditassocid, itassocid)
niter+=1
print("Iterative combination complete.")
return itassocid
# ------------------------------------------------------------------------------------------#
# ------------------------------------------------------------------------------------------#
# Supporting functions
# ------------------------------------------------------------------------------------------#
# ------------------------------------------------------------------------------------------#
def group_skycoords(galaxyra, galaxydec, galaxycz, galaxygrpid):
"""
-----
Obtain a list of group centers (RA/Dec/cz) given a list of galaxy coordinates (equatorial)
and their corresponding group ID numbers.
Inputs (all same length)
galaxyra : 1D iterable, list of galaxy RA values in decimal degrees
galaxydec : 1D iterable, list of galaxy dec values in decimal degrees
galaxycz : 1D iterable, list of galaxy cz values in km/s
galaxygrpid : 1D iterable, group ID number for every galaxy in previous arguments.
Outputs (all shape match `galaxyra`)
groupra : RA in decimal degrees of galaxy i's group center.
groupdec : Declination in decimal degrees of galaxy i's group center.
groupcz : Redshift velocity in km/s of galaxy i's group center.
Note: the FoF code of AA Berlind uses theta_i = declination, with theta_cen =
the central declination. This version uses theta_i = pi/2-dec, with some trig functions
changed so that the output *matches* that of Berlind's FoF code (my "deccen" is the same as
his "thetacen", to be exact.)
-----
"""
galaxyra=np.asarray(galaxyra)
galaxydec=np.asarray(galaxydec)
galaxycz=np.asarray(galaxycz)
galaxygrpid=np.asarray(galaxygrpid)
# Prepare cartesian coordinates of input galaxies
ngalaxies = len(galaxyra)
galaxyphi = galaxyra * np.pi/180.
galaxytheta = np.pi/2. - galaxydec*np.pi/180.
galaxyx = np.sin(galaxytheta)*np.cos(galaxyphi)
galaxyy = np.sin(galaxytheta)*np.sin(galaxyphi)
galaxyz = np.cos(galaxytheta)
# Prepare output arrays
uniqidnumbers = np.unique(galaxygrpid)
groupra = np.zeros(ngalaxies)
groupdec = np.zeros(ngalaxies)
groupcz = np.zeros(ngalaxies)
for i,uid in enumerate(uniqidnumbers):
sel=np.where(galaxygrpid==uid)
nmembers = len(galaxygrpid[sel])
xcen=np.sum(galaxycz[sel]*galaxyx[sel])/nmembers
ycen=np.sum(galaxycz[sel]*galaxyy[sel])/nmembers
zcen=np.sum(galaxycz[sel]*galaxyz[sel])/nmembers
czcen = np.sqrt(xcen**2 + ycen**2 + zcen**2)
deccen = np.arcsin(zcen/czcen)*180.0/np.pi # degrees
if (ycen >=0 and xcen >=0):
phicor = 0.0
elif (ycen < 0 and xcen < 0):
phicor = 180.0
elif (ycen >= 0 and xcen < 0):
phicor = 180.0
elif (ycen < 0 and xcen >=0):
phicor = 360.0
elif (xcen==0 and ycen==0):
print("Warning: xcen=0 and ycen=0 for group {}".format(galaxygrpid[i]))
# set up phicorrection and return phicen.
racen=np.arctan(ycen/xcen)*(180/np.pi)+phicor # in degrees
# set values at each element in the array that belongs to the group under iteration
groupra[sel] = racen # in degrees
groupdec[sel] = deccen # in degrees
groupcz[sel] = czcen
return groupra, groupdec, groupcz
def nearest_neighbor_assign(galaxyra, galaxydec, galaxycz, galaxymag, grpid, rprojboundary, vprojboundary, centermethod):
"""
For a list of galaxies defined by groups, refine group ID numbers using a nearest-neighbor
search and applying the search boundaries.
Parameters
------------
galaxyra, galaxydec, galaxycz : iterable
Input coordinates of galaxies (RA/Dec in decimal degrees, cz in km/s)
galaxymag : iterable
M_r magnitudes or stellar/baryonic masses of input galaxies. (note code refers to 'mags' throughout, but
underlying `fit_in_group` function will distinguish the two.)
grpid : iterable
Group ID number for every input galaxy, at current iteration (potential group).
rprojboundary, vprojboundary : callable
Input functions to assess the search boundaries around potential groups, function of group-integrated luminosity, units Mpc/h and km/s.
Returns
------------
associd : iterable
Refined group ID numbers based on NN "stitching" of groups.
"""
# Prepare output array
associd = deepcopy(grpid)
# Get the group RA/Dec/cz for every galaxy
groupra, groupdec, groupcz = group_skycoords(galaxyra, galaxydec, galaxycz, grpid)
# Get unique potential groups
uniqgrpid, uniqind = np.unique(grpid, return_index=True)
potra, potdec, potcz = groupra[uniqind], groupdec[uniqind], groupcz[uniqind]
# Build & query the K-D Tree
potphi = potra*np.pi/180.
pottheta = np.pi/2. - potdec*np.pi/180.
#zmpc = potcz/HUBBLE_CONST
#xmpc = 2.*np.pi*zmpc*potra*np.cos(np.pi*potdec/180.) / 360.
#ympc = np.float64(2.*np.pi*zmpc*potdec / 360.)
zmpc = potcz/HUBBLE_CONST * np.cos(pottheta)
xmpc = potcz/HUBBLE_CONST*np.sin(pottheta)*np.cos(potphi)
ympc = potcz/HUBBLE_CONST*np.sin(pottheta)*np.sin(potphi)
coords = np.array([xmpc, ympc, zmpc]).T
kdt = cKDTree(coords)
nndist, nnind = kdt.query(coords,k=2)
nndist=nndist[:,1] # ignore self match
nnind=nnind[:,1]
# go through potential groups and adjust membership for input galaxies
alreadydone=np.zeros(len(uniqgrpid)).astype(int)
ct=0
for idx, uid in enumerate(uniqgrpid):
# find the nearest neighbor group
nbridx = nnind[idx]
Gpgalsel=np.where(grpid==uid)
GNNgalsel=np.where(grpid==uniqgrpid[nbridx])
combinedra,combineddec,combinedcz = np.hstack((galaxyra[Gpgalsel],galaxyra[GNNgalsel])),np.hstack((galaxydec[Gpgalsel],galaxydec[GNNgalsel])),np.hstack((galaxycz[Gpgalsel],galaxycz[GNNgalsel]))
combinedmag = np.hstack((galaxymag[Gpgalsel], galaxymag[GNNgalsel]))
if fit_in_group(combinedra, combineddec, combinedcz, combinedmag, rprojboundary, vprojboundary, centermethod) and (not alreadydone[idx]) and (not alreadydone[nbridx]):
# check for reciprocity: is the nearest-neighbor of GNN Gp? If not, leave them both as they are and let it be handled during the next iteration.
nbrnnidx = nnind[nbridx]
if idx==nbrnnidx:
# change group ID of NN galaxies
associd[GNNgalsel]=int(grpid[Gpgalsel][0])
alreadydone[idx]=1
alreadydone[nbridx]=1
else:
alreadydone[idx]=1
else:
alreadydone[idx]=1
return associd
def fit_in_group(galra, galdec, galcz, galmag, rprojboundary, vprojboundary, center='arithmetic'):
"""
Check whether two potential groups can be merged based on the integrated luminosity of the
potential members, given limiting input group sizes.
Parameters
----------------
galra, galdec, galcz : iterable
Coordinates of input galaxies -- all galaxies belonging to the pair of groups that are being assessed.
galmag : iterable
M_r absolute magnitudes of all input galaxies, or galaxy stellar masses - the function can distinguish the two.
rprojboundary, vprojboundary : callable
Limiting projected- and velocity-space group sizes as function of group-integrated luminosity or stellar mass.
center : str
Specifies method of computing proposed center. Options: 'arithmetic' or 'luminosity'. The latter is a weighted-mean positioning based on M_r (like center of mass).
Returns
----------------
fitingroup : bool
Bool indicating whether the series of input galaxies can be merged into a single group of the specified size.
"""
if (galmag<0).all():
memberintmag = get_int_mag(galmag, np.full(len(galmag), 1))
elif (galmag>0).all():
memberintmag = get_int_mass(galmag, np.full(len(galmag), 1))
grpn = len(galra)
galphi = galra*np.pi/180.
galtheta = np.pi/2. - galdec*np.pi/180.
galx = np.sin(galtheta)*np.cos(galphi)
galy = np.sin(galtheta)*np.sin(galphi)
galz = np.cos(galtheta)
if center=='arithmetic':
xcen = np.sum(galcz*galx)/grpn
ycen = np.sum(galcz*galy)/grpn
zcen = np.sum(galcz*galz)/grpn
czcenter = np.sqrt(xcen**2+ycen**2+zcen**2)
deccenter = np.arcsin(zcen/czcenter)*(180.0/np.pi)
phicorr = 0.0*int((ycen >=0 and xcen >=0)) + 180.0*int((ycen < 0 and xcen < 0) or (ycen >= 0 and xcen < 0)) + 360.0*int((ycen < 0 and xcen >=0))
racenter = np.arctan(ycen/xcen)*(180.0/np.pi)+phicorr
elif center=='luminosity':
unlogmag = 10**(-0.4*galmag)
xcen = np.sum(galcz*galx*unlogmag)/np.sum(unlogmag)
ycen = np.sum(galcz*galy*unlogmag)/np.sum(unlogmag)
zcen = np.sum(galcz*galz*unlogmag)/np.sum(unlogmag)
czcenter = np.sqrt(xcen**2+ycen**2+zcen**2)
deccenter = np.arcsin(zcen/czcenter)*(180.0/np.pi)
phicorr = 0.0*int((ycen >=0 and xcen >=0)) + 180.0*int((ycen < 0 and xcen < 0) or (ycen >= 0 and xcen < 0)) + 360.0*int((ycen < 0 and xcen >=0))
racenter = np.arctan(ycen/xcen)*(180.0/np.pi)+phicorr
# check if all members are within rproj and vproj of group center
halfangle = angular_separation(racenter,deccenter,galra[:,None],galdec[:,None])/2.0
projsep = (galcz[:,None]+czcenter)/100. * halfangle
lossep = np.abs(galcz[:,None]-czcenter)
fitingroup=(np.all(projsep<rprojboundary(memberintmag)) and np.all(lossep<vprojboundary(memberintmag)))
return fitingroup
def angular_separation(ra1,dec1,ra2,dec2):
"""
Compute the angular separation bewteen two lists of galaxies using the Haversine formula.
Parameters
------------
ra1, dec1, ra2, dec2 : array-like
Lists of right-ascension and declination values for input targets, in decimal degrees.
Returns
------------
angle : np.array
Array containing the angular separations between coordinates in list #1 and list #2, as above.
Return value expressed in radians, NOT decimal degrees.
"""
phi1 = ra1*np.pi/180.
phi2 = ra2*np.pi/180.
theta1 = np.pi/2. - dec1*np.pi/180.
theta2 = np.pi/2. - dec2*np.pi/180.
return 2*np.arcsin(np.sqrt(np.sin((theta2-theta1)/2.0)**2.0 + np.sin(theta1)*np.sin(theta2)*np.sin((phi2 - phi1)/2.0)**2.0))
def multiplicity_function(grpids, return_by_galaxy=False):
"""
Return counts for binning based on group ID numbers.
Parameters
----------
grpids : iterable
List of group ID numbers. Length must match # galaxies.
Returns
-------
occurences : list
Number of galaxies in each galaxy group (length matches # groups).
"""
grpids=np.asarray(grpids)
uniqid = np.unique(grpids)
if return_by_galaxy:
grpn_by_gal=np.zeros(len(grpids)).astype(int)
for idv in grpids:
sel = np.where(grpids==idv)
grpn_by_gal[sel]=len(sel[0])
return grpn_by_gal
else:
occurences=[]
for uid in uniqid:
sel = np.where(grpids==uid)
occurences.append(len(grpids[sel]))
return occurences
def get_int_mag(galmags, grpid):
"""
Given a list of galaxy absolute magnitudes and group ID numbers,
compute group-integrated total magnitudes.
Parameters
------------
galmags : iterable
List of absolute magnitudes for every galaxy (SDSS r-band).
grpid : iterable
List of group ID numbers for every galaxy.
Returns
------------
grpmags : np array
Array containing group-integrated magnitudes for each galaxy. Length matches `galmags`.
"""
galmags=np.asarray(galmags)
grpid=np.asarray(grpid)
grpmags = np.zeros(len(galmags))
uniqgrpid=np.unique(grpid)
for uid in uniqgrpid:
sel=np.where(grpid==uid)
totalmag = -2.5*np.log10(np.sum(10**(-0.4*galmags[sel])))
grpmags[sel]=totalmag
return grpmags
def get_int_mass(galmass, grpid):
"""
Given a list of galaxy stellar or baryonic masses and group ID numbers,
compute the group-integrated stellar or baryonic mass, galaxy-wise.
Parameters
---------------
galmass : iterable
List of galaxy log(mass).
grpid : iterable
List of group ID numbers for every galaxy.
Returns
---------------
grpmstar : np.array
Array containing group-integrated stellar masses for each galaxy; length matches `galmstar`.
"""
galmass=np.asarray(galmass)
grpid=np.asarray(grpid)
grpmass = np.zeros(len(galmass))
uniqgrpid=np.unique(grpid)
for uid in uniqgrpid:
sel=np.where(grpid==uid)
totalmass = np.log10(np.sum(10**galmass[sel]))
grpmass[sel]=totalmass
return grpmass
def HAMwrapper(galra, galdec, galcz, galmag, galgrpid, volume, inputfilename=None, outputfilename=None):
"""
Perform halo abundance matching on a galaxy group catalog (wrapper around the C code of <NAME>).
Parameters
-------------
galra, galdec, galcz : iterable
Input coordinates of galaxies (in decimal degrees, and km/s).
galmag : iterable
Input r-band absolute magnitudes of galaxies, or their stellar or baryonic masses. The code
will distinguish between mags/masses, albeit variables in the code refer to 'mag' throughout.
galgrpid : iterable
Group ID number for every input galaxy.
value to true if matching abundance on mass (like group-int stellar mass), for which the values are >0.
volume : float, units in (Mpc/h)^3
Survey volume.
inputfilename : string, default None
Filename to save input HAM file for the C executable. If None, the file is removed during execution.
outputfilename : string, default None
Filename to save output HAM file from the C executable. If None, the file is removed during execution.
Returns
-------------
haloid : np.float64 array
ID of abundance-matched halos (matches number of unique values in `galgrpid`).
halologmass : np.float64 array
Log(halo mass per h) of each halo, length matches `haloid`.
halorvir : np.float64 array
Virial radii of each halo.
halosigma : np.float64 array
Theoretical velocity dispersion of each halo.
"""
galra=np.array(galra)
galdec=np.array(galdec)
galcz=np.array(galcz)
galmag=np.array(galmag)
galgrpid=np.array(galgrpid)
deloutfile=(outputfilename==None)
delinfile=(inputfilename==None)
# Prepare inputs
grpra, grpdec, grpcz = group_skycoords(galra, galdec, galcz, galgrpid)
if (galmag<0).all():
grpmag = get_int_mag(galmag, galgrpid)
elif (galmag>0).all():
grpmag = -1*get_int_mass(galmag, galgrpid) # need -1 to trick Andreas' HAM code into using masses.
grprproj, grpsigma = get_rproj_czdisp(galra, galdec, galcz, galgrpid)
# Reshape them to match len grps
uniqgrpid, uniqind = np.unique(galgrpid, return_index=True)
grpra=grpra[uniqind]
grpdec=grpdec[uniqind]
grpcz=grpcz[uniqind]
grprproj=grprproj[uniqind]
grpsigma=grpsigma[uniqind]
grpmag = grpmag[uniqind]
grpN=[]
for uid in uniqgrpid: grpN.append(len(galgrpid[np.where(galgrpid==uid)]))
grpN=np.asarray(grpN)
# Create input file and write to it
if inputfilename is None:
inputfilename = "temporaryhaminput"+str(time.time())+".txt"
f = open(inputfilename, 'w')
for i in range(0,len(grpra)):
f.write("G\t{a}\t{b}\t{c}\t{d}\t{e}\t{f}\t{g}\t{h}\n".format(a=int(uniqgrpid[i]),b=grpra[i],c=grpdec[i],d=grpcz[i],e=grpN[i],f=grpsigma[i],g=grprproj[i],h=grpmag[i]))
f.close()
# try to do the HAM
if outputfilename is None: outputfilename='temporaryhamoutput'+str(time.time())+".txt"
#try:
hamcommand = "./massmatch HaloMF337tinker.dat {} < ".format(volume)+inputfilename+" > "+outputfilename
try:
os.system(hamcommand)
except:
raise RunTimeError("OS call to HAM C executable failed; check input data type")
hamfile=np.genfromtxt(outputfilename)
haloid = np.float64(hamfile[:,0])
halologmass = np.float64(hamfile[:,1])
halorvir = np.float64(hamfile[:,2])
halosigma = np.float64(hamfile[:,3])
if deloutfile: os.remove(outputfilename)
if delinfile: os.remove(inputfilename)
return haloid, halologmass, halorvir, halosigma
def get_rproj_czdisp(galaxyra, galaxydec, galaxycz, galaxygrpid):
"""
Compute the observational projected radius, in Mpc/h, and the observational
velocity dispersion, in km/s, for a galaxy group catalog. Input should match
the # of galaxies, and the output will as well. Based on FoF4 code of Berlind+
2006.
Parameters
----------
galaxyra : iterable
Right-ascension of grouped galaxies in decimal degrees.
galaxydec : iterable
Declination of grouped galaxies in decimal degrees.
galaxycz : iterable
Redshift velocity (cz) of grouped galaxies in km/s.
galaxygrpid : iterable
Group ID numbers of grouped galaxies, shape should match `galaxyra`.
Returns
-------
rproj : np.array, shape matches `galaxyra`
For element index i, projected radius of galaxy group to which galaxy i belongs, in Mpc/h.
vdisp : np.array, shape matches `galaxyra`
For element index i, velocity dispersion of galaxy group to which galaxy i belongs, in km/s.
"""
galaxyra=np.asarray(galaxyra)
galaxydec=np.asarray(galaxydec)
galaxycz=np.asarray(galaxycz)
galaxygrpid=np.asarray(galaxygrpid)
rproj=np.zeros(len(galaxyra))
vdisp=np.zeros(len(galaxyra))
grpra, grpdec, grpcz = group_skycoords(galaxyra, galaxydec, galaxycz, galaxygrpid)
grpra = grpra*np.pi/180. #convert everything to radians
galaxyra=galaxyra*np.pi/180.
galaxydec=galaxydec*np.pi/180.
grpdec = grpdec*np.pi/180.
uniqid = np.unique(galaxygrpid)
cspeed=299800 # km/s
for uid in uniqid:
sel = np.where(galaxygrpid==uid)
nmembers=len(sel[0])
if nmembers==1:
rproj[sel]=0.
vdisp[sel]=0.
else:
phicen=grpra[sel][0]
thetacen=grpdec[sel][0]
cosDpsi=np.cos(thetacen)*np.cos(galaxydec[sel])+np.sin(thetacen)*np.sin(galaxydec[sel])*np.cos((phicen - galaxyra[sel]))
sinDpsi=np.sqrt(1-cosDpsi**2)
rp=sinDpsi*galaxycz[sel]/HUBBLE_CONST
rproj[sel]=np.sqrt(np.sum(rp**2)/len(sel[0]))
czcen = grpcz[sel][0]
Dz2 = np.sum((galaxycz[sel]-czcen)**2.0)
vdisp[sel]=np.sqrt(Dz2/(nmembers-1))/(1.+czcen/cspeed)
return rproj, vdisp
def getmhoffset(delta1, delta2, borc1, borc2, cc):
"""
Credit: <NAME> & <NAME>
Adapted from Katie's code, using eqns from "Sample Variance Considerations for Cluster Surveys," Hu & Kravtsov (2003) ApJ, 584, 702
(astro-ph/0203169)
delta1 is overdensity of input, delta2 is overdensity of output -- for mock, delta1 = 200
borc = 1 if wrt background density, borc = 0 if wrt critical density
cc is concentration of halo- use cc=6
"""
if borc1 == 0:
delta1 = delta1/0.3
if borc2 == 0:
delta2 = delta2/0.3
xin = 1./cc
f_1overc = (xin)**3. * (np.log(1. + (1./xin)) - (1. + xin)**(-1.))
f1 = delta1/delta2 * f_1overc
a1=0.5116
a2=-0.4283
a3=-3.13e-3
a4=-3.52e-5
p = a2 + a3*np.log(f1) + a4*(np.log(f1))**2.
x_f1 = (a1*f1**(2.*p) + (3./4.)**2.)**(-1./2.) + 2.*f1
r2overr1 = x_f1
m1overm2 = (delta1/delta2) * (1./r2overr1)**3. * (1./cc)**3.
return m1overm2
def decayexp(x, a, b, c, d):
return np.abs(a)*np.exp(-1*np.abs(b)*x + c)+np.abs(d)
|
zhutchens1/g3groups | create_ecoresolve_baryonicmassselgroups.py | """
<NAME> - November 2020
This program creates baryonic mass-selected group catalogs for ECO/RESOLVE-G3 using the new algorithm, described in the readme markdown.
The outline of this code is:
(1) Read in observational data from RESOLVE-B and ECO (the latter includes RESOLVE-A).
(2) Prepare arrays of input parameters and for storing results.
(3) Perform FoF only for giants in ECO, using an adaptive linking strategy.
(a) Get the adaptive links for every ECO galaxy.
(b) Fit those adaptive links for use in RESOLVE-B.
(c) Perform giant-only FoF for ECO
(d) Perform giant-only FoF for RESOLVE-B, by interpolating the fit to obtain separations for RESOLVE-B.
(4) From giant-only groups, fit model for individual giant projected radii and peculiar velocites, to use for association.
(5) Associate dwarf galaxies to giant-only FoF groups for ECO and RESOLVE-B (note different selection floors for dwarfs).
(6) Based on giant+dwarf groups, calibrate boundaries (as function of giant+dwarf integrated baryonic mass) for iterative combination
(7) Iterative combination on remaining ungrouped dwarf galaxies
(8) halo mass assignment
(9) Finalize arrays + output
"""
import virtools as vz
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d, UnivariateSpline
from scipy.optimize import curve_fit
from center_binned_stats import center_binned_stats
import foftools as fof
import iterativecombination as ic
from smoothedbootstrap import smoothedbootstrap as sbs
import sys
from lss_dens import lss_dens_by_galaxy
def giantmodel(x, a, b):
return np.abs(a)*np.log(np.abs(b)*x+1)
def exp(x, a, b, c):
return np.abs(a)*np.exp(1*np.abs(b)*x + c)
def sepmodel(x, a, b, c, d, e):
#return np.abs(a)*np.exp(-1*np.abs(b)*x + c)+d
#return a*(x**3)+b*(x**2)+c*x+d
return a*(x**4)+b*(x**3)+c*(x**2)+(d*x)+e
def sigmarange(x):
q84, q16 = np.percentile(x, [84 ,16])
return (q84-q16)/2
if __name__=='__main__':
####################################
# Step 1: Read in obs data
####################################
ecodata = pd.read_csv("ECOdata_022521.csv")
resolvedata = pd.read_csv("RESOLVEdata_022521.csv")
resolvebdata = resolvedata[resolvedata.f_b==1]
####################################
# Step 2: Prepare arrays
####################################
ecosz = len(ecodata)
econame = np.array(ecodata.name)
ecoresname = np.array(ecodata.resname)
ecoradeg = np.array(ecodata.radeg)
ecodedeg = np.array(ecodata.dedeg)
ecocz = np.array(ecodata.cz)
ecologmstar = np.array(ecodata.logmstar)
ecologmgas = np.array(ecodata.logmgas)
ecologmbary = np.log10(10.**ecologmstar+10.**ecologmgas)
ecourcolor = np.array(ecodata.modelu_rcorr)
ecog3grp = np.full(ecosz, -99.) # id number of g3 group
ecog3grpn = np.full(ecosz, -99.) # multiplicity of g3 group
ecog3grpradeg = np.full(ecosz,-99.) # ra of group center
ecog3grpdedeg = np.full(ecosz,-99.) # dec of group center
ecog3grpcz = np.full(ecosz,-99.) # cz of group center
ecog3logmh = np.full(ecosz,-99.) # abundance-matched halo mass
resbana_g3grp = np.full(ecosz,-99.) # for RESOLVE-B analogue dataset
resbsz = int(len(resolvebdata))
resbname = np.array(resolvebdata.name)
resbradeg = np.array(resolvebdata.radeg)
resbdedeg = np.array(resolvebdata.dedeg)
resbcz = np.array(resolvebdata.cz)
resblogmstar = np.array(resolvebdata.logmstar)
resblogmgas = np.array(resolvebdata.logmgas)
resblogmbary = np.log10(10.**resblogmstar+10.**resblogmgas)
resburcolor = np.array(resolvebdata.modelu_rcorr)
resbg3grp = np.full(resbsz, -99.)
resbg3grpn = np.full(resbsz, -99.)
resbg3grpradeg = np.full(resbsz, -99.)
resbg3grpdedeg = np.full(resbsz, -99.)
resbg3grpcz = np.full(resbsz, -99.)
resbg3logmh = np.full(resbsz, -99.)
####################################
# Step 3: Giant-Only FOF
####################################
ecogiantsel = (ecologmbary>=9.9) & (ecocz>2530.) & (ecocz<8000.)
# (a) compute sep values for eco giants
ecovolume = 192351.36 # Mpc^3 with h=1 **
meansep0 = (ecovolume/len(ecologmbary[ecogiantsel]))**(1/3.)
# (c) perform giant-only FoF on ECO
blos = 1.1
bperp = 0.07 # from Duarte & Mamon 2014
ecogiantfofid = fof.fast_fof(ecoradeg[ecogiantsel], ecodedeg[ecogiantsel], ecocz[ecogiantsel], bperp, blos, meansep0) # meansep0 if fixed LL
ecog3grp[ecogiantsel] = ecogiantfofid
resbana_g3grp[ecogiantsel] = ecogiantfofid # RESOLVE-B analogue dataset
# (d) perform giant-only FoF on RESOLVE-B
resbgiantsel = (resblogmbary>=9.9) & (resbcz>4250) & (resbcz<7300)
resbgiantfofid = fof.fast_fof(resbradeg[resbgiantsel], resbdedeg[resbgiantsel], resbcz[resbgiantsel], bperp, blos, meansep0)
resbg3grp[resbgiantsel] = resbgiantfofid
# (e) check the FOF results
plt.figure()
binv = np.arange(0.5,3000.5,3)
plt.hist(fof.multiplicity_function(ecog3grp[ecog3grp!=-99.], return_by_galaxy=False), bins=binv, histtype='step', linewidth=3, label='ECO Giant-Only FoF Groups')
plt.hist(fof.multiplicity_function(resbg3grp[resbg3grp!=-99.], return_by_galaxy=False), bins=binv, histtype='step', linewidth=1.5, hatch='\\', label='RESOLVE-B Giant-Only FoF Groups')
plt.xlabel("Number of Giant Galaxies per Group")
plt.ylabel("Number of Giant-Only FoF Groups")
plt.yscale('log')
plt.legend(loc='best')
plt.xlim(0,80)
plt.show()
##########################################
# Step 4: Compute Association Boundaries
##########################################
ecogiantgrpra, ecogiantgrpdec, ecogiantgrpcz = fof.group_skycoords(ecoradeg[ecogiantsel], ecodedeg[ecogiantsel], ecocz[ecogiantsel], ecogiantfofid)
relvel = np.abs(ecogiantgrpcz - ecocz[ecogiantsel])
relprojdist = (ecogiantgrpcz + ecocz[ecogiantsel])/100. * np.sin(ic.angular_separation(ecogiantgrpra, ecogiantgrpdec, ecoradeg[ecogiantsel], ecodedeg[ecogiantsel])/2.0)
ecogiantgrpn = fof.multiplicity_function(ecogiantfofid, return_by_galaxy=True)
uniqecogiantgrpn, uniqindex = np.unique(ecogiantgrpn, return_index=True)
keepcalsel = np.where(uniqecogiantgrpn>1)
median_relprojdist = np.array([np.median(relprojdist[np.where(ecogiantgrpn==sz)]) for sz in uniqecogiantgrpn[keepcalsel]])
median_relvel = np.array([np.median(relvel[np.where(ecogiantgrpn==sz)]) for sz in uniqecogiantgrpn[keepcalsel]])
rproj_median_error = np.std(np.array([sbs(relprojdist[np.where(ecogiantgrpn==sz)], 100000, np.median, kwargs=dict({'axis':1 })) for sz in uniqecogiantgrpn[keepcalsel]]), axis=1)
dvproj_median_error = np.std(np.array([sbs(relvel[np.where(ecogiantgrpn==sz)], 100000, np.median, kwargs=dict({'axis':1})) for sz in uniqecogiantgrpn[keepcalsel]]), axis=1)
#rprojslope, rprojint = np.polyfit(uniqecogiantgrpn[keepcalsel], median_relprojdist, deg=1, w=1/rproj_median_error)
#dvprojslope, dvprojint = np.polyfit(uniqecogiantgrpn[keepcalsel], median_relvel, deg=1, w=1/dvproj_median_error)
poptrproj, jk = curve_fit(giantmodel, uniqecogiantgrpn[keepcalsel], median_relprojdist, sigma=rproj_median_error)
poptdvproj,jk = curve_fit(giantmodel, uniqecogiantgrpn[keepcalsel], median_relvel, sigma=dvproj_median_error)#, p0=[160,6.5,45,-600])
rproj_boundary = lambda N: 3*giantmodel(N, *poptrproj) #3*(rprojslope*N+rprojint)
vproj_boundary = lambda N: 4.5*giantmodel(N, *poptdvproj) #4.5*(dvprojslope*N+dvprojint)
assert rproj_boundary(1)>0, "Rproj boundary fit can't be extrapolated to N=1"
assert vproj_boundary(1)>0, "dv proj boundary fit can't be extrapolated to N=1"
# get virial radii from abundance matching to giant-only groups
gihaloid, gilogmh, gir280, gihalovdisp = ic.HAMwrapper(ecoradeg[ecogiantsel], ecodedeg[ecogiantsel], ecocz[ecogiantsel], ecologmbary[ecogiantsel], ecog3grp[ecogiantsel],\
ecovolume, inputfilename=None, outputfilename=None)
gilogmh = np.log10(10**gilogmh)#no longer needed as of 7/29: /fof.getmhoffset(280,337,1,1,6))
gihalorvir = (3*(10**gilogmh) / (4*np.pi*337*0.3*2.77e11) )**(1/3.)
gihalon = fof.multiplicity_function(np.sort(ecog3grp[ecogiantsel]), return_by_galaxy=False)
plt.figure()
plt.plot(gihalon, gihalorvir, 'k.')
plt.show()
plt.figure()
sel = (ecogiantgrpn>1)
plt.scatter(gihalon, gihalovdisp, marker='D', color='purple', label=r'ECO HAM Velocity Dispersion')
plt.plot(ecogiantgrpn[sel], relvel[sel], 'r.', alpha=0.2, label='ECO Giant Galaxies')
plt.errorbar(uniqecogiantgrpn[keepcalsel], median_relvel, fmt='k^', label=r'$\Delta v_{\rm proj}$ (Median of $\Delta v_{\rm proj,\, gal}$)',yerr=dvproj_median_error)
tx = np.linspace(1,max(ecogiantgrpn),1000)
plt.plot(tx, giantmodel(tx, *poptdvproj), label=r'$1\Delta v_{\rm proj}^{\rm fit}$')
plt.plot(tx, 4.5*giantmodel(tx, *poptdvproj), 'g', label=r'$4.5\Delta v_{\rm proj}^{\rm fit}$', linestyle='-.')
plt.xlabel("Number of Giant Members")
plt.ylabel("Relative Velocity to Group Center [km/s]")
plt.legend(loc='best')
plt.show()
plt.clf()
plt.scatter(gihalon, gihalorvir, marker='D', color='purple', label=r'ECO Group Virial Radii')
plt.plot(ecogiantgrpn[sel], relprojdist[sel], 'r.', alpha=0.2, label='ECO Giant Galaxies')
plt.errorbar(uniqecogiantgrpn[keepcalsel], median_relprojdist, fmt='k^', label=r'$R_{\rm proj}$ (Median of $R_{\rm proj,\, gal}$)',yerr=rproj_median_error)
plt.plot(tx, giantmodel(tx, *poptrproj), label=r'$1R_{\rm proj}^{\rm fit}$')
plt.plot(tx, 3*giantmodel(tx, *poptrproj), 'g', label=r'$3R_{\rm proj}^{\rm fit}$', linestyle='-.')
plt.xlabel("Number of Giant Members in Galaxy's Group")
plt.ylabel("Projected Distance from Giant to Group Center [Mpc/h]")
plt.legend(loc='best')
#plt.xlim(0,20)
#plt.ylim(0,2.5)
#plt.xticks(np.arange(0,22,2))
plt.show()
####################################
# Step 5: Association of Dwarfs
####################################
ecodwarfsel = (ecologmbary<9.9) & (ecologmbary>=9.4) & (ecocz>2530) & (ecocz<8000)
resbdwarfsel = (resblogmbary<9.9) & (resblogmbary>=9.1) & (resbcz>4250) & (resbcz<7300)
resbana_dwarfsel = (ecologmbary<9.9) & (ecologmbary>=9.1) & (ecocz>2530) & (ecocz<8000)
resbgiantgrpra, resbgiantgrpdec, resbgiantgrpcz = fof.group_skycoords(resbradeg[resbgiantsel], resbdedeg[resbgiantsel], resbcz[resbgiantsel], resbgiantfofid)
resbgiantgrpn = fof.multiplicity_function(resbgiantfofid, return_by_galaxy=True)
ecodwarfassocid, junk = fof.fast_faint_assoc(ecoradeg[ecodwarfsel],ecodedeg[ecodwarfsel],ecocz[ecodwarfsel],ecogiantgrpra,ecogiantgrpdec,ecogiantgrpcz,ecogiantfofid,\
rproj_boundary(ecogiantgrpn),vproj_boundary(ecogiantgrpn))
resbdwarfassocid, junk = fof.fast_faint_assoc(resbradeg[resbdwarfsel],resbdedeg[resbdwarfsel],resbcz[resbdwarfsel],resbgiantgrpra,resbgiantgrpdec,resbgiantgrpcz,resbgiantfofid,\
rproj_boundary(resbgiantgrpn),vproj_boundary(resbgiantgrpn))
resbana_dwarfassocid, jk = fof.fast_faint_assoc(ecoradeg[resbana_dwarfsel], ecodedeg[resbana_dwarfsel], ecocz[resbana_dwarfsel], ecogiantgrpra, ecogiantgrpdec, ecogiantgrpcz, ecogiantfofid,\
rproj_boundary(ecogiantgrpn), vproj_boundary(ecogiantgrpn))
ecog3grp[ecodwarfsel] = ecodwarfassocid
resbg3grp[resbdwarfsel] = resbdwarfassocid
resbana_g3grp[resbana_dwarfsel] = resbana_dwarfassocid
###############################################
# Step 6: Calibration for Iter. Combination
###############################################
ecogdgrpn = fof.multiplicity_function(ecog3grp, return_by_galaxy=True)
#ecogdsel = np.logical_not((ecogdgrpn==1) & (ecologmbary>-19.4) & (ecog3grp>0)) # select galaxies that AREN'T ungrouped dwarfs
ecogdsel = np.logical_not(np.logical_or(ecog3grp==-99., ((ecogdgrpn==1) & (ecologmbary<9.9) & (ecologmbary>=9.4))))
ecogdgrpra, ecogdgrpdec, ecogdgrpcz = fof.group_skycoords(ecoradeg[ecogdsel], ecodedeg[ecogdsel], ecocz[ecogdsel], ecog3grp[ecogdsel])
ecogdrelvel = np.abs(ecogdgrpcz - ecocz[ecogdsel])
ecogdrelprojdist = (ecogdgrpcz + ecocz[ecogdsel])/100. * np.sin(ic.angular_separation(ecogdgrpra, ecogdgrpdec, ecoradeg[ecogdsel], ecodedeg[ecogdsel])/2.0)
ecogdn = ecogdgrpn[ecogdsel]
ecogdtotalmass = ic.get_int_mass(ecologmbary[ecogdsel], ecog3grp[ecogdsel])
massbins=np.arange(9.9,14,0.15)
binsel = np.where(np.logical_and(ecogdn>1, ecogdtotalmass<14))
gdmedianrproj, massbincenters, massbinedges, jk = center_binned_stats(ecogdtotalmass[binsel], ecogdrelprojdist[binsel], np.median, bins=massbins)
gdmedianrproj_err, jk, jk, jk = center_binned_stats(ecogdtotalmass[binsel], ecogdrelprojdist[binsel], sigmarange, bins=massbins)
gdmedianrelvel, jk, jk, jk = center_binned_stats(ecogdtotalmass[binsel], ecogdrelvel[binsel], np.median, bins=massbins)
gdmedianrelvel_err, jk, jk, jk = center_binned_stats(ecogdtotalmass[binsel], ecogdrelvel[binsel], sigmarange, bins=massbins)
nansel = np.isnan(gdmedianrproj)
if 0:
guess=None
else:
guess=None# [-1,0.5,-6]#None#[1e-5, 0.4, 0.2, 1]
poptr, pcovr = curve_fit(exp, massbincenters[~nansel], gdmedianrproj[~nansel], p0=guess, sigma=gdmedianrproj_err[~nansel])
poptv, pcovv = curve_fit(exp, massbincenters[~nansel], gdmedianrelvel[~nansel], p0=[3e-5,4e-1,5e-03], sigma=gdmedianrelvel_err[~nansel])
tx = np.linspace(7,15,100)
plt.figure()
plt.plot(ecogdtotalmass[binsel], ecogdrelprojdist[binsel], 'k.', alpha=0.2, label='ECO Galaxies in N>1 Giant+Dwarf Groups')
plt.errorbar(massbincenters, gdmedianrproj, yerr=gdmedianrproj_err, fmt='r^', label='Medians')
plt.plot(tx, exp(tx,*poptr), label='Fit to Medians')
plt.plot(tx, 3*exp(tx,*poptr), label='3 times Fit to Medians')
plt.xlabel(r"Integrated baryonic Mass of Giant + Dwarf Members")
plt.ylabel("Projected Distance from Galaxy to Group Center [Mpc/h]")
plt.legend(loc='best')
plt.xlim(9.9,13)
plt.ylim(0,3)
plt.show()
plt.figure()
plt.plot(ecogdtotalmass[binsel], ecogdrelvel[binsel], 'k.', alpha=0.2, label='Mock Galaxies in N=2 Giant+Dwarf Groups')
plt.errorbar(massbincenters, gdmedianrelvel, yerr=gdmedianrelvel_err, fmt='r^',label='Medians')
plt.plot(tx, exp(tx, *poptv), label='Fit to Medians')
plt.plot(tx, 4.5*exp(tx, *poptv), label='4.5 times Fit to Medians')
plt.ylabel("Relative Velocity between Galaxy and Group Center")
plt.xlabel(r"Integrated baryonic Mass of Giant + Dwarf Members")
plt.xlim(9.9,13.2)
plt.ylim(0,2000)
plt.show()
rproj_for_iteration = lambda M: 3*exp(M, *poptr)
vproj_for_iteration = lambda M: 4.5*exp(M, *poptv)
# --------------- now need to do this calibration for the RESOLVE-B analogue dataset, down to 9.1 baryonic mass) -------------$
resbana_gdgrpn = fof.multiplicity_function(resbana_g3grp, return_by_galaxy=True)
#resbana_gdsel = np.logical_not((resbana_gdgrpn==1) & (ecologmbary>-19.4) & (resbana_g3grp!=-99.) & (resbana_g3grp>0)) # select galaxies that AREN'T ungrouped dwarfs
resbana_gdsel = np.logical_not(np.logical_or(resbana_g3grp==-99., ((resbana_gdgrpn==1) & (ecologmbary<9.9) & (ecologmbary>=9.1))))
resbana_gdgrpra, resbana_gdgrpdec, resbana_gdgrpcz = fof.group_skycoords(ecoradeg[resbana_gdsel], ecodedeg[resbana_gdsel], ecocz[resbana_gdsel], resbana_g3grp[resbana_gdsel])
resbana_gdrelvel = np.abs(resbana_gdgrpcz - ecocz[resbana_gdsel])
resbana_gdrelprojdist = (resbana_gdgrpcz + ecocz[resbana_gdsel])/100. *np.sin(ic.angular_separation(resbana_gdgrpra, resbana_gdgrpdec, ecoradeg[resbana_gdsel], ecodedeg[resbana_gdsel])/2.0)
resbana_gdn = resbana_gdgrpn[resbana_gdsel]
resbana_gdtotalmass = ic.get_int_mass(ecologmbary[resbana_gdsel], resbana_g3grp[resbana_gdsel])
massbins2=np.arange(9.9,14,0.15)
binsel2 = np.where(np.logical_and(resbana_gdn>1, resbana_gdtotalmass>-24))
gdmedianrproj, massbincenters, massbinedges, jk = center_binned_stats(resbana_gdtotalmass[binsel2], resbana_gdrelprojdist[binsel2], np.median, bins=massbins2)
gdmedianrproj_err, jk, jk, jk = center_binned_stats(resbana_gdtotalmass[binsel2], resbana_gdrelprojdist[binsel2], sigmarange, bins=massbins2)
gdmedianrelvel, jk, jk, jk = center_binned_stats(resbana_gdtotalmass[binsel2], resbana_gdrelvel[binsel2], np.median, bins=massbins2)
gdmedianrelvel_err, jk, jk, jk = center_binned_stats(resbana_gdtotalmass[binsel2], resbana_gdrelvel[binsel2], sigmarange, bins=massbins2)
nansel = np.isnan(gdmedianrproj)
poptr_resbana, jk = curve_fit(exp, massbincenters[~nansel], gdmedianrproj[~nansel], p0=poptr)#, sigma=2**massbincenters[~nansel])
poptv_resbana, jk = curve_fit(exp, massbincenters[~nansel], gdmedianrelvel[~nansel], p0=poptv)
tx = np.linspace(7,15)
plt.figure()
plt.plot(resbana_gdtotalmass[binsel2], resbana_gdrelprojdist[binsel2], 'k.', alpha=0.2, label='Mock Galaxies in N>1 Giant+Dwarf Groups')
plt.errorbar(massbincenters, gdmedianrproj, yerr=gdmedianrproj_err, fmt='r^', label='Medians')
plt.plot(tx, exp(tx,*poptr_resbana), label='Fit to Medians')
plt.plot(tx, 3*exp(tx,*poptr_resbana), label='3 times Fit to Medians')
plt.xlabel(r"Integrated baryonic Mass of Giant + Dwarf Members")
plt.ylabel("Projected Distance from Galaxy to Group Center [Mpc/h]")
plt.legend(loc='best')
plt.xlim(9.9,13.2)
plt.ylim(0,3)
plt.show()
plt.figure()
plt.plot(resbana_gdtotalmass[binsel2], resbana_gdrelvel[binsel2], 'k.', alpha=0.2, label='Mock Galaxies in N=2 Giant+Dwarf Groups')
plt.errorbar(massbincenters, gdmedianrelvel,yerr=gdmedianrelvel_err, fmt='r^',label='Medians')
plt.plot(tx, exp(tx, *poptv_resbana), label='Fit to Medians')
plt.plot(tx, 4.5*exp(tx, *poptv_resbana), label='4.5 times Fit to Medians')
plt.ylabel("Relative Velocity between Galaxy and Group Center")
plt.xlabel(r"Integrated baryonic Mass of Giant + Dwarf Members")
plt.xlim(9.9,13.2)
plt.ylim(0,2000)
plt.show()
rproj_for_iteration_resbana = lambda M: 3*exp(M, *poptr_resbana)
vproj_for_iteration_resbana = lambda M: 4.5*exp(M, *poptv_resbana)
###########################################################
# Step 7: Iterative Combination of Dwarf Galaxies
###########################################################
assert (ecog3grp[(ecologmbary>9.9) & (ecocz<8000) & (ecocz>2530)]!=-99.).all(), "Not all giants are grouped."
ecogrpnafterassoc = fof.multiplicity_function(ecog3grp, return_by_galaxy=True)
resbgrpnafterassoc = fof.multiplicity_function(resbg3grp, return_by_galaxy=True)
resbana_grpnafterassoc = fof.multiplicity_function(resbana_g3grp, return_by_galaxy=True)
eco_ungroupeddwarf_sel = (ecologmbary<9.9) & (ecologmbary>=9.4) & (ecocz<8000) & (ecocz>2530) & (ecogrpnafterassoc==1)
ecoitassocid = ic.iterative_combination(ecoradeg[eco_ungroupeddwarf_sel], ecodedeg[eco_ungroupeddwarf_sel], ecocz[eco_ungroupeddwarf_sel], ecologmbary[eco_ungroupeddwarf_sel],\
rproj_for_iteration, vproj_for_iteration, starting_id=np.max(ecog3grp)+1, centermethod='arithmetic')
resb_ungroupeddwarf_sel = (resblogmbary<9.9) & (resblogmbary>=9.1) & (resbcz<7300) & (resbcz>4250) & (resbgrpnafterassoc==1)
resbitassocid = ic.iterative_combination(resbradeg[resb_ungroupeddwarf_sel], resbdedeg[resb_ungroupeddwarf_sel], resbcz[resb_ungroupeddwarf_sel], resblogmbary[resb_ungroupeddwarf_sel],\
rproj_for_iteration, vproj_for_iteration, starting_id=np.max(resbg3grp)+1, centermethod='arithmetic')
resbana_ungroupeddwarf_sel = (ecologmbary<9.9) & (ecologmbary>=9.1) & (ecocz<8000) & (ecocz>2530) & (resbana_grpnafterassoc==1)
resbana_itassocid = ic.iterative_combination(ecoradeg[resbana_ungroupeddwarf_sel], ecodedeg[resbana_ungroupeddwarf_sel], ecocz[resbana_ungroupeddwarf_sel], ecologmbary[resbana_ungroupeddwarf_sel],\
rproj_for_iteration_resbana, vproj_for_iteration_resbana, starting_id=np.max(resbana_g3grp)+1, centermethod='arithmetic')
ecog3grp[eco_ungroupeddwarf_sel] = ecoitassocid
resbg3grp[resb_ungroupeddwarf_sel] = resbitassocid
resbana_g3grp[resbana_ungroupeddwarf_sel] = resbana_itassocid
#plt.figure()
#plt.hist(fof.multiplicity_function(ecoitassocid, return_by_galaxy=False), log=True)
#plt.hist(fof.multiplicity_function(resbitassocid, return_by_galaxy=False), log=True, histtype='step')
#plt.show()
plt.figure()
binv = np.arange(0.5,1200.5,3)
plt.hist(fof.multiplicity_function(ecog3grp[ecog3grp!=-99.], return_by_galaxy=False), bins=binv, log=True, label='ECO Groups', histtype='step', linewidth=3)
plt.hist(fof.multiplicity_function(resbg3grp[resbg3grp!=-99.], return_by_galaxy=False), bins=binv, log=True, label='RESOLVE-B Groups', histtype='step', hatch='\\')
plt.xlabel("Number of Giant + Dwarf Group Members")
plt.ylabel("Number of Groups")
plt.legend(loc='best')
plt.xlim(0,100)
plt.show()
############################################################
# Step 8: Halo Abundance Matching
###########################################################
# --- for RESOLVE-B analogue ----#
resbana_hamsel = (resbana_g3grp!=-99.)
resbana_haloid, resbana_halomass, jk, jk = ic.HAMwrapper(ecoradeg[resbana_hamsel], ecodedeg[resbana_hamsel], ecocz[resbana_hamsel], ecologmbary[resbana_hamsel], resbana_g3grp[resbana_hamsel],\
ecovolume, inputfilename=None, outputfilename=None)
resbana_halomass = np.log10(10**resbana_halomass)# no longer needed as of 7/29: fof.getmhoffset(280,337,1,1,6))
junk, uniqindex = np.unique(resbana_g3grp[resbana_hamsel], return_index=True)
resbana_intmass = ic.get_int_mass(ecologmbary[resbana_hamsel], resbana_g3grp[resbana_hamsel])[uniqindex]
sortind = np.argsort(resbana_intmass)
sortedmass = resbana_intmass[sortind]
resbcubicspline = interp1d(sortedmass, resbana_halomass[sortind], fill_value='extrapolate')
resbintmass = ic.get_int_mass(resblogmbary[resbg3grp!=-99.], resbg3grp[resbg3grp!=-99.])
resbg3logmh[resbg3grp!=-99.] = resbcubicspline(resbintmass)-np.log10(0.7)
# ---- for ECO ----- #
ecohamsel = (ecog3grp!=-99.)
haloid, halomass, junk, junk = ic.HAMwrapper(ecoradeg[ecohamsel], ecodedeg[ecohamsel], ecocz[ecohamsel], ecologmbary[ecohamsel], ecog3grp[ecohamsel],\
ecovolume, inputfilename=None, outputfilename=None)
junk, uniqindex = np.unique(ecog3grp[ecohamsel], return_index=True)
halomass = halomass-np.log10(0.7)
for i,idv in enumerate(haloid):
sel = np.where(ecog3grp==idv)
ecog3logmh[sel] = halomass[i] # m337b
# calculate Rvir in arcsec
ecog3rvir = (3*(10**ecog3logmh) / (4*np.pi*337*0.3*1.36e11) )**(1/3.)
resbg3rvir = (3*(10**resbg3logmh) / (4*np.pi*337*0.3*1.36e11))**(1/3.)
ecointmass = ic.get_int_mass(ecologmbary[ecohamsel], ecog3grp[ecohamsel])
plt.figure()
plt.plot(ecointmass, ecog3logmh[ecog3grp!=-99.], '.', color='palegreen', alpha=0.6, label='ECO', markersize=11)
plt.plot(resbintmass, resbg3logmh[resbg3grp!=-99.], 'k.', alpha=1, label='RESOLVE-B', markersize=3)
plt.plot
plt.xlabel("group-integrated log baryonic mass")
plt.ylabel(r"group halo mass (log$M_\odot$)")
plt.legend(loc='best')
plt.show()
########################################
# (9) Output arrays
########################################
# ---- first get the quantities for ECO ---- #
#eco_in_gf = np.where(ecog3grp!=-99.)
ecog3grpn = fof.multiplicity_function(ecog3grp, return_by_galaxy=True)
ecog3grpngi = np.zeros(len(ecog3grpn))
ecog3grpndw = np.zeros(len(ecog3grpn))
for uid in np.unique(ecog3grp):
grpsel = np.where(ecog3grp==uid)
gisel = np.where(np.logical_and((ecog3grp==uid),(ecologmbary>=9.9)))
dwsel = np.where(np.logical_and((ecog3grp==uid), (ecologmbary<9.9)))
if len(gisel[0])>0.:
ecog3grpngi[grpsel] = len(gisel[0])
if len(dwsel[0])>0.:
ecog3grpndw[grpsel] = len(dwsel[0])
ecog3grpradeg, ecog3grpdedeg, ecog3grpcz = fof.group_skycoords(ecoradeg, ecodedeg, ecocz, ecog3grp)
ecog3rproj = fof.get_grprproj_e17(ecoradeg, ecodedeg, ecocz, ecog3grp, h=0.7) / (ecog3grpcz/70.) * 206265 # in arcsec
ecog3fc = fof.get_central_flag(ecologmbary, ecog3grp)
ecog3router = fof.get_outermost_galradius(ecoradeg, ecodedeg, ecocz, ecog3grp) # in arcsec
ecog3router[(ecog3grpngi+ecog3grpndw)==1] = 0.
junk, ecog3vdisp = fof.get_rproj_czdisp(ecoradeg, ecodedeg, ecocz, ecog3grp)
ecog3rvir = ecog3rvir*206265/(ecog3grpcz/70.)
ecog3grpgas = ic.get_int_mass(ecologmgas, ecog3grp)
ecog3grpstars = ic.get_int_mass(ecologmstar, ecog3grp)
ecog3ADtest = vz.AD_test(ecocz, ecog3grp)
ecog3tcross = vz.group_crossing_time(ecoradeg, ecodedeg, ecocz, ecog3grp)
ecog3colorgap = vz.group_color_gap(ecog3grp, ecologmbary, ecourcolor)
ecog3dsprob = vz.fast_DS_test(ecoradeg,ecodedeg,ecocz,ecog3grp,niter=2500)
ecog3nndens, ecog3edgeflag, ecog3nndens2d, ecog3edgeflag2d, ecog3edgescale2d = lss_dens_by_galaxy(ecog3grp,\
ecoradeg, ecodedeg, ecocz, ecog3logmh, Nnn=3, rarange=(130.05,237.45), decrange=(-1,50), czrange=(2530,7470))
outofsample = (ecog3grp==-99.)
ecog3grpn[outofsample]=-99.
ecog3grpngi[outofsample]=-99.
ecog3grpndw[outofsample]=-99.
ecog3grpradeg[outofsample]=-99.
ecog3grpdedeg[outofsample]=-99.
ecog3grpcz[outofsample]=-99.
ecog3logmh[outofsample]=-99.
ecog3rvir[outofsample]=-99.
ecog3rproj[outofsample]=-99.
ecog3fc[outofsample]=-99.
ecog3router[outofsample]=-99.
ecog3vdisp[outofsample]=-99.
ecog3grpgas[outofsample]=-99.
ecog3grpstars[outofsample]=-99.
ecog3ADtest[outofsample]=-99.
ecog3tcross[outofsample]=-99.
ecog3colorgap[outofsample]=-99.
ecog3dsprob[outofsample]=-99.
ecog3nndens[outofsample]=-99.
ecog3edgeflag[outofsample]=-99.
ecog3nndens2d[outofsample]=-99.
ecog3edgeflag2d[outofsample]=-99.
ecog3edgescale2d[outofsample]=-99.
insample = ecog3grpn!=-99.
ecodata['g3grp_b'] = ecog3grp
ecodata['g3grpradeg_b'] = ecog3grpradeg
ecodata['g3grpdedeg_b'] = ecog3grpdedeg
ecodata['g3grpcz_b'] = ecog3grpcz
ecodata['g3grpndw_b'] = ecog3grpndw
ecodata['g3grpngi_b'] = ecog3grpngi
ecodata['g3logmh_b'] = ecog3logmh
ecodata['g3r337_b'] = ecog3rvir
ecodata['g3rproj_b'] = ecog3rproj
ecodata['g3router_b'] = ecog3router
ecodata['g3fc_b'] = ecog3fc
ecodata['g3vdisp_b'] = ecog3vdisp
ecodata['g3grplogG_b'] = ecog3grpgas
ecodata['g3grplogS_b'] = ecog3grpstars
ecodata['g3grpadAlpha_b'] = ecog3ADtest
ecodata['g3grptcross_b'] = ecog3tcross
ecodata['g3grpcolorgap_b'] = ecog3colorgap
ecodata['g3grpdsProb_b'] = ecog3dsprob
ecodata['g3grpnndens_b'] = ecog3nndens
ecodata['g3grpedgeflag_b'] = ecog3edgeflag
ecodata['g3grpnndens2d_b'] = ecog3nndens2d
ecodata['g3grpedgeflag2d_b'] = ecog3edgeflag2d
ecodata['g3grpedgescale2d_b'] = ecog3edgescale2d
ecodata.to_csv("ECOdata_G3catalog_baryonic.csv", index=False)
# ------ now do RESOLVE
sz = len(resolvedata)
resolvename = np.array(resolvedata.name)
resolveg3grp = np.full(sz, -99.)
resolveg3grpngi = np.full(sz, -99.)
resolveg3grpndw = np.full(sz, -99.)
resolveg3grpradeg = np.full(sz, -99.)
resolveg3grpdedeg = np.full(sz, -99.)
resolveg3grpcz = np.full(sz, -99.)
resolveg3logmh = np.full(sz, -99.)
resolveg3rvir = np.full(sz, -99.)
resolveg3rproj = np.full(sz,-99.)
resolveg3fc = np.full(sz,-99.)
resolveg3router = np.full(sz,-99.)
resolveg3vdisp = np.full(sz,-99.)
resolveg3grpgas = np.full(sz, -99.)
resolveg3grpstars = np.full(sz, -99.)
resolveg3ADtest = np.full(sz, -99.)
resolveg3tcross = np.full(sz, -99.)
resolveg3colorgap = np.full(sz, -99.)
resolveg3dsprob = np.full(sz,-99.)
resolveg3nndens = np.full(sz, -99.)
resolveg3edgeflag = np.full(sz, -99.)
resolveg3nndens2d = np.full(sz, -99.)
resolveg3edgeflag2d = np.full(sz, -99.)
resolveg3edgescale2d = np.full(sz, -99.)
resbg3grpngi = np.full(len(resbg3grp), 0.)
resbg3grpndw = np.full(len(resbg3grp), 0.)
for uid in np.unique(resbg3grp):
grpsel = np.where(resbg3grp==uid)
gisel = np.where(np.logical_and((resbg3grp==uid),(resblogmbary>=9.9)))
dwsel = np.where(np.logical_and((resbg3grp==uid), (resblogmbary<9.9)))
if len(gisel[0])>0.:
resbg3grpngi[grpsel] = len(gisel[0])
if len(dwsel[0])>0.:
resbg3grpndw[grpsel] = len(dwsel[0])
resbg3grpradeg, resbg3grpdedeg, resbg3grpcz = fof.group_skycoords(resbradeg, resbdedeg, resbcz, resbg3grp)
resbg3intmbary = ic.get_int_mass(resblogmbary, resbg3grp)
resbg3rproj = fof.get_grprproj_e17(resbradeg, resbdedeg, resbcz, resbg3grp, h=0.7) / (resbg3grpcz/70.) * 206265 # in arcsec
resbg3fc = fof.get_central_flag(resblogmbary, resbg3grp)
resbg3router = fof.get_outermost_galradius(resbradeg, resbdedeg, resbcz, resbg3grp) # in arcsec
resbg3router[(resbg3grpngi+resbg3grpndw)==1] = 0.
junk, resbg3vdisp = fof.get_rproj_czdisp(resbradeg, resbdedeg, resbcz, resbg3grp)
resbg3rvir = resbg3rvir*206265/(resbg3grpcz/70.)
resbg3rvir = resbg3rvir*206265/(resbg3grpcz/70.)
resbg3grpgas = ic.get_int_mass(resblogmgas, resbg3grp)
resbg3grpstars = ic.get_int_mass(resblogmstar, resbg3grp)
resbg3ADtest = vz.AD_test(resbcz, resbg3grp)
resbg3tcross = vz.group_crossing_time(resbradeg, resbdedeg, resbcz, resbg3grp)
resbg3colorgap = vz.group_color_gap(resbg3grp, resblogmstar, resburcolor)
resbg3dsprob = vz.fast_DS_test(resbradeg,resbdedeg,resbcz,resbg3grp,niter=2500)
RESB_RADEG_REMAPPED = np.copy(resbradeg)
REMAPSEL = np.where(resbradeg>18*15.)
RESB_RADEG_REMAPPED[REMAPSEL] = resbradeg[REMAPSEL]-360.
resbg3nndens, resbg3edgeflag, resbg3nndens2d, resbg3edgeflag2d, resbg3edgescale2d = lss_dens_by_galaxy(resbg3grp,\
RESB_RADEG_REMAPPED, resbdedeg, resbcz, resbg3logmh, Nnn=3, rarange=(-2*15.,3*15.), decrange=(-1.25,1.25),\
czrange=(4250,7250)) # must use remapped RESOLVE-B RA because of 0/360 wraparound
outofsample = (resbg3grp==-99.)
resbg3grpngi[outofsample]=-99.
resbg3grpndw[outofsample]=-99.
resbg3grpradeg[outofsample]=-99.
resbg3grpdedeg[outofsample]=-99.
resbg3grpcz[outofsample]=-99.
resbg3logmh[outofsample]=-99.
resbg3rvir[outofsample]=-99.
resbg3rproj[outofsample]=-99.
resbg3router[outofsample]=-99.
resbg3fc[outofsample]=-99.
resbg3vdisp[outofsample]=-99.
resbg3grpgas[outofsample]=-99.
resbg3grpstars[outofsample]=-99.
resbg3ADtest[outofsample]=-99.
resbg3tcross[outofsample]=-99.
resbg3colorgap[outofsample]=-99.
resbg3dsprob[outofsample]=-99.
resbg3nndens[outofsample]=-99.
resbg3edgeflag[outofsample]=-99.
resbg3nndens2d[outofsample]=-99.
resbg3edgeflag2d[outofsample]=-99.
resbg3edgescale2d[outofsample]=-99.
for i,nm in enumerate(resolvename):
if nm.startswith('rs'):
sel_in_eco = np.where(ecoresname==nm)
resolveg3grp[i] = ecog3grp[sel_in_eco]
resolveg3grpngi[i] = ecog3grpngi[sel_in_eco]
resolveg3grpndw[i] = ecog3grpndw[sel_in_eco]
resolveg3grpradeg[i] = ecog3grpradeg[sel_in_eco]
resolveg3grpdedeg[i] = ecog3grpdedeg[sel_in_eco]
resolveg3grpcz[i] = ecog3grpcz[sel_in_eco]
resolveg3logmh[i] = ecog3logmh[sel_in_eco]
resolveg3rvir[i] = ecog3rvir[sel_in_eco]
resolveg3rproj[i] = ecog3rproj[sel_in_eco]
resolveg3fc[i] = ecog3fc[sel_in_eco]
resolveg3router[i]=ecog3router[sel_in_eco]
resolveg3vdisp[i]=ecog3vdisp[sel_in_eco]
resolveg3grpstars[i] = ecog3grpstars[sel_in_eco]
resolveg3grpgas[i] = ecog3grpgas[sel_in_eco]
resolveg3ADtest[i] = ecog3ADtest[sel_in_eco]
resolveg3tcross[i] = ecog3tcross[sel_in_eco]
resolveg3colorgap[i] = ecog3colorgap[sel_in_eco]
resolveg3dsprob[i] = ecog3dsprob[sel_in_eco]
resolveg3nndens[i] = ecog3nndens[sel_in_eco]
resolveg3edgeflag[i] = ecog3edgeflag[sel_in_eco]
resolveg3nndens2d[i] = ecog3nndens2d[sel_in_eco]
resolveg3edgeflag2d[i] = ecog3edgeflag2d[sel_in_eco]
resolveg3edgescale2d[i] = ecog3edgescale2d[sel_in_eco]
elif nm.startswith('rf'):
sel_in_resb = np.where(resbname==nm)
resolveg3grp[i] = resbg3grp[sel_in_resb]
resolveg3grpngi[i] = resbg3grpngi[sel_in_resb]
resolveg3grpndw[i] = resbg3grpndw[sel_in_resb]
resolveg3grpradeg[i] = resbg3grpradeg[sel_in_resb]
resolveg3grpdedeg[i] = resbg3grpdedeg[sel_in_resb]
resolveg3grpcz[i] = resbg3grpcz[sel_in_resb]
resolveg3logmh[i] = resbg3logmh[sel_in_resb]
resolveg3rvir[i] = resbg3rvir[sel_in_resb]
resolveg3rproj[i] = resbg3rproj[sel_in_resb]
resolveg3fc[i] = resbg3fc[sel_in_resb]
resolveg3router[i] = resbg3router[sel_in_resb]
resolveg3vdisp[i] = resbg3vdisp[sel_in_resb]
resolveg3grpgas[i] = resbg3grpgas[sel_in_resb]
resolveg3grpstars[i] = resbg3grpstars[sel_in_resb]
resolveg3ADtest[i] = resbg3ADtest[sel_in_resb]
resolveg3tcross[i] = resbg3tcross[sel_in_resb]
resolveg3colorgap[i] = resbg3colorgap[sel_in_resb]
resolveg3nndens[i] = resbg3nndens[sel_in_resb]
resolveg3edgeflag[i] = resbg3edgeflag[sel_in_resb]
resolveg3nndens2d[i] = resbg3nndens2d[sel_in_resb]
resolveg3edgeflag2d[i] = resbg3edgeflag2d[sel_in_resb]
resolveg3edgescale2d[i] = resbg3edgescale2d[sel_in_resb]
else:
assert False, nm+" not in RESOLVE"
resolvedata['g3grp_b'] = resolveg3grp
resolvedata['g3grpngi_b'] = resolveg3grpngi
resolvedata['g3grpndw_b'] = resolveg3grpndw
resolvedata['g3grpradeg_b'] = resolveg3grpradeg
resolvedata['g3grpdedeg_b'] = resolveg3grpdedeg
resolvedata['g3grpcz_b'] = resolveg3grpcz
resolvedata['g3logmh_b'] = resolveg3logmh
resolvedata['g3r337_b'] = resolveg3rvir
resolvedata['g3rproj_b'] = resolveg3rproj
resolvedata['g3router_b'] = resolveg3router
resolvedata['g3fc_b'] = resolveg3fc
resolvedata['g3vdisp_b'] = resolveg3vdisp
resolvedata['g3grplogG_b'] = resolveg3grpgas
resolvedata['g3grplogS_b'] = resolveg3grpstars
resolvedata['g3grpadAlpha_b'] = resolveg3ADtest
resolvedata['g3grptcross_b'] = resolveg3tcross
resolvedata['g3grpcolorgap_b'] = resolveg3colorgap
resolvedata['g3grpnndens_b'] = resolveg3nndens
resolvedata['g3grpedgeflag_b'] = resolveg3edgeflag
resolvedata['g3grpnndens2d_b'] = resolveg3nndens2d
resolvedata['g3grpedgeflag2d_b'] = resolveg3edgeflag2d
resolvedata['g3grpedgescale2d_b'] = resolveg3edgescale2d
resolvedata.to_csv("RESOLVEdata_G3catalog_baryonic.csv", index=False)
|
zhutchens1/g3groups | foftools.py | <filename>foftools.py
# -*- coding: utf-8 -*-
"""
@package 'foftools'
@author: <NAME>, UNC Chapel Hill
This package contains classes and functions for performing galaxy group
identification using the friends-of-friends (FoF) and probability friends-of-friends
(PFoF) algorithms. Additionally, it includes functions for group association of faint
galaxies (Eckert+ 2016), as well as related tools such as functions for computing
group-integrated quantities (like luminosity or stellar mass).
The previous version of foftools, 3.3 (28 Feb 2020) is now historic and been renamed
`objectbasedfoftools.py` within the git repository. The new version, 4.0, provides
the same tools with a performance-based approach that prioritizes numpy/njit optimization
over readability/convenience of python classes, which require itertions throughout
the many necessary algorithms for group finding.
"""
import numpy as np
import pandas as pd
import itertools
from scipy.integrate import quad
from scipy.interpolate import interp1d
from math import erf
from copy import deepcopy
import math
import time
import warnings
from numba import njit
__versioninfo__ = "foftools version 4.0 (previous version 3.3 now labeled `objectbasedfoftools.py`)"
from astropy.cosmology import LambdaCDM
cosmo = LambdaCDM(H0=100.0, Om0=0.3, Ode0=0.7) # this puts everything in "per h" units.
SPEED_OF_LIGHT = 3.00E+05 # km/s
# -------------------------------------------------------------- #
# friends-of-friends (FOF) algorithm
# -------------------------------------------------------------- #
def fast_fof(ra, dec, cz, bperp, blos, s, printConf=True):
"""
-----------
Compute group membership from galaxies' equatorial coordinates using a friends-of-friends algorithm,
based on the method of Berlind et al. 2006. This algorithm is designed to identify groups
in volume-limited catalogs down to a common magnitude floor. All input arrays (RA, Dec, cz)
must have already been selected to be above the group-finding floor.
Arguments:
ra (iterable): list of right-ascesnsion coordinates of galaxies in decimal degrees.
dec (iterable): list of declination coordinates of galaxies in decimal degrees.
cz (iterable): line-of-sight recessional velocities of galaxies in km/s.
bperp (scalar): linking proportion for the on-sky plane (use 0.07 for RESOLVE/ECO)
blos (scalar): linking proportion for line-of-sight component (use 1.1 for RESOLVE/ECO)
s (scalar): mean separation of galaxies above floor in volume-limited catalog.
printConf (bool, default True): bool indicating whether to print confirmation at the end.
Returns:
grpid (np.array): list containing unique group ID numbers for each target in the input coordinates.
The list will have shape len(ra).
-----------
"""
t1 = time.time()
Ngalaxies = len(ra)
ra = np.float64(ra)
dec = np.float64(dec)
cz = np.float64(cz)
assert (len(ra)==len(dec) and len(dec)==len(cz)),"RA/Dec/cz arrays must equivalent length."
#check if s is adaptive or fixed
if np.isscalar(s):
adaptive=False
else:
adaptive=True
s = np.float64(s)[:,None] # convert to column vector
phi = (ra * np.pi/180.)
theta =(np.pi/2. - dec*(np.pi/180.))
transv_cmvgdist = (cosmo.comoving_transverse_distance(cz/SPEED_OF_LIGHT).value)
los_cmvgdist = (cosmo.comoving_distance(cz/SPEED_OF_LIGHT).value)
friendship = np.zeros((Ngalaxies, Ngalaxies))
# Compute on-sky and line-of-sight distance between galaxy pairs
column_phi = phi[:, None]
column_theta = theta[:, None]
half_angle = np.arcsin((np.sin((column_theta-theta)/2.0)**2.0 + np.sin(column_theta)*np.sin(theta)*np.sin((column_phi-phi)/2.0)**2.0)**0.5)
# Compute on-sky perpendicular distance
column_transv_cmvgdist = transv_cmvgdist[:, None]
dperp = (column_transv_cmvgdist + transv_cmvgdist) * (half_angle) # In Mpc/h
# Compute line-of-sight distances
dlos = np.abs(los_cmvgdist - los_cmvgdist[:, None])
# Compute friendship - fixed case
if not adaptive:
index = np.where(np.logical_and(dlos<=blos*s, dperp<=bperp*s))
friendship[index]=1
assert np.all(np.abs(friendship-friendship.T) < 1e-8), "Friendship matrix must be symmetric."
if printConf:
print('FoF complete in {a:0.4f} s'.format(a=time.time()-t1))
# compute friendship - adaptive case
elif adaptive:
index = np.where(np.logical_and(dlos-blos*s<=0, dperp-bperp*s<=0))
friendship[index]=1
if printConf:
print('FoF complete in {a:0.4f} s'.format(a=time.time()-t1))
return collapse_friendship_matrix(friendship)
# -------------------------------------------------------------- #
# probability friends-of-friends algorithm #
# -------------------------------------------------------------- #
@njit
def gauss(x, mu, sigma):
"""
Gaussian function.
Arguments:
x - dynamic variable
mu - centroid of distribution
sigma - standard error of distribution
Returns:
PDF value evaluated at `x`
"""
return 1/(math.sqrt(2*np.pi) * sigma) * math.exp(-1 * 0.5 * ((x-mu)/sigma) * ((x-mu)/sigma))
@njit
def pfof_integral(z, czi, czerri, czj, czerrj, VL):
c=SPEED_OF_LIGHT
return gauss(z, czi/c, czerri/c) * (0.5*math.erf((z+VL-czj/c)/((2**0.5)*czerrj/c)) - 0.5*math.erf((z-VL-czj/c)/((2**0.5)*czerrj/c)))
def fast_pfof(ra, dec, cz, czerr, perpll, losll, Pth, printConf=True):
"""
-----
Compute group membership from galaxies' equatorial coordinates using a probabilitiy
friends-of-friends (PFoF) algorithm, based on the method of Liu et al. 2008. PFoF is
a variant of FoF (see `foftools.fast_fof`, Berlind+2006), which treats galaxies as Gaussian
probability distributions, allowing group membership selection to account for the
redshift errors of photometric redshift measurements.
Arguments:
ra (iterable): list of right-ascesnsion coordinates of galaxies in decimal degrees.
dec (iterable): list of declination coordinates of galaxies in decimal degrees.
cz (iterable): line-of-sight recessional velocities of galaxies in km/s.
czerr (iterable): errors on redshifts of galaxies in km/s.
perpll (float): perpendicular linking length in Mpc/h.
losll (float): line-of-sight linking length in km/s.
Pth (float): Threshold probability from which to construct the group catalog. If None, the
function will return a NxN matrix of friendship probabilities.
printConf (bool, default True): bool indicating whether to print confirmation at the end.
Returns:
grpid (np.array): list containing unique group ID numbers for each target in the input coordinates.
The list will have shape len(ra).
-----
"""
print('you know.... you could speed this up more if check for transverse friendship before integrating...')
t1 = time.time()
Ngalaxies = len(ra)
ra = np.float32(ra)
dec = np.float32(dec)
cz = np.float32(cz)
czerr = np.float32(czerr)
assert (len(ra)==len(dec) and len(dec)==len(cz)),"RA/Dec/cz arrays must equivalent length."
phi = (ra * np.pi/180.)
theta = (np.pi/2. - dec*(np.pi/180.))
transv_cmvgdist = (cosmo.comoving_transverse_distance(cz/SPEED_OF_LIGHT).value)
friendship = np.zeros((Ngalaxies, Ngalaxies))
# Compute on-sky perpendicular distance
column_phi = phi[:, None]
column_theta = theta[:, None]
half_angle = np.arcsin((np.sin((column_theta-theta)/2.0)**2.0 + np.sin(column_theta)*np.sin(theta)*np.sin((column_phi-phi)/2.0)**2.0)**0.5)
column_transv_cmvgdist = transv_cmvgdist[:, None]
dperp = (column_transv_cmvgdist + transv_cmvgdist) * half_angle # In Mpc/h
# Compute line-of-sight probabilities
prob_dlos=np.zeros((Ngalaxies, Ngalaxies))
c=SPEED_OF_LIGHT
VL = losll/c
for i in range(0,Ngalaxies):
for j in range(0, i+1):
if j<i:
val = quad(pfof_integral, 0, 100, args=(cz[i], czerr[i], cz[j], czerr[j], VL),\
points=np.float64([cz[i]/c-5*czerr[i]/c,cz[i]/c-3*czerr[i]/c, cz[i]/c, cz[i]/c+3*czerr[i]/c, cz[i]/c+5*czerr[i]/c]),\
wvar=cz[i]/c)
prob_dlos[i][j]=val[0]
prob_dlos[j][i]=val[0]
elif i==j:
prob_dlos[i][j]=1
# Produce friendship matrix and return groups
index = np.where(np.logical_and(prob_dlos>Pth, dperp<=perpll))
friendship[index]=1
assert np.all(np.abs(friendship-friendship.T) < 1e-8), "Friendship matrix must be symmetric."
if printConf:
print('PFoF complete in {a:0.4f} s'.format(a=time.time()-t1))
return collapse_friendship_matrix(friendship)
# -------------------------------------------------------------- #
# algorithms for extracting group catalog from FOF friendship #
# -------------------------------------------------------------- #
def collapse_friendship_matrix(friendship_matrix):
"""
----
Collapse a friendship matrix resultant of a FoF computation into an array of
unique group numbers.
Arguments:
friendship_matrix (iterable): iterable of shape (N, N) where N is the number of targets.
Each element (i,j) of the matrix should represent the galaxy i and galaxy j are friends,
as determined by the FoF linking length.
Returns:
grpid (iterable): 1-D array of size N containing unique group ID numbers for every target.
----
"""
friendship_matrix=np.array(friendship_matrix)
Ngalaxies = len(friendship_matrix[0])
grpid = np.zeros(Ngalaxies)
grpnumber = 1
for row_num,row in enumerate(friendship_matrix):
if not grpid[row_num]:
group_indices = get_group_ind(friendship_matrix, row_num, visited=[row_num])
grpid[group_indices]=grpnumber
grpnumber+=1
return grpid
def get_group_ind(matrix, active_row_num, visited):
"""
----
Recursive algorithm to form a tree of indices from a friendship matrix row. Similar
to the common depth-first search tree-finding algorithm, but enabling identification
of isolated nodes and no backtracking up the resultant trees' edges.
Example: Consider a group formed of the indices [10,12,133,53], but not all are
connected to one another.
10 ++++ 12
+
133 ++++ 53
The function `collapse_friendship_matrix` begins when 10 is the active row number. This algorithm
searches for friends of #10, which are #12 and #133. Then it *visits* the #12 and #133 galaxies
recursively, finding their friends also. It adds 12 and 133 to the visited array, noting that
#10 - #12's lone friend - has already been visited. It then finds #53 as a friend of #133,
but again notes that #53's only friend it has been visited. It then returns the array
visited=[10, 12, 133, 53], which form the FoF group we desired to find.
Arguments:
matrix (iterable): iterable of shape (N, N) where N is the number of targets.
Each element (i,j) of the matrix should represent the galaxy i and galaxy j are friends,
as determined from the FoF linking lengths.
active_row_num (int): row number to start the recursive row searching.
visited (int): array containing group members that have already been visited. The recursion
ends if all friends have been visited. In the initial call, use visited=[active_row_num].
----
"""
friends_of_active = np.where(matrix[active_row_num])
for friend_ind in [k for k in friends_of_active[0] if k not in visited]:
visited.append(friend_ind)
visited = get_group_ind(matrix, friend_ind, visited)
return visited
# -------------------------------------------------------------- #
# functions for galaxy association to existing groups
# -------------------------------------------------------------- #
def fast_faint_assoc(faintra, faintdec, faintcz, grpra, grpdec, grpcz, grpid, radius_boundary, velocity_boundary, losll=-1):
"""
Associate galaxies to a group catalog based on given radius and velocity boundaries, based on a method
similar to that presented in Eckert+ 2016.
Parameters
----------
faintra : iterable
Right-ascension of faint galaxies in degrees.
faintdec : iterable
Declination of faint galaxies in degrees.
faintcz : iterable
Redhshift velocities of faint galaxies in km/s.
grpra : iterable
Right-ascension of group centers in degrees.
grpdec : iterable
Declination of group centers in degrees. Length matches `grpra`.
grpcz : iterable
Redshift velocity of group center in km/s. Length matches `grpra`.
grpid : iterable
group ID of each FoF group (i.e., from `foftools.fast_fof`.) Length matches `grpra`.
radius_boundary : iterable
Radius within which to search for faint galaxies around FoF groups. Length matches `grpra`.
velocity_boundary : iterable
Velocity from group center within which to search for faint galaxies around FoF groups. Length matches `grpra`.
losll : scalar, default -1
Line-of-sight linking length in km/s. If losll>0, then associations are made with the *larger of* the velocity
boundary of the LOS linking length. If losll=-1 (default), use only the velocity boundary to associate.
Returns
-------
assoc_grpid : iterable
group ID of every faint galaxy. Length matches `faintra`.
assoc_flag : iterable
association flag for every galaxy (see function description). Length matches `faintra`.
"""
velocity_boundary=np.asarray(velocity_boundary)
radius_boundary=np.asarray(radius_boundary)
Nfaint = len(faintra)
assoc_grpid = np.zeros(Nfaint).astype(int)
assoc_flag = np.zeros(Nfaint).astype(int)
radius_ratio=np.zeros(Nfaint)
# resize group coordinates to be the # of groups, not # galaxies
junk, uniqind = np.unique(grpid, return_index=True)
grpra = grpra[uniqind]
grpdec = grpdec[uniqind]
grpcz = grpcz[uniqind]
grpid = grpid[uniqind]
velocity_boundary=velocity_boundary[uniqind]
radius_boundary=radius_boundary[uniqind]
# Redefine velocity boundary array to take larger of (dV, linking length)
if losll>0:
velocity_boundary[np.where(velocity_boundary<=losll)]=losll
# Make Nfaints x Ngroups grids for transverse/LOS distances from group centers
faintphi = (faintra * np.pi/180.)[:,None]
fainttheta = (np.pi/2. - faintdec*(np.pi/180.))[:,None]
faint_cmvg = (cosmo.comoving_transverse_distance(faintcz/SPEED_OF_LIGHT).value)[:, None]
grpphi = (grpra * np.pi/180.)
grptheta = (np.pi/2. - grpdec*(np.pi/180.))
grp_cmvg = cosmo.comoving_transverse_distance(grpcz/SPEED_OF_LIGHT).value
half_angle = np.arcsin((np.sin((fainttheta-grptheta)/2.0)**2.0 + np.sin(fainttheta)*np.sin(grptheta)*np.sin((faintphi-grpphi)/2.0)**2.0)**0.5)
Rp = (faint_cmvg + grp_cmvg) * np.sin(half_angle)
DeltaV = np.abs(faintcz[:,None] - grpcz)
for gg in range(0,len(grpid)):
for fg in range(0,Nfaint):
tempratio = Rp[fg][gg]/radius_boundary[gg]
condition=((tempratio<1) and (DeltaV[fg][gg]<velocity_boundary[gg]))
# multiple groups competing (has already been associated before)
if condition and assoc_flag[fg]:
# multiple grps competing to associate galaxy
if tempratio<radius_ratio[fg]:
radius_ratio[fg]=tempratio
assoc_grpid[fg]=grpid[gg]
assoc_flag[fg]=1
else:
pass
# galaxy not associated yet - go ahead and do it
elif condition and (not assoc_flag[fg]):
radius_ratio[fg]=tempratio
assoc_grpid[fg]=grpid[gg]
assoc_flag[fg]=1
# condition not met
elif (not condition):
pass
else:
print("Galaxy failed association algorithm at index {}".format(fg))
# assign group ID numbers to galaxies that didn't associate
still_isolated = np.where(assoc_grpid==0)
assoc_grpid[still_isolated]=np.arange(np.max(grpid)+1, np.max(grpid)+1+len(still_isolated[0]), 1)
assoc_flag[still_isolated]=-1
return assoc_grpid, assoc_flag
# -------------------------------------------------------------- #
# functions for computing properties of groups #
# -------------------------------------------------------------- #
def group_skycoords(galaxyra, galaxydec, galaxycz, galaxygrpid):
"""
-----
Obtain a list of group centers (RA/Dec/cz) given a list of galaxy coordinates (equatorial)
and their corresponding group ID numbers.
Inputs (all same length)
galaxyra : 1D iterable, list of galaxy RA values in decimal degrees
galaxydec : 1D iterable, list of galaxy dec values in decimal degrees
galaxycz : 1D iterable, list of galaxy cz values in km/s
galaxygrpid : 1D iterable, group ID number for every galaxy in previous arguments.
Outputs (all shape match `galaxyra`)
groupra : RA in decimal degrees of galaxy i's group center.
groupdec : Declination in decimal degrees of galaxy i's group center.
groupcz : Redshift velocity in km/s of galaxy i's group center.
Note: the FoF code of AA Berlind uses theta_i = declination, with theta_cen =
the central declination. This version uses theta_i = pi/2-dec, with some trig functions
changed so that the output *matches* that of Berlind's FoF code (my "deccen" is the same as
his "thetacen", to be exact.)
-----
"""
# Prepare cartesian coordinates of input galaxies
ngalaxies = len(galaxyra)
galaxyphi = galaxyra * np.pi/180.
galaxytheta = np.pi/2. - galaxydec*np.pi/180.
galaxyx = np.sin(galaxytheta)*np.cos(galaxyphi)
galaxyy = np.sin(galaxytheta)*np.sin(galaxyphi)
galaxyz = np.cos(galaxytheta)
# Prepare output arrays
uniqidnumbers = np.unique(galaxygrpid)
groupra = np.zeros(ngalaxies)
groupdec = np.zeros(ngalaxies)
groupcz = np.zeros(ngalaxies)
for i,uid in enumerate(uniqidnumbers):
sel=np.where(galaxygrpid==uid)
nmembers = len(galaxygrpid[sel])
xcen=np.sum(galaxycz[sel]*galaxyx[sel])/nmembers
ycen=np.sum(galaxycz[sel]*galaxyy[sel])/nmembers
zcen=np.sum(galaxycz[sel]*galaxyz[sel])/nmembers
czcen = np.sqrt(xcen**2 + ycen**2 + zcen**2)
deccen = np.arcsin(zcen/czcen)*180.0/np.pi # degrees
if (ycen >=0 and xcen >=0):
phicor = 0.0
elif (ycen < 0 and xcen < 0):
phicor = 180.0
elif (ycen >= 0 and xcen < 0):
phicor = 180.0
elif (ycen < 0 and xcen >=0):
phicor = 360.0
elif (xcen==0 and ycen==0):
print("Warning: xcen=0 and ycen=0 for group {}".format(galaxygrpid[i]))
# set up phicorrection and return phicen.
racen=np.arctan(ycen/xcen)*(180/np.pi)+phicor # in degrees
# set values at each element in the array that belongs to the group under iteration
groupra[sel] = racen # in degrees
groupdec[sel] = deccen # in degrees
groupcz[sel] = czcen
return groupra, groupdec, groupcz
def get_rproj_czdisp(galaxyra, galaxydec, galaxycz, galaxygrpid, HUBBLE_CONST=70.):
"""
Compute the observational projected radius, in Mpc/h, and the observational
velocity dispersion, in km/s, for a galaxy group catalog. Input should match
the # of galaxies, and the output will as well. Based on FoF4 code of Berlind+
2006.
Parameters
----------
galaxyra : iterable
Right-ascension of grouped galaxies in decimal degrees.
galaxydec : iterable
Declination of grouped galaxies in decimal degrees.
galaxycz : iterable
Redshift velocity (cz) of grouped galaxies in km/s.
galaxygrpid : iterable
Group ID numbers of grouped galaxies, shape should match `galaxyra`.
Returns
-------
rproj : np.array, shape matches `galaxyra`
For element index i, projected radius of galaxy group to which galaxy i belongs, in Mpc/h.
vdisp : np.array, shape matches `galaxyra`
For element index i, velocity dispersion of galaxy group to which galaxy i belongs, in km/s.
"""
galaxyra=np.asarray(galaxyra)
galaxydec=np.asarray(galaxydec)
galaxycz=np.asarray(galaxycz)
galaxygrpid=np.asarray(galaxygrpid)
rproj=np.zeros(len(galaxyra))
vdisp=np.zeros(len(galaxyra))
grpra, grpdec, grpcz = group_skycoords(galaxyra, galaxydec, galaxycz, galaxygrpid)
grpra = grpra*np.pi/180. #convert everything to radians
galaxyra=galaxyra*np.pi/180.
galaxydec=galaxydec*np.pi/180.
grpdec = grpdec*np.pi/180.
uniqid = np.unique(galaxygrpid)
cspeed=299800 # km/s
for uid in uniqid:
sel = np.where(galaxygrpid==uid)
nmembers=len(sel[0])
if nmembers==1:
rproj[sel]=0.
vdisp[sel]=0.
else:
phicen=grpra[sel][0]
thetacen=grpdec[sel][0]
cosDpsi=np.cos(thetacen)*np.cos(galaxydec[sel])+np.sin(thetacen)*np.sin(galaxydec[sel])*np.cos((phicen - galaxyra[sel]))
sinDpsi=np.sqrt(1-cosDpsi**2)
rp=sinDpsi*galaxycz[sel]/HUBBLE_CONST
rproj[sel]=np.sqrt(np.sum(rp**2)/len(sel[0]))
czcen = grpcz[sel][0]
Dz2 = np.sum((galaxycz[sel]-czcen)**2.0)
vdisp[sel]=np.sqrt(Dz2/(nmembers-1))/(1.+czcen/cspeed)
return rproj, vdisp
def multiplicity_function(grpids, return_by_galaxy=False):
"""
Return counts for binning based on group ID numbers.
Parameters
----------
grpids : iterable
List of group ID numbers. Length must match # galaxies.
Returns
-------
occurences : list
Number of galaxies in each galaxy group (length matches # groups).
"""
grpids=np.asarray(grpids)
uniqid = np.unique(grpids)
if return_by_galaxy:
grpn_by_gal=np.zeros(len(grpids)).astype(int)
for idv in grpids:
sel = np.where(grpids==idv)
grpn_by_gal[sel]=len(sel[0])
return grpn_by_gal
else:
occurences=[]
for uid in uniqid:
sel = np.where(grpids==uid)
occurences.append(len(grpids[sel]))
return occurences
def get_grprproj_e17(galra, galdec, galcz, galgrpid, h):
"""
Credit: <NAME> for original python code
Compute the observational group projected radius from Eckert et al. (2017). Adapted from
Katie's IDL code, which was used to calculate grprproj for FoF groups in RESOLVE.
75% radius of all members
Parameters
--------------------
galra : iterable
RA of input galaxies in decimal degrees
galdec : iterable
Declination of input galaxies in decimal degrees
galcz : iterable
Observed local group-corrected radial velocities of input galaxies (km/s)
galgrpid : iterable
Group ID numbers for input galaxies, length matches `galra`.
Returns
--------------------
grprproj : np.array
Group projected radii in Mpc/h, length matches `galra`.
"""
rproj75dist = np.zeros(len(galgrpid))
uniqgrpid = np.unique(galgrpid)
for uid in uniqgrpid:
galsel = np.where(galgrpid==uid)
if len(galsel[0])> 2:
ras = np.array(galra[galsel])*np.pi/180 #in radians
decs = np.array(galdec[galsel])*np.pi/180 #in radians
czs = np.array(galcz[galsel])
grpn = len(galsel[0])
H0 = 100*h #km/s/Mpc
grpdec = np.mean(decs)
grpra = np.mean(ras)
grpcz = np.mean(czs)
theta = 2*np.arcsin(np.sqrt((np.sin((decs-grpdec)/2))**2 + np.cos(decs)*np.cos(grpdec)*(np.sin((ras-grpra)/2)**2)))
theta = np.array(theta)
rproj = theta*grpcz/H0
sortorder = np.argsort(rproj)
rprojsrt_y = rproj[sortorder]
rprojval_x = np.arange(0 , grpn)/(grpn-1.) #array from 0 to 1, use for interpolation
#print(rprojsrt, rprojval, grpn)
f = interp1d(rprojval_x, rprojsrt_y)
rproj75val = f(0.75)
else:
rproj75val = 0.0
#rprojval_x = 0.0
#rprojsrt_y = 0.0
rproj75dist[galsel]=rproj75val
return rproj75dist
def getmhoffset(delta1, delta2, borc1, borc2, cc):
"""
Credit: <NAME> & <NAME>
Adapted from Katie's code, using eqns from "Sample Variance Considerations for Cluster Surveys," Hu & Kravtsov (2003) ApJ, 584, 702
(astro-ph/0203169)
delta1 is overdensity of input, delta2 is overdensity of output -- for mock, delta1 = 200
borc = 1 if wrt background density, borc = 0 if wrt critical density
cc is concentration of halo- use cc=6
"""
if borc1 == 0:
delta1 = delta1/0.3
if borc2 == 0:
delta2 = delta2/0.3
xin = 1./cc
f_1overc = (xin)**3. * (np.log(1. + (1./xin)) - (1. + xin)**(-1.))
f1 = delta1/delta2 * f_1overc
a1=0.5116
a2=-0.4283
a3=-3.13e-3
a4=-3.52e-5
p = a2 + a3*np.log(f1) + a4*(np.log(f1))**2.
x_f1 = (a1*f1**(2.*p) + (3./4.)**2.)**(-1./2.) + 2.*f1
r2overr1 = x_f1
m1overm2 = (delta1/delta2) * (1./r2overr1)**3. * (1./cc)**3.
return m1overm2
def get_central_flag(galquantity, galgrpid):
"""
Produce 1/0 flag indicating central/satellite for a galaxy
group dataset.
Parameters
-------------------
galquantity : np.array
Quantity by which to select centrals. If (galquantity>0).all(), the central is taken as the maximum galquantity in each group.
If (galquantity<0).all(), the quantity is assumed to be an abs. magnitude, and the central is the minimum quanity in each group.
galgrpid : np.array
Group ID number for each galaxy.
Returns
-------------------
cflag : np.array
1/0 flag indicating central/satellite status.
"""
cflag = np.zeros(len(galquantity))
uniqgrpid = np.unique(galgrpid)
if ((galquantity>-1).all()):
centralfn = np.max
if ((galquantity<0).all()):
centralfn = np.min
for uid in uniqgrpid:
galsel = np.where(galgrpid==uid)
centralmass = centralfn(galquantity[galsel])
centralsel = np.where((galgrpid==uid) & (galquantity==centralmass))
cflag[centralsel]=1.
satsel = np.where((galgrpid==uid) & (galquantity!=centralmass))
cflag[satsel]=0.
return cflag
def get_outermost_galradius(galra, galdec, galcz, galgrpid):
"""
Get the radius, in arcseconds, to the outermost gruop galaxy.
Parameters
-------------------
galra : np.array
RA in decimal degrees of grouped galaxies.
galdec : np.array
Dec in decimal degrees of grouped galaxies.
galgrprpid : np.array
Group ID number of input galaxies.
Returns
--------------------
radius : np.array
Radius to outermost member of galaxy's group (length = # galaxies = len(galra)). Units: arcseconds.
"""
radius = np.zeros(len(galra))
grpra, grpdec, grpcz = group_skycoords(galra, galdec, galcz, galgrpid)
#angsep = angular_separation(galra, galdec, grpra, grpdec) # arcsec
angsep = np.sqrt((grpra-galra)**2. + (grpdec-galdec)**2.)*(np.pi/180.)
rproj = (galcz+grpcz)/70. * np.sin(angsep/2.)
for uid in np.unique(galgrpid):
galsel = np.where(galgrpid==uid)
radius[galsel] = np.max(angsep[galsel])
#radius[galsel] = np.max(rproj[galsel])
#return radius*206265/(grpcz/70.)
return radius*206265
def angular_separation(ra1,dec1,ra2,dec2):
"""
Compute the angular separation bewteen two lists of galaxies using the Haversine formula.
Parameters
------------
ra1, dec1, ra2, dec2 : array-like
Lists of right-ascension and declination values for input targets, in decimal degrees.
Returns
------------
angle : np.array
Array containing the angular separations between coordinates in list #1 and list #2, as above.
Return value expressed in radians, NOT decimal degrees.
"""
phi1 = ra1*np.pi/180.
phi2 = ra2*np.pi/180.
theta1 = np.pi/2. - dec1*np.pi/180.
theta2 = np.pi/2. - dec2*np.pi/180.
return 2*np.arcsin(np.sqrt(np.sin((theta2-theta1)/2.0)**2.0 + np.sin(theta1)*np.sin(theta2)*np.sin((phi2 - phi1)/2.0)**2.0))
def sepmodel(x, a, b, c, d, e):
#return np.abs(a)*np.exp(-1*np.abs(b)*x + c)+d
#return a*(x**3)+b*(x**2)+c*x+d
return a*(x**4)+b*(x**3)+c*(x**2)+(d*x)+e
def giantmodel(x, a, b):
return np.abs(a)*np.log(np.abs(b)*x+1)
|
clones/django-coltrane | coltrane/templatetags/coltrane.py | from django.db.models import get_model
from django import template
from django.contrib.comments.models import Comment, FreeComment
from template_utils.templatetags.generic_content import GenericContentNode
from coltrane.models import Entry, Link
register = template.Library()
class LatestFeaturedNode(GenericContentNode):
def _get_query_set(self):
return self.queryset.filter(featured__exact=True)
def do_featured_entries(parser, token):
"""
Retrieves the latest ``num`` featured entries and stores them in a
specified context variable.
Syntax::
{% get_featured_entries [num] as [varname] %}
Example::
{% get_featured_entries 5 as featured_entries %}
"""
bits = token.contents.split()
if len(bits) != 4:
raise template.TemplateSyntaxError("'%s' tag takes three arguments" % bits[0])
if bits[2] != 'as':
raise template.TemplateSyntaxError("second argument to '%s' tag must be 'as'" % bits[0])
return LatestFeaturedNode('coltrane.entry', bits[1], bits[3])
def do_featured_entry(parser, token):
"""
Retrieves the latest featured Entry and stores it in a specified
context variable.
Syntax::
{% get_featured_entry as [varname] %}
Example::
{% get_featured_entry as featured_entry %}
"""
bits = token.contents.split()
if len(bits) != 3:
raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
if bits[1] != 'as':
raise template.TemplateSyntaxError("first argument to '%s' tag must be 'as'" % bits[0])
return LatestFeaturedNode('coltrane.entry', 1, bits[2])
register.tag('get_featured_entries', do_featured_entries)
register.tag('get_featured_entry', do_featured_entry)
|
clones/django-coltrane | coltrane/models.py | <reponame>clones/django-coltrane
"""
Models for a weblog application.
"""
import datetime
from comment_utils.managers import CommentedObjectManager
from comment_utils.moderation import CommentModerator, moderator
from django.conf import settings
from django.db import models
from django.utils.encoding import smart_str
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.comments import models as comment_models
import tagging
from tagging.fields import TagField
from template_utils.markup import formatter
from coltrane import managers
class Category(models.Model):
"""
A category that an Entry can belong to.
"""
title = models.CharField(max_length=250)
slug = models.SlugField(prepopulate_from=('title',), unique=True,
help_text=u'Used in the URL for the category. Must be unique.')
description = models.TextField(help_text=u'A short description of the category, to be used in list pages.')
description_html = models.TextField(editable=False, blank=True)
class Meta:
verbose_name_plural = 'Categories'
ordering = ['title']
class Admin:
pass
def __unicode__(self):
return self.title
def save(self):
self.description_html = formatter(self.description)
super(Category, self).save()
def get_absolute_url(self):
return ('coltrane_category_detail', (), { 'slug': self.slug })
get_absolute_url = models.permalink(get_absolute_url)
def _get_live_entries(self):
"""
Returns Entries in this Category with status of "live".
Access this through the property ``live_entry_set``.
"""
from coltrane.models import Entry
return self.entry_set.filter(status__exact=Entry.LIVE_STATUS)
live_entry_set = property(_get_live_entries)
class Entry(models.Model):
"""
An entry in the weblog.
Slightly denormalized, because it uses two fields each for the
excerpt and the body: one for the actual text the user types in,
and another to store the HTML version of the Entry (e.g., as
generated by a text-to-HTML converter like Textile or Markdown).
This saves having to run the conversion each time the Entry is
displayed.
Entries can be grouped by categories or by tags or both, or not
grouped at all.
"""
LIVE_STATUS = 1
DRAFT_STATUS = 2
HIDDEN_STATUS = 3
STATUS_CHOICES = (
(LIVE_STATUS, 'Live'),
(DRAFT_STATUS, 'Draft'),
(HIDDEN_STATUS, 'Hidden'),
)
# Metadata.
author = models.ForeignKey(User)
enable_comments = models.BooleanField(default=True)
featured = models.BooleanField(default=False)
pub_date = models.DateTimeField(u'Date posted', default=datetime.datetime.today)
slug = models.SlugField(prepopulate_from=('title',),
unique_for_date='pub_date',
help_text=u'Used in the URL of the entry. Must be unique for the publication date of the entry.')
status = models.IntegerField(choices=STATUS_CHOICES, default=LIVE_STATUS,
help_text=u'Only entries with "live" status will be displayed publicly.')
title = models.CharField(max_length=250)
# The actual entry bits.
body = models.TextField()
body_html = models.TextField(editable=False, blank=True)
excerpt = models.TextField(blank=True, null=True)
excerpt_html = models.TextField(blank=True, null=True, editable=False)
# Categorization.
categories = models.ManyToManyField(Category, filter_interface=models.HORIZONTAL, blank=True)
tags = TagField()
# Managers.
live = managers.LiveEntryManager()
objects = models.Manager()
class Meta:
get_latest_by = 'pub_date'
ordering = ['-pub_date']
verbose_name_plural = 'Entries'
class Admin:
date_hierarchy = 'pub_date'
fields = (
('Metadata', { 'fields':
('title', 'slug', 'pub_date', 'author', 'status', 'featured', 'enable_comments') }),
('Entry', { 'fields':
('excerpt', 'body') }),
('Categorization', { 'fields':
('tags', 'categories') }),
)
list_display = ('title', 'pub_date', 'author', 'status', 'enable_comments', '_get_comment_count')
list_filter = ('status', 'categories')
search_fields = ('excerpt', 'body', 'title')
def __unicode__(self):
return self.title
def save(self):
if self.excerpt:
self.excerpt_html = formatter(self.excerpt)
self.body_html = formatter(self.body)
super(Entry, self).save()
def get_absolute_url(self):
return ('coltrane_entry_detail', (), { 'year': self.pub_date.strftime('%Y'),
'month': self.pub_date.strftime('%b').lower(),
'day': self.pub_date.strftime('%d'),
'slug': self.slug })
get_absolute_url = models.permalink(get_absolute_url)
def _next_previous_helper(self, direction):
return getattr(self, 'get_%s_by_pub_date' % direction)(status__exact=self.LIVE_STATUS)
def get_next(self):
"""
Returns the next Entry with "live" status by ``pub_date``, if
there is one, or ``None`` if there isn't.
In public-facing templates, use this method instead of
``get_next_by_pub_date``, because ``get_next_by_pub_date``
does not differentiate entry status.
"""
return self._next_previous_helper('next')
def get_previous(self):
"""
Returns the previous Entry with "live" status by ``pub_date``,
if there is one, or ``None`` if there isn't.
In public-facing templates, use this method instead of
``get_previous_by_pub_date``, because
``get_previous_by_pub_date`` does not differentiate entry
status..
"""
return self._next_previous_helper('previous')
def _get_comment_count(self):
model = settings.USE_FREE_COMMENTS and comment_models.FreeComment or comment_models.Comment
ctype = ContentType.objects.get_for_model(self)
return model.objects.filter(content_type__pk=ctype.id, object_id__exact=self.id).count()
_get_comment_count.short_description = 'Number of comments'
class ColtraneModerator(CommentModerator):
akismet = True
auto_close_field = 'pub_date'
email_notification = True
enable_field = 'enable_comments'
close_after = settings.COMMENTS_MODERATE_AFTER
tagging.register(Entry, 'tag_set')
|
erksch/fnet-pytorch | verify_conversion.py | import argparse
import json
import ml_collections
import sentencepiece as spm
import torch
from flax.training import checkpoints
from jax import random
import jax
import jax.numpy as jnp
import numpy as np
from fnet import FNetForPreTraining
from f_net.models import PreTrainingModel as JaxPreTrainingModel
from f_net.configs.pretraining import get_config
def compare_output(jax_checkpoint_path, torch_statedict_path, torch_config_path, vocab_path):
tokenizer = spm.SentencePieceProcessor()
tokenizer.Load(vocab_path)
tokenizer.SetEncodeExtraOptions("")
print("Loading PyTorch checkpoint...")
with open(torch_config_path) as f:
fnet_torch_config = json.load(f)
fnet_torch = FNetForPreTraining(fnet_torch_config)
statedict = torch.load(torch_statedict_path, map_location=torch.device('cpu'))
fnet_torch.load_state_dict(statedict)
fnet_torch.eval()
print("Done")
print("Loading Jax checkpoint...")
random_seed = 0
rng = random.PRNGKey(random_seed)
rng, init_rng = random.split(rng)
config = get_config()
with config.unlocked():
config.vocab_size = tokenizer.GetPieceSize()
frozen_config = ml_collections.FrozenConfigDict(config)
fnet_jax_model = JaxPreTrainingModel(config=frozen_config, random_seed=random_seed)
fnet_jax_params = jax_init_params(fnet_jax_model, init_rng, frozen_config)
fnet_jax_params = checkpoints.restore_checkpoint(jax_checkpoint_path, {'target': fnet_jax_params})['target']
print("Done")
input_ids, token_type_ids, mlm_positions, mlm_ids = get_input(tokenizer, fnet_torch_config['max_position_embeddings'])
with torch.no_grad():
fnet_torch_output = fnet_torch(input_ids, token_type_ids, mlm_positions)
print(fnet_torch_output)
fnet_jax_output = fnet_jax_model.apply({"params": fnet_jax_params}, **{
"input_ids": input_ids.numpy(),
"input_mask": (input_ids.numpy() > 0).astype(np.int32),
"type_ids": token_type_ids.numpy(),
"masked_lm_positions": mlm_positions.numpy(),
"masked_lm_labels": mlm_ids.numpy(),
"masked_lm_weights": (mlm_positions.numpy() > 0).astype(np.float32),
"next_sentence_labels": np.array([1]),
"deterministic": True
})
print(fnet_jax_output)
atol = 1e-01
assert np.allclose(fnet_torch_output['mlm_logits'].numpy(), fnet_jax_output['masked_lm_logits'], atol=atol)
assert np.allclose(fnet_torch_output['nsp_logits'].numpy(), fnet_jax_output['next_sentence_logits'], atol=atol)
print(f"Inference results of both models are equal up to {atol}")
def jax_init_params(model, key, config):
init_batch = {
"input_ids": jnp.ones((1, config.max_seq_length), jnp.int32),
"input_mask": jnp.ones((1, config.max_seq_length), jnp.int32),
"type_ids": jnp.ones((1, config.max_seq_length), jnp.int32),
"masked_lm_positions": jnp.ones((1, config.max_predictions_per_seq), jnp.int32),
"masked_lm_labels": jnp.ones((1, config.max_predictions_per_seq), jnp.int32),
"masked_lm_weights": jnp.ones((1, config.max_predictions_per_seq), jnp.int32),
"next_sentence_labels": jnp.ones((1, 1), jnp.int32)
}
key, dropout_key = random.split(key)
jit_init = jax.jit(model.init)
initial_variables = jit_init({
"params": key,
"dropout": dropout_key
}, **init_batch)
return initial_variables["params"]
def get_input(tokenizer, seq_len):
text = "<NAME> (May 28, 1915 – May 7, 2001) was an American linguist, " \
"known mainly for his work concerning " \
"linguistic typology and the genetic classification of languages."
cls_id = tokenizer.PieceToId("[CLS]")
mask_id = tokenizer.PieceToId("[MASK]")
sep_id = tokenizer.PieceToId("[SEP]")
pad_id = tokenizer.pad_id()
token_ids = [cls_id] + tokenizer.EncodeAsIds(text) + [sep_id]
input_ids = torch.full((1, seq_len), pad_id, dtype=torch.long)
input_ids[0, :len(token_ids)] = torch.LongTensor(token_ids)
# mask some tokens
mlm_positions = torch.LongTensor([1, 5, 7])
mlm_ids = input_ids[0, mlm_positions]
input_ids[0, mlm_positions] = mask_id
token_type_ids = torch.full((1, seq_len), 0, dtype=torch.long)
max_mlm_maskings = 80
full_mlm_positions = torch.full((1, max_mlm_maskings), 0, dtype=torch.long)
full_mlm_positions[:, :len(mlm_positions)] = mlm_positions
full_mlm_ids = torch.full((1, max_mlm_maskings), 0, dtype=torch.long)
full_mlm_ids[:, :len(mlm_ids)] = mlm_ids
return input_ids, token_type_ids, full_mlm_positions, full_mlm_ids
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('--jax', type=str, required=True, help='path to FNet jax checkpoint')
parser.add_argument('--torch', type=str, required=True, help='path to PyTorch statedict checkpoint')
parser.add_argument('--config', type=str, required=True, help='path to PyTorch checkpoint config')
parser.add_argument('--vocab', type=str, required=True, help='path to vocab file')
args = parser.parse_args()
compare_output(args.jax, args.torch, args.config, args.vocab)
|
ttocsnamfuak/hwkWeaterAPI | config.py | <reponame>ttocsnamfuak/hwkWeaterAPI
#Open Weather API
api_key = 'a8c2dd6be0fb9a88e48d445b1b7d7430'
|
Tech901/sample-flask-app | main.py | from flask import Flask, request, render_template, redirect, url_for
from datetime import datetime
import json
app = Flask(__name__)
@app.route("/")
def index():
time = datetime.now().strftime("%c")
return render_template("index.html", current_time=time)
@app.route('/name')
def name():
first_name = request.args.get('first', '')
last_name = request.args.get('last', '')
return render_template("name.html", name=f"{first_name} {last_name}")
@app.route('/guestbook', methods=['GET', 'POST'])
def guestbook():
if request.method == 'POST':
# Handle POST requests & save entries to a file
name = request.form['guest_name']
with open("guests.txt", 'a') as f:
f.write(f"{name}\n")
# Redirect the user...
return redirect(url_for("guestbook"))
# Read all of the guest entries from a file.
guests = []
with open("guests.txt") as f:
guests = f.readlines()
return render_template("guestbook.html", guests=guests)
@app.route('/api/guestbook')
def guestbook_api():
guests = []
with open("guests.txt") as f:
guests = f.readlines()
data = json.dumps({
'count': len(guests),
'guests': guests,
})
return data |
victor-uemura/cliff-api-client | two.py | # Step 2: takes untagged messages and splits them by sentence and then looks for location identifiers. put all statements w locations into new sheet.
from cliff.api import Cliff
import pandas as pd
import geoip2.database
import re
reader = geoip2.database.Reader("../GeoLite2-City_20210202/GeoLite2-City.mmdb")
my_cliff = Cliff('http://localhost:8080')
file_name = "../processedData/messages.xlsx" # path to file + file name
sheet = "Sheet1" # sheet name or sheet number or list of sheet numbers and names
df = pd.read_excel(io=file_name, sheet_name=sheet)
excel_data = []
check_repeat = []
for index, row in df.iterrows():
parsed_row = re.split('[?.:]', row['message'])
for sentence in parsed_row:
if (len(sentence.split()) < 4 and len(sentence.strip()) > 2):
if (sentence.strip() not in check_repeat):
temp_data = {}
check_repeat.append(sentence.strip())
result = my_cliff.parse_text(sentence)
try:
targets = result['results']['places']['focus']
if targets != {} :
# message, author
temp_data['author'] = row['author']
temp_data['message'] = sentence.strip()
# city data
temp_data['cities'] = []
if targets['cities'] != [] :
for city in targets['cities']:
temp_data['cities'].append((city['name'], city['lat'], city['lon']))
#state data
temp_data['states'] = []
if targets['states'] != [] :
for state in targets['states']:
temp_data['states'].append((state['name'], state['lat'], state['lon']))
#country data
temp_data['countries'] = []
if targets['countries'] != []:
for country in targets['countries']:
temp_data['countries'].append((country['name'], country['lat'], country['lon']))
#ip data
# ip_info = reader.city(row['ip'])
temp_data['ip'] = row['ip']
excel_data.append(temp_data)
except:
print("error occured", result)
excel_frame = pd.DataFrame(excel_data)
excel_frame.to_excel("../processedData/targeted_messages.xlsx", index=False) |
victor-uemura/cliff-api-client | five.py | <reponame>victor-uemura/cliff-api-client
#Create spreadsheet with country, state and city counts
from cliff.api import Cliff
import pandas as pd
import ast
file_name = "../processedData/author_location.xlsx" # path to file + file name
sheet = "Sheet1" # sheet name or sheet number or list of sheet numbers and names
df = pd.read_excel(io=file_name, sheet_name=sheet)
city_data = []
state_data = []
country_data = []
city_check = []
state_check = []
country_check = []
for index, row in df.iterrows():
for city in ast.literal_eval(row['cities']):
if city not in city_check:
city_check.append(city)
temp_city = {}
temp_city['name'] = city[0]
temp_city['lat'] = city[1]
temp_city['lon'] = city[2]
temp_city['count'] = 1
city_data.append(temp_city)
else :
for item in city_data:
if item['name'] == city[0]:
item['count'] += 1
for state in ast.literal_eval(row['states']):
if state not in state_check:
state_check.append(state)
temp_state = {}
temp_state['name'] = state[0]
temp_state['lat'] = state[1]
temp_state['lon'] = state[2]
temp_state['count'] = 1
state_data.append(temp_state)
else :
for item in state_data:
if item['name'] == state[0]:
item['count'] += 1
for country in ast.literal_eval(row['countries']):
if country not in country_check:
country_check.append(country)
temp_country = {}
temp_country['name'] = country[0]
temp_country['lat'] = country[1]
temp_country['lon'] = country[2]
temp_country['count'] = 1
country_data.append(temp_country)
else :
for item in country_data:
if item['name'] == country[0]:
item['count'] += 1
city_excel_frame = pd.DataFrame(city_data)
city_excel_frame.to_excel("../processedData/cities.xlsx", index=False)
state_excel_frame = pd.DataFrame(state_data)
state_excel_frame.to_excel("../processedData/states.xlsx", index=False)
country_excel_frame = pd.DataFrame(country_data)
country_excel_frame.to_excel("../processedData/countries.xlsx", index=False)
|
victor-uemura/cliff-api-client | cliff/api.py | <gh_stars>1-10
import logging
import json
import requests
class Cliff:
# Make requests to a CLIFF geo-parsing / NER server
PARSE_TEXT_PATH = "/cliff-2.6.1/parse/text"
PARSE_NLP_JSON_PATH = "/cliff-2.6.1/parse/json"
PARSE_SENTENCES_PATH = "/cliff-2.6.1/parse/sentences"
GEONAMES_LOOKUP_PATH = "/cliff-2.6.1/geonames"
EXTRACT_TEXT_PATH = "/cliff-2.6.1/extract"
GERMAN = "DE";
SPANISH = "ES";
ENGLISH = "EN";
JSON_PATH_TO_ABOUT_COUNTRIES = 'results.places.about.countries'
STATUS_OK = "ok"
def __init__(self, url, text_replacements=None):
self._log = logging.getLogger(__name__)
self._url = url
self._replacements = text_replacements if text_replacements is not None else {}
self._log.info("initialized CLIFF @ {}".format(url))
def parse_text(self, text, demonyms=False, language=ENGLISH):
cleaned_text = self._get_replaced_text(text)
return self._parse_query(self.PARSE_TEXT_PATH, cleaned_text, demonyms, language)
def parse_sentences(self, json_object, demonyms=False, language=ENGLISH):
return self._parse_query(self.PARSE_SENTENCES_PATH, json.dumps(json_object), demonyms, language)
def geonames_lookup(self, geonames_id):
return self._query(self.GEONAMES_LOOKUP_PATH, {'id': geonames_id})['results']
def extract_content(self, url):
# uses the boilerpipe engine
return self._get_query(self.EXTRACT_TEXT_PATH, {'url': url})
def _demonyms_text(self, demonyms=False):
return "true" if demonyms else "false"
def _url_to(self, path):
return "{}{}".format(self._url, path)
def _get_replaced_text(self, text):
replaced_text = text
for replace, find in self._replacements.items():
replaced_text = text.replace(find, replace)
return replaced_text
def _parse_query(self, path, text, demonyms=False, language=ENGLISH):
payload = {'q': text, 'replaceAllDemonyms': self._demonyms_text(demonyms), 'language': language}
self._log.debug("Querying %r (demonyms=%r)", path, demonyms)
return self._query(path, payload)
def _query(self, path, args):
try:
url = self._url_to(path)
r = requests.post(url, data=args)
self._log.debug('CLIFF says %r', r.content)
return r.json()
except requests.exceptions.RequestException as e:
self._log.exception(e)
return ""
def _get_query(self, path, args):
try:
url = self._url_to(path)
r = requests.get(url, params=args)
self._log.debug('CLIFF says %r', r.content)
return r.json()
except requests.exceptions.RequestException as e:
self._log.exception(e)
return ""
|
victor-uemura/cliff-api-client | four.py | #Step 4: takes messages and makes sure location is counted once per author
from cliff.api import Cliff
import pandas as pd
import ast
file_name = "../processedData/final_targeted_messages.xlsx" # path to file + file name
sheet = "Sheet1" # sheet name or sheet number or list of sheet numbers and names
df = pd.read_excel(io=file_name, sheet_name=sheet)
excel_data = []
author_id = []
for index, row in df.iterrows():
if row['author'] not in author_id or str(row['author']) == "0":
author_id.append(row['author'])
temp_data = {}
temp_data['author'] = row['author']
temp_data['cities'] = row['cities']
temp_data['states'] = row['states']
temp_data['countries'] = row['countries']
excel_data.append(temp_data)
else:
for data_row in excel_data:
if data_row['author'] == row['author']:
if row['cities'] != []:
for city in ast.literal_eval(row['cities']):
if city not in ast.literal_eval(data_row['cities']):
temp_cities = ast.literal_eval(data_row['cities'])
temp_cities.append(city)
data_row['cities'] = str(temp_cities)
if row['states'] != []:
for state in ast.literal_eval(row['states']):
if state not in ast.literal_eval(data_row['states']):
temp_state = ast.literal_eval(data_row['states'])
temp_state.append(state)
data_row['states'] = str(temp_state)
if row['countries'] != []:
for country in ast.literal_eval(row['countries']):
if country not in ast.literal_eval(data_row['countries']):
temp_country = ast.literal_eval(data_row['countries'])
temp_country.append(country)
data_row['countries'] = str(temp_country)
excel_frame = pd.DataFrame(excel_data)
excel_frame.to_excel("../processedData/author_location.xlsx", index=False)
|
victor-uemura/cliff-api-client | cliff/test.py | <filename>cliff/test.py
import unittest
import os
from cliff.api import Cliff
from dotenv import load_dotenv
# load env-vars from .env file if there is one
basedir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
test_env = os.path.join(basedir, '.env')
if os.path.isfile(test_env):
load_dotenv(dotenv_path=os.path.join(basedir, '.env'), verbose=True)
GEONAME_LONDON_UK = 2643743
GEONAME_LONDERRY_NH = 5088905
class BasicCliffTest(unittest.TestCase):
# A basic set of test cases to make sure the API can pull from the server correctly.
def setUp(self):
self._url = os.getenv("CLIFF_URL")
self._cliff = Cliff(self._url)
def test_parse_text(self):
results = self._cliff.parse_text("This is about Einstien at the IIT in New Delhi.")
results = results['results']
print(results)
self.assertEqual(len(results['organizations']), 1)
self.assertEqual(len(results['places']['mentions']), 1)
self.assertEqual(results['places']['mentions'][0]['id'], 1261481)
self.assertEqual(len(results['people']), 1)
def test_extract_content(self):
test_url = "https://www.foxnews.com/us/temple-university-stands-by-marc-lamont-hill-after-cnn-fires-him-for-anti-israel-remarks"
results = self._cliff.extract_content(test_url)
results = results['results']
self.assertEqual(test_url, results['url'])
self.assertTrue(len(results['text']) > 100)
def test_geonames_lookup(self):
results = self._cliff.geonames_lookup(4943351)
self.assertEqual(results['id'], 4943351)
self.assertEqual(results['lon'], -71.09172)
self.assertEqual(results['lat'], 42.35954)
self.assertEqual(results['name'], "Massachusetts Institute of Technology")
self.assertEqual(results['parent']['name'], "City of Cambridge")
self.assertEqual(results['parent']['parent']['name'], "Middlesex County")
self.assertEqual(results['parent']['parent']['parent']['name'], "Massachusetts")
self.assertEqual(results['parent']['parent']['parent']['parent']['name'], "United States")
def test_local_replacements(self):
replacements = {
'Londonderry': 'London',
}
# make sure non-replaced fetches the city in the UK
results = self._cliff.parse_text("This is about London.")['results']
mention = results['places']['mentions'][0]
self.assertEqual(GEONAME_LONDON_UK, mention['id'])
# now see if it gets the city with replacements
replacing_cliff = Cliff(self._url, text_replacements=replacements)
results = replacing_cliff.parse_text("This is about London.")['results']
replaced_mention = results['places']['mentions'][0]
self.assertEqual(GEONAME_LONDERRY_NH, replaced_mention['id'])
|
victor-uemura/cliff-api-client | ips.py | #Reads members csv file and then creates spreadsheet with country and city counts.
import pandas as pd
import geoip2.database
reader = geoip2.database.Reader("../GeoLite2-City_20210202/GeoLite2-City.mmdb")
file_name = "../processedData/core_members.xls" # path to file + file name
sheet = "Sheet1" # sheet name or sheet number or list of sheet numbers and names
df = pd.read_excel(io=file_name, sheet_name=sheet)
city_data = []
country_data = []
check_city = []
check_country = []
for index, row in df.iterrows():
response = reader.city(row['ip'])
if response.city.name != None and str(response.city.name + response.country.name) not in check_city:
check_city.append(str(response.city.name + response.country.name))
temp_city = {}
temp_city['name'] = response.city.name
temp_city['country'] = response.country.name
temp_city['lat'] = response.location.latitude
temp_city['lon'] = response.location.longitude
temp_city['count'] = 1
city_data.append(temp_city)
else:
for item in city_data:
if item['name'] == response.city.name and item['country'] == response.country.name:
item['count'] += 1
if response.country.name != None and response.country.name not in check_country:
check_country.append(response.country.name)
temp_country = {}
temp_country['name'] = response.country.name
temp_country['count'] = 1
country_data.append(temp_country)
else:
for item in country_data:
if item['name'] == response.country.name:
item['count'] += 1
city_excel_frame = pd.DataFrame(city_data)
city_excel_frame.to_excel("../processedData/ip_cities.xlsx", index=False)
country_excel_frame = pd.DataFrame(country_data)
country_excel_frame.to_excel("../processedData/ip_countries.xlsx", index=False) |
victor-uemura/cliff-api-client | test.py | import logging
import sys
from cliff.test import *
test_classes = [
BasicCliffTest
]
logging.basicConfig(level=logging.WARN)
# now run all the tests
suites = [unittest.TestLoader().loadTestsFromTestCase(test_class) for test_class in test_classes]
if __name__ == "__main__":
suite = unittest.TestSuite(suites)
test_result = unittest.TextTestRunner(verbosity=2).run(suite)
if not test_result.wasSuccessful():
sys.exit(1)
|
victor-uemura/cliff-api-client | setup.py | <gh_stars>1-10
#! /usr/bin/env python
from setuptools import setup
import re
from os import path
version = ''
with open('cliff/__init__.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1)
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md')) as f:
long_description = f.read()
setup(name='mediacloud-cliff',
version=version,
description='Media Cloud CLIFF API Client Library',
long_description=long_description,
long_description_content_type='text/markdown',
author='<NAME>',
author_email='<EMAIL>',
url='http://cliff.mediacloud.org',
packages={'cliff'},
package_data={'': ['LICENSE']},
include_package_data=True,
install_requires=['requests'],
license='MIT',
zip_safe=False
)
|
dcartman/pygame-menu | test/test_widget_textinput.py | <reponame>dcartman/pygame-menu<filename>test/test_widget_textinput.py
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST WIDGET - TEXTINPUT
Test TextInput and ColorInput widgets.
"""
__all__ = ['TextInputWidgetTest']
from test._utils import MenuUtils, surface, PygameEventUtils, TEST_THEME, PYGAME_V2, \
BaseTest
import pygame
import pygame_menu
import pygame_menu.controls as ctrl
from pygame_menu.widgets.core.widget import WidgetTransformationNotImplemented
class TextInputWidgetTest(BaseTest):
# noinspection SpellCheckingInspection,PyTypeChecker
def test_textinput(self) -> None:
"""
Test TextInput widget.
"""
menu = MenuUtils.generic_menu()
# Assert bad settings
self.assertRaises(ValueError,
lambda: menu.add.text_input('title',
input_type=pygame_menu.locals.INPUT_FLOAT,
default='bad'))
self.assertRaises(ValueError, # Default and password cannot coexist
lambda: menu.add.text_input('title',
password=True,
default='bad'))
# Create text input widget
textinput = menu.add.text_input('title', input_underline='_')
textinput.set_value('new_value') # No error
textinput._selected = False
textinput.draw(surface)
textinput.select(update_menu=True)
textinput.draw(surface)
self.assertEqual(textinput.get_value(), 'new_value')
textinput.clear()
self.assertEqual(textinput.get_value(), '')
# Create selection box
string = 'the text'
textinput._cursor_render = True
textinput.set_value(string)
textinput._select_all()
self.assertEqual(textinput._get_selected_text(), 'the text')
textinput.draw(surface)
textinput._unselect_text()
textinput.draw(surface)
# Assert events
textinput.update(PygameEventUtils.key(0, keydown=True, testmode=False))
PygameEventUtils.test_widget_key_press(textinput)
textinput.update(PygameEventUtils.key(ctrl.KEY_APPLY, keydown=True))
textinput.update(PygameEventUtils.key(pygame.K_LSHIFT, keydown=True))
textinput.clear()
# Type
textinput.update(PygameEventUtils.key(pygame.K_t, keydown=True, char='t'))
textinput.update(PygameEventUtils.key(pygame.K_e, keydown=True, char='e'))
textinput.update(PygameEventUtils.key(pygame.K_s, keydown=True, char='s'))
textinput.update(PygameEventUtils.key(pygame.K_t, keydown=True, char='t'))
# Keyup
textinput.update(PygameEventUtils.key(pygame.K_a, keyup=True, char='a'))
self.assertEqual(textinput.get_value(), 'test') # The text we typed
# Ctrl events
textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_c)) # copy
textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_v)) # paste
textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_z)) # undo
self.assertEqual(textinput.get_value(), 'tes')
textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_y)) # redo
self.assertEqual(textinput.get_value(), 'test')
textinput._select_all()
textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_x)) # cut
self.assertEqual(textinput.get_value(), '')
textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_z)) # undo
self.assertEqual(textinput.get_value(), 'test')
textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_y)) # redo
self.assertEqual(textinput.get_value(), '')
textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_z)) # undo
self.assertEqual(textinput.get_value(), 'test')
# Test ignore ctrl events
textinput._copy_paste_enabled = False
self.assertFalse(textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_c)))
self.assertFalse(textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_v)))
max_history = textinput._max_history
textinput._max_history = 0
self.assertFalse(textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_z)))
self.assertFalse(textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_y)))
self.assertFalse(textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_x)))
textinput._selection_enabled = False
self.assertFalse(textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_a)))
self.assertFalse(textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_r))) # invalid
# Reset
textinput._copy_paste_enabled = True
textinput._max_history = max_history
textinput._selection_enabled = True
# Test selection, if user selects all and types anything the selected
# text must be destroyed
textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_a)) # select all
textinput._unselect_text()
self.assertEqual(textinput._get_selected_text(), '')
textinput._select_all()
self.assertEqual(textinput._get_selected_text(), 'test')
textinput._unselect_text()
self.assertEqual(textinput._get_selected_text(), '')
textinput.update(PygameEventUtils.keydown_mod_ctrl(pygame.K_a))
self.assertEqual(textinput._get_selected_text(), 'test')
textinput.update(PygameEventUtils.key(pygame.K_t, keydown=True, char='t'))
textinput._select_all()
self.assertTrue(textinput.update(PygameEventUtils.key(pygame.K_ESCAPE, keydown=True)))
textinput._select_all()
self.assertTrue(textinput.update(PygameEventUtils.key(pygame.K_BACKSPACE, keydown=True)))
self.assertEqual(textinput.get_value(), '')
textinput.set_value('t')
# Releasing shift disable selection
textinput._selection_active = True
textinput.update(PygameEventUtils.key(pygame.K_LSHIFT, keyup=True))
self.assertFalse(textinput._selection_active)
# Arrows while selection
textinput._select_all()
self.assertIsNotNone(textinput._selection_surface)
textinput.update(PygameEventUtils.key(pygame.K_LEFT, keydown=True))
self.assertIsNone(textinput._selection_surface)
textinput._select_all()
self.assertIsNotNone(textinput._selection_surface)
textinput.update(PygameEventUtils.key(pygame.K_RIGHT, keydown=True))
self.assertIsNone(textinput._selection_surface)
textinput._select_all()
textinput._selection_active = True
self.assertEqual(textinput._selection_box, [0, 1])
textinput.update(PygameEventUtils.key(pygame.K_LEFT, keydown=True))
self.assertEqual(textinput._selection_box, [0, 0])
textinput._select_all()
textinput._selection_active = True
textinput.update(PygameEventUtils.key(pygame.K_RIGHT, keydown=True))
self.assertEqual(textinput._selection_box, [0, 1])
# Remove while selection
textinput._select_all()
textinput.update(PygameEventUtils.key(pygame.K_DELETE, keydown=True))
self.assertEqual(textinput.get_value(), '')
textinput.set_value('t')
# Now the value must be t
self.assertEqual(textinput._get_selected_text(), '')
self.assertEqual(textinput.get_value(), 't')
# Test readonly
textinput.update(PygameEventUtils.key(pygame.K_t, keydown=True, char='k'))
self.assertEqual(textinput.get_value(), 'tk')
textinput.readonly = True
textinput.update(PygameEventUtils.key(pygame.K_t, keydown=True, char='k'))
self.assertEqual(textinput.get_value(), 'tk')
textinput.readonly = False
# Test keyup
self.assertIn(pygame.K_t, textinput._keyrepeat_counters.keys())
self.assertFalse(textinput.update(
PygameEventUtils.key(pygame.K_t, keyup=True, char='1')))
self.assertNotIn(pygame.K_t, textinput._keyrepeat_counters.keys())
# Test tab
self.assertEqual(textinput._tab_size, 4)
textinput.update(PygameEventUtils.key(pygame.K_TAB, keydown=True))
self.assertEqual(textinput.get_value(), 'tk ')
# Test invalid unicode
self.assertFalse(textinput.update(PygameEventUtils.key(pygame.K_1, keydown=True)))
# Up/Down disable active status
textinput.active = True
textinput.update(PygameEventUtils.key(ctrl.KEY_MOVE_UP, keydown=True))
self.assertFalse(textinput.active)
textinput.active = True
textinput.update(PygameEventUtils.key(ctrl.KEY_MOVE_DOWN, keydown=True))
self.assertFalse(textinput.active)
textinput.active = True
self.assertTrue(textinput.update(PygameEventUtils.key(pygame.K_ESCAPE, keydown=True)))
self.assertFalse(textinput.active)
# Test mouse
textinput._selected = True
textinput._selection_time = 0
textinput.update(PygameEventUtils.middle_rect_click(textinput))
self.assertTrue(textinput._cursor_visible)
textinput._select_all()
textinput._selection_active = True
self.assertEqual(textinput._cursor_position, 6)
self.assertEqual(textinput._selection_box, [0, 6])
textinput.update(PygameEventUtils.middle_rect_click(textinput, evtype=pygame.MOUSEBUTTONDOWN))
self.assertEqual(textinput._selection_box, [0, 0])
# Check click pos
textinput._check_mouse_collide_input(PygameEventUtils.middle_rect_click(textinput)[0].pos)
self.assertEqual(textinput._cursor_position, 6)
# Test touch
textinput._cursor_position = 0
textinput._check_touch_collide_input(PygameEventUtils.middle_rect_click(textinput)[0].pos)
self.assertEqual(textinput._cursor_position, 6)
# Update mouse
for i in range(50):
textinput.update(PygameEventUtils.key(pygame.K_t, keydown=True, char='t'))
textinput._update_cursor_mouse(50)
textinput._cursor_render = True
textinput._render_cursor()
# Test multiple are selected
menu.add.text_input('title', password=True, input_underline='_').select()
self.assertRaises(pygame_menu.menu._MenuMultipleSelectedWidgetsException, lambda: menu.draw(surface))
textinput.clear()
textinput.select(update_menu=True)
menu.draw(surface)
# Clear the menu
self.assertEqual(menu._stats.removed_widgets, 0)
self.assertEqual(textinput.get_menu(), menu)
menu.clear()
self.assertIsNone(textinput.get_menu())
self.assertEqual(menu._stats.removed_widgets, 3)
menu.add.generic_widget(textinput)
self.assertEqual(textinput.get_menu(), menu)
menu.clear()
self.assertEqual(menu._stats.removed_widgets, 4)
def test_password(self) -> None:
"""
Test password.
"""
menu = MenuUtils.generic_menu()
password_input = menu.add.text_input('title', password=True, input_underline='_')
self.assertRaises(ValueError, # Password cannot be set
lambda: password_input.set_value('new_value'))
password_input.set_value('') # No error
password_input._selected = False
password_input.draw(surface)
password_input.select(update_menu=True)
password_input.draw(surface)
self.assertEqual(password_input.get_value(), '')
password_input.clear()
self.assertEqual(password_input.get_value(), '')
# Test none width password
password_input._password_char = ''
self.assertRaises(ValueError, lambda: password_input._apply_font())
def test_unicode(self) -> None:
"""
Test unicode support.
"""
menu = MenuUtils.generic_menu()
textinput = menu.add.text_input('title', input_underline='_')
textinput.set_value('tk')
# Test alt+x
textinput.update(PygameEventUtils.key(pygame.K_SPACE, keydown=True))
textinput.update(PygameEventUtils.key(pygame.K_2, keydown=True, char='2'))
textinput.update(PygameEventUtils.key(pygame.K_1, keydown=True, char='1'))
textinput.update(PygameEventUtils.key(pygame.K_1, keydown=True, char='5'))
self.assertEqual(textinput.get_value(), 'tk 215')
textinput.update(PygameEventUtils.keydown_mod_alt(pygame.K_x)) # convert 215 to unicode
self.assertEqual(textinput.get_value(), 'tkȕ')
textinput.update(PygameEventUtils.key(pygame.K_SPACE, keydown=True))
textinput.update(PygameEventUtils.key(pygame.K_SPACE, keydown=True))
textinput.update(PygameEventUtils.key(pygame.K_b, keydown=True, char='B'))
textinput.update(PygameEventUtils.key(pygame.K_1, keydown=True, char='1'))
textinput.update(PygameEventUtils.keydown_mod_alt(pygame.K_x)) # convert 215 to unicode
self.assertEqual(textinput.get_value(), 'tkȕ ±')
# Remove all
textinput.clear()
textinput.update(PygameEventUtils.key(pygame.K_b, keydown=True, char='B'))
textinput.update(PygameEventUtils.key(pygame.K_1, keydown=True, char='1'))
textinput.update(PygameEventUtils.keydown_mod_alt(pygame.K_x)) # convert 215 to unicode
self.assertEqual(textinput.get_value(), '±')
textinput.update(PygameEventUtils.keydown_mod_alt(pygame.K_x)) # convert same to unicode, do nothing
self.assertEqual(textinput.get_value(), '±')
# Test consecutive
textinput.update(PygameEventUtils.key(pygame.K_2, keydown=True, char='2'))
textinput.update(PygameEventUtils.key(pygame.K_0, keydown=True, char='0'))
textinput.update(PygameEventUtils.key(pygame.K_1, keydown=True, char='1'))
textinput.update(PygameEventUtils.key(pygame.K_3, keydown=True, char='3'))
textinput.update(PygameEventUtils.keydown_mod_alt(pygame.K_x)) # convert 215 to unicode
self.assertEqual(textinput.get_value(), '±–')
# Test 0x
textinput.clear()
PygameEventUtils.release_key_mod()
textinput.update(PygameEventUtils.key(pygame.K_0, keydown=True, char='0'))
self.assertEqual(textinput.get_value(), '0')
textinput.update(PygameEventUtils.key(pygame.K_x, keydown=True, char='x'))
self.assertEqual(textinput.get_value(), '0x')
textinput.update(PygameEventUtils.keydown_mod_alt(pygame.K_x))
self.assertEqual(textinput.get_value(), '0x')
textinput.update(PygameEventUtils.key(pygame.K_b, keydown=True, char='B'))
textinput.update(PygameEventUtils.key(pygame.K_1, keydown=True, char='1'))
self.assertEqual(textinput.get_value(), '0xB1')
textinput.update(PygameEventUtils.keydown_mod_alt(pygame.K_x))
self.assertEqual(textinput.get_value(), '±')
PygameEventUtils.release_key_mod()
textinput.update(PygameEventUtils.key(pygame.K_0, keydown=True, char='0'))
textinput.update(PygameEventUtils.key(pygame.K_x, keydown=True, char='x'))
textinput.update(PygameEventUtils.key(pygame.K_b, keydown=True, char='B'))
textinput.update(PygameEventUtils.key(pygame.K_1, keydown=True, char='1'))
textinput.update(PygameEventUtils.keydown_mod_alt(pygame.K_x))
self.assertEqual(textinput.get_value(), '±±')
# Test keyup
self.assertIn(pygame.K_1, textinput._keyrepeat_counters.keys())
self.assertFalse(textinput.update(
PygameEventUtils.key(pygame.K_1, keyup=True, char='1')))
self.assertNotIn(pygame.K_1, textinput._keyrepeat_counters.keys())
# Test tab
self.assertEqual(textinput._tab_size, 4)
textinput.update(PygameEventUtils.key(pygame.K_TAB, keydown=True))
self.assertEqual(textinput.get_value(), '±± ')
# Test invalid unicode
self.assertFalse(textinput.update(PygameEventUtils.key(pygame.K_1, keydown=True)))
# Test others
textinput._input_type = 'other'
self.assertTrue(textinput._check_input_type('-'))
self.assertFalse(textinput._check_input_type('x'))
textinput._maxwidth_update = None
self.assertIsNone(textinput._update_maxlimit_renderbox())
def test_undo_redo(self) -> None:
"""
Test undo/redo.
"""
menu = MenuUtils.generic_menu()
# Test maxchar and undo/redo
textinput = menu.add.text_input('title',
input_underline='_',
maxchar=20)
textinput.set_value('the size of this textinput is way greater than the limit')
self.assertEqual(textinput.get_value(), 'eater than the limit') # same as maxchar
self.assertEqual(textinput._cursor_position, 20)
textinput._undo() # This must set default at ''
self.assertEqual(textinput.get_value(), '')
textinput._redo()
self.assertEqual(textinput.get_value(), 'eater than the limit')
textinput.draw(surface)
textinput._copy()
textinput._paste()
textinput._block_copy_paste = False
textinput._select_all()
textinput._cut()
self.assertEqual(textinput.get_value(), '')
textinput._undo()
self.assertEqual(textinput.get_value(), 'eater than the limit')
self.assertEqual(textinput._history_index, 1)
textinput._history_index = 0
self.assertFalse(textinput._undo())
textinput._history_index = len(textinput._history) - 1
self.assertFalse(textinput._redo())
def test_copy_paste(self) -> None:
"""
Test copy/paste.
"""
menu = MenuUtils.generic_menu()
# Test copy/paste
textinput_nocopy = menu.add.text_input('title',
input_underline='_',
maxwidth=20,
copy_paste_enable=False)
textinput_nocopy.set_value('this cannot be copied')
textinput_nocopy._copy()
textinput_nocopy._paste()
textinput_nocopy._cut()
self.assertEqual(textinput_nocopy.get_value(), 'this cannot be copied')
# Test copy/paste without block
textinput_copy = menu.add.text_input('title',
input_underline='_',
maxwidth=20,
maxchar=20)
textinput_copy.set_value('this value should be cropped as this is longer than the max char')
self.assertFalse(textinput_copy._block_copy_paste)
textinput_copy._copy()
self.assertTrue(textinput_copy._block_copy_paste)
textinput_copy._block_copy_paste = False
textinput_copy._select_all()
textinput_copy._cut()
self.assertEqual(textinput_copy.get_value(), '')
textinput_copy._block_copy_paste = False
textinput_copy._paste()
# self.assertEqual(textinput_copy.get_value(), 'er than the max char')
textinput_copy._cut()
textinput_copy._block_copy_paste = False
# self.assertEqual(textinput_copy.get_value(), '')
textinput_copy._valid_chars = ['e', 'r']
textinput_copy._paste()
# Copy password
textinput_copy._password = True
self.assertFalse(textinput_copy._copy())
def test_overflow_removal(self) -> None:
"""
Test text with max width and right overflow removal.
"""
menu = MenuUtils.generic_menu()
menu._copy_theme()
menu._theme.widget_font_size = 20
textinput = menu.add.text_input(
'Some long text: ',
maxwidth=19,
textinput_id='long_text',
input_underline='_'
)
self.assertRaises(WidgetTransformationNotImplemented, lambda: textinput.resize())
self.assertRaises(WidgetTransformationNotImplemented, lambda: textinput.set_max_width())
self.assertRaises(WidgetTransformationNotImplemented, lambda: textinput.set_max_height())
self.assertRaises(WidgetTransformationNotImplemented, lambda: textinput.scale())
self.assertRaises(WidgetTransformationNotImplemented, lambda: textinput.rotate())
textinput.flip(True, True)
self.assertEqual(textinput._flip, (False, True))
# noinspection SpellCheckingInspection
textinput.set_value('aaaaaaaaaaaaaaaaaaaaaaaaaa')
self.assertEqual(textinput._cursor_position, 26)
self.assertEqual(textinput._renderbox, [1, 26, 25])
textinput.update(PygameEventUtils.key(pygame.K_BACKSPACE, keydown=True))
self.assertEqual(textinput._cursor_position, 25)
self.assertEqual(textinput._renderbox, [0, 25, 25])
textinput.update(PygameEventUtils.key(pygame.K_a, keydown=True, char='a'))
self.assertEqual(textinput._cursor_position, 26)
self.assertEqual(textinput._renderbox, [1, 26, 25])
textinput.update(PygameEventUtils.key(pygame.K_BACKSPACE, keydown=True))
self.assertEqual(textinput._cursor_position, 25)
self.assertEqual(textinput._renderbox, [0, 25, 25])
# noinspection PyTypeChecker
def test_textinput_underline(self) -> None:
"""
Test underline.
"""
# Test underline edge cases
theme = TEST_THEME.copy()
theme.title_font_size = 35
theme.widget_font_size = 25
menu = pygame_menu.Menu(
column_min_width=400,
height=300,
theme=theme,
title='Label',
onclose=pygame_menu.events.CLOSE,
width=400
)
textinput = menu.add.text_input('title', input_underline='_')
self.assertEqual(menu._widget_offset[1], 107 if PYGAME_V2 else 106)
self.assertEqual(textinput.get_width(), 376)
self.assertEqual(textinput._current_underline_string, '______________________________')
menu.render()
self.assertEqual((menu.get_width(widget=True), menu.get_width(inner=True)), (376, 400))
self.assertEqual(textinput.get_width(), 376)
self.assertEqual(textinput._current_underline_string, '______________________________')
menu.render()
self.assertEqual((menu.get_width(widget=True), menu.get_width(inner=True)), (376, 400))
textinput.set_title('nice')
self.assertEqual(textinput.get_width(), 379)
self.assertEqual(textinput._current_underline_string, '______________________________')
menu.render()
self.assertEqual((menu.get_width(widget=True), menu.get_width(inner=True)), (379, 400))
# noinspection SpellCheckingInspection
textinput.set_value('QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ')
self.assertEqual(textinput.get_width(), 712)
self.assertEqual(textinput._current_underline_string,
'____________________________________________________________')
menu.render()
self.assertEqual((menu.get_width(widget=True), menu.get_width(inner=True)), (712, 400))
textinput.set_padding(100)
self.assertEqual(textinput.get_width(), 912)
self.assertEqual(textinput._current_underline_string,
'____________________________________________________________')
menu.render()
self.assertEqual((menu.get_width(widget=True), menu.get_width(inner=True)), (912, 380))
textinput.set_padding(200)
self.assertEqual(textinput.get_width(), 1112)
self.assertEqual(textinput._current_underline_string,
'____________________________________________________________')
menu.render()
self.assertEqual((menu.get_width(widget=True), menu.get_width(inner=True)), (1112, 380))
# Test underline
textinput = menu.add.text_input('title: ')
textinput.set_value('this is a test value')
self.assertEqual(textinput.get_width(), 266)
menu.clear()
textinput = menu.add.text_input('title: ', input_underline='.-')
# noinspection SpellCheckingInspection
textinput.set_value('QQQQQQQQQQQQQQQ')
self.assertEqual(textinput.get_width(), 373)
self.assertEqual(textinput._current_underline_string, '.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-')
textinput = menu.add.text_input('title: ', input_underline='_', input_underline_len=10)
self.assertEqual(textinput._current_underline_string, '_' * 10)
# Text underline with different column widths
menu = pygame_menu.Menu(
column_max_width=200,
height=300,
theme=theme,
title='Label',
onclose=pygame_menu.events.CLOSE,
width=400
)
self.assertRaises(pygame_menu.menu._MenuSizingException, lambda: menu.add.frame_v(300, 100))
self.assertRaises(pygame_menu.menu._MenuSizingException, lambda: menu.add.frame_v(201, 100))
self.assertEqual(len(menu._widgets), 0)
textinput = menu.add.text_input('title', input_underline='_')
self.assertEqual(menu._widget_offset[1], 107 if PYGAME_V2 else 106)
self.assertEqual(textinput.get_width(), 178)
self.assertEqual(textinput._current_underline_string, '____________')
v_frame = menu.add.frame_v(150, 100, background_color=(20, 20, 20))
v_frame.pack(textinput)
self.assertEqual(menu._widget_offset[1], 76 if PYGAME_V2 else 75)
self.assertEqual(textinput.get_width(), 134)
self.assertEqual(textinput._current_underline_string, '________')
# Test cursor size
self.assertRaises(AssertionError, lambda: menu.add.text_input('title', cursor_size=(1, 0)))
self.assertRaises(AssertionError, lambda: menu.add.text_input('title', cursor_size=(-1, -1)))
self.assertRaises(AssertionError, lambda: menu.add.text_input('title', cursor_size=(1, 1, 0)))
self.assertRaises(AssertionError, lambda: menu.add.text_input('title', cursor_size=[1, 1]))
self.assertRaises(AssertionError, lambda: menu.add.text_input('title', cursor_size=(1.6, 2.5)))
textinput_cursor = menu.add.text_input('title', cursor_size=(10, 2))
self.assertEqual(textinput_cursor._cursor_size, (10, 2))
# noinspection PyArgumentEqualDefault,PyTypeChecker
def test_colorinput(self) -> None:
"""
Test ColorInput widget.
"""
def _assert_invalid_color(widg) -> None:
"""
Assert that the widget color is invalid.
:param widg: Widget object
"""
r, g, b = widg.get_value()
self.assertEqual(r, -1)
self.assertEqual(g, -1)
self.assertEqual(b, -1)
def _assert_color(widg, cr, cg, cb) -> None:
"""
Assert that the widget color is invalid.
:param widg: Widget object
:param cr: Red channel, number between 0 and 255
:param cg: Green channel, number between 0 and 255
:param cb: Blue channel, number between 0 and 255
"""
r, g, b = widg.get_value()
self.assertEqual(r, cr)
self.assertEqual(g, cg)
self.assertEqual(b, cb)
menu = MenuUtils.generic_menu(theme=TEST_THEME.copy())
# Base rgb
widget = menu.add.color_input('title', color_type='rgb', input_separator=',')
widget.set_value((123, 234, 55))
self.assertRaises(AssertionError,
lambda: widget.set_value('0,0,0'))
self.assertRaises(AssertionError,
lambda: widget.set_value((255, 0,)))
self.assertRaises(AssertionError,
lambda: widget.set_value((255, 255, -255)))
_assert_color(widget, 123, 234, 55)
# Test separator
widget = menu.add.color_input('color', color_type='rgb', input_separator='+')
widget.set_value((34, 12, 12))
self.assertEqual(widget._input_string, '34+12+12')
self.assertRaises(AssertionError,
lambda: menu.add.color_input('title', color_type='rgb', input_separator=''))
self.assertRaises(AssertionError,
lambda: menu.add.color_input('title', color_type='rgb', input_separator=' '))
self.assertRaises(AssertionError,
lambda: menu.add.color_input('title', color_type='unknown'))
for i in range(10):
self.assertRaises(AssertionError,
lambda: menu.add.color_input('title', color_type='rgb', input_separator=str(i)))
# Empty rgb
widget = menu.add.color_input('color', color_type='rgb', input_separator=',')
PygameEventUtils.test_widget_key_press(widget)
self.assertEqual(widget._cursor_position, 0)
widget.update(PygameEventUtils.key(pygame.K_RIGHT, keydown=True))
self.assertEqual(widget._cursor_position, 0)
_assert_invalid_color(widget)
# Write sequence: 2 -> 25 -> 25, -> 25,0,
# The comma after the zero must be automatically set
self.assertFalse(widget.update(PygameEventUtils.key(0, keydown=True, testmode=False)))
widget.update(PygameEventUtils.key(pygame.K_2, keydown=True, char='2'))
widget.update(PygameEventUtils.key(pygame.K_5, keydown=True, char='5'))
widget.update(PygameEventUtils.key(pygame.K_COMMA, keydown=True, char=','))
self.assertEqual(widget._input_string, '25,')
widget.update(PygameEventUtils.key(pygame.K_0, keydown=True, char='0'))
self.assertEqual(widget._input_string, '25,0,')
_assert_invalid_color(widget)
# Now, sequence: 25,0,c -> 25c,0, with cursor c
widget.update(PygameEventUtils.key(pygame.K_LEFT, keydown=True))
widget.update(PygameEventUtils.key(pygame.K_LEFT, keydown=True))
widget.update(PygameEventUtils.key(pygame.K_LEFT, keydown=True))
self.assertEqual(widget._cursor_position, 2)
# Sequence. 25,0, -> 255,0, -> 255,0, trying to write another 5 in the same position
# That should be cancelled because 2555 > 255
widget.update(PygameEventUtils.key(pygame.K_5, keydown=True, char='5'))
self.assertEqual(widget._input_string, '255,0,')
widget.update(PygameEventUtils.key(pygame.K_5, keydown=True, char='5'))
self.assertEqual(widget._input_string, '255,0,')
# Invalid left zeros, try to write 255,0, -> 255,00, but that should be disabled
widget.update(PygameEventUtils.key(pygame.K_RIGHT, keydown=True))
widget.update(PygameEventUtils.key(pygame.K_0, keydown=True, char='0'))
self.assertEqual(widget._input_string, '255,0,')
# Second comma cannot be deleted because there's a number between ,0,
widget.update(PygameEventUtils.key(pygame.K_BACKSPACE, keydown=True))
self.assertEqual(widget._input_string, '255,0,')
widget.update(PygameEventUtils.key(pygame.K_LEFT, keydown=True))
widget.update(PygameEventUtils.key(pygame.K_DELETE, keydown=True))
self.assertEqual(widget._input_string, '255,0,')
# Current cursor is at 255c,0,
# Now right comma and 0 can be deleted
widget.update(PygameEventUtils.key(pygame.K_END, keydown=True))
widget.update(PygameEventUtils.key(pygame.K_BACKSPACE, keydown=True))
widget.update(PygameEventUtils.key(pygame.K_BACKSPACE, keydown=True))
self.assertEqual(widget._input_string, '255,')
# Fill with zeros, then number with 2 consecutive 0 types must be 255,0,0
# Commas should be inserted automatically
widget.readonly = True
widget.update(PygameEventUtils.key(pygame.K_0, keydown=True, char='0'))
self.assertEqual(widget._input_string, '255,')
widget.readonly = False
widget.update(PygameEventUtils.key(pygame.K_0, keydown=True, char='0'))
widget.update(PygameEventUtils.key(pygame.K_0, keydown=True, char='0'))
self.assertEqual(widget._input_string, '255,0,0')
_assert_color(widget, 255, 0, 0)
# At this state, user cannot add more zeros at right
for i in range(5):
widget.update(PygameEventUtils.key(pygame.K_0, keydown=True, char='0'))
self.assertEqual(widget._input_string, '255,0,0')
widget.get_rect()
widget.clear()
self.assertEqual(widget._input_string, '')
# Assert invalid defaults rgb
self.assertRaises(AssertionError,
lambda: menu.add.color_input('title', color_type='rgb', default=(255, 255,)))
self.assertRaises(AssertionError,
lambda: menu.add.color_input('title', color_type='rgb', default=(255, 255)))
self.assertRaises(AssertionError,
lambda: menu.add.color_input('title', color_type='rgb', default=(255, 255, 255, 255)))
# Assert hex widget
widget = menu.add.color_input('title', color_type='hex')
self.assertEqual(widget._input_string, '#')
self.assertEqual(widget._cursor_position, 1)
_assert_invalid_color(widget)
self.assertRaises(AssertionError,
lambda: widget.set_value('#FF'))
self.assertRaises(AssertionError,
lambda: widget.set_value('#FFFFF<'))
self.assertRaises(AssertionError,
lambda: widget.set_value('#FFFFF'))
self.assertRaises(AssertionError,
lambda: widget.set_value('#F'))
# noinspection SpellCheckingInspection
self.assertRaises(AssertionError,
lambda: widget.set_value('FFFFF'))
self.assertRaises(AssertionError,
lambda: widget.set_value('F'))
widget.set_value('FF00FF')
_assert_color(widget, 255, 0, 255)
widget.set_value('#12FfAa')
_assert_color(widget, 18, 255, 170)
widget.set_value(' 59C1e5')
_assert_color(widget, 89, 193, 229)
widget.render()
widget.draw(surface)
widget.clear()
self.assertEqual(widget._input_string, '#') # This cannot be empty
self.assertEqual(widget._cursor_position, 1)
# In hex widget # cannot be deleted
widget.update(PygameEventUtils.key(pygame.K_BACKSPACE, keydown=True))
self.assertEqual(widget._cursor_position, 1)
widget.update(PygameEventUtils.key(pygame.K_LEFT, keydown=True))
widget.update(PygameEventUtils.key(pygame.K_DELETE, keydown=True))
self.assertEqual(widget._input_string, '#')
widget.update(PygameEventUtils.key(pygame.K_END, keydown=True))
for i in range(10):
widget.update(PygameEventUtils.key(pygame.K_f, keydown=True, char='f'))
self.assertEqual(widget._input_string, '#ffffff')
_assert_color(widget, 255, 255, 255)
# Test hex formats
widget = menu.add.color_input('title', color_type='hex', hex_format='none')
widget.set_value('#ff00ff')
self.assertFalse(widget.update(PygameEventUtils.key(0, keydown=True, testmode=False)))
self.assertEqual(widget.get_value(as_string=True), '#ff00ff')
widget.set_value('#FF00ff')
self.assertEqual(widget.get_value(as_string=True), '#FF00ff')
widget = menu.add.color_input('title', color_type='hex', hex_format='lower')
widget.set_value('#FF00ff')
self.assertEqual(widget.get_value(as_string=True), '#ff00ff')
widget.set_value('AABBcc')
self.assertEqual(widget.get_value(as_string=True), '#aabbcc')
widget = menu.add.color_input('title', color_type='hex', hex_format='upper')
widget.set_value('#FF00ff')
self.assertEqual(widget.get_value(as_string=True), '#FF00FF')
widget.set_value('AABBcc')
self.assertEqual(widget.get_value(as_string=True), '#AABBCC')
# Test dynamic sizing
widget = menu.add.color_input('title', color_type='hex', hex_format='upper', dynamic_width=True)
self.assertEqual(widget.get_width(), 200)
widget.set_value('#ffffff')
width = 342 if PYGAME_V2 else 345
self.assertEqual(widget.get_width(), width)
widget.set_value(None)
self.assertEqual(widget.get_width(), 200)
self.assertEqual(widget.get_value(as_string=True), '#')
widget.set_value('#ffffff')
self.assertEqual(widget.get_width(), width)
widget.update(
PygameEventUtils.key(pygame.K_BACKSPACE,
keydown=True)) # remove the last character, now color is invalid
self.assertEqual(widget.get_value(as_string=True), '#FFFFF') # is upper
widget.render()
self.assertEqual(widget.get_width(), 200)
widget = menu.add.color_input('title', color_type='hex', hex_format='upper', dynamic_width=False)
self.assertEqual(widget.get_width(), width)
widget.set_value('#ffffff')
self.assertEqual(widget.get_width(), width)
def test_value(self) -> None:
"""
Test textinput value.
"""
menu = MenuUtils.generic_menu()
test = ['']
def onwidgetchange(m: 'pygame_menu.Menu', w: 'pygame_menu.widgets.Widget') -> None:
"""
Callback executed if widget changes.
"""
self.assertIn(w, m.get_widgets())
test[0] = w.get_value()
menu.set_onwidgetchange(onwidgetchange)
# Text
text = menu.add.text_input('title', 'value')
self.assertEqual(test[0], '')
self.assertEqual(text.get_value(), 'value')
self.assertFalse(text.value_changed())
text.set_value('new')
self.assertEqual(text.get_value(), 'new')
self.assertTrue(text.value_changed())
text.reset_value()
self.assertEqual(text.get_value(), 'value')
self.assertFalse(text.value_changed())
text.change()
self.assertEqual(test[0], 'value')
# Color
color = menu.add.color_input('title', color_type='hex', hex_format='none')
self.assertEqual(color._default_value, '')
self.assertEqual(color.get_value(), (-1, -1, -1))
self.assertFalse(color.value_changed())
self.assertRaises(AssertionError, lambda: color.set_value((255, 0, 0)))
color.set_value('ff0000')
self.assertEqual(color.get_value(), (255, 0, 0))
self.assertTrue(color.value_changed())
color.reset_value()
self.assertEqual(color.get_value(), (-1, -1, -1))
self.assertFalse(color.value_changed())
color = menu.add.color_input('title', color_type='hex', hex_format='none', default='#ff0000')
self.assertEqual(color._default_value, '#ff0000')
self.assertEqual(color.get_value(), (255, 0, 0))
self.assertFalse(color.value_changed())
color.set_value('#00ff00')
self.assertEqual(color.get_value(), (0, 255, 0))
self.assertTrue(color.value_changed())
color.reset_value()
self.assertEqual(color.get_value(), (255, 0, 0))
self.assertFalse(color.value_changed())
def test_empty_title(self) -> None:
"""
Test empty title.
"""
menu = MenuUtils.generic_menu()
text = menu.add.text_input('')
self.assertEqual(text.get_size(), (16, 49))
|
dcartman/pygame-menu | pygame_menu/examples/multi_input.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
EXAMPLE - MULTI-INPUT
Shows different inputs (widgets).
"""
__all__ = ['main']
import pygame
import pygame_menu
from pygame_menu.examples import create_example_window
from typing import Tuple, Optional
# Constants and global variables
FPS = 60
WINDOW_SIZE = (640, 480)
sound: Optional['pygame_menu.sound.Sound'] = None
surface: Optional['pygame.Surface'] = None
main_menu: Optional['pygame_menu.Menu'] = None
def main_background() -> None:
"""
Background color of the main menu, on this function user can plot
images, play sounds, etc.
"""
surface.fill((40, 40, 40))
def check_name_test(value: str) -> None:
"""
This function tests the text input widget.
:param value: The widget value
"""
print(f'User name: {value}')
def update_menu_sound(value: Tuple, enabled: bool) -> None:
"""
Update menu sound.
:param value: Value of the selector (Label and index)
:param enabled: Parameter of the selector, (True/False)
"""
assert isinstance(value, tuple)
if enabled:
main_menu.set_sound(sound, recursive=True)
print('Menu sounds were enabled')
else:
main_menu.set_sound(None, recursive=True)
print('Menu sounds were disabled')
def main(test: bool = False) -> None:
"""
Main program.
:param test: Indicate function is being tested
"""
# -------------------------------------------------------------------------
# Globals
# -------------------------------------------------------------------------
global main_menu
global sound
global surface
# -------------------------------------------------------------------------
# Create window
# -------------------------------------------------------------------------
surface = create_example_window('Example - Multi Input', WINDOW_SIZE)
clock = pygame.time.Clock()
# -------------------------------------------------------------------------
# Set sounds
# -------------------------------------------------------------------------
sound = pygame_menu.sound.Sound()
# Load example sounds
sound.load_example_sounds()
# Disable a sound
sound.set_sound(pygame_menu.sound.SOUND_TYPE_ERROR, None)
# -------------------------------------------------------------------------
# Create menus: Settings
# -------------------------------------------------------------------------
settings_menu_theme = pygame_menu.themes.THEME_ORANGE.copy()
settings_menu_theme.title_offset = (5, -2)
settings_menu_theme.widget_alignment = pygame_menu.locals.ALIGN_LEFT
settings_menu_theme.widget_font = pygame_menu.font.FONT_OPEN_SANS_LIGHT
settings_menu_theme.widget_font_size = 20
settings_menu = pygame_menu.Menu(
height=WINDOW_SIZE[1] * 0.85,
theme=settings_menu_theme,
title='Settings',
width=WINDOW_SIZE[0] * 0.9
)
# Add text inputs with different configurations
settings_menu.add.text_input(
'First name: ',
default='John',
onreturn=check_name_test,
textinput_id='first_name'
)
settings_menu.add.text_input(
'Last name: ',
default='Rambo',
maxchar=10,
textinput_id='last_name',
input_underline='.'
)
settings_menu.add.text_input(
'Your age: ',
default=25,
maxchar=3,
maxwidth=3,
textinput_id='age',
input_type=pygame_menu.locals.INPUT_INT,
cursor_selection_enable=False
)
settings_menu.add.text_input(
'Some long text: ',
maxwidth=19,
textinput_id='long_text',
input_underline='_'
)
settings_menu.add.text_input(
'Password: ',
maxchar=6,
password=True,
textinput_id='pass',
input_underline='_'
)
# Selectable items
items = [('Easy', 'EASY'),
('Medium', 'MEDIUM'),
('Hard', 'HARD')]
# Create selector with 3 difficulty options
settings_menu.add.selector(
'Select difficulty:\t',
items,
selector_id='difficulty',
default=1
)
settings_menu.add.selector(
'Select difficulty fancy',
items,
selector_id='difficulty_fancy',
default=1,
style='fancy'
)
settings_menu.add.dropselect(
'Select difficulty (drop)',
items,
default=1,
dropselect_id='difficulty_drop'
)
settings_menu.add.dropselect_multiple(
title='Pick 3 colors',
items=[('Black', (0, 0, 0)),
('Blue', (0, 0, 255)),
('Cyan', (0, 255, 255)),
('Fuchsia', (255, 0, 255)),
('Green', (0, 255, 0)),
('Red', (255, 0, 0)),
('White', (255, 255, 255)),
('Yellow', (255, 255, 0))],
dropselect_multiple_id='pickcolors',
max_selected=3,
open_middle=True,
selection_box_height=6 # How many options show if opened
)
# Create switch
settings_menu.add.toggle_switch('First Switch', False,
toggleswitch_id='first_switch')
settings_menu.add.toggle_switch('Other Switch', True,
toggleswitch_id='second_switch',
state_text=('Apagado', 'Encencido'))
# Single value from range
rslider = settings_menu.add.range_slider('Choose a number', 50, (0, 100), 1,
rangeslider_id='range_slider',
value_format=lambda x: str(int(x)))
# Range
settings_menu.add.range_slider('How do you rate pygame-menu?', (7, 10), (1, 10), 1,
rangeslider_id='range_slider_double')
# Create discrete range
range_values_discrete = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F'}
settings_menu.add.range_slider('Pick a letter', 0, list(range_values_discrete.keys()),
rangeslider_id='range_slider_discrete',
slider_text_value_enabled=False,
value_format=lambda x: range_values_discrete[x])
# Add a progress bar
progress = settings_menu.add.progress_bar('Progress', default=rslider.get_value(),
progressbar_id='progress')
def on_change_slider(val: int) -> None:
"""
Updates the progress bar.
:param val: Value of the progress from 0 to 100
"""
progress.set_value(val)
rslider.set_onchange(on_change_slider)
# Add a block
settings_menu.add.clock(clock_format='%Y/%m/%d %H:%M', title_format='Clock: {0}')
def data_fun() -> None:
"""
Print data of the menu.
"""
print('Settings data:')
data = settings_menu.get_input_data()
for k in data.keys():
print(f'\t{k}\t=>\t{data[k]}')
# Add final buttons
settings_menu.add.button('Store data', data_fun, button_id='store') # Call function
settings_menu.add.button('Restore original values', settings_menu.reset_value)
settings_menu.add.button('Return to main menu', pygame_menu.events.BACK,
align=pygame_menu.locals.ALIGN_CENTER)
# -------------------------------------------------------------------------
# Create menus: More settings
# -------------------------------------------------------------------------
more_settings_menu = pygame_menu.Menu(
height=WINDOW_SIZE[1] * 0.85,
theme=settings_menu_theme,
title='More Settings',
width=WINDOW_SIZE[0] * 0.9
)
more_settings_menu.add.image(
pygame_menu.baseimage.IMAGE_EXAMPLE_PYGAME_MENU,
scale=(0.25, 0.25),
align=pygame_menu.locals.ALIGN_CENTER
)
more_settings_menu.add.color_input(
'Color 1 RGB: ',
color_type='rgb'
)
more_settings_menu.add.color_input(
'Color 2 RGB: ',
color_type='rgb',
default=(255, 0, 0),
input_separator='-'
)
def print_color(color: Tuple) -> None:
"""
Test onchange/onreturn.
:param color: Color tuple
"""
print('Returned color: ', color)
more_settings_menu.add.color_input(
'Color in Hex: ',
color_type='hex',
hex_format='lower',
color_id='hex_color',
onreturn=print_color
)
more_settings_menu.add.vertical_margin(25)
more_settings_menu.add.button(
'Return to main menu',
pygame_menu.events.BACK,
align=pygame_menu.locals.ALIGN_CENTER
)
# -------------------------------------------------------------------------
# Create menus: Column buttons
# -------------------------------------------------------------------------
button_column_menu_theme = pygame_menu.themes.THEME_ORANGE.copy()
button_column_menu_theme.background_color = pygame_menu.BaseImage(
image_path=pygame_menu.baseimage.IMAGE_EXAMPLE_GRAY_LINES,
drawing_mode=pygame_menu.baseimage.IMAGE_MODE_REPEAT_XY
)
button_column_menu_theme.widget_font_size = 25
button_column_menu = pygame_menu.Menu(
columns=2,
height=WINDOW_SIZE[1] * 0.45,
rows=3,
theme=button_column_menu_theme,
title='Textures+Columns',
width=WINDOW_SIZE[0] * 0.9
)
for i in range(4):
button_column_menu.add.button(f'Button {i}', pygame_menu.events.BACK)
button_column_menu.add.button(
'Return to main menu', pygame_menu.events.BACK,
background_color=pygame_menu.BaseImage(
image_path=pygame_menu.baseimage.IMAGE_EXAMPLE_METAL
)
).background_inflate_to_selection_effect()
# -------------------------------------------------------------------------
# Create menus: Main menu
# -------------------------------------------------------------------------
main_menu_theme = pygame_menu.themes.THEME_ORANGE.copy()
main_menu_theme.title_font = pygame_menu.font.FONT_COMIC_NEUE
main_menu_theme.widget_font = pygame_menu.font.FONT_COMIC_NEUE
main_menu_theme.widget_font_size = 30
main_menu = pygame_menu.Menu(
height=WINDOW_SIZE[1] * 0.7,
onclose=pygame_menu.events.EXIT, # User press ESC button
theme=main_menu_theme,
title='Main menu',
width=WINDOW_SIZE[0] * 0.8
)
main_menu.add.button('Settings', settings_menu)
main_menu.add.button('More Settings', more_settings_menu)
main_menu.add.button('Menu in textures and columns', button_column_menu)
main_menu.add.selector('Menu sounds ',
[('Off', False), ('On', True)],
onchange=update_menu_sound)
main_menu.add.button('Quit', pygame_menu.events.EXIT)
# -------------------------------------------------------------------------
# Main loop
# -------------------------------------------------------------------------
while True:
# Tick
clock.tick(FPS)
# Paint background
main_background()
# Main menu
main_menu.mainloop(surface, main_background, disable_loop=test, fps_limit=FPS)
# Flip surface
pygame.display.flip()
# At first loop returns
if test:
break
if __name__ == '__main__':
main()
|
dcartman/pygame-menu | pygame_menu/examples/other/__init__.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
EXAMPLES / OTHER
Example file directory.
"""
|
dcartman/pygame-menu | test/test_widget_table.py | <gh_stars>0
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST WIDGET - TABLE
Test Table widget.
"""
__all__ = ['TableWidgetTest']
from test._utils import MenuUtils, surface, PYGAME_V2, BaseTest
import pygame
import pygame_menu
class TableWidgetTest(BaseTest):
def test_table(self) -> None:
"""
Test table.
"""
if not PYGAME_V2:
return
menu = MenuUtils.generic_menu()
btn = menu.add.button('1')
table = menu.add.table('table', background_color='red')
self.assertTrue(table.is_rectangular())
self.assertEqual(table.get_inner_size(), (0, 0))
self.assertEqual(table.get_size(apply_padding=False), (0, 0))
self.assertRaises(RuntimeError, lambda: table.pack(btn))
# Test add rows
row1 = table.add_row([1, 2, 3], row_background_color='blue', cell_align=pygame_menu.locals.ALIGN_CENTER)
self.assertTrue(table.is_rectangular())
self.assertEqual(row1.get_size(), (51, 41))
self.assertEqual(table.get_size(apply_padding=False), (51, 41))
row2 = table.add_row([10, 20, 30], row_background_color='green', cell_padding=10)
self.assertEqual(row1.get_size(), (162, 41))
self.assertEqual(row2.get_size(), (162, 61))
self.assertEqual(table.get_size(apply_padding=False), (162, 102))
table.draw(surface)
self.assertTrue(table.is_rectangular())
# Test get cell
self.assertEqual(table.get_cell(2, 1), row1.get_widgets(unpack_subframes=False)[1])
self.assertEqual(table.get_cell(1, 2), row2.get_widgets(unpack_subframes=False)[0])
self.assertRaises(AssertionError, lambda: table.get_cell(0, 0))
self.assertRaises(AssertionError, lambda: table.get_cell(0, 1))
self.assertRaises(AssertionError, lambda: table.get_cell(1, 0))
c1 = table.get_cell(1, 1)
self.assertEqual(c1, row1.get_widgets(unpack_subframes=False)[0])
# Test cell properties
self.assertEqual(c1.get_attribute('align'), pygame_menu.locals.ALIGN_CENTER)
self.assertEqual(c1.get_attribute('border_color'), (0, 0, 0, 255))
self.assertEqual(c1.get_attribute('border_position'), pygame_menu.widgets.core.widget.WIDGET_FULL_BORDER)
self.assertEqual(c1.get_attribute('border_width'), 1)
self.assertEqual(c1.get_attribute('column'), 1)
self.assertEqual(c1.get_attribute('padding'), (0, 0, 0, 0))
self.assertEqual(c1.get_attribute('row'), 1)
self.assertEqual(c1.get_attribute('table'), table)
self.assertEqual(c1.get_attribute('vertical_position'), pygame_menu.locals.POSITION_NORTH)
# Update cell
c5 = table.update_cell_style(2, 2)
self.assertIsNone(c5._background_color)
self.assertEqual(c5.get_attribute('background_color'), (0, 255, 0, 255))
table.update_cell_style(2, 2, background_color='white')
self.assertEqual(c5._background_color, (255, 255, 255, 255))
table.update_cell_style(3, 1, background_color='cyan')
self.assertEqual(c5.get_padding(), (10, 10, 10, 10))
table.update_cell_style(2, 2, padding=0)
self.assertEqual(c5.get_padding(), (0, 0, 20, 0)) # vertical position north
table.update_cell_style(2, 2, vertical_position=pygame_menu.locals.POSITION_CENTER)
self.assertEqual(c5.get_padding(), (10, 0, 10, 0)) # vertical position north
table.update_cell_style(2, 2, vertical_position=pygame_menu.locals.POSITION_SOUTH)
self.assertEqual(c5.get_padding(), (20, 0, 0, 0)) # vertical position north
table.update_cell_style(1, 1, font_color='white')
table.draw(surface)
self.assertEqual(table.get_size(), (158, 110))
table.update_cell_style(2, 2, padding=50)
self.assertEqual(table.get_size(), (258, 190))
# Test align
c2 = table.get_cell(2, 1)
self.assertEqual(c2.get_size(), (134, 41))
self.assertEqual(c2.get_padding(), (0, 58, 0, 59))
table.update_cell_style(2, 1, align=pygame_menu.locals.ALIGN_LEFT)
self.assertEqual(c2.get_size(), (134, 41))
self.assertEqual(c2.get_padding(), (0, 117, 0, 0))
table.update_cell_style(2, 1, align=pygame_menu.locals.ALIGN_RIGHT)
self.assertEqual(c2.get_padding(), (0, 0, 0, 117))
self.assertEqual(c2.get_attribute('border_width'), 1)
table.update_cell_style(2, 1, border_width=0)
self.assertEqual(c2.get_attribute('border_width'), 0)
table.draw(surface)
# Test hide
self.assertTrue(c2.is_visible())
table.hide()
table.draw(surface)
self.assertFalse(c2.is_visible())
table.show()
self.assertTrue(c2.is_visible())
# Add and remove row
self.assertEqual(table.get_size(), (258, 190))
row3 = table.add_row([12])
self.assertFalse(table.is_rectangular())
self.assertEqual(row1.get_total_packed(), 3)
self.assertEqual(row3.get_total_packed(), 1)
self.assertEqual(table.get_size(), (258, 231))
table.remove_row(row3)
self.assertEqual(table.get_size(), (258, 190))
# Add new row with an image
table.update_cell_style(2, 2, padding=0)
b_image = pygame_menu.BaseImage(pygame_menu.baseimage.IMAGE_EXAMPLE_PYGAME_MENU)
b_image.scale(0.1, 0.1)
row3 = table.add_row(['image', b_image, 'ez'])
self.assertIsInstance(row3.get_widgets()[1], pygame_menu.widgets.Image)
# Remove table from menu
menu.remove_widget(table)
# Add sub-table
menu.add.generic_widget(table)
table2 = menu.add.table(font_size=10)
table2row1 = table2.add_row([1, 2])
table2.add_row([3, 4])
self.assertIn(btn, menu.get_widgets())
row4 = table.add_row(['sub-table', table2, btn], cell_align=pygame_menu.locals.ALIGN_CENTER,
cell_vertical_position=pygame_menu.locals.POSITION_CENTER)
table.update_cell_style(2, 4, background_color='white')
self.assertNotIn(btn, menu.get_widgets())
self.assertEqual(btn.get_frame(), row4)
self.assertEqual(table2.get_frame(), row4)
self.assertEqual(table2.get_frame_depth(), 2)
self.assertEqual(table2row1.get_widgets()[0].get_frame(), table2row1)
self.assertEqual(table2row1.get_widgets()[0].get_frame_depth(), 4)
# Try to add an existing row as a new row
self.assertRaises(AssertionError, lambda: table.add_row([row1]))
self.assertRaises(AssertionError, lambda: table.add_row([table2row1.get_widgets()[0]]))
# Update padding
self.assertEqual(table.get_size(), (265, 201))
table.set_padding(0)
self.assertEqual(table.get_size(), (249, 193))
# Add surface
new_surface = pygame.Surface((40, 40))
new_surface.fill((255, 192, 203))
inner_surface = pygame.Surface((20, 20))
inner_surface.fill((75, 0, 130))
new_surface.blit(inner_surface, (10, 10))
row5 = table.add_row([new_surface, 'epic', new_surface],
cell_border_position=pygame_menu.locals.POSITION_SOUTH)
self.assertIsInstance(row5.get_widgets()[0], pygame_menu.widgets.SurfaceWidget)
self.assertIsInstance(row5.get_widgets()[1], pygame_menu.widgets.Label)
self.assertIsInstance(row5.get_widgets()[2], pygame_menu.widgets.SurfaceWidget)
self.assertEqual(table.get_size(), (249, 234))
# Create table with fixed surface for testing sizing
table3 = menu.add.table(background_color='purple')
table3._draw_cell_borders(surface)
self.assertRaises(AssertionError, lambda: table3.remove_row(row1)) # Empty table
table3.add_row([new_surface])
self.assertRaises(AssertionError, lambda: table3.remove_row(row1)) # Empty table
self.assertEqual(table3.get_margin(), (0, 0))
self.assertEqual(table3.get_size(), (56, 48))
table3.set_padding(False)
self.assertEqual(table3.get_size(), (40, 40))
# Test others
surf_same_table = pygame.Surface((10, 200))
surf_same_table.fill((0, 0, 0))
surf_widget = menu.add.surface(surf_same_table)
# Create frame
menu._test_print_widgets()
frame = menu.add.frame_v(300, 300, background_color='yellow', padding=0)
frame.pack(surf_widget)
menu.remove_widget(surf_widget)
self.assertEqual(table._translate_virtual, (0, 0))
frame.pack(table, align=pygame_menu.locals.ALIGN_CENTER,
vertical_position=pygame_menu.locals.POSITION_CENTER)
self.assertEqual(table._translate_virtual, (25, 33))
# Add to scrollable frame
frame2 = menu.add.frame_v(300, 400, max_height=300, background_color='brown')
menu.remove_widget(frame)
frame2.pack(table)
# Add scrollable frame to table
menu._test_print_widgets()
frame3 = menu.add.frame_v(200, 200, max_width=100, max_height=100, background_color='cyan')
self.assertIn(frame3, menu._update_frames)
row6 = table.add_row([frame3, table3], cell_border_width=0)
row6_widgs = row6.get_widgets(unpack_subframes=False)
self.assertIn(frame3, menu._update_frames)
self.assertEqual(row6.get_widgets(unpack_subframes=False)[1], table3)
self.assertEqual(table.get_cell(*table.get_cell_column_row(table3)), table3)
# Remove row6, this should remove table3 from update frames as well
table.remove_row(row6)
self.assertNotIn(frame3, menu._update_frames)
# Check value
self.assertRaises(ValueError, lambda: table.get_value())
# Remove table from scrollable frame
self.assertEqual(row6.get_total_packed(), 2)
row7 = table.add_row(row6)
self.assertNotEqual(row6, row7)
self.assertEqual(row6_widgs, row7.get_widgets(unpack_subframes=False))
self.assertEqual(row6.get_total_packed(), 0)
self.assertIn(frame3, menu._update_frames)
# Unpack table from frame
frame2.unpack(table)
self.assertIn(frame3, menu._update_frames)
self.assertTrue(table.is_floating())
table.set_float(False)
menu._test_print_widgets()
img = menu.add.image(pygame_menu.baseimage.IMAGE_EXAMPLE_METAL)
img.scale(0.2, 0.2)
table.add_row(img)
# Test single position
table.update_cell_style(1, 1, border_position=pygame_menu.locals.POSITION_SOUTH)
# Test update using -1 column/row
self.assertEqual(len(table.update_cell_style(-1, 1)), 3)
self.assertEqual(len(table.update_cell_style(-1, 7)), 1)
self.assertEqual(len(table.update_cell_style(1, -1)), 7)
self.assertEqual(len(table.update_cell_style(-1, -1)), 18)
self.assertEqual(len(table.update_cell_style(1, [1, -1])), 7)
self.assertEqual(len(table.update_cell_style(1, [1, 1])), 1)
self.assertEqual(len(table.update_cell_style([1, -1], [1, -1])), 18)
self.assertRaises(AssertionError, lambda: self.assertEqual(len(table.update_cell_style([1, 7], [1, -1])), 18))
self.assertEqual(len(table.update_cell_style([1, 2], 1)), 2)
self.assertFalse(table.update([]))
def test_table_update(self) -> None:
"""
Test table update.
"""
menu = MenuUtils.generic_menu()
btn = menu.add.button('click', lambda: print('clicked'))
sel = menu.add.dropselect('sel', items=[('a', 'a'), ('b', 'b')])
table = menu.add.table()
table.add_row([btn, sel])
menu.render()
menu.draw(surface)
self.assertEqual(table._update_widgets, [btn, sel])
self.assertRaises(AssertionError, lambda: table.add_row([table]))
f = menu.add.frame_h(100, 100)
f._relax = True
f.pack(table)
self.assertRaises(AssertionError, lambda: table.add_row([f]))
def test_value(self) -> None:
"""
Test table value.
"""
menu = MenuUtils.generic_menu()
table = menu.add.table()
self.assertRaises(ValueError, lambda: table.get_value())
self.assertRaises(ValueError, lambda: table.set_value('value'))
self.assertFalse(table.value_changed())
table.reset_value()
|
dcartman/pygame-menu | test/test_selection.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST WIDGET SELECTION.
Test widget selection effects.
"""
__all__ = ['SelectionTest']
from test._utils import MenuUtils, surface, BaseTest
import copy
from pygame_menu.widgets import Button
from pygame_menu.widgets.selection import LeftArrowSelection, RightArrowSelection, \
HighlightSelection, NoneSelection, SimpleSelection
from pygame_menu.widgets.core.selection import Selection
from pygame_menu.widgets.selection.arrow_selection import ArrowSelection
class SelectionTest(BaseTest):
def setUp(self) -> None:
"""
Setup sound engine.
"""
self.menu = MenuUtils.generic_menu()
self.menu.enable()
def test_copy(self) -> None:
"""
Test copy.
"""
s = LeftArrowSelection()
s1 = copy.copy(s)
s2 = copy.deepcopy(s)
s3 = s.copy()
self.assertNotEqual(s, s1)
self.assertNotEqual(s, s2)
self.assertNotEqual(s, s3)
def test_abstracts(self) -> None:
"""
Test abstract objects errors.
"""
w = Button('epic')
# Create abstract selection object
sel = Selection(0, 0, 0, 0)
self.assertRaises(NotImplementedError, lambda: sel.draw(surface, w))
# Create abstract arrow selection
arrow = ArrowSelection(0, 0, 0, 0)
self.assertRaises(NotImplementedError, lambda: arrow.draw(surface, w))
def test_arrow(self) -> None:
"""
Test arrow selection.
"""
w = Button('epic')
w.set_selection_effect(LeftArrowSelection())
self.menu.add.generic_widget(w)
self.menu.draw(surface)
w.set_selection_effect(RightArrowSelection())
self.menu.draw(surface)
# Create abstract arrow selection
arrow = ArrowSelection(0, 0, 0, 0)
self.assertRaises(NotImplementedError, lambda: arrow.draw(surface, w))
def test_highlight(self) -> None:
"""
Test highlight selection.
"""
w = Button('epic')
border_width = 1
margin_x = 18
margin_y = 10
w.set_selection_effect(HighlightSelection(
border_width=border_width,
margin_x=margin_x,
margin_y=margin_y
))
self.menu.add.generic_widget(w)
self.menu.draw(surface)
# noinspection PyTypeChecker
sel: 'HighlightSelection' = w.get_selection_effect()
self.assertEqual(sel.get_height(), margin_y)
self.assertEqual(sel.get_width(), margin_x)
# Test inflate
rect = w.get_rect()
inflate_rect = sel.inflate(rect)
self.assertEqual(-inflate_rect.x + rect.x, sel.get_width() / 2)
self.assertEqual(-inflate_rect.y + rect.y, sel.get_height() / 2)
# Test margin xy
sel.margin_xy(10, 20)
self.assertEqual(sel.margin_left, 10)
self.assertEqual(sel.margin_right, 10)
self.assertEqual(sel.margin_top, 20)
self.assertEqual(sel.margin_bottom, 20)
# Test null border
sel._border_width = 0
sel.draw(surface, w)
# Test background color
sel.set_background_color('red')
self.assertEqual(sel.get_background_color(), (255, 0, 0, 255))
def test_none(self) -> None:
"""
Test none selection.
"""
w = Button('epic')
w.set_selection_effect(NoneSelection())
self.menu.add.generic_widget(w)
self.menu.draw(surface)
rect = w.get_rect()
new_rect = w.get_selection_effect().inflate(rect)
self.assertTrue(rect == new_rect)
self.assertFalse(w.get_selection_effect().widget_apply_font_color)
# Widgets default selection effect is None
last_selection = w.get_selection_effect()
w.set_selection_effect()
self.assertIsInstance(w.get_selection_effect(), NoneSelection)
self.assertNotEqual(w.get_selection_effect(), last_selection)
def test_simple(self) -> None:
"""
Test simple selection.
"""
w = Button('epic')
w.set_selection_effect(SimpleSelection())
self.menu.add.generic_widget(w)
self.menu.draw(surface)
rect = w.get_rect()
new_rect = w.get_selection_effect().inflate(rect)
self.assertTrue(rect == new_rect)
self.assertTrue(w.get_selection_effect().widget_apply_font_color)
|
dcartman/pygame-menu | pygame_menu/widgets/selection/simple.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
SIMPLE
Simple selection effect.
"""
__all__ = ['SimpleSelection']
import pygame
import pygame_menu
from pygame_menu.widgets.core import Selection
class SimpleSelection(Selection):
"""
This selection effect only tells widget to apply selection color to font if
selected.
"""
def __init__(self) -> None:
super(SimpleSelection, self).__init__(
margin_left=0, margin_right=0, margin_top=0, margin_bottom=0
)
# noinspection PyMissingOrEmptyDocstring
def draw(self, surface: 'pygame.Surface', widget: 'pygame_menu.widgets.Widget') -> 'SimpleSelection':
return self
|
dcartman/pygame-menu | test/test_widget_progressbar.py | <gh_stars>0
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST WIDGET - PROGRESSBAR
Test ProgressBar widget.
"""
__all__ = ['ProgressBarWidgetTest']
from test._utils import MenuUtils, surface, BaseTest, PYGAME_V2
import pygame_menu
from pygame_menu.widgets.core.widget import WidgetTransformationNotImplemented
class ProgressBarWidgetTest(BaseTest):
def test_progressbar(self) -> None:
"""
Test progressbar slider.
"""
menu = MenuUtils.generic_menu()
pb = pygame_menu.widgets.ProgressBar('progress',
progress_text_font=pygame_menu.font.FONT_BEBAS)
menu.add.generic_widget(pb, configure_defaults=True)
menu.draw(surface)
self.assertRaises(AssertionError, lambda: pygame_menu.widgets.ProgressBar(
'progress', default=-1))
self.assertEqual(pb.get_size(), (312, 49))
self.assertEqual(pb._width, 150)
# Test invalid transforms
self.assertRaises(WidgetTransformationNotImplemented, lambda: pb.rotate())
self.assertRaises(WidgetTransformationNotImplemented, lambda: pb.flip())
self.assertRaises(WidgetTransformationNotImplemented, lambda: pb.scale())
self.assertRaises(WidgetTransformationNotImplemented, lambda: pb.resize())
self.assertRaises(WidgetTransformationNotImplemented, lambda: pb.set_max_width())
self.assertRaises(WidgetTransformationNotImplemented, lambda: pb.set_max_height())
self.assertFalse(pb.update([]))
# noinspection PyTypeChecker
def test_value(self) -> None:
"""
Test progressbar value.
"""
menu = MenuUtils.generic_menu()
pb = menu.add.progress_bar('progress', default=50,
progress_text_align=pygame_menu.locals.ALIGN_LEFT)
self.assertRaises(AssertionError, lambda: pb.set_value(-1))
self.assertRaises(AssertionError, lambda: pb.set_value('a'))
self.assertEqual(pb.get_value(), 50)
self.assertFalse(pb.value_changed())
pb.set_value(75)
self.assertEqual(pb.get_value(), 75)
self.assertTrue(pb.value_changed())
pb.reset_value()
self.assertEqual(pb.get_value(), 50)
self.assertFalse(pb.value_changed())
def test_empty_title(self) -> None:
"""
Test empty title.
"""
menu = MenuUtils.generic_menu()
pb = menu.add.progress_bar('', box_margin=(0, 0), padding=0,
progress_text_align=pygame_menu.locals.ALIGN_RIGHT)
self.assertEqual(pb.get_size(), (150, 41 if PYGAME_V2 else 42))
self.assertFalse(pb.is_selected())
|
dcartman/pygame-menu | pygame_menu/widgets/widget/surface.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
SURFACE
Surface widget. This widget contains an external surface.
"""
__all__ = [
'SurfaceWidget',
'SurfaceWidgetManager'
]
import pygame
import pygame_menu
from abc import ABC
from pygame_menu.widgets.core.widget import Widget, WidgetTransformationNotImplemented, \
AbstractWidgetManager
from pygame_menu._types import CallbackType, Optional, EventVectorType, Callable, \
Any
# noinspection PyMissingOrEmptyDocstring
class SurfaceWidget(Widget):
"""
Surface widget. Implements a widget from an external surface.
.. note::
SurfaceWidget only accepts translation transformation.
:param surface: Pygame surface object
:param surface_id: Surface ID
:param onselect: Function when selecting the widget
"""
_surface_obj: 'pygame.Surface'
def __init__(
self,
surface: 'pygame.Surface',
surface_id: str = '',
onselect: CallbackType = None
) -> None:
assert isinstance(surface, pygame.Surface)
assert isinstance(surface_id, str)
super(SurfaceWidget, self).__init__(
onselect=onselect,
widget_id=surface_id
)
self._surface_obj = surface
def set_title(self, title: str) -> 'SurfaceWidget':
return self
def set_surface(self, surface: 'pygame.Surface') -> 'SurfaceWidget':
"""
Update the widget surface.
:param surface: New surface
:return: Self reference
"""
assert isinstance(surface, pygame.Surface)
self._surface_obj = surface
self._render()
self.force_menu_surface_update()
return self
def _apply_font(self) -> None:
pass
def scale(self, *args, **kwargs) -> 'SurfaceWidget':
raise WidgetTransformationNotImplemented()
def resize(self, *args, **kwargs) -> 'SurfaceWidget':
raise WidgetTransformationNotImplemented()
def set_max_width(self, *args, **kwargs) -> 'SurfaceWidget':
raise WidgetTransformationNotImplemented()
def set_max_height(self, *args, **kwargs) -> 'SurfaceWidget':
raise WidgetTransformationNotImplemented()
def rotate(self, *args, **kwargs) -> 'SurfaceWidget':
raise WidgetTransformationNotImplemented()
def flip(self, *args, **kwargs) -> 'SurfaceWidget':
raise WidgetTransformationNotImplemented()
def _draw(self, surface: 'pygame.Surface') -> None:
surface.blit(self._surface_obj, self._rect.topleft)
def get_surface(self) -> 'pygame.Surface':
return self._surface_obj
def _render(self) -> Optional[bool]:
self._rect.width, self._rect.height = self._surface_obj.get_size()
return
def update(self, events: EventVectorType) -> bool:
self.apply_update_callbacks(events)
for event in events:
if self._check_mouseover(event):
break
return False
class SurfaceWidgetManager(AbstractWidgetManager, ABC):
"""
SurfaceWidget manager.
"""
def surface(
self,
surface: 'pygame.Surface',
surface_id: str = '',
onselect: Optional[Callable[[bool, 'Widget', 'pygame_menu.Menu'], Any]] = None,
selectable: bool = False,
**kwargs
) -> 'pygame_menu.widgets.SurfaceWidget':
"""
Add a surface widget to the Menu.
If ``onselect`` is defined, the callback is executed as follows, where
``selected`` is a boolean representing the selected status:
.. code-block:: python
onselect(selected, widget, menu)
kwargs (Optional)
- ``align`` (str) – Widget `alignment <https://pygame-menu.readthedocs.io/en/latest/_source/themes.html#alignment>`_
- ``background_color`` (tuple, list, str, int, :py:class:`pygame.Color`, :py:class:`pygame_menu.baseimage.BaseImage`) – Color of the background. ``None`` for no-color
- ``background_inflate`` (tuple, list) – Inflate background on x-axis and y-axis (x, y) in px
- ``border_color`` (tuple, list, str, int, :py:class:`pygame.Color`) – Widget border color. ``None`` for no-color
- ``border_inflate`` (tuple, list) – Widget border inflate on x-axis and y-axis (x, y) in px
- ``border_position`` (str, tuple, list) – Widget border positioning. It can be a single position, or a tuple/list of positions. Only are accepted: north, south, east, and west. See :py:mod:`pygame_menu.locals`
- ``border_width`` (int) – Border width in px. If ``0`` disables the border
- ``cursor`` (int, :py:class:`pygame.cursors.Cursor`, None) – Cursor of the widget if the mouse is placed over
- ``float`` (bool) - If ``True`` the widget don't contribute width/height to the Menu widget positioning computation, and don't add one unit to the rows
- ``float_origin_position`` (bool) - If ``True`` the widget position is set to the top-left position of the Menu if the widget is floating
- ``margin`` (tuple, list) – Widget (left, bottom) margin in px
- ``padding`` (int, float, tuple, list) – Widget padding according to CSS rules. General shape: (top, right, bottom, left)
- ``selection_color`` (tuple, list, str, int, :py:class:`pygame.Color`) – Color of the selected widget; only affects the font color
- ``selection_effect`` (:py:class:`pygame_menu.widgets.core.Selection`) – Widget selection effect. Applied only if ``selectable`` is ``True``
- ``shadow_color`` (tuple, list, str, int, :py:class:`pygame.Color`) – Color of the widget shadow
- ``shadow_radius`` (int) - Border radius of the shadow
- ``shadow_type`` (str) - Shadow type, it can be ``'rectangular'`` or ``'ellipse'``
- ``shadow_width`` (int) - Width of the shadow. If ``0`` the shadow is disabled
.. note::
All theme-related optional kwargs use the default Menu theme if not
defined.
.. note::
This is applied only to the base Menu (not the currently displayed,
stored in ``_current`` pointer); for such behaviour apply to
:py:meth:`pygame_menu.menu.Menu.get_current` object.
:param surface: Pygame surface object
:param surface_id: Surface ID
:param onselect: Callback executed when selecting the widget; only executed if ``selectable`` is ``True``
:param selectable: Surface accepts user selection
:param kwargs: Optional keyword arguments
:return: Widget object
:rtype: :py:class:`pygame_menu.widgets.SurfaceWidget`
"""
assert isinstance(selectable, bool)
# Remove invalid keys from kwargs
for key in list(kwargs.keys()):
if key not in ('align', 'background_color', 'background_inflate',
'border_color', 'border_inflate', 'border_width',
'cursor', 'margin', 'padding', 'selection_color',
'selection_effect', 'border_position', 'float',
'float_origin_position', 'shadow_color', 'shadow_radius',
'shadow_type', 'shadow_width'):
kwargs.pop(key, None)
# Filter widget attributes to avoid passing them to the callbacks
attributes = self._filter_widget_attributes(kwargs)
widget = SurfaceWidget(
surface=surface,
surface_id=surface_id,
onselect=onselect
)
widget.is_selectable = selectable
self._check_kwargs(kwargs)
self._configure_widget(widget=widget, **attributes)
self._append_widget(widget)
return widget
|
dcartman/pygame-menu | pygame_menu/_scrollarea.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
SCROLLAREA
ScrollArea class to manage scrolling in Menu.
"""
__all__ = [
# Main class
'ScrollArea',
# Utils
'get_scrollbars_from_position'
]
import pygame
import pygame_menu
from pygame_menu._base import Base
from pygame_menu._decorator import Decorator
from pygame_menu.locals import POSITION_SOUTHEAST, POSITION_SOUTHWEST, POSITION_WEST, \
POSITION_NORTHEAST, POSITION_NORTHWEST, POSITION_CENTER, POSITION_EAST, \
POSITION_NORTH, ORIENTATION_HORIZONTAL, ORIENTATION_VERTICAL, \
SCROLLAREA_POSITION_BOTH_HORIZONTAL, POSITION_SOUTH, SCROLLAREA_POSITION_FULL, \
SCROLLAREA_POSITION_BOTH_VERTICAL
from pygame_menu.utils import make_surface, assert_color, assert_position, \
assert_orientation, get_finger_pos
from pygame_menu.widgets import ScrollBar
from pygame_menu._types import Union, NumberType, Tuple, List, Dict, Tuple2NumberType, \
CursorInputType, Optional, Tuple2IntType, NumberInstance, ColorInputType, \
EventVectorType, EventType, VectorInstance, StringVector, Any
def get_scrollbars_from_position(
position: str
) -> Union[str, Tuple[str, str], Tuple[str, str, str, str]]:
"""
Return the scrollbars from the given position.
Raises ``ValueError`` if invalid position.
:param position: Position
:return: Scrollbars
"""
if position in (POSITION_EAST, POSITION_EAST, POSITION_WEST, POSITION_NORTH):
return position
elif position == POSITION_NORTHWEST:
return POSITION_NORTH, POSITION_WEST
elif position == POSITION_NORTHEAST:
return POSITION_NORTH, POSITION_EAST
elif position == POSITION_SOUTHWEST:
return POSITION_SOUTH, POSITION_WEST
elif position == POSITION_SOUTHEAST:
return POSITION_SOUTH, POSITION_EAST
elif position == SCROLLAREA_POSITION_FULL:
return POSITION_SOUTH, POSITION_EAST, POSITION_WEST, POSITION_NORTH
elif position == SCROLLAREA_POSITION_BOTH_HORIZONTAL:
return POSITION_SOUTH, POSITION_NORTH
elif position == SCROLLAREA_POSITION_BOTH_VERTICAL:
return POSITION_EAST, POSITION_WEST
elif position == POSITION_CENTER:
raise ValueError('cannot init scrollbars from center position')
else:
raise ValueError('unknown ScrollArea position')
DEFAULT_SCROLLBARS = get_scrollbars_from_position(POSITION_SOUTHEAST)
class ScrollArea(Base):
"""
The ScrollArea class provides a scrolling view managing up to 4 scroll bars.
A scroll area is used to display the contents of a child surface (``world``).
If the surface exceeds the size of the drawing surface, the view provide
scroll bars so that the entire area of the child surface can be viewed.
.. note::
See :py:mod:`pygame_menu.locals` for valid ``scrollbars`` and
``shadow_position`` values.
.. note::
ScrollArea cannot be copied or deep-copied.
:param area_width: Width of scrollable area in px
:param area_height: Height of scrollable area in px
:param area_color: Background color, it can be a color or an image
:param controls_joystick: Use joystick events
:param controls_keyboard: Use keyboard events
:param controls_mouse: Use mouse events
:param controls_touchscreen: Use touchscreen events
:param extend_x: Px to extend the surface on x-axis in px from left. Recommended use only within Menus
:param extend_y: Px to extend the surface on y-axis in px from top. Recommended use only within Menus
:param menubar: Menubar for style compatibility. ``None`` if ScrollArea is not used within a Menu (for example, in Frames)
:param parent_scrollarea: Parent ScrollArea if the new one is added within another area
:param scrollarea_id: Scrollarea ID
:param scrollbar_color: Scrollbars color
:param scrollbar_cursor: Scrollbar cursor
:param scrollbar_slider_color: Color of the sliders
:param scrollbar_slider_hover_color: Color of the slider if hovered or clicked
:param scrollbar_slider_pad: Space between slider and scrollbars borders in px
:param scrollbar_thick: Scrollbar thickness in px
:param scrollbars: Positions of the scrollbars. See :py:mod:`pygame_menu.locals`
:param shadow: Indicate if a shadow is drawn on each scrollbar
:param shadow_color: Color of the shadow of each scrollbar
:param shadow_offset: Offset of the scrollbar shadow in px
:param shadow_position: Position of the scrollbar shadow. See :py:mod:`pygame_menu.locals`
:param world: Surface to draw and scroll
"""
_area_color: Optional[Union[ColorInputType, 'pygame_menu.BaseImage']]
_bg_surface: Optional['pygame.Surface']
_decorator: 'Decorator'
_extend_x: int
_extend_y: int
_menu: Optional['pygame_menu.Menu']
_menubar: 'pygame_menu.widgets.MenuBar'
_parent_scrollarea: 'ScrollArea'
_rect: 'pygame.Rect'
_scrollbar_positions: Tuple[str, ...]
_scrollbar_thick: int
_scrollbars: List['ScrollBar']
_scrollbars_props: Tuple[Any, ...]
_translate: Tuple2IntType
_view_rect: 'pygame.Rect'
_world: 'pygame.Surface'
def __init__(
self,
area_width: int,
area_height: int,
area_color: Optional[Union[ColorInputType, 'pygame_menu.BaseImage']] = None,
controls_joystick: bool = True,
controls_keyboard: bool = True,
controls_mouse: bool = True,
controls_touchscreen: bool = True,
extend_x: int = 0,
extend_y: int = 0,
menubar: Optional['pygame_menu.widgets.MenuBar'] = None,
parent_scrollarea: Optional['ScrollArea'] = None,
scrollarea_id: str = '',
scrollbar_color: ColorInputType = (235, 235, 235),
scrollbar_cursor: CursorInputType = None,
scrollbar_slider_color: ColorInputType = (200, 200, 200),
scrollbar_slider_hover_color: ColorInputType = (180, 180, 180),
scrollbar_slider_pad: NumberType = 0,
scrollbar_thick: int = 20,
scrollbars: StringVector = DEFAULT_SCROLLBARS,
shadow: bool = False,
shadow_color: ColorInputType = (0, 0, 0),
shadow_offset: int = 2,
shadow_position: str = POSITION_SOUTHEAST,
world: Optional['pygame.Surface'] = None
) -> None:
super(ScrollArea, self).__init__(object_id=scrollarea_id)
assert isinstance(area_height, int)
assert isinstance(area_width, int)
assert isinstance(controls_joystick, bool)
assert isinstance(controls_keyboard, bool)
assert isinstance(controls_mouse, bool)
assert isinstance(controls_touchscreen, bool)
assert isinstance(extend_x, int)
assert isinstance(extend_y, int)
assert isinstance(scrollbar_slider_pad, NumberInstance)
assert isinstance(scrollbar_thick, int)
assert isinstance(shadow, bool)
assert isinstance(shadow_offset, int)
assert isinstance(world, (pygame.Surface, type(None)))
if area_color is not None and not isinstance(area_color, pygame_menu.BaseImage):
area_color = assert_color(area_color)
scrollbar_color = assert_color(scrollbar_color)
scrollbar_slider_color = assert_color(scrollbar_slider_color)
shadow_color = assert_color(shadow_color)
assert_position(shadow_position)
assert area_width > 0 and area_height > 0, \
'area size must be greater than zero'
assert isinstance(scrollbars, (str, VectorInstance))
unique_scrolls = []
if isinstance(scrollbars, str):
unique_scrolls.append(scrollbars)
else:
for s in scrollbars:
if s not in unique_scrolls:
unique_scrolls.append(s)
self._area_color = area_color
self._bg_surface = None
self._bg_surface = None
self._decorator = Decorator(self)
self._scrollbar_positions = tuple(unique_scrolls) # Ensure unique
self._scrollbar_thick = scrollbar_thick
self._translate = (0, 0)
self._world = world
self._extend_x = extend_x
self._extend_y = extend_y
self._menubar = menubar
self._scrollbars_props = (scrollbar_color, scrollbar_thick, scrollbar_slider_color,
scrollbar_slider_hover_color, scrollbar_slider_pad,
scrollbar_cursor, shadow, shadow_color, shadow_position,
shadow_offset, controls_joystick, controls_mouse,
controls_touchscreen, controls_keyboard)
self.set_parent_scrollarea(parent_scrollarea)
self.create_rect(area_width, area_height)
# Menu reference
self._menu = None
def create_rect(self, width: int, height: int) -> None:
"""
Create rect object.
:param width: Area width
:param height: Area height
"""
assert isinstance(width, int)
assert isinstance(height, int)
self._rect = pygame.Rect(0, 0, int(width), int(height))
self._scrollbars = []
self._view_rect = self.get_view_rect()
# Unpack properties
(scrollbar_color, scrollbar_thick, scrollbar_slider_color,
scrollbar_slider_hover_color, scrollbar_slider_pad,
scrollbar_cursor, shadow, shadow_color, shadow_position,
shadow_offset, controls_joystick, controls_mouse, controls_touchscreen,
controls_keyboard) = self._scrollbars_props
for pos in self._scrollbar_positions:
assert_position(pos)
if pos == POSITION_EAST or pos == POSITION_WEST:
sbar = ScrollBar(
length=self._view_rect.height,
onchange=self._on_vertical_scroll,
orientation=ORIENTATION_VERTICAL,
page_ctrl_color=scrollbar_color,
page_ctrl_thick=scrollbar_thick,
slider_color=scrollbar_slider_color,
slider_hover_color=scrollbar_slider_hover_color,
slider_pad=scrollbar_slider_pad,
values_range=(0, max(1, self.get_hidden_height()))
)
else:
sbar = ScrollBar(
length=self._view_rect.width,
onchange=self._on_horizontal_scroll,
page_ctrl_color=scrollbar_color,
page_ctrl_thick=scrollbar_thick,
slider_color=scrollbar_slider_color,
slider_hover_color=scrollbar_slider_hover_color,
slider_pad=scrollbar_slider_pad,
values_range=(0, max(1, self.get_hidden_width()))
)
sbar.set_shadow(
enabled=shadow,
color=shadow_color,
position=shadow_position,
offset=shadow_offset
)
sbar.set_controls(
joystick=controls_joystick,
mouse=controls_mouse,
touchscreen=controls_touchscreen,
keyboard=controls_keyboard
)
sbar.set_cursor(cursor=scrollbar_cursor)
sbar.set_scrollarea(self)
sbar.configured = True
sbar.hide()
self._scrollbars.append(sbar)
self._apply_size_changes()
def _make_background_surface(self) -> None:
"""
Create background surface.
"""
# If bg surface is created, and it's the same size
if self._bg_surface is not None and \
self._bg_surface.get_width() == self._rect.width and \
self._bg_surface.get_height() == self._rect.height:
return
# Make surface
self._bg_surface = make_surface(width=self._rect.width + self._extend_x,
height=self._rect.height + self._extend_y)
if self._area_color is not None:
if isinstance(self._area_color, pygame_menu.BaseImage):
self._area_color.draw(surface=self._bg_surface,
area=self._bg_surface.get_rect())
else:
self._bg_surface.fill(assert_color(self._area_color))
def set_parent_scrollarea(self, parent: Optional['ScrollArea']) -> None:
"""
Set parent ScrollArea.
:param parent: Parent ScrollArea
"""
assert isinstance(parent, (ScrollArea, type(None)))
assert parent != self, 'parent scrollarea cannot be set as itself'
self._parent_scrollarea = parent
def get_parent(self) -> Optional['ScrollArea']:
"""
Return the parent ScrollArea.
:return: Parent ScrollArea object
"""
return self._parent_scrollarea
def get_depth(self) -> int:
"""
Return the depth of the ScrollArea (how many parents do it has recursively).
:return: Depth's number
"""
parent = self._parent_scrollarea
count = 0
if parent is not None:
while True:
if parent is None:
break
count += 1
parent = parent._parent_scrollarea
return count
def __copy__(self) -> 'ScrollArea':
"""
Copy method.
:return: Raises copy exception
"""
raise _ScrollAreaCopyException('ScrollArea class cannot be copied')
def __deepcopy__(self, memodict: Dict) -> 'ScrollArea':
"""
Deep-copy method.
:param memodict: Memo dict
:return: Raises copy exception
"""
raise _ScrollAreaCopyException('ScrollArea class cannot be copied')
def force_menu_surface_update(self) -> 'ScrollArea':
"""
Forces menu surface update after next rendering call.
.. note::
This method is expensive, as menu surface update forces re-rendering
of all widgets (because them can change in size, position, etc...).
:return: Self reference
"""
if self._menu is not None:
self._menu._widgets_surface_need_update = True
return self
def force_menu_surface_cache_update(self) -> 'ScrollArea':
"""
Forces menu surface cache to update after next drawing call.
This also updates widget decoration.
.. note::
This method only updates the surface cache, without forcing re-rendering
of all Menu widgets as
:py:meth:`pygame_menu.widgets.core.widget.Widget.force_menu_surface_update`
does.
:return: Self reference
"""
if self._menu is not None:
self._menu._widget_surface_cache_need_update = True
self._decorator.force_cache_update()
return self
def _apply_size_changes(self) -> None:
"""
Apply size changes to scrollbar.
"""
self._view_rect = self.get_view_rect()
for sbar in self._scrollbars:
pos = self._scrollbar_positions[self._scrollbars.index(sbar)]
d_size, dx, dy = 0, 0, 0
if self._menubar is not None:
d_size, (dx, dy) = self._menubar.get_scrollbar_style_change(pos)
if pos == POSITION_WEST:
sbar.set_position(x=self._view_rect.left - self._scrollbar_thick + dx,
y=self._view_rect.top + dy)
elif pos == POSITION_EAST:
sbar.set_position(x=self._view_rect.right + dx,
y=self._view_rect.top + dy)
elif pos == POSITION_NORTH:
sbar.set_position(x=self._view_rect.left + dx,
y=self._view_rect.top - self._scrollbar_thick + dy)
elif pos == POSITION_SOUTH: # South
sbar.set_position(x=self._view_rect.left + dx,
y=self._view_rect.bottom + dy)
else:
raise ValueError('unknown position, only west, east, north, and'
'south are allowed')
if pos in (POSITION_NORTH, POSITION_SOUTH):
if self.get_hidden_width() != 0:
sbar.set_length(self._view_rect.width + d_size)
sbar.set_maximum(self.get_hidden_width())
sbar.set_page_step(self._view_rect.width * self.get_hidden_width() /
(self._view_rect.width + self.get_hidden_width()))
sbar.show()
else:
sbar.hide()
elif pos in (POSITION_EAST, POSITION_WEST):
if self.get_hidden_height() != 0:
sbar.set_length(self._view_rect.height + d_size)
sbar.set_maximum(self.get_hidden_height())
sbar.set_page_step(self._view_rect.height * self.get_hidden_height() /
(self._view_rect.height + self.get_hidden_height()))
sbar.show()
else:
sbar.hide()
def draw(self, surface: 'pygame.Surface') -> 'ScrollArea':
"""
Draw the ScrollArea.
:param surface: Surface to render the area
:return: Self reference
"""
if not self._world:
return self
# Background surface already has previous decorators
if self._area_color is not None:
self._make_background_surface()
surface.blit(self._bg_surface,
(self._rect.x - self._extend_x, self._rect.y - self._extend_y))
# Draw world surface
# noinspection PyTypeChecker
surface.blit(self._world, self._view_rect.topleft,
(self.get_offsets(), self._view_rect.size))
# Then draw scrollbars
for sbar in self._scrollbars:
if not sbar.is_visible():
continue
if sbar.get_orientation() == ORIENTATION_HORIZONTAL:
if self.get_hidden_width():
sbar.draw(surface)
else:
if self.get_hidden_height():
sbar.draw(surface)
# Draw post decorator
self._decorator.draw_post(surface)
return self
def get_hidden_width(self) -> int:
"""
Return the total width out of the bounds of the viewable area.
Zero is returned if the world width is lower than the viewable area.
:return: Hidden width in px
"""
if not self._world:
return 0
return int(max(0, self._world.get_width() - self._view_rect.width))
def get_hidden_height(self) -> int:
"""
Return the total height out of the bounds of the viewable area.
Zero is returned if the world height is lower than the viewable area.
:return: Hidden height in px
"""
if not self._world:
return 0
return int(max(0, self._world.get_height() - self._view_rect.height))
def get_offsets(self) -> Tuple2IntType:
"""
Return the offset introduced by the scrollbars in the world.
:return: ScrollArea offset on x-axis and y-axis (x, y)
"""
offsets = [0, 0]
for sbar in self._scrollbars:
if not sbar.is_visible():
continue
if sbar.get_orientation() == ORIENTATION_HORIZONTAL:
if self.get_hidden_width():
offsets[0] = sbar.get_value() # Cannot add as each scrollbar can only affect 1 axis only
else:
if self.get_hidden_height():
offsets[1] = sbar.get_value()
return offsets[0], offsets[1]
def get_rect(self, to_real_position: bool = False) -> 'pygame.Rect':
"""
Return the :py:class:`pygame.Rect` object of the ScrollArea.
:param to_real_position: Get real position fof the scroll area
:return: Pygame.Rect object
"""
rect = self._rect.copy()
if to_real_position:
rect = self.to_real_position(rect)
return rect
def get_scrollbar_thickness(self, orientation: str, visible: bool = True) -> int:
"""
Return the scroll thickness of the area. If it's hidden return zero.
:param orientation: Orientation of the scroll. See :py:mod:`pygame_menu.locals`
:param visible: If ``True`` returns the real thickness depending on if it is visible or not
:return: Thickness in px
"""
assert_orientation(orientation)
assert isinstance(visible, bool)
if visible:
total = 0
for sbar in self._scrollbars:
if sbar.get_orientation() == orientation and sbar.is_visible():
total += sbar.get_thickness()
return total
if orientation == ORIENTATION_HORIZONTAL:
return int(self._rect.height - self._view_rect.height)
elif orientation == ORIENTATION_VERTICAL:
return int(self._rect.width - self._view_rect.width)
def get_world_rect(self, absolute: bool = False) -> 'pygame.Rect':
"""
Return the world rect.
:param absolute: To absolute position
:return: World rect object
"""
rect = self._world.get_rect()
if absolute:
rect = self.to_absolute_position(rect)
return rect
def get_view_rect(self) -> 'pygame.Rect':
"""
Subtract width of scrollbars from area with the given size and return
the viewable area.
The viewable area depends on the world size, because scroll bars may or
may not be displayed.
:return: View rect object
"""
rect = pygame.Rect(self._rect)
# No scrollbar: area is large enough to display world
if not self._world or (self._world.get_width() <= self._rect.width
and self._world.get_height() <= self._rect.height):
return rect
# All scrollbars: the world is too large
if self._world.get_height() > self._rect.height \
and self._world.get_width() > self._rect.width:
if POSITION_WEST in self._scrollbar_positions:
rect.left += self._scrollbar_thick
rect.width -= self._scrollbar_thick
if POSITION_EAST in self._scrollbar_positions:
rect.width -= self._scrollbar_thick
if POSITION_NORTH in self._scrollbar_positions:
rect.top += self._scrollbar_thick
rect.height -= self._scrollbar_thick
if POSITION_SOUTH in self._scrollbar_positions:
rect.height -= self._scrollbar_thick
return rect
# Calculate the maximum variations introduces by the scrollbars
bars_total_width = 0
bars_total_height = 0
if POSITION_NORTH in self._scrollbar_positions:
bars_total_height += self._scrollbar_thick
if POSITION_SOUTH in self._scrollbar_positions:
bars_total_height += self._scrollbar_thick
if POSITION_WEST in self._scrollbar_positions:
bars_total_width += self._scrollbar_thick
if POSITION_EAST in self._scrollbar_positions:
bars_total_width += self._scrollbar_thick
if self._world.get_height() > self._rect.height:
if POSITION_WEST in self._scrollbar_positions:
rect.left += self._scrollbar_thick
rect.width -= self._scrollbar_thick
if POSITION_EAST in self._scrollbar_positions:
rect.width -= self._scrollbar_thick
if self._world.get_width() > self._rect.width - bars_total_width:
if POSITION_NORTH in self._scrollbar_positions:
rect.top += self._scrollbar_thick
rect.height -= self._scrollbar_thick
if POSITION_SOUTH in self._scrollbar_positions:
rect.height -= self._scrollbar_thick
if self._world.get_width() > self._rect.width:
if POSITION_NORTH in self._scrollbar_positions:
rect.top += self._scrollbar_thick
rect.height -= self._scrollbar_thick
if POSITION_SOUTH in self._scrollbar_positions:
rect.height -= self._scrollbar_thick
if self._world.get_height() > self._rect.height - bars_total_height:
if POSITION_WEST in self._scrollbar_positions:
rect.left += self._scrollbar_thick
rect.width -= self._scrollbar_thick
if POSITION_EAST in self._scrollbar_positions:
rect.width -= self._scrollbar_thick
return rect
def hide_scrollbars(self, orientation: str) -> 'ScrollArea':
"""
Hide scrollbar from given orientation.
:param orientation: Orientation. See :py:mod:`pygame_menu.locals`
:return: Self reference
"""
assert_orientation(orientation)
for sbar in self._scrollbars:
if sbar.get_orientation() == orientation:
sbar.hide()
return self
def show_scrollbars(self, orientation: str) -> 'ScrollArea':
"""
Hide scrollbar from given orientation.
:param orientation: Orientation. See :py:mod:`pygame_menu.locals`
:return: Self reference
"""
assert_orientation(orientation)
for sbar in self._scrollbars:
if sbar.get_orientation() == orientation:
sbar.show()
return self
def get_world_size(self) -> Tuple2IntType:
"""
Return the world size.
:return: Width, height in pixels
"""
if self._world is None:
return 0, 0
return self._world.get_width(), self._world.get_height()
def get_size(self, inner: bool = False) -> Tuple2IntType:
"""
Return the area size.
:param inner: If ``True`` returns the rect view area
:return: Width, height in pixels
"""
if inner:
return self._view_rect.width, self._view_rect.height
return self._rect.width, self._rect.height
def mouse_is_over(self, view: bool = False) -> bool:
"""
Return ``True`` if the mouse is placed over the ScrollArea.
:param view: If ``True`` uses "view rect" instead of "rect"
:return: ``True`` if the mouse is over the object
"""
rect = self._view_rect if view else self._rect
return bool(self.to_absolute_position(rect).collidepoint(*pygame.mouse.get_pos()))
def _on_horizontal_scroll(self, value: NumberType) -> None:
"""
Call when a horizontal scroll bar as changed to update the
position of the opposite one if it exists.
:param value: New position of the slider
"""
for sbar in self._scrollbars:
if sbar.get_orientation() == ORIENTATION_HORIZONTAL \
and self.get_hidden_width() != 0 \
and sbar.get_value() != value:
sbar.set_value(value)
def _on_vertical_scroll(self, value: NumberType) -> None:
"""
Call when a vertical scroll bar as changed to update the
position of the opposite one if it exists.
:param value: New position of the slider
"""
for sbar in self._scrollbars:
if sbar.get_orientation() == ORIENTATION_VERTICAL \
and self.get_hidden_height() != 0 \
and sbar.get_value() != value:
sbar.set_value(value)
def get_parent_scroll_value_percentage(self, orientation: str) -> Tuple[float]:
"""
Get percentage scroll values of scroll and parents; if ``0`` the scroll
is at top/left, ``1`` bottom/right.
:param orientation: Orientation. See :py:mod:`pygame_menu.locals`
:return: Value from ``0`` to ``1`` as a tuple; first item is the current scrollarea
"""
values = [self.get_scroll_value_percentage(orientation)]
parent = self._parent_scrollarea
if parent is not None:
while True: # Recursive
if parent is None:
break
values.append(parent.get_scroll_value_percentage(orientation))
parent = parent._parent_scrollarea
return tuple(values)
def get_scroll_value_percentage(self, orientation: str) -> float:
"""
Get the scroll value in percentage; if ``0`` the scroll is at top/left,
``1`` bottom/right.
.. note::
If ScrollArea does not contain such orientation scroll, ``-1`` is returned.
:param orientation: Orientation. See :py:mod:`pygame_menu.locals`
:return: Value from ``0`` to ``1``
"""
assert_orientation(orientation)
for sbar in self._scrollbars:
if not sbar.is_visible():
continue
if sbar.get_orientation() == orientation:
return sbar.get_value_percentage()
return -1
def scroll_to(self, orientation: str, value: NumberType) -> 'ScrollArea':
"""
Scroll to position in terms of the percentage.
:param orientation: Orientation. See :py:mod:`pygame_menu.locals`
:param value: If ``0`` scrolls to top/left, ``1`` to bottom/right
:return: Self reference
"""
assert_orientation(orientation)
assert isinstance(value, NumberInstance) and 0 <= value <= 1
for sbar in self._scrollbars:
if not sbar.is_visible():
continue
if sbar.get_orientation() == orientation:
v_min, v_max = sbar.get_minmax()
delta = v_max - v_min
new_value = int(min(v_min + delta * float(value), v_max))
sbar.set_value(new_value)
break
return self
# noinspection PyTypeChecker
def scroll_to_rect(
self,
rect: 'pygame.Rect',
margin: Tuple2NumberType = (0, 0),
scroll_parent: bool = True
) -> bool:
"""
Ensure that the given rect is in the viewable area.
:param rect: Rect in the world surface reference
:param margin: Extra margin around the rect on x-axis and y-axis in px
:param scroll_parent: If ``True`` parent scroll also scrolls to rect
:return: Scrollarea scrolled to rect. If ``False`` the rect was already inside the visible area
"""
# Check if visible
if self.to_real_position(rect, visible=True).height == 0 and \
self._parent_scrollarea is not None and scroll_parent:
self._parent_scrollarea.scroll_to_rect(self._parent_scrollarea.get_rect(), margin, scroll_parent)
self._parent_scrollarea.scroll_to_rect(self.get_rect(), margin, scroll_parent)
real_rect = self.to_real_position(rect)
# Add margin to rect
real_rect.x += margin[0]
real_rect.y += margin[1]
# Check rect is in viewable area
sx = self.get_scrollbar_thickness(ORIENTATION_VERTICAL)
sy = self.get_scrollbar_thickness(ORIENTATION_HORIZONTAL)
view_rect = self.get_absolute_view_rect()
if view_rect.topleft[0] <= real_rect.topleft[0] + sx \
and view_rect.topleft[1] <= real_rect.topleft[1] + sy \
and view_rect.bottomright[0] + sx >= real_rect.bottomright[0] \
and view_rect.bottomright[1] + sy >= real_rect.bottomright[1]:
return False
for sbar in self._scrollbars:
if not sbar.is_visible():
continue
if sbar.get_orientation() == ORIENTATION_HORIZONTAL and self.get_hidden_width():
shortest_move = min(real_rect.left - view_rect.left,
real_rect.right - view_rect.right, key=abs)
value = min(sbar.get_maximum(), sbar.get_value() + shortest_move)
value = max(sbar.get_minimum(), value)
sbar.set_value(value)
if sbar.get_orientation() == ORIENTATION_VERTICAL and self.get_hidden_height():
shortest_move = min(real_rect.bottom - view_rect.bottom,
real_rect.top - view_rect.top, key=abs)
value = min(sbar.get_maximum(), sbar.get_value() + shortest_move)
value = max(sbar.get_minimum(), value)
sbar.set_value(value)
if self._parent_scrollarea is not None and scroll_parent:
self._parent_scrollarea.scroll_to_rect(rect, margin, scroll_parent)
return True
def set_position(self, x: int, y: int) -> 'ScrollArea':
"""
Set the position.
:param x: X position
:param y: Y position
:return: Self reference
"""
self._rect.x = x + self._extend_x + self._translate[0]
self._rect.y = y + self._extend_y + self._translate[1]
self._apply_size_changes()
return self
def get_position(self) -> Tuple2IntType:
"""
Return the ScrollArea position.
:return: X, Y position in px
"""
return self._rect.x, self._rect.y
def get_widget_position_relative_to_view_rect(
self,
widget: 'pygame_menu.widgets.Widget'
) -> Tuple2NumberType:
"""
Get widget position relative to view rect on x-axis and y-axis. On each axis,
the relative position goes from ``-inf`` to ``+inf``. If between (0, 1) the
widget is inside the view rect.
.. note::
Only top-left widget position is checked.
:param widget: Widget to check the position
:return: Relative position to view rect on x-axis and y-axis
"""
assert widget.get_scrollarea() == self, \
'{0} scrollarea {1} is different than current {2}' \
.format(widget, widget.get_scrollarea().get_class_id(), self.get_class_id())
wx, wy = widget.get_position()
view_rect = self.get_view_rect()
vx, vy = view_rect.width, view_rect.height
offx, offy = self.get_offsets()
return (wx - offx) / vx, (wy - offy) / vy
def translate(self, x: NumberType, y: NumberType) -> 'ScrollArea':
"""
Translate on x-axis and y-axis (x, y) in px.
:param x: X translation in px
:param y: Y translation in px
:return: Self reference
"""
assert isinstance(x, NumberInstance)
assert isinstance(y, NumberInstance)
self._rect.x -= self._translate[0]
self._rect.y -= self._translate[1]
self._translate = (x, y)
self._rect.x += x
self._rect.y += y
self._apply_size_changes()
return self
def get_translate(self) -> Tuple2IntType:
"""
Get object translation on both axis.
:return: Translation on x-axis and y-axis (x, y) in px
"""
return self._translate
def set_world(self, surface: 'pygame.Surface') -> 'ScrollArea':
"""
Update the scrolled surface.
:param surface: New world surface
:return: Self reference
"""
self._world = surface
self._apply_size_changes()
return self
def get_world(self) -> Optional['pygame.Surface']:
"""
Return the world surface area.
.. warning::
Use with caution.
:return: World surface. ``None`` if it has not been set yet
"""
return self._world
def get_parent_position(self) -> Tuple2IntType:
"""
Return parent ScrollArea position.
:return: Position on x, y-axis in px
"""
if self._parent_scrollarea is not None:
px, py = self._parent_scrollarea.get_position()
ox, oy = self._parent_scrollarea.get_offsets()
par_x, par_y = 0, 0
if self._parent_scrollarea.get_parent() is not None:
par_x, par_y = self._parent_scrollarea.get_parent_position()
return px - ox + par_x, py - oy + par_y
return 0, 0
def to_absolute_position(self, virtual: 'pygame.Rect') -> 'pygame.Rect':
"""
Return the absolute position of a rect within the ScrollArea. Absolute
position is concerning the parent ScrollArea. If ``None``, the rect is
not changed at all.
.. note::
Absolute position must be used if desired to get the widget position
outside a scrolled area status, for example the view rect, or the
scrollbars.
:param virtual: Rect in the world surface reference
:return: Rect in absolute position
"""
rect = pygame.Rect(virtual)
parent_position = self.get_parent_position()
rect.x += parent_position[0]
rect.y += parent_position[1]
return rect
def get_absolute_view_rect(self) -> 'pygame.Rect':
"""
Return the ScrollArea absolute view rect clipped if it is not visible by
its parent ScrollArea.
:return: Clipped absolute view rect
"""
view_rect_absolute = self.to_absolute_position(self._view_rect)
if self._parent_scrollarea is not None:
parent = self._parent_scrollarea
if parent is not None:
while True: # Recursive
if parent is None:
break
view_rect_absolute = parent.get_absolute_view_rect().clip(view_rect_absolute)
parent = parent._parent_scrollarea
return view_rect_absolute
def to_real_position(self, virtual: Union['pygame.Rect', Tuple2NumberType], visible: bool = False
) -> Union['pygame.Rect', Tuple2IntType]:
"""
Return the real position/Rect according to the ScrollArea origin of a
position/Rect in the world surface reference.
.. note::
Real position must be used if desired to get the widget position within
a scrolled area status.
:param virtual: Position/Rect in the world surface reference
:param visible: If a ``virtual`` is Rect object, return only the visible width/height
:return: Real rect or real position
"""
assert isinstance(virtual, (pygame.Rect, VectorInstance))
offsets = self.get_offsets()
parent_position = self.get_parent_position()
if isinstance(virtual, pygame.Rect):
rect = pygame.Rect(virtual) # virtual.copy() should also work
rect.x = virtual.x + self._rect.x - offsets[0] + parent_position[0]
rect.y = virtual.y + self._rect.y - offsets[1] + parent_position[1]
if visible:
return self.get_absolute_view_rect().clip(rect) # Visible width and height
return rect
x_coord = self._rect.x + virtual[0] - offsets[0] + parent_position[0]
y_coord = self._rect.y + virtual[1] - offsets[1] + parent_position[1]
return int(x_coord), int(y_coord)
def to_world_position(
self,
real: Union['pygame.Rect', Tuple2NumberType]
) -> Union['pygame.Rect', Tuple2IntType]:
"""
Return the position/Rect in the world surface reference of a real
position/Rect according to the ScrollArea origin.
.. note::
Virtual position must be used if desired to get the widget position
within a scrolled area status.
:param real: Position/Rect according ScrollArea origin
:return: Rect in world or position in world
"""
assert isinstance(real, (pygame.Rect, VectorInstance))
offsets = self.get_offsets()
parent_position = self.get_parent_position()
if isinstance(real, pygame.Rect):
rect = pygame.Rect(real)
rect.x = real.x - self._rect.x + offsets[0] - parent_position[0]
rect.y = real.y - self._rect.y + offsets[1] - parent_position[1]
return rect
x_coord = real[0] - self._rect.x + offsets[0] - parent_position[0]
y_coord = real[1] - self._rect.y + offsets[1] - parent_position[1]
return int(x_coord), int(y_coord)
def is_scrolling(self) -> bool:
"""
Return ``True`` if the user is scrolling.
:return: ``True`` if user scrolls
"""
scroll = False
for sbar in self._scrollbars:
scroll = scroll or sbar.scrolling
return scroll
def update(self, events: EventVectorType) -> bool:
"""
Called by end user to update scroll state.
:param events: List of pygame events
:return: ``True`` if updated
"""
updated = [False, False]
for sbar in self._scrollbars:
if not sbar.is_visible():
continue
if self.get_hidden_width() and not updated[0] and \
sbar.get_orientation() == ORIENTATION_HORIZONTAL:
updated[0] = sbar.update(events)
elif self.get_hidden_height() and not updated[1] and \
sbar.get_orientation() == ORIENTATION_VERTICAL:
updated[1] = sbar.update(events)
return updated[0] or updated[1]
def set_menu(self, menu: 'pygame_menu.Menu') -> 'ScrollArea':
"""
Set the Menu reference.
:param menu: Menu object
:return: Self reference
"""
self._menu = menu
for sbar in self._scrollbars:
sbar.set_menu(menu)
return self
def get_menu(self) -> Optional['pygame_menu.Menu']:
"""
Return the Menu reference (if exists).
:return: Menu reference
"""
return self._menu
def collide(
self,
widget: Union['pygame_menu.widgets.Widget', 'pygame.Rect'],
event: EventType
) -> bool:
"""
If user event collides a widget within the ScrollArea respect to the
relative position.
:param widget: Widget or rect
:param event: Pygame event
:return: ``True`` if collide
"""
if not isinstance(widget, pygame.Rect):
widget_rect = widget.get_rect(to_real_position=True)
else:
widget_rect = widget
return bool(widget_rect.collidepoint(*get_finger_pos(self._menu, event)))
def get_decorator(self) -> 'Decorator':
"""
Return the ScrollArea decorator API.
.. note::
Menu drawing order:
1. Menu background color/image
2. Menu ``prev`` decorator
3. Menu **ScrollArea** ``prev`` decorator
4. Menu **ScrollArea** widgets
5. Menu **ScrollArea** ``post`` decorator
6. Menu title
7. Menu ``post`` decorator
:return: Decorator API
"""
return self._decorator
class _ScrollAreaCopyException(Exception):
"""
If user tries to copy a ScrollArea.
"""
pass
|
dcartman/pygame-menu | test/test_decorator.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST DECORATOR
Decorator API.
"""
__all__ = ['DecoratorTest']
from test._utils import MenuUtils, surface, TEST_THEME, BaseTest
import copy
import pygame
import pygame_menu
import timeit
# Configure the tests
TEST_TIME_DRAW = False
class DecoratorTest(BaseTest):
@staticmethod
def test_time_draw() -> None:
"""
This test the time that takes to draw the decorator surface with several decorations.
"""
if not TEST_TIME_DRAW:
return
widg = pygame_menu.widgets.NoneWidget()
deco = widg.get_decorator()
deco.cache = True
for i in range(10000):
deco.add_pixel(1, 2, (0, 0, 0))
# (100) no cache, 0.214
# (100) with cache, 0.646
# (250) no cache, 0.467
# (250) with cache, 0.594
# (300) no cache, 0.581
# (300) with cache, 0.606
# (400) no cache, 0.82
# (400) with cache, 0.638
# (500) no cache, 1.087
# (500) with cache, 0.601
# (750) no cache, 1.484
# (750) with cache, 0.664
# (1.000) no cache, 2.228
# (1.000) with cache, 0.615
# (10.000) no cache, 20.430
# (10.000) with cache, 0.599
print('Total decorations', deco._total_decor(), 'Cache', deco.cache)
total_tests = 10
t = 0 # total time
for i in range(total_tests):
ti = timeit.timeit(lambda: widg.draw(surface), number=1000)
print('Test', i, 'time:', ti)
t += ti
print('Average time:', round(t / total_tests, 3))
def test_cache(self) -> None:
"""
Test cache.
"""
widg = pygame_menu.widgets.NoneWidget()
deco = widg.get_decorator()
deco.cache = True
# Prev
self.assertIsNone(deco._cache_surface['prev'])
self.assertIsNone(deco._cache_surface['post'])
f = deco.add_circle(1, 1, 1, (0, 0, 0), True)
self.assertIsNone(deco._cache_surface['prev'])
self.assertIsNone(deco._cache_surface['post'])
deco.draw_prev(surface)
self.assertIsNotNone(deco._cache_surface['prev'])
self.assertIsNone(deco._cache_surface['post'])
p = deco._cache_surface['prev']
deco.add_circle(1, 1, 1, (0, 0, 0), True)
deco.draw_prev(surface)
self.assertNotEqual(deco._cache_surface['prev'], p)
self.assertIsNone(deco._cache_surface['post'])
self.assertFalse(deco._cache_needs_update['prev'])
self.assertFalse(deco._cache_needs_update['post'])
deco.add_circle(1, 1, 1, (0, 0, 0), True)
self.assertTrue(deco._cache_needs_update['prev'])
self.assertFalse(deco._cache_needs_update['post'])
deco.draw_prev(surface)
self.assertFalse(deco._cache_needs_update['prev'])
self.assertFalse(deco._cache_needs_update['post'])
self.assertEqual(deco._total_decor(), 3)
deco.disable(f)
self.assertTrue(deco._cache_needs_update['prev'])
self.assertFalse(deco._cache_needs_update['post'])
deco.remove_all()
self.assertEqual(deco._total_decor(), 0)
self.assertFalse(deco._cache_needs_update['prev'])
self.assertFalse(deco._cache_needs_update['post'])
deco.draw_prev(surface)
self.assertFalse(deco._cache_needs_update['prev'])
self.assertFalse(deco._cache_needs_update['post'])
# Post
deco.add_circle(1, 1, 1, (0, 0, 0), False, prev=False)
self.assertTrue(deco._cache_needs_update['post'])
self.assertIsNone(deco._cache_surface['post'])
deco.draw_post(surface)
self.assertEqual(deco._total_decor(), 1)
self.assertFalse(deco._cache_needs_update['post'])
self.assertIsNotNone(deco._cache_surface['post'])
deco.remove_all()
self.assertEqual(deco._total_decor(), 0)
def test_copy(self) -> None:
"""
Test decorator copy.
"""
widg = pygame_menu.widgets.NoneWidget()
deco = widg.get_decorator()
self.assertRaises(Exception, lambda: copy.copy(deco))
self.assertRaises(Exception, lambda: copy.deepcopy(deco))
def test_add_remove(self) -> None:
"""
Test add remove.
"""
widg = pygame_menu.widgets.NoneWidget()
deco = widg.get_decorator()
d = deco._add_none()
self.assertEqual(len(deco._decor['prev']), 1)
self.assertEqual(len(deco._decor['post']), 0)
self.assertEqual(len(deco._decor_prev_id), 1)
self.assertIn(d, deco._decor_prev_id)
self.assertEqual(deco._total_decor(), 1)
assert isinstance(d, str)
self.assertRaises(IndexError, lambda: deco.remove('none'))
deco.remove(d)
self.assertEqual(len(deco._decor['prev']), 0)
self.assertEqual(len(deco._decor['post']), 0)
self.assertEqual(len(deco._decor_prev_id), 0)
p = deco.add_pixel(1, 1, (1, 1, 1))
self.assertEqual(len(deco._coord_cache.keys()), 0)
deco.draw_prev(surface)
self.assertEqual(len(deco._coord_cache.keys()), 1)
deco.remove(p)
self.assertEqual(len(deco._coord_cache.keys()), 0)
def test_enable_disable(self) -> None:
"""
Test enable disable decoration.
"""
menu = MenuUtils.generic_menu()
btn = menu.add.button('Button')
deco = btn.get_decorator()
# Callable
test = [False]
def fun(surf, obj: 'pygame_menu.widgets.Button') -> None:
"""
Test callable decoration.
"""
test[0] = True
assert isinstance(surf, pygame.Surface)
assert isinstance(obj, pygame_menu.widgets.Button)
call_id = deco.add_callable(fun)
self.assertFalse(test[0])
btn.draw(surface)
self.assertTrue(test[0])
self.assertRaises(IndexError, lambda: deco.is_enabled('unknown'))
self.assertTrue(deco.is_enabled(call_id))
# Now disable the decoration
deco.disable(call_id)
self.assertFalse(deco.is_enabled(call_id))
test[0] = False
btn.draw(surface)
self.assertFalse(test[0])
deco.enable(call_id)
btn.draw(surface)
self.assertTrue(test[0])
deco.remove(call_id)
self.assertFalse(call_id in deco._decor_enabled.keys())
# Disable unknown deco
self.assertRaises(IndexError, lambda: deco.disable('unknown'))
self.assertRaises(IndexError, lambda: deco.enable('unknown'))
def test_general(self) -> None:
"""
Test all decorators.
"""
menu = MenuUtils.generic_menu(theme=TEST_THEME.copy())
btn = menu.add.button('Button')
deco = btn.get_decorator()
poly = [(50, 50), (50, 100), (100, 50)]
color = (1, 1, 1)
# Polygon
self.assertRaises(AssertionError, lambda: deco.add_polygon([(1, 1)], color, True))
self.assertRaises(AssertionError, lambda: deco.add_polygon([(1, 1)], color, True, 1))
self.assertRaises(AssertionError, lambda: deco.add_polygon([(1, 1)], color, True, gfx=False))
# deco.add_filled_polygon(poly, color)
deco.add_polygon(poly, color, True)
deco.add_polygon(poly, color, False)
deco.add_polygon(poly, color, False, gfx=False)
deco.draw_prev(surface)
# Circle
self.assertRaises(AssertionError, lambda: deco.add_circle(1, 1, 0, color, True))
self.assertRaises(AssertionError, lambda: deco.add_circle(1, 1, 0, color, True, gfx=False))
self.assertRaises(AssertionError, lambda: deco.add_circle(50, 50, 100, color, True, 1))
deco.add_circle(1, 1, 100, color, False, 5)
deco.add_circle(50, 50, 100, color, True)
# Surface
img = pygame_menu.BaseImage(pygame_menu.baseimage.IMAGE_EXAMPLE_PYGAME_MENU)
img.scale(0.15, 0.15)
deco.add_surface(60, 60, img.get_surface(), prev=False)
# BaseImage
img_dec = deco.add_baseimage(0, 0, img)
self.assertEqual(len(deco._coord_cache), 3)
menu.draw(surface)
self.assertEqual(len(deco._coord_cache), 7)
self.assertEqual(deco._coord_cache[img_dec], (299, 173, ((299, 173),)))
# If widget changes in size, coord cache should change too
btn.translate(1, 0)
menu.draw(surface)
self.assertEqual(deco._coord_cache[img_dec], (300, 173, ((300, 173),))) # +1
# As some problems occur here, test the position of the widget before padding
w, h, (x, y) = btn.get_width(), btn.get_height(), btn.get_position()
self.assertEqual(menu.get_width(widget=True), w)
self.assertEqual(menu.get_height(widget=True), h)
wo = (menu.get_height(inner=True) - h) / 2
self.assertEqual(menu._widget_offset[1], int(wo))
self.assertEqual(btn.get_rect().center, (int(x + w / 2), int(y + h / 2)))
# If widget changes padding, the center does not change if pad is equal, so the coord cache must be the same
btn.set_padding(100)
menu.draw(surface)
# Test sizing
self.assertEqual(menu.get_width(widget=True), w + 200)
self.assertEqual(menu.get_height(widget=True), h + 200)
wo = (menu.get_height(inner=True) - (h + 200)) / 2
self.assertEqual(menu._widget_offset[1], int(wo))
self.assertEqual(btn.get_rect().x, x - 100)
self.assertEqual(btn.get_rect().y, y - 100)
self.assertEqual(btn.get_rect().center, (int(x + w / 2), int(y + h / 2)))
self.assertEqual(deco._coord_cache[img_dec], (300, 173, ((300, 173),)))
# Padding left is 0, then widget center changes
btn.set_padding((100, 100, 100, 0))
menu.draw(surface)
self.assertEqual(deco._coord_cache[img_dec], (300, 173, ((300, 173),)))
btn.set_padding((100, 0, 100, 0))
menu.draw(surface)
self.assertEqual(deco._coord_cache[img_dec], (300, 173, ((300, 173),)))
# Text
self.assertRaises(ValueError, lambda: deco.add_text(100, 200, 'nice', pygame_menu.font.FONT_8BIT, 0, color))
deco.add_text(-150, 0, 'nice', pygame_menu.font.FONT_8BIT, 20, color, centered=True)
menu.draw(surface)
# Ellipse
self.assertRaises(AssertionError, lambda: deco.add_ellipse(0, 0, 0, 0, color, True))
deco.add_ellipse(-250, 0, 110, 150, (255, 0, 0), True)
deco.add_ellipse(-250, 0, 110, 150, (255, 0, 0), False)
# Callable
test = [False]
def fun(surf, obj: 'pygame_menu.widgets.Button') -> None:
"""
Test callable decoration.
"""
test[0] = True
assert isinstance(surf, pygame.Surface)
assert isinstance(obj, pygame_menu.widgets.Button)
deco.add_callable(fun)
self.assertFalse(test[0])
btn.draw(surface)
self.assertTrue(test[0])
test[0] = False
def fun_noargs() -> None:
"""
No args fun.
"""
test[0] = True
self.assertFalse(test[0])
deco.add_callable(fun_noargs, pass_args=False)
btn.draw(surface)
self.assertTrue(test[0])
# Textured polygon
deco.add_textured_polygon(((10, 10), (100, 100), (120, 10)), img)
# Arc
deco.add_arc(0, 0, 50, 0, 100, (0, 255, 0), True)
deco.add_arc(0, 0, 50, 0, 100, (0, 255, 0), False)
# Pie
deco.add_pie(0, 0, 50, 0, 100, (0, 255, 0))
# Bezier
deco.add_bezier(((100, 100), (0, 0), (0, -100)), (70, 10, 100), 10)
# Rect
deco.add_rect(200, 30, pygame.Rect(0, 0, 100, 300), (0, 0, 100))
deco.add_rect(0, 30, pygame.Rect(0, 0, 100, 300), (100, 0, 100), width=10)
# Pixel
for i in range(5):
for j in range(5):
deco.add_pixel(10 * i, 10 * j, color)
# Line
deco.add_line((10, 10), (100, 100), (45, 180, 34), 10)
deco.add_hline(1, 2, 3, color)
deco.add_vline(1, 2, 3, color)
# Fill
deco.add_fill((0, 0, 0))
menu.draw(surface)
deco.remove_all()
|
dcartman/pygame-menu | pygame_menu/_types.py | <reponame>dcartman/pygame-menu<filename>pygame_menu/_types.py
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
TYPES
Defines common pygame-menu types.
"""
from pygame.color import Color as __Color
from pygame.event import Event as EventType
from typing import Union, List, Tuple, Any, Callable, Sequence, Mapping, Optional
# noinspection PyUnresolvedReferences
from typing import Dict, Type # lgtm [py/unused-import]
# noinspection PyUnresolvedReferences
from typing_extensions import Literal # lgtm [py/unused-import]
# Common types
ArgsType = Optional[Sequence[Any]]
CallableNoArgsType = Callable[[], Any]
CallbackType = Optional[Callable]
EventListType = List[EventType]
EventVectorType = Union[EventListType, Tuple[EventType]]
KwargsType = Optional[Mapping[Any, Any]]
NumberType = Union[int, float]
# Colors
ColorType = Union[Tuple[int, int, int], Tuple[int, int, int, int]]
ColorInputType = Union[ColorType, str, int, __Color]
# Color input gradient; from, to, vertical, forward
ColorInputGradientType = Tuple[ColorInputType, ColorInputType, bool, bool]
# Vectors
Vector2BoolType = Union[Tuple[bool, bool], List[bool]]
Vector2IntType = Union[Tuple[int, int], List[int]]
Vector2FloatType = Union[Tuple[float, float], List[float]]
Vector2NumberType = Union[Tuple[NumberType, NumberType], List[NumberType]]
# Generic length
VectorTupleType = Tuple[NumberType, ...]
VectorListType = List[NumberType]
VectorType = Union[VectorTupleType, VectorListType]
VectorIntType = Union[Tuple[int, ...], List[int]]
# Tuples
Tuple2BoolType = Tuple[bool, bool]
Tuple2IntType = Tuple[int, int]
Tuple2NumberType = Tuple[NumberType, NumberType]
Tuple3IntType = Tuple[int, int, int]
Tuple4IntType = Tuple[int, int, int, int]
Tuple4Tuple2IntType = Tuple[Tuple2IntType, Tuple2IntType, Tuple2IntType, Tuple2IntType]
TupleIntType = Tuple[int, ...]
# Menu constructor types
MenuColumnMaxWidthType = Optional[Union[int, float, VectorType]]
MenuColumnMinWidthType = Union[int, float, VectorType]
MenuRowsType = Optional[Union[int, VectorIntType]]
# Other
PaddingType = Optional[Union[NumberType, List[NumberType], Tuple[NumberType],
Tuple[NumberType, NumberType],
Tuple[NumberType, NumberType, NumberType, NumberType],
Tuple[NumberType, NumberType, NumberType, NumberType]]]
StringVector = Union[str, Tuple[str, ...], List[str]]
# Instances
ColorInputInstance = (int, str, tuple, list, __Color)
NumberInstance = (int, float)
PaddingInstance = (int, float, tuple, list, type(None))
VectorInstance = (tuple, list)
# Cursor
try:
# noinspection PyUnresolvedReferences
from pygame.cursors import Cursor as __Cursor
CursorInputType = Optional[Union[int, __Cursor]]
CursorInputInstance = (int, __Cursor, type(None))
except (AttributeError, ImportError):
CursorInputType, CursorInputInstance = Optional[int], (int, type(None))
CursorType = CursorInputType
|
dcartman/pygame-menu | pygame_menu/widgets/selection/arrow_selection.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
LEFT ARROW CLASS
Selector with a left arrow on the item.
"""
__all__ = ['ArrowSelection']
import pygame
import pygame_menu
from pygame_menu.utils import assert_vector
from pygame_menu.widgets.core import Selection
from pygame_menu._types import NumberType, Tuple2IntType, Optional, NumberInstance
SELECTOR_CLOCK = pygame.time.Clock()
class ArrowSelection(Selection):
"""
Widget selection arrow class.
Parent class for left and right arrow selection classes.
:param margin_left: Left margin (px)
:param margin_right: Right margin (px)
:param margin_top: Top margin (px)
:param margin_bottom: Bottom margin (px)
:param arrow_size: Size of arrow on x-axis and y-axis (width, height) in px
:param arrow_vertical_offset: Vertical offset of the arrow (px)
:param blink_ms: Milliseconds between each blink; if ``0`` blinking is disabled
"""
_arrow_vertical_offset: int
_arrow_size: Tuple2IntType
_blink_ms: NumberType
_blink_time: NumberType
_blink_status: bool
_last_widget: Optional['pygame_menu.widgets.Widget']
def __init__(
self,
margin_left: NumberType,
margin_right: NumberType,
margin_top: NumberType,
margin_bottom: NumberType,
arrow_size: Tuple2IntType = (10, 15),
arrow_vertical_offset: NumberType = 0,
blink_ms: NumberType = 0
) -> None:
super(ArrowSelection, self).__init__(
margin_left=margin_left,
margin_right=margin_right,
margin_top=margin_top,
margin_bottom=margin_bottom
)
assert_vector(arrow_size, 2, int)
assert isinstance(arrow_vertical_offset, NumberInstance)
assert isinstance(blink_ms, int)
assert arrow_size[0] > 0 and arrow_size[1] > 0, 'arrow size must be greater than zero'
assert blink_ms >= 0, 'blinking milliseconds must be greater than or equal to zero'
self._arrow_vertical_offset = int(arrow_vertical_offset)
self._arrow_size = (arrow_size[0], arrow_size[1])
self._blink_ms = blink_ms
self._blink_time = 0
self._blink_status = True
self._last_widget = None
# noinspection PyMissingOrEmptyDocstring
def draw(self, surface: 'pygame.Surface', widget: 'pygame_menu.widgets.Widget') -> 'ArrowSelection':
raise NotImplementedError('override is mandatory')
def _draw_arrow(
self,
surface: 'pygame.Surface',
widget: 'pygame_menu.widgets.Widget',
a: Tuple2IntType,
b: Tuple2IntType,
c: Tuple2IntType
) -> None:
"""
Draw the selection arrow.
:param surface: Surface to draw
:param widget: Widget object
:param a: Arrow coord A
:param b: Arrow coord B
:param c: Arrow coord C
"""
SELECTOR_CLOCK.tick(60) # As blink is in ms
self._blink_time += SELECTOR_CLOCK.get_time()
# Switch the blinking if the time exceeded or the widget has changed
if self._blink_ms != 0 and (self._blink_time > self._blink_ms or self._last_widget != widget):
self._blink_status = not self._blink_status or self._last_widget != widget
self._blink_time = 0
self._last_widget = widget
# Draw the arrow only if blinking is enabled
if self._blink_status:
pygame.draw.polygon(surface, self.color, [a, b, c])
|
dcartman/pygame-menu | test/test_widget_image.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST WIDGET - IMAGE
Test Image widget.
"""
__all__ = ['ImageWidgetTest']
from test._utils import MenuUtils, surface, PygameEventUtils, BaseTest
import pygame_menu
class ImageWidgetTest(BaseTest):
def test_image_widget(self) -> None:
"""
Test image widget.
"""
menu = MenuUtils.generic_menu()
image = menu.add.image(pygame_menu.baseimage.IMAGE_EXAMPLE_GRAY_LINES, font_color=(2, 9))
image.set_title('epic')
self.assertEqual(image.get_title(), '')
self.assertEqual(image.get_image(), image._image)
image.update(PygameEventUtils.mouse_motion(image))
self.assertEqual(image.get_height(apply_selection=True), 264)
self.assertFalse(image._selected)
self.assertEqual(image.get_selected_time(), 0)
# Test transformations
self.assertEqual(image.get_size(), (272, 264))
image.scale(2, 2)
self.assertEqual(image.get_size(), (528, 520))
image.resize(500, 500)
# Remove padding
image.set_padding(0)
self.assertEqual(image.get_size(), (500, 500))
# Set max width
image.set_max_width(400)
self.assertEqual(image.get_size(), (400, 500))
image.set_max_width(800)
self.assertEqual(image.get_size(), (400, 500))
image.set_max_width(300, scale_height=True)
self.assertEqual(image.get_size(), (300, 375))
# Set max height
image.set_max_height(400)
self.assertEqual(image.get_size(), (300, 375))
image.set_max_height(300)
self.assertEqual(image.get_size(), (300, 300))
image.set_max_height(200, scale_width=True)
self.assertEqual(image.get_size(), (200, 200))
self.assertEqual(image.get_angle(), 0)
image.rotate(90)
self.assertEqual(image.get_angle(), 90)
image.rotate(60)
self.assertEqual(image.get_angle(), 60)
# Flip
image.flip(True, True)
self.assertEqual(image._flip, (True, True))
image.flip(False, False)
self.assertEqual(image._flip, (False, False))
image.draw(surface)
def test_value(self) -> None:
"""
Test image value.
"""
menu = MenuUtils.generic_menu()
image = menu.add.image(pygame_menu.baseimage.IMAGE_EXAMPLE_GRAY_LINES)
self.assertRaises(ValueError, lambda: image.get_value())
self.assertRaises(ValueError, lambda: image.set_value('value'))
self.assertFalse(image.value_changed())
image.reset_value()
|
dcartman/pygame-menu | pygame_menu/widgets/core/selection.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
SELECTION
Widget selection effect.
"""
__all__ = ['Selection']
import copy
import pygame
import pygame_menu
from pygame_menu.utils import assert_color
from pygame_menu._types import NumberType, ColorType, ColorInputType, Tuple2IntType, \
Tuple4IntType, NumberInstance, Optional, Union
class Selection(object):
"""
Widget selection effect class.
.. note::
All selection classes must be copyable.
:param margin_left: Left margin
:param margin_right: Right margin
:param margin_top: Top margin
:param margin_bottom: Bottom margin
"""
color: ColorType
color_bg: Optional[ColorType]
margin_bottom: NumberType
margin_left: NumberType
margin_right: NumberType
margin_top: NumberType
widget_apply_font_color: bool
def __init__(
self,
margin_left: NumberType,
margin_right: NumberType,
margin_top: NumberType,
margin_bottom: NumberType
) -> None:
assert isinstance(margin_left, NumberInstance)
assert isinstance(margin_right, NumberInstance)
assert isinstance(margin_top, NumberInstance)
assert isinstance(margin_bottom, NumberInstance)
assert margin_left >= 0, 'left margin of widget selection cannot be negative'
assert margin_right >= 0, 'right margin of widget selection cannot be negative'
assert margin_top >= 0, 'top margin of widget selection cannot be negative'
assert margin_bottom >= 0, 'bottom margin of widget selection cannot be negative'
self.color = (0, 0, 0) # Main color of the selection effect
self.color_bg = None
self.margin_bottom = margin_bottom
self.margin_left = margin_left
self.margin_right = margin_right
self.margin_top = margin_top
self.widget_apply_font_color = True # Widgets apply "selected_color" if selected
def margin_xy(self, x: NumberType, y: NumberType) -> 'Selection':
"""
Set margins at left-right / top-bottom.
:param x: Left-Right margin in px
:param y: Top-Bottom margin in px
:return: Self reference
"""
assert isinstance(x, NumberInstance) and x >= 0
assert isinstance(y, NumberInstance) and y >= 0
self.margin_left = x
self.margin_right = x
self.margin_top = y
self.margin_bottom = y
return self
def zero_margin(self) -> 'Selection':
"""
Makes selection margin zero.
:return: Self reference
"""
self.margin_top = 0
self.margin_left = 0
self.margin_right = 0
self.margin_bottom = 0
return self
def copy(self) -> 'Selection':
"""
Creates a deep copy of the object.
:return: Copied selection effect
"""
return copy.deepcopy(self)
def __copy__(self) -> 'Selection':
"""
Copy method.
:return: Copied selection
"""
return self.copy()
def set_color(self, color: ColorInputType) -> 'Selection':
"""
Set the selection effect color.
:param color: Selection color
:return: Self reference
"""
self.color = assert_color(color)
return self
def set_background_color(self, color: Union[ColorInputType, 'pygame_menu.BaseImage']) -> 'Selection':
"""
Set the selection background color. It will replace the background color of the widget
if selected.
:param color: Background color
:return: Self reference
"""
self.color_bg = color
if not isinstance(color, pygame_menu.BaseImage):
self.color_bg = assert_color(self.color_bg)
return self
def get_background_color(self) -> Optional[Union[ColorType, 'pygame_menu.BaseImage']]:
"""
Return the background color.
:return: Background color or None
"""
return self.color_bg
def get_margin(self) -> Tuple4IntType:
"""
Return the top, left, bottom and right margins of the selection.
:return: Tuple of (top, left, bottom, right) margins in px
"""
return int(self.margin_top), int(self.margin_left), \
int(self.margin_bottom), int(self.margin_right)
def get_xy_margin(self) -> Tuple2IntType:
"""
Return the x/y margins of the selection.
:return: Margin tuple on x-axis and y-axis (x, y) in px
"""
return int(self.margin_left + self.margin_right), \
int(self.margin_top + self.margin_bottom)
def get_width(self) -> int:
"""
Return the selection width as sum of left and right margins.
:return: Width in px
"""
_, l, _, r = self.get_margin()
return l + r
def get_height(self) -> int:
"""
Return the selection height as sum of top and bottom margins.
:return: Height in px
"""
t, _, b, _ = self.get_margin()
return t + b
def inflate(
self,
rect: 'pygame.Rect', inflate: Optional[Tuple2IntType] = None
) -> 'pygame.Rect':
"""
Grow or shrink the rectangle size according to margins.
:param rect: Rect object
:param inflate: Extra border inflate
:return: Inflated rect
"""
if inflate is None:
inflate = (0, 0)
assert isinstance(rect, pygame.Rect)
return pygame.Rect(
int(rect.x - self.margin_left - inflate[0] / 2),
int(rect.y - self.margin_top - inflate[1] / 2),
int(rect.width + self.margin_left + self.margin_right + inflate[0]),
int(rect.height + self.margin_top + self.margin_bottom + inflate[1])
)
def draw(self, surface: 'pygame.Surface', widget: 'pygame_menu.widgets.Widget') -> 'Selection':
"""
Draw the selection.
:param surface: Surface to draw
:param widget: Widget object
:return: Self reference
"""
raise NotImplementedError('override is mandatory')
|
dcartman/pygame-menu | pygame_menu/font.py | <reponame>dcartman/pygame-menu
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
FONTS
Menu fonts.
"""
__all__ = [
# Fonts path included in resources
'FONT_8BIT',
'FONT_BEBAS',
'FONT_COMIC_NEUE',
'FONT_DIGITAL',
'FONT_FRANCHISE',
'FONT_FIRACODE',
'FONT_FIRACODE_BOLD',
'FONT_FIRACODE_BOLD_ITALIC',
'FONT_FIRACODE_ITALIC',
'FONT_HELVETICA',
'FONT_MUNRO',
'FONT_NEVIS',
'FONT_OPEN_SANS',
'FONT_OPEN_SANS_BOLD',
'FONT_OPEN_SANS_ITALIC',
'FONT_OPEN_SANS_LIGHT',
'FONT_PT_SERIF',
'FONT_EXAMPLES',
# Typing
'FontType',
'FontInstance',
# Utils
'assert_font',
'get_font'
]
from pathlib import Path
from typing import Union, Optional, Any
import os.path as path
import pygame.font as __font
# Available fonts path
__fonts_path__ = path.join(path.dirname(path.abspath(__file__)), 'resources', 'fonts', '{0}')
FONT_8BIT = __fonts_path__.format('8bit.ttf')
FONT_BEBAS = __fonts_path__.format('bebas.ttf')
FONT_COMIC_NEUE = __fonts_path__.format('comic_neue.ttf')
FONT_DIGITAL = __fonts_path__.format('digital.ttf')
FONT_FIRACODE = __fonts_path__.format('FiraCode-Regular.ttf')
FONT_FIRACODE_BOLD = __fonts_path__.format('FiraCode-Bold.ttf')
FONT_FIRACODE_BOLD_ITALIC = __fonts_path__.format('FiraMono-BoldItalic.ttf')
FONT_FIRACODE_ITALIC = __fonts_path__.format('FiraMono-Italic.ttf')
FONT_FRANCHISE = __fonts_path__.format('franchise.ttf')
FONT_HELVETICA = __fonts_path__.format('helvetica.ttf')
FONT_MUNRO = __fonts_path__.format('munro.ttf')
FONT_NEVIS = __fonts_path__.format('nevis.ttf')
FONT_OPEN_SANS = __fonts_path__.format('opensans_regular.ttf')
FONT_OPEN_SANS_BOLD = __fonts_path__.format('opensans_bold.ttf')
FONT_OPEN_SANS_ITALIC = __fonts_path__.format('opensans_italic.ttf')
FONT_OPEN_SANS_LIGHT = __fonts_path__.format('opensans_light.ttf')
FONT_PT_SERIF = __fonts_path__.format('ptserif_regular.ttf')
FONT_EXAMPLES = (FONT_8BIT, FONT_BEBAS, FONT_COMIC_NEUE, FONT_DIGITAL, FONT_FRANCHISE,
FONT_HELVETICA, FONT_MUNRO, FONT_NEVIS, FONT_OPEN_SANS,
FONT_OPEN_SANS_BOLD, FONT_OPEN_SANS_ITALIC, FONT_OPEN_SANS_LIGHT,
FONT_PT_SERIF, FONT_FIRACODE, FONT_FIRACODE_BOLD, FONT_FIRACODE_ITALIC,
FONT_FIRACODE_BOLD_ITALIC)
# Stores font cache
_cache = {}
FontType = Union[str, __font.Font, Path]
FontInstance = (str, __font.Font, Path)
def assert_font(font: Any) -> None:
"""
Asserts if the given object is a font type.
:param font: Font object
"""
assert isinstance(font, FontInstance), \
'value must be a font type (str, Path, pygame.Font)'
def get_font(name: FontType, size: int) -> '__font.Font':
"""
Return a :py:class:`pygame.font.Font` object from a name or file.
:param name: Font name or path
:param size: Font size in px
:return: Font object
"""
assert_font(name)
assert isinstance(size, int)
font: Optional['__font.Font']
if isinstance(name, __font.Font):
font = name
return font
else:
name = str(name)
if name == '':
raise ValueError('font name cannot be empty')
if size <= 0:
raise ValueError('font size cannot be lower or equal than zero')
# Font is not a file, then use a system font
if not path.isfile(name):
font_name = name
name = __font.match_font(font_name)
if name is None: # Show system available fonts
from difflib import SequenceMatcher
from random import randrange
system_fonts = __font.get_fonts()
# Get the most similar example
most_similar = 0
most_similar_index = 0
for i in range(len(system_fonts)):
# noinspection PyArgumentEqualDefault
sim = SequenceMatcher(None, system_fonts[i], font_name).ratio()
if sim > most_similar:
most_similar = sim
most_similar_index = i
sys_font_sim = system_fonts[most_similar_index]
sys_suggestion = f'system font "{font_name}" unknown, use "{sys_font_sim}" instead'
sys_message = 'check system fonts with pygame.font.get_fonts() function'
# Get examples
examples_number = 3
examples = []
j = 0
for i in range(len(system_fonts)):
font_random = system_fonts[randrange(0, len(system_fonts))]
if font_random not in examples:
examples.append(font_random)
j += 1
if j >= examples_number:
break
examples.sort()
fonts_random = ', '.join(examples)
sys_message_2 = f'some examples: {fonts_random}'
# Raise the exception
raise ValueError(f'{sys_suggestion}\n{sys_message}\n{sys_message_2}')
# Try to load the font
font = None
if (name, size) in _cache:
return _cache[(name, size)]
try:
font = __font.Font(name, size)
except IOError:
pass
# If font was not loaded throw an exception
if font is None:
raise IOError(f'font file "{font}" cannot be loaded')
_cache[(name, size)] = font
return font
|
dcartman/pygame-menu | test/test_widget_rangeslider.py | <gh_stars>0
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST WIDGET - RANGE SLIDER
Test RangeSlider widget.
"""
__all__ = ['RangeSliderWidgetTest']
from test._utils import MenuUtils, surface, PygameEventUtils, BaseTest
import pygame
import pygame_menu
import pygame_menu.controls as ctrl
from pygame_menu.widgets.core.widget import WidgetTransformationNotImplemented
class RangeSliderWidgetTest(BaseTest):
# noinspection PyTypeChecker
def test_single_rangeslider(self) -> None:
"""
Test single range slider.
"""
menu = MenuUtils.generic_menu()
# Single slider
slider = pygame_menu.widgets.RangeSlider('Range S')
test = [0, 0]
def onchange(x: float) -> None:
"""
Change slider.
"""
# noinspection PyTypeChecker
test[0] = x
def onreturn(x: float) -> None:
"""
Return slider.
"""
# noinspection PyTypeChecker
test[1] = x
slider.set_onchange(onchange)
slider.set_onreturn(onreturn)
menu.add.generic_widget(slider, True)
self.assertEqual(slider.get_value(), 0)
slider.set_value(0.5)
self.assertEqual(slider.get_value(), 0.5)
self.assertEqual(slider._value, [0.5, 0])
self.assertEqual(test[0], 0)
slider.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
self.assertEqual(test[0], 0.4)
self.assertEqual(slider.get_value(), 0.4)
slider.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
self.assertAlmostEqual(slider.get_value(), 0.3)
for _ in range(10):
slider.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
self.assertEqual(slider.get_value(), 0)
self.assertTrue(slider.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True)))
self.assertEqual(slider.get_value(), 0.1)
self.assertEqual(test[1], 0)
slider.update(PygameEventUtils.key(ctrl.KEY_APPLY, keydown=True))
self.assertEqual(test[1], 0.1)
# Ignore invalid key
self.assertFalse(slider.update(
PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True, testmode=False)))
# Ignore for readonly
slider.draw(surface)
slider.draw_after_if_selected(surface)
slider.readonly = True
self.assertFalse(slider.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True)))
self.assertEqual(slider.get_value(), 0.1)
slider._update_value(0)
self.assertEqual(slider.get_value(), 0.1)
slider.readonly = False
# Test invalid values
self.assertRaises(AssertionError, lambda: slider.set_value(-1))
self.assertRaises(AssertionError, lambda: slider.set_value([0.4, 0.5]))
# Test invalid transforms
self.assertRaises(WidgetTransformationNotImplemented, lambda: slider.rotate())
self.assertRaises(WidgetTransformationNotImplemented, lambda: slider.flip())
self.assertRaises(WidgetTransformationNotImplemented, lambda: slider.scale())
self.assertRaises(WidgetTransformationNotImplemented, lambda: slider.resize())
self.assertRaises(WidgetTransformationNotImplemented, lambda: slider.set_max_width())
self.assertRaises(WidgetTransformationNotImplemented, lambda: slider.set_max_height())
# Test mouse click
self.assertFalse(slider._selected_mouse)
pos = slider._test_get_pos_value(0.5)
slider.update(PygameEventUtils.middle_rect_click(pos, evtype=pygame.MOUSEBUTTONDOWN))
self.assertEqual(slider.get_value(), 0.1)
self.assertTrue(slider._selected_mouse)
self.assertFalse(slider._scrolling)
slider.update(PygameEventUtils.middle_rect_click(pos))
self.assertFalse(slider._scrolling)
self.assertEqual(slider.get_value(), 0.5)
self.assertFalse(slider._selected_mouse)
# Mouse click out of range
slider._selected_mouse = True
pos = slider._test_get_pos_value(1, dx=100)
slider.update(PygameEventUtils.middle_rect_click(pos))
self.assertEqual(slider.get_value(), 0.5)
self.assertFalse(slider._selected_mouse)
slider._selected_mouse = True
pos = slider._test_get_pos_value(0, dx=-100)
slider.update(PygameEventUtils.middle_rect_click(pos))
self.assertEqual(slider.get_value(), 0.5)
self.assertFalse(slider._selected_mouse)
# Test extremes
slider._selected_mouse = True
pos = slider._test_get_pos_value(0)
slider.update(PygameEventUtils.middle_rect_click(pos))
self.assertEqual(slider.get_value(), 0)
slider._selected_mouse = True
pos = slider._test_get_pos_value(1)
slider.update(PygameEventUtils.middle_rect_click(pos))
self.assertEqual(slider.get_value(), 1)
# Scroll to 0.5
pos2 = slider._test_get_pos_value(0.5)
self.assertFalse(slider._scrolling)
slider_rect = slider._get_slider_inflate_rect(0, to_real_position=True)
slider.update(PygameEventUtils.middle_rect_click(slider_rect, evtype=pygame.MOUSEBUTTONDOWN))
self.assertTrue(slider._scrolling)
self.assertTrue(slider._selected_mouse)
dx = pos[0] - pos2[0]
slider.update(PygameEventUtils.mouse_motion(slider_rect, rel=(-dx, pos[1]), update_mouse=True))
self.assertEqual(slider.get_value(), 0.5)
self.assertTrue(slider._scrolling)
slider.update(PygameEventUtils.middle_rect_click(pos))
self.assertFalse(slider._scrolling)
# Check invalid constructor for single slider
self.assertRaises(AssertionError, lambda: pygame_menu.widgets.RangeSlider(
'Range S', default_value=2))
self.assertRaises(AssertionError, lambda: pygame_menu.widgets.RangeSlider(
'Range S', default_value=1, range_values=[1, 0]))
self.assertRaises(AssertionError, lambda: pygame_menu.widgets.RangeSlider(
'Range S', default_value=1, range_values=[1, 1]))
self.assertRaises(AssertionError, lambda: pygame_menu.widgets.RangeSlider(
'Range S', default_value='a'))
# Ignore tabs
self.assertFalse(slider.update(PygameEventUtils.key(ctrl.KEY_TAB, keydown=True)))
# Check LEFT key in repeat
self.assertIn(ctrl.KEY_RIGHT, slider._keyrepeat_counters.keys())
self.assertEqual(slider.get_value(), 0.5)
# Make left repeat
slider._keyrepeat_counters[ctrl.KEY_RIGHT] += 1e4
self.assertEqual(len(slider._events), 0)
self.assertFalse(slider.update([]))
self.assertEqual(len(slider._events), 1)
self.assertFalse(slider.update([])) # As key is not pressed, event continues
self.assertEqual(len(slider._events), 0)
# Keyup, removes counters
slider.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keyup=True))
self.assertNotIn(ctrl.KEY_RIGHT, slider._keyrepeat_counters.keys())
self.assertFalse(hasattr(slider, '_range_box'))
# Single slider with range box
slider_rb = pygame_menu.widgets.RangeSlider('Range', range_box_single_slider=True)
menu.add.generic_widget(slider_rb, True)
slider_rb.draw(surface)
self.assertTrue(hasattr(slider_rb, '_range_box'))
self.assertEqual(slider_rb._range_box.get_width(), 0)
slider_rb.set_value(1)
self.assertEqual(slider_rb._range_box.get_width(), 150)
def test_single_discrete(self) -> None:
"""
Test single range slider with discrete values.
"""
menu = MenuUtils.generic_menu()
# Single slider with discrete values
rv = [0, 1, 2, 3, 4, 5]
slider = pygame_menu.widgets.RangeSlider('Range', range_values=rv)
menu.add.generic_widget(slider, True)
self.assertRaises(AssertionError, lambda: pygame_menu.widgets.RangeSlider(
'Range', default_value=0.5, range_values=rv))
self.assertRaises(AssertionError, lambda: pygame_menu.widgets.RangeSlider(
'Range', default_value=-1, range_values=rv))
self.assertRaises(AssertionError, lambda: slider.set_value(-1))
self.assertRaises(AssertionError, lambda: slider.set_value([0, 1]))
self.assertRaises(AssertionError, lambda: slider.set_value((0, 1)))
# Test key events
self.assertFalse(slider.update(PygameEventUtils.key(ctrl.KEY_TAB, keydown=True)))
slider.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True))
self.assertEqual(slider.get_value(), 1)
slider.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True))
self.assertEqual(slider.get_value(), 2)
slider._increment = 0
slider.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True))
self.assertEqual(slider.get_value(), 3)
slider.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
self.assertEqual(slider.get_value(), 2)
slider.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
self.assertEqual(slider.get_value(), 1)
slider.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
self.assertEqual(slider.get_value(), 0)
slider.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
self.assertEqual(slider.get_value(), 0)
# Test click mouse
slider._selected_mouse = True
pos = slider._test_get_pos_value(2)
slider.update(PygameEventUtils.middle_rect_click(pos))
self.assertEqual(slider.get_value(), 2)
self.assertFalse(slider._selected_mouse)
# Test invalid click
slider._selected_mouse = True
pos = slider._test_get_pos_value(2, dx=1000)
slider.update(PygameEventUtils.middle_rect_click(pos))
self.assertEqual(slider.get_value(), 2)
self.assertFalse(slider._selected_mouse)
# Scroll to 4
pos = slider._test_get_pos_value(2)
pos2 = slider._test_get_pos_value(4)
self.assertFalse(slider._scrolling)
slider_rect = slider._get_slider_inflate_rect(0, to_real_position=True)
slider.update(PygameEventUtils.middle_rect_click(slider_rect, evtype=pygame.MOUSEBUTTONDOWN))
self.assertTrue(slider._scrolling)
self.assertTrue(slider._selected_mouse)
dx = pos[0] - pos2[0]
slider.update(PygameEventUtils.mouse_motion(slider_rect, rel=(-dx, pos[1]), update_mouse=True))
self.assertEqual(slider.get_value(), 4)
self.assertTrue(slider._scrolling)
slider.update(PygameEventUtils.middle_rect_click(pos))
self.assertFalse(slider._scrolling)
# Back to 2
slider.set_value(2)
# Invalid scrolling if clicked outside the slider
slider.update(PygameEventUtils.middle_rect_click(
slider._test_get_pos_value(0), evtype=pygame.MOUSEBUTTONDOWN))
self.assertFalse(slider._scrolling)
# noinspection PyTypeChecker
def test_double(self) -> None:
"""
Test double range slider.
"""
menu = MenuUtils.generic_menu()
# Double slider
slider = pygame_menu.widgets.RangeSlider(
'Range',
range_text_value_tick_number=3,
default_value=(0.2, 1.0),
slider_text_value_font=pygame_menu.font.FONT_BEBAS,
range_text_value_font=pygame_menu.font.FONT_8BIT,
slider_text_value_triangle=False
)
slider._slider_text_value_vmargin = -2
menu.add.generic_widget(slider, True)
slider.draw(surface)
slider.draw_after_if_selected(surface)
self.assertEqual(slider.get_value(), (0.2, 1.0))
self.assertRaises(AssertionError, lambda: slider.set_value(0.2))
self.assertRaises(AssertionError, lambda: slider.set_value((0.2, 0.2)))
self.assertRaises(AssertionError, lambda: slider.set_value((1.0, 0.2)))
self.assertRaises(AssertionError, lambda: slider.set_value((0.2, 0.5, 1.0)))
# Test slider selection
self.assertTrue(slider._slider_selected[0])
self.assertTrue(slider.update(PygameEventUtils.key(ctrl.KEY_TAB, keydown=True)))
self.assertFalse(slider._slider_selected[0])
slider.draw(surface)
slider.draw_after_if_selected(surface)
# Test click sliders
slider_rect = slider._get_slider_inflate_rect(0, to_real_position=True)
self.assertTrue(slider.update(
PygameEventUtils.middle_rect_click(slider_rect, evtype=pygame.MOUSEBUTTONDOWN)))
self.assertTrue(slider._slider_selected[0])
self.assertFalse(slider.update( # Slider already selected
PygameEventUtils.middle_rect_click(slider_rect, evtype=pygame.MOUSEBUTTONDOWN)))
# Click if sliders are colliding
slider.set_value((0.5, 0.50000001))
slider_rect = slider._get_slider_inflate_rect(1, to_real_position=True)
self.assertFalse(slider.update(
PygameEventUtils.middle_rect_click(slider_rect, evtype=pygame.MOUSEBUTTONDOWN)))
self.assertTrue(slider._slider_selected[0])
slider.set_value((0.5, 0.7))
slider_rect = slider._get_slider_inflate_rect(1, to_real_position=True)
self.assertTrue(slider.update(
PygameEventUtils.middle_rect_click(slider_rect, evtype=pygame.MOUSEBUTTONDOWN)))
self.assertTrue(slider._slider_selected[1])
# Test left slider
pos = slider._test_get_pos_value(0.5)
pos2 = slider._test_get_pos_value(0.6)
slider_rect = slider._get_slider_inflate_rect(0, to_real_position=True)
self.assertEqual(slider_rect, pygame.Rect(344, 311, 15, 28))
slider.update(PygameEventUtils.middle_rect_click(slider_rect, evtype=pygame.MOUSEBUTTONDOWN))
self.assertTrue(slider._slider_selected[0])
self.assertTrue(slider._scrolling)
self.assertTrue(slider._selected_mouse)
dx = pos[0] - pos2[0]
slider.update(PygameEventUtils.mouse_motion(slider_rect, rel=(-dx, pos[1]), update_mouse=True))
self.assertEqual(slider.get_value(), (0.6, 0.7))
# As slider moved, ignore this
slider.update(PygameEventUtils.mouse_motion(slider_rect, rel=(-dx, pos[1]), update_mouse=True))
self.assertEqual(slider.get_value(), (0.6, 0.7))
self.assertTrue(slider._scrolling)
self.assertTrue(slider._slider_selected[0])
# Move to 0
self.assertTrue(slider._selected_mouse)
pos = slider._test_get_pos_value(0)
pos2 = slider._test_get_pos_value(0.6)
dx = pos[0] - pos2[0]
slider.update(PygameEventUtils.mouse_motion(slider_rect, rel=(dx, pos[1]), update_mouse=True))
self.assertEqual(slider.get_value(), (0, 0.7))
# Move more than 0.7
pos = slider._test_get_pos_value(0)
pos2 = slider._test_get_pos_value(0.75)
slider_rect = slider._get_slider_inflate_rect(0, to_real_position=True)
dx = pos[0] - pos2[0]
slider.update(PygameEventUtils.mouse_motion(slider_rect, rel=(-dx, pos[1]), update_mouse=True))
self.assertEqual(slider.get_value(), (0, 0.7))
# Move to 0.7 - eps
pos = slider._test_get_pos_value(0)
pos2 = slider._test_get_pos_value(0.7 - 1e-6)
slider_rect = slider._get_slider_inflate_rect(0, to_real_position=True)
dx = pos[0] - pos2[0]
slider.update(PygameEventUtils.mouse_motion(slider_rect, rel=(-dx, pos[1]), update_mouse=True))
self.assertAlmostEqual(slider.get_value()[0], 0.7 - 1e-7, places=1)
# Ignore if move 0.7 + eps
self.assertFalse(slider.update(
PygameEventUtils.mouse_motion(slider_rect, rel=(1, pos[1]), update_mouse=True)))
# Change to right
slider_rect = slider._get_slider_inflate_rect(1, to_real_position=True)
self.assertTrue(slider.update(PygameEventUtils.key(ctrl.KEY_TAB, keydown=True)))
pos = slider._test_get_pos_value(0.7)
pos2 = slider._test_get_pos_value(0.8)
dx = pos[0] - pos2[0]
self.assertFalse(slider.update(
PygameEventUtils.mouse_motion(slider_rect, rel=(-1, pos[1]), update_mouse=True)))
self.assertTrue(slider.update(
PygameEventUtils.mouse_motion(slider_rect, rel=(-dx, pos[1]), update_mouse=True)))
self.assertAlmostEqual(slider.get_value()[1], 0.8)
# Test left/right
slider.set_value((0.7, 0.8))
slider.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
slider.set_value((0.7, 0.8)) # Ignored
slider.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True))
slider.set_value((0.7, 0.9))
slider.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True))
slider.set_value((0.7, 1.0))
slider.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True))
slider.set_value((0.7, 1.0))
slider.set_value((0.7, 0.8))
slider.update(PygameEventUtils.key(ctrl.KEY_TAB, keydown=True))
slider.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True))
slider.set_value((0.7, 0.8))
slider.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
slider.set_value((0.6, 0.8))
# Reset value
slider.reset_value()
self.assertEqual(slider.get_value(), (0.2, 1.0))
def test_double_discrete(self) -> None:
"""
Test double range slider with discrete values.
"""
menu = MenuUtils.generic_menu()
rv = [0, 1, 2, 3, 4, 5]
# Double slider discrete
slider = pygame_menu.widgets.RangeSlider('Range', range_text_value_tick_number=3,
range_values=rv, default_value=(1, 4))
menu.add.generic_widget(slider, True)
slider.draw(surface)
# Test set values
slider.set_value([1, 2])
self.assertEqual(slider.get_value(), (1, 2))
# Test invalid values
self.assertRaises(AssertionError, lambda: slider.set_value((1.1, 2.2)))
self.assertRaises(AssertionError, lambda: slider.set_value((1, 1)))
self.assertRaises(AssertionError, lambda: slider.set_value((2, 1)))
self.assertRaises(AssertionError, lambda: slider.set_value(1))
# Test left/right
self.assertTrue(slider.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True)))
self.assertEqual(slider.get_value(), (0, 2))
self.assertFalse(slider.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True)))
self.assertEqual(slider.get_value(), (0, 2))
self.assertTrue(slider.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True)))
self.assertEqual(slider.get_value(), (1, 2))
self.assertFalse(slider.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True)))
self.assertEqual(slider.get_value(), (1, 2))
slider._update_value(0.99)
self.assertEqual(slider.get_value(), (1, 2))
self.assertEqual(slider._get_slider_inflate_rect(0, to_absolute_position=True),
pygame.Rect(301, 209, 15, 28))
def test_kwargs(self) -> None:
"""
Test rangeslider kwargs from manager.
"""
menu = MenuUtils.generic_menu()
slider = menu.add.range_slider('Range', 0.5, (0, 1), 1, range_margin=(100, 0))
self.assertEqual(len(slider._kwargs), 0)
self.assertEqual(slider._range_margin, (100, 0))
def test_empty_title(self) -> None:
"""
Test empty title.
"""
menu = MenuUtils.generic_menu()
r = menu.add.range_slider('', 0.5, (0, 1), 0.1)
self.assertEqual(r.get_size(), (198, 66))
def test_invalid_range(self) -> None:
"""
Test invalid ranges. #356
"""
menu = MenuUtils.generic_menu()
r = menu.add.range_slider('Infection Rate', default=2, increment=0.5, range_values=(2, 10))
self.assertEqual(r.get_value(), 2)
self.assertTrue(r.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True)))
self.assertEqual(r.get_value(), 2.5)
self.assertTrue(r.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True)))
self.assertEqual(r.get_value(), 2)
self.assertFalse(r.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True)))
self.assertEqual(r.get_value(), 2)
for _ in range(20):
r.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True))
self.assertEqual(r.get_value(), 10)
def test_value(self) -> None:
"""
Test rangeslider value.
"""
menu = MenuUtils.generic_menu()
# Single
r = menu.add.range_slider('Range', 0.5, (0, 1), 0.1)
self.assertEqual(r.get_value(), 0.5)
self.assertFalse(r.value_changed())
r.set_value(0.8)
self.assertTrue(r.value_changed())
self.assertEqual(r.get_value(), 0.8)
r.reset_value()
self.assertEqual(r.get_value(), 0.5)
self.assertFalse(r.value_changed())
# Double
r = menu.add.range_slider('Range', [0.2, 0.6], (0, 1), 0.1)
self.assertEqual(r.get_value(), (0.2, 0.6))
self.assertFalse(r.value_changed())
self.assertRaises(AssertionError, lambda: r.set_value(0.8))
r.set_value((0.5, 1))
self.assertTrue(r.value_changed())
self.assertEqual(r.get_value(), (0.5, 1))
r.reset_value()
self.assertEqual(r.get_value(), (0.2, 0.6))
self.assertFalse(r.value_changed())
|
dcartman/pygame-menu | pygame_menu/examples/other/scrollbar.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
EXAMPLE - USE SCROLLBAR WIDGET
Shows how the ScrollBar can be used on a surface.
"""
__all__ = ['main']
import pygame
import pygame_menu
from pygame_menu.examples import create_example_window
from pygame_menu.utils import make_surface
from pygame_menu.widgets import ScrollBar
def make_world(width: int, height: int) -> 'pygame.Surface':
"""
Create a test surface.
:param width: Width in pixels
:param height: Height in pixels
:return: World surface
"""
world = make_surface(width, height)
world.fill((200, 200, 200))
color = [70, 20, 20]
max_x = len(list(range(100, width, 200)))
max_y = len(list(range(100, height, 200)))
number_x = 0
for x in range(100, width, 200):
number_y = 0
for y in range(100, height, 200):
if number_x in (0, max_x - 1) or number_y in (0, max_y - 1):
# White circles to delimit world boundaries
# noinspection PyArgumentList
pygame.draw.circle(world, (255, 255, 255), (x, y), 100, 10)
else:
# noinspection PyArgumentList
pygame.draw.circle(world, color, (x, y), 100, 10)
if color[0] + 15 < 255:
color[0] += 15
elif color[1] + 15 < 255:
color[1] += 15
else:
color[2] += 15
number_y += 1
number_x += 1
return world
def h_changed(value: int) -> None:
"""
:param value: Value data
"""
print('Horizontal position changed:', value)
def v_changed(value: int) -> None:
"""
:param value: Value data
"""
print('Vertical position changed:', value)
def main(test: bool = False) -> None:
"""
Main function.
:param test: Indicate function is being tested
"""
scr_size = (480, 480)
screen = create_example_window('Example - Scrollbar', scr_size)
world = make_world(int(scr_size[0] * 4), scr_size[1] * 3)
screen.fill((120, 90, 130))
thick_h = 20
thick_v = 40
# Horizontal ScrollBar
sb_h = ScrollBar(
length=scr_size[0] - thick_v,
values_range=(50, world.get_width() - scr_size[0] + thick_v),
slider_pad=2,
page_ctrl_thick=thick_h,
onchange=h_changed
)
sb_h.set_shadow(
color=(0, 0, 0),
position=pygame_menu.locals.POSITION_SOUTHEAST
)
sb_h.set_controls(False)
sb_h.set_position(0, scr_size[1] - thick_h)
sb_h.set_page_step(scr_size[0] - thick_v)
# Vertical ScrollBar
sb_v = ScrollBar(
length=scr_size[1] - thick_h,
values_range=(0, world.get_height() - scr_size[1] + thick_h),
orientation=pygame_menu.locals.ORIENTATION_VERTICAL,
slider_pad=6,
slider_color=(135, 193, 180),
slider_hover_color=(180, 180, 180),
page_ctrl_thick=thick_v,
page_ctrl_color=(253, 246, 220),
onchange=v_changed
)
sb_v.set_shadow(
color=(52, 54, 56),
position=pygame_menu.locals.POSITION_NORTHWEST,
offset=4
)
sb_v.set_controls(False)
sb_v.set_position(scr_size[0] - thick_v, 0)
sb_v.set_page_step(scr_size[1] - thick_h)
clock = pygame.time.Clock()
# -------------------------------------------------------------------------
# Main loop
# -------------------------------------------------------------------------
while True:
# Clock tick
clock.tick(60)
# Application events
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN and event.key == pygame.K_h:
sb_h.set_value(100)
if event.type == pygame.KEYDOWN and event.key == pygame.K_v:
sb_v.set_value(200)
sb_h.update([event])
sb_h.draw(screen)
sb_v.update([event])
sb_v.draw(screen)
trunc_world_orig = (sb_h.get_value(), sb_v.get_value())
trunc_world = (scr_size[0] - thick_v, scr_size[1] - thick_h)
# noinspection PyTypeChecker
screen.blit(world, (0, 0), (trunc_world_orig, trunc_world))
pygame.display.update()
# At first loop returns
if test:
break
if __name__ == '__main__':
main()
|
dcartman/pygame-menu | pygame_menu/widgets/selection/highlight.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
HIGHLIGHT
Widget selection highlight box effect.
"""
__all__ = ['HighlightSelection']
import pygame
import pygame_menu
from pygame_menu.widgets.core import Selection
from pygame_menu._types import NumberType
class HighlightSelection(Selection):
"""
Widget selection highlight class.
.. note::
Widget background color may not reach the entire selection area.
:param border_width: Border width of the highlight box (px)
:param margin_x: X margin of selected highlight box (px)
:param margin_y: Y margin of selected highlight box (px)
"""
_border_width: int
def __init__(
self,
border_width: int = 1,
margin_x: NumberType = 16,
margin_y: NumberType = 8
) -> None:
assert isinstance(border_width, int)
assert margin_x >= 0 and margin_y >= 0
assert border_width >= 0
margin_x = float(margin_x)
margin_y = float(margin_y)
super(HighlightSelection, self).__init__(
margin_left=margin_x / 2,
margin_right=margin_x / 2,
margin_top=margin_y / 2,
margin_bottom=margin_y / 2
)
self._border_width = border_width
# noinspection PyMissingOrEmptyDocstring
def draw(self, surface: 'pygame.Surface', widget: 'pygame_menu.widgets.Widget') -> 'HighlightSelection':
if self._border_width == 0:
return self
# noinspection PyArgumentList
pygame.draw.rect(
surface,
self.color,
self.inflate(widget.get_rect()),
self._border_width
)
return self
|
dcartman/pygame-menu | test/test_widget_selector.py | <reponame>dcartman/pygame-menu
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST WIDGET - SELECTOR
Test Selector widget.
"""
__all__ = ['SelectorWidgetTest']
from test._utils import MenuUtils, surface, PygameEventUtils, BaseTest
import pygame_menu
import pygame_menu.controls as ctrl
class SelectorWidgetTest(BaseTest):
# noinspection PyArgumentEqualDefault,PyTypeChecker
def test_selector(self) -> None:
"""
Test selector widget.
"""
menu = MenuUtils.generic_menu()
selector = menu.add.selector('selector',
[('1 - Easy', 'EASY'),
('2 - Medium', 'MEDIUM'),
('3 - Hard', 'HARD')],
default=1)
menu.enable()
menu.draw(surface)
selector.draw(surface)
selector._selected = False
selector.draw(surface)
# Test events
selector.update(PygameEventUtils.key(0, keydown=True, testmode=False))
selector.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
selector.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True))
selector.update(PygameEventUtils.key(ctrl.KEY_APPLY, keydown=True))
selector.update(PygameEventUtils.joy_hat_motion(ctrl.JOY_LEFT))
selector.update(PygameEventUtils.joy_hat_motion(ctrl.JOY_RIGHT))
selector.update(PygameEventUtils.joy_motion(1, 0))
selector.update(PygameEventUtils.joy_motion(-1, 0))
click_pos = selector.get_rect(to_real_position=True, apply_padding=False).center
selector.update(PygameEventUtils.mouse_click(click_pos[0], click_pos[1]))
# Check left/right clicks
self.assertEqual(selector.get_index(), 0)
click_pos = selector.get_rect(to_real_position=True, apply_padding=False).midleft
selector.update(PygameEventUtils.mouse_click(click_pos[0] + 150, click_pos[1]))
self.assertEqual(selector.get_index(), 2)
selector.update(PygameEventUtils.mouse_click(click_pos[0] + 150, click_pos[1]))
self.assertEqual(selector.get_index(), 1)
selector.update(PygameEventUtils.mouse_click(click_pos[0] + 150, click_pos[1]))
self.assertEqual(selector.get_index(), 0)
selector.update(PygameEventUtils.mouse_click(click_pos[0] + 250, click_pos[1]))
self.assertEqual(selector.get_index(), 1)
selector.update(PygameEventUtils.mouse_click(click_pos[0] + 250, click_pos[1]))
self.assertEqual(selector.get_index(), 2)
selector.update(PygameEventUtils.mouse_click(click_pos[0] + 250, click_pos[1]))
self.assertEqual(selector.get_index(), 0)
# Test left/right touch
click_pos = selector.get_rect(to_real_position=True, apply_padding=False).midleft
selector._touchscreen_enabled = True
selector.update(PygameEventUtils.touch_click(click_pos[0] + 150, click_pos[1],
menu=selector.get_menu()))
self.assertEqual(selector.get_index(), 2)
selector.update(PygameEventUtils.touch_click(click_pos[0] + 250, click_pos[1],
menu=selector.get_menu()))
self.assertEqual(selector.get_index(), 0)
selector.update(PygameEventUtils.touch_click(click_pos[0] + 250, click_pos[1],
menu=selector.get_menu()))
self.assertEqual(selector.get_index(), 1)
# Update elements
new_elements = [('4 - Easy', 'EASY'),
('5 - Medium', 'MEDIUM'),
('6 - Hard', 'HARD')]
selector.update_items(new_elements)
selector.set_value('6 - Hard')
self.assertEqual(selector.get_value()[1], 2)
self.assertRaises(AssertionError, lambda: selector.set_value(bool))
self.assertRaises(AssertionError, lambda: selector.set_value(200))
selector.set_value(1)
self.assertEqual(selector.get_value()[1], 1)
self.assertEqual(selector.get_value()[0][0], '5 - Medium')
selector.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
self.assertEqual(selector.get_value()[0][0], '4 - Easy')
selector.readonly = True
selector.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
self.assertEqual(selector.get_value()[0][0], '4 - Easy')
selector._left()
self.assertEqual(selector.get_value()[0][0], '4 - Easy')
selector._right()
self.assertEqual(selector.get_value()[0][0], '4 - Easy')
# Test fancy selector
sel_fancy = menu.add.selector(
'Fancy ',
[('1 - Easy', 'EASY'),
('2 - Medium', 'MEDIUM'),
('3 - Hard', 'HARD')],
default=1,
style=pygame_menu.widgets.widget.selector.SELECTOR_STYLE_FANCY
)
self.assertEqual(sel_fancy.get_items(), [('1 - Easy', 'EASY'),
('2 - Medium', 'MEDIUM'),
('3 - Hard', 'HARD')])
self.assertRaises(AssertionError, lambda: menu.add.selector(
'title', [('a', 'a'), ('b', 'b')], default=2))
def test_value(self) -> None:
"""
Test selector value.
"""
menu = MenuUtils.generic_menu()
sel = menu.add.selector('title', [('a', 'a'), ('b', 'b')], default=1)
self.assertEqual(sel.get_value(), (('b', 'b'), 1))
self.assertFalse(sel.value_changed())
sel.set_value('a')
self.assertEqual(sel.get_value(), (('a', 'a'), 0))
self.assertTrue(sel.value_changed())
sel.reset_value()
self.assertEqual(sel.get_value(), (('b', 'b'), 1))
self.assertFalse(sel.value_changed())
def test_empty_title(self) -> None:
"""
Test empty title.
"""
menu = MenuUtils.generic_menu()
sel = menu.add.selector('', [('a', 'a'), ('b', 'b')])
self.assertEqual(sel.get_size(), (83, 49))
|
dcartman/pygame-menu | test/test_version.py | <filename>test/test_version.py
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST VERSION
Test version management.
"""
__all__ = ['VersionTest']
from test._utils import BaseTest
import pygame_menu
class VersionTest(BaseTest):
def test_version(self) -> None:
"""
Test version.
"""
self.assertTrue(isinstance(pygame_menu.version.ver, str))
self.assertTrue(isinstance(repr(pygame_menu.version.vernum), str))
self.assertTrue(isinstance(str(pygame_menu.version.vernum), str))
|
dcartman/pygame-menu | pygame_menu/__pyinstaller/hook-pygame_menu.py | <reponame>dcartman/pygame-menu
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
PYGAME-MENU HOOK
Used by Pyinstaller.
"""
import os
# noinspection PyProtectedMember
from pygame_menu import __file__ as pygame_menu_main_file
# Get pygame_menu's folder
pygame_menu_folder = os.path.dirname(os.path.abspath(pygame_menu_main_file))
# datas is the variable that pyinstaller looks for while processing hooks
datas = []
# A helper to append the relative path of a resource to hook variable - datas
def _append_to_datas(file_path: str, target_folder: str, base_target_folder: str = 'pygame_menu',
relative: bool = True) -> None:
"""
Add path to datas.
:param file_path: File path
:param target_folder: Folder to paste the resources. If empty uses the containing folder of the file as ``base_target_folder+target_folder``
:param base_target_folder: Base folder of the resource
:param relative: If ``True`` append ``pygame_menu_folder``
"""
global datas
if relative:
res_path = os.path.join(pygame_menu_folder, file_path)
else:
res_path = file_path
if target_folder == '':
target_folder = os.path.basename(os.path.dirname(res_path))
if os.path.exists(res_path):
datas.append((res_path, os.path.join(base_target_folder, target_folder)))
# Append data
from pygame_menu.font import FONT_EXAMPLES
from pygame_menu.baseimage import IMAGE_EXAMPLES
from pygame_menu.sound import SOUND_EXAMPLES
pygame_menu_resources = os.path.join('pygame_menu', 'resources')
for f in FONT_EXAMPLES:
_append_to_datas(f, target_folder='', base_target_folder=pygame_menu_resources)
for f in IMAGE_EXAMPLES:
_append_to_datas(f, target_folder='', base_target_folder=pygame_menu_resources)
for f in SOUND_EXAMPLES:
_append_to_datas(f, target_folder='', base_target_folder=pygame_menu_resources)
|
dcartman/pygame-menu | pygame_menu/widgets/selection/__init__.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
SELECTION
This module contains the widget highlight effects.
"""
from pygame_menu.widgets.selection.highlight import HighlightSelection
from pygame_menu.widgets.selection.left_arrow import LeftArrowSelection
from pygame_menu.widgets.selection.none import NoneSelection
from pygame_menu.widgets.selection.right_arrow import RightArrowSelection
from pygame_menu.widgets.selection.simple import SimpleSelection
|
dcartman/pygame-menu | test/test_widget_frame.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST WIDGET - FRAME
Test Frame. Frame is the most complex widget as this interacts with menu, modifies
its layout and contains other widgets.
"""
__all__ = ['FrameWidgetTest']
from test._utils import MenuUtils, surface, PygameEventUtils, test_reset_surface, \
TEST_THEME, PYGAME_V2, WIDGET_MOUSEOVER, reset_widgets_over, THEME_NON_FIXED_TITLE
import unittest
import pygame
import pygame_menu
import pygame_menu.controls as ctrl
from pygame_menu.locals import ORIENTATION_VERTICAL, ORIENTATION_HORIZONTAL, \
POSITION_SOUTHEAST
from pygame_menu.utils import set_pygame_cursor, get_cursor
from pygame_menu.widgets import Button
from pygame_menu.widgets.core.widget import WidgetTransformationNotImplemented
# noinspection PyProtectedMember
from pygame_menu._scrollarea import get_scrollbars_from_position
# noinspection PyProtectedMember
from pygame_menu.widgets.widget.frame import _FrameDoNotAcceptScrollarea
class FrameWidgetTest(unittest.TestCase):
def setUp(self) -> None:
"""
Setup frame widget test.
"""
test_reset_surface()
def test_general(self) -> None:
"""
Test frame widget containers.
"""
menu = MenuUtils.generic_menu(theme=TEST_THEME.copy())
menu.add.button('rr')
frame = menu.add.frame_h(250, 100, background_color=(200, 0, 0))
frame._pack_margin_warning = False
btn = menu.add.button('nice1')
menu.add.button('44')
frame2 = menu.add.frame_v(50, 250, background_color=(0, 0, 200))
frame2._pack_margin_warning = False
btn2 = menu.add.button('nice2')
btn3 = menu.add.button('nice3')
frame11 = menu.add.frame_v(50, 90, background_color=(0, 200, 0))
frame11._pack_margin_warning = False
btn11 = menu.add.button('11')
btn12 = menu.add.button('12')
frame11.pack(btn11)
frame11.pack(btn12)
frame.pack(btn)
frame.pack(btn2, pygame_menu.locals.ALIGN_CENTER, vertical_position=pygame_menu.locals.POSITION_CENTER)
frame.pack(frame11, pygame_menu.locals.ALIGN_RIGHT, vertical_position=pygame_menu.locals.POSITION_SOUTH)
frame2.pack(menu.add.button('1'))
frame2.pack(menu.add.button('2'), align=pygame_menu.locals.ALIGN_CENTER)
frame2.pack(menu.add.button('3'), align=pygame_menu.locals.ALIGN_RIGHT)
for w in frame.get_widgets():
w.get_selection_effect().zero_margin()
for w in frame2.get_widgets():
w.get_selection_effect().zero_margin()
menu.render()
wid = menu.get_widgets()
self.assertEqual(wid[0].get_col_row_index(), (0, 0, 0))
self.assertEqual(wid[1].get_col_row_index(), (0, 1, 1))
self.assertEqual(wid[2].get_col_row_index(), (0, 1, 2))
self.assertEqual(wid[3].get_col_row_index(), (0, 1, 3))
self.assertEqual(wid[4].get_col_row_index(), (0, 1, 4))
self.assertEqual(wid[5].get_col_row_index(), (0, 1, 5))
self.assertEqual(wid[6].get_col_row_index(), (0, 1, 6))
self.assertEqual(wid[7].get_col_row_index(), (0, 2, 7))
self.assertEqual(wid[8].get_col_row_index(), (0, 3, 8))
self.assertEqual(wid[9].get_col_row_index(), (0, 3, 9))
self.assertEqual(wid[10].get_col_row_index(), (0, 3, 10))
self.assertEqual(wid[11].get_col_row_index(), (0, 3, 11))
self.assertEqual(wid[12].get_col_row_index(), (0, 4, 12))
self.assertIsNone(btn3.get_frame())
self.assertEqual(btn2.get_frame(), frame)
self.assertEqual(btn2.get_translate(), (0, 0))
self.assertEqual(btn2.get_translate(virtual=True), (88, 29))
self.assertFalse(btn2.is_floating())
menu.remove_widget(btn2)
self.assertIsNone(btn2.get_frame())
self.assertEqual(btn2.get_translate(), (0, 0))
self.assertEqual(btn2.get_translate(virtual=True), (0, 0))
self.assertTrue(btn2.is_floating())
wid = menu.get_widgets()
self.assertEqual(wid[0].get_position(), (278, 5))
self.assertEqual(wid[1].get_position(), (165, 56 if PYGAME_V2 else 57))
self.assertEqual(wid[2].get_position(), (165, 56 if PYGAME_V2 else 57))
self.assertEqual(wid[3].get_position(), (365, 66 if PYGAME_V2 else 67))
self.assertEqual(wid[4].get_position(), (365, 66 if PYGAME_V2 else 67))
self.assertEqual(wid[5].get_position(), (365, 107 if PYGAME_V2 else 109))
self.assertEqual(wid[6].get_position(), (273, 166 if PYGAME_V2 else 167))
self.assertEqual(wid[7].get_position(), (265, 217 if PYGAME_V2 else 219))
self.assertEqual(wid[8].get_position(), (265, 217 if PYGAME_V2 else 219))
self.assertEqual(wid[9].get_position(), (281, 258 if PYGAME_V2 else 261))
self.assertEqual(wid[10].get_position(), (298, 299 if PYGAME_V2 else 303))
self.assertEqual(wid[11].get_position(), (253, 477 if PYGAME_V2 else 479))
theme = TEST_THEME.copy()
menu = MenuUtils.generic_menu(theme=theme)
menu.get_theme().widget_selection_effect.zero_margin()
menu.get_theme().widget_font_size = 18
frame = menu.add.frame_v(250, 150, background_color=(50, 50, 50))
frame._pack_margin_warning = False
frame_title = menu.add.frame_h(250, 30, background_color=(180, 180, 180))
frame_title._pack_margin_warning = False
frame_content = menu.add.frame_v(250, 120)
frame_content._pack_margin_warning = False
frame.pack(frame_title)
frame.pack(frame_content)
frame_title.pack(menu.add.label('Settings'), margin=(2, 2))
close_btn = frame_title.pack(
menu.add.button('Close', pygame_menu.events.EXIT, padding=(0, 5), background_color=(160, 160, 160)),
align=pygame_menu.locals.ALIGN_RIGHT, margin=(-2, 2))
frame_content.pack(menu.add.label('Pick a number', font_color=(150, 150, 150)),
align=pygame_menu.locals.ALIGN_CENTER)
frame_numbers = menu.add.frame_h(250, 42, background_color=(255, 255, 255), font_color=(2000, 0, 0),
frame_id='frame_numbers')
frame_numbers._pack_margin_warning = False
frame_content.pack(frame_numbers)
for i in range(9):
frame_numbers.pack(menu.add.button(i, font_color=(5 * i, 11 * i, 13 * i), font_size=30),
align=pygame_menu.locals.ALIGN_CENTER)
self.assertRaises(AssertionError, lambda: frame_numbers.pack(close_btn))
frame_content.pack(menu.add.vertical_margin(15))
frame_content.pack(menu.add.toggle_switch('Nice toggle', False, width=100, font_color=(150, 150, 150)),
align=pygame_menu.locals.ALIGN_CENTER)
menu.render()
self.assertEqual(menu.get_width(widget=True), 250)
self.assertEqual(menu.get_height(widget=True), 150)
self.assertEqual(menu._widget_offset[1], 97)
self.assertEqual(frame_numbers.get_widgets()[0].get_translate(), (0, 0))
self.assertEqual(frame_numbers.get_widgets()[0].get_translate(virtual=True), (48, 0))
self.assertEqual(frame_numbers.get_widgets()[0].get_position(), (223, 153 if PYGAME_V2 else 154))
self.assertEqual(frame_numbers._recursive_render, 0)
prev_widg = frame_numbers.get_widgets()
c_widget = frame_numbers._control_widget
self.assertEqual(c_widget, prev_widg[0])
frame_numbers.unpack(c_widget)
self.assertTrue(c_widget.is_floating())
self.assertIn(c_widget, menu.get_widgets())
self.assertRaises(ValueError, lambda: frame_numbers.unpack(prev_widg[0]))
self.assertEqual(frame_numbers._control_widget, prev_widg[1])
for w in frame_numbers.get_widgets():
frame_numbers.unpack(w)
self.assertEqual(len(frame_numbers._widgets), 0)
self.assertRaises(AssertionError, lambda: frame_numbers.unpack(prev_widg[0]))
# Test sizes
size_exception = pygame_menu.widgets.widget.frame._FrameSizeException
self.assertFalse(frame_numbers._relax)
self.assertEqual(len(frame_numbers.get_widgets(unpack_subframes_include_frame=True)), 0)
self.assertRaises(size_exception, lambda: frame_numbers.pack(menu.add.frame_v(100, 400)))
self.assertRaises(size_exception, lambda: frame_numbers.pack(menu.add.frame_v(400, 10)))
self.assertEqual(len(frame_numbers.get_widgets(unpack_subframes_include_frame=True)), 0)
frame_numbers.pack(menu.add.frame_v(10, 10), align=pygame_menu.locals.ALIGN_CENTER)
frame_numbers.pack(menu.add.frame_v(10, 10), align=pygame_menu.locals.ALIGN_RIGHT)
frame_numbers.pack(menu.add.frame_v(10, 10))
frame_v = menu.add.frame_v(400, 100, font_color=(2000, 0, 0)) # Clearly an invalid font color
frame_v._pack_margin_warning = False
self.assertRaises(size_exception, lambda: frame_v.pack(menu.add.frame_v(100, 400)))
self.assertRaises(size_exception, lambda: frame_v.pack(menu.add.frame_v(500, 100)))
frame_v.pack(menu.add.frame_v(25, 25), vertical_position=pygame_menu.locals.POSITION_CENTER)
frame_v.pack(menu.add.frame_v(25, 25), vertical_position=pygame_menu.locals.POSITION_CENTER)
frame_v.pack(menu.add.frame_v(25, 25), vertical_position=pygame_menu.locals.POSITION_CENTER)
frame_v.pack(menu.add.frame_v(25, 25), vertical_position=pygame_menu.locals.POSITION_SOUTH)
self.assertRaises(size_exception, lambda: frame_v.pack(menu.add.frame_v(100, 1)))
# Apply transforms
wid = frame_v
wid.set_position(1, 1)
self.assertEqual(wid.get_position(), (1, 1))
wid.translate(1, 1)
self.assertEqual(wid.get_translate(), (1, 1))
self.assertRaises(WidgetTransformationNotImplemented, lambda: wid.rotate(10))
self.assertEqual(wid._angle, 0)
self.assertRaises(WidgetTransformationNotImplemented, lambda: wid.scale(100, 100))
self.assertFalse(wid._scale[0])
self.assertEqual(wid._scale[1], 1)
self.assertEqual(wid._scale[2], 1)
wid.resize(10, 10)
self.assertFalse(wid._scale[0])
self.assertEqual(wid._scale[1], 1)
self.assertEqual(wid._scale[2], 1)
self.assertRaises(WidgetTransformationNotImplemented, lambda: wid.flip(True, True))
self.assertFalse(wid._flip[0])
self.assertFalse(wid._flip[1])
self.assertRaises(WidgetTransformationNotImplemented, lambda: wid.set_max_width(100))
self.assertIsNone(wid._max_width[0])
self.assertRaises(WidgetTransformationNotImplemented, lambda: wid.set_max_height(100))
self.assertIsNone(wid._max_height[0])
# Selection
wid.select()
self.assertFalse(wid.is_selected())
self.assertFalse(wid.is_selectable)
w_eff = wid.get_selection_effect()
wid.set_selection_effect(menu.get_theme().widget_selection_effect)
self.assertEqual(wid.get_selection_effect(), w_eff)
draw = [False]
# noinspection PyUnusedLocal
def _draw(*args) -> None:
draw[0] = True
draw_id = wid.add_draw_callback(_draw)
wid.draw(surface)
self.assertTrue(draw[0])
draw[0] = False
wid.remove_draw_callback(draw_id)
wid.draw(surface)
self.assertFalse(draw[0])
wid._draw(surface)
wid.update([])
# Test frame with Widgets not included in same menu
frame_v.clear()
self.assertEqual(frame_v.get_widgets(), ())
b1 = frame_v.pack(menu.add.button('v1'))
b2 = frame_v.pack(menu.add.button('v1'))
self.assertFalse(b1.is_floating())
self.assertFalse(b2.is_floating())
self.assertEqual(b1.get_frame(), frame_v)
self.assertEqual(b2.get_frame(), frame_v)
self.assertEqual(b1.get_translate(virtual=True), (0, 0))
self.assertEqual(b2.get_translate(virtual=True), (0, 25 if PYGAME_V2 else 26))
menu.remove_widget(frame_v)
self.assertTrue(b1.is_floating())
self.assertTrue(b2.is_floating())
self.assertIsNone(b1.get_frame())
self.assertIsNone(b2.get_frame())
self.assertIsNone(frame_v.get_menu())
self.assertEqual(b1.get_translate(virtual=True), (0, 0))
self.assertEqual(b2.get_translate(virtual=True), (0, 0))
# Test widget addition on frame which is not inserted in a menu
self.assertRaises(AssertionError, lambda: frame_v.pack(menu.add.button('invalid')))
h = menu.add.frame_h(400, 300, background_color=(0, 60, 80))
btn = pygame_menu.widgets.Button('button')
self.assertRaises(AssertionError, lambda: h.pack(btn)) # Not configured
menu.add.configure_defaults_widget(btn)
h.pack(btn)
h.pack(menu.add.button('button legit'))
self.assertTrue(h.contains_widget(btn))
def test_value(self) -> None:
"""
Test frame value.
"""
menu = MenuUtils.generic_menu()
f = menu.add.frame_v(300, 800)
self.assertRaises(ValueError, lambda: f.get_value())
self.assertRaises(ValueError, lambda: f.set_value('value'))
self.assertFalse(f.value_changed())
f.reset_value()
def test_make_scrollarea(self) -> None:
"""
Test make scrollarea.
"""
menu = MenuUtils.generic_menu()
f = menu.add.frame_v(300, 800, frame_id='f1')
# Test invalid settings
create_sa = lambda: f.make_scrollarea(200, 300, 'red', 'white', None, True, 'red', 1,
POSITION_SOUTHEAST, 'yellow', 'green', 0, 20,
get_scrollbars_from_position(POSITION_SOUTHEAST))
create_sa()
# Disable
f._accepts_scrollarea = False
self.assertRaises(_FrameDoNotAcceptScrollarea, create_sa)
f._accepts_scrollarea = True
# Test none
f._has_title = True
f.make_scrollarea(None, None, 'red', 'white', None, True, 'red', 1,
POSITION_SOUTHEAST, 'yellow', 'green', 0, 20,
get_scrollbars_from_position(POSITION_SOUTHEAST))
create_sa()
self.assertRaises(AssertionError, lambda: f.set_scrollarea(f._frame_scrollarea))
def test_sort(self) -> None:
"""
Test frame sorting.
"""
menu = MenuUtils.generic_menu()
b0 = menu.add.button('b0')
b1 = menu.add.button('b1')
b2 = menu.add.button('b2')
b3 = menu.add.button('b3')
f1 = menu.add.frame_v(300, 800, frame_id='f1')
f2 = menu.add.frame_v(200, 500, frame_id='f2')
# Test basics
self.assertEqual(f1.get_size(), (300, 800))
self.assertEqual(f2.get_size(), (200, 500))
self.assertEqual(menu._widgets, [b0, b1, b2, b3, f1, f2])
f1.pack(b1)
self.assertEqual(b1.get_frame(), f1)
self.assertEqual(menu._widgets, [b0, b2, b3, f1, b1, f2])
f2.pack(b3)
self.assertEqual(menu._widgets, [b0, b2, f1, b1, f2, b3])
f1.pack(b2)
self.assertEqual(menu._widgets, [b0, f1, b1, b2, f2, b3])
f1.pack(f2)
self.assertEqual(menu._widgets, [b0, f1, b1, b2, f2, b3])
self.assertEqual(menu.get_selected_widget(), b0)
# Add two more buttons
b4 = menu.add.button('b4')
self.assertEqual(menu._widgets, [b0, f1, b1, b2, f2, b3, b4])
b5 = menu.add.button('b5')
self.assertEqual(menu._widgets, [b0, f1, b1, b2, f2, b3, b4, b5])
# Test positioning
self.assertEqual(f1.get_indices(), (2, 4))
self.assertEqual(f2.get_indices(), (5, 5))
f2.pack(b5)
self.assertEqual(menu._widgets, [b0, f1, b1, b2, f2, b3, b5, b4])
f1.pack(b0)
self.assertEqual(menu.get_selected_widget(), b0)
self.assertEqual(menu._widgets, [f1, b1, b2, f2, b3, b5, b0, b4])
f1.pack(b4)
self.assertEqual(menu._widgets, [f1, b1, b2, f2, b3, b5, b0, b4])
self.assertRaises(AssertionError, lambda: f1.pack(b4))
self.assertRaises(AssertionError, lambda: f1.pack(b3))
self.assertEqual(f2.get_frame(), f1)
self.assertEqual(f2.get_frame_depth(), 1)
self.assertEqual(b3.get_frame(), f2)
self.assertEqual(b3.get_frame_depth(), 2)
self.assertEqual(f1.get_indices(), (1, 7))
self.assertEqual(f2.get_indices(), (4, 5))
# Unpack f2
f1.unpack(f2)
self.assertEqual(menu._widgets, [f1, b1, b2, b0, b4, f2, b3, b5])
self.assertEqual(f1.get_indices(), (1, 4))
self.assertEqual(f2.get_indices(), (6, 7))
# Create new frame 3, inside 2
f3 = menu.add.frame_h(150, 200, frame_id='f3')
f2.pack(f3)
self.assertEqual(f3.get_indices(), (-1, -1))
self.assertEqual(menu._widgets, [f1, b1, b2, b0, b4, f2, b3, b5, f3])
self.assertEqual(b1, f3.pack(f1.unpack(b1)))
self.assertEqual(menu._widgets, [f1, b2, b0, b4, f2, b3, b5, f3, b1])
# Create container frame
f4 = menu.add.frame_v(400, 1500, frame_id='f4')
self.assertIsNone(f2.get_frame())
f4.pack(f2)
self.assertEqual(menu._widgets, [f1, b2, b0, b4, f4, f2, b3, b5, f3, b1])
f4.pack(f1.unpack(b2))
self.assertEqual(menu._widgets, [f1, b0, b4, f4, f2, b3, b5, f3, b1, b2])
# Sort two widgets
self.assertEqual(len(menu._update_frames), 0)
menu.move_widget_index(b2, f2)
self.assertEqual(menu._widgets, [f1, b0, b4, f4, b2, f2, b3, b5, f3, b1])
self.assertRaises(AssertionError, lambda: menu.move_widget_index(b2, b3))
menu.move_widget_index(b3, b5)
self.assertEqual(menu._widgets, [f1, b0, b4, f4, b2, f2, b5, b3, f3, b1])
menu.move_widget_index(f3, b5)
self.assertEqual(menu._widgets, [f1, b0, b4, f4, b2, f2, f3, b1, b5, b3])
f3.pack(f2.unpack(b5))
self.assertEqual(menu._widgets, [f1, b0, b4, f4, b2, f2, f3, b1, b5, b3])
menu.move_widget_index(b1, b5)
self.assertEqual(menu._widgets, [f1, b0, b4, f4, b2, f2, f3, b5, b1, b3])
menu.move_widget_index(b3, f3)
self.assertEqual(menu._widgets, [f1, b0, b4, f4, b2, f2, b3, f3, b5, b1])
menu.move_widget_index(f3, b3)
self.assertEqual(menu._widgets, [f1, b0, b4, f4, b2, f2, f3, b5, b1, b3])
self.assertEqual(menu.get_selected_widget(), b0)
# Test advanced packing
f4.pack(f1)
self.assertEqual(menu._widgets, [f4, b2, f2, f3, b5, b1, b3, f1, b0, b4])
f4.unpack(f2)
self.assertEqual(menu._widgets, [f4, b2, f1, b0, b4, f2, f3, b5, b1, b3])
menu.remove_widget(f4)
self.assertIsNone(b2.get_frame())
self.assertIsNone(f1.get_frame())
self.assertEqual(b0.get_frame(), f1)
self.assertEqual(b4.get_frame(), f1)
self.assertEqual(menu._widgets, [f2, f3, b5, b1, b3, b2, f1, b0, b4])
f3.pack(f1)
self.assertEqual(menu._widgets, [f2, f3, b5, b1, f1, b0, b4, b3, b2])
# Assert limits
self.assertEqual(f1.get_indices(), (5, 6))
self.assertEqual(f2.get_indices(), (1, 7))
self.assertEqual(f3.get_indices(), (2, 4))
self.assertEqual(f4.get_indices(), (-1, -1))
f2.pack(b2)
self.assertEqual(menu._widgets, [f2, f3, b5, b1, f1, b0, b4, b3, b2])
self.assertEqual(f1.get_indices(), (5, 6))
self.assertEqual(f2.get_indices(), (1, 8))
self.assertEqual(f3.get_indices(), (2, 4))
self.assertEqual(f4.get_indices(), (-1, -1))
f2.pack(f3.unpack(f1))
self.assertEqual(menu._widgets, [f2, f3, b5, b1, b3, b2, f1, b0, b4])
f2.pack(f2.unpack(f3))
self.assertEqual(menu._widgets, [f2, b3, b2, f1, b0, b4, f3, b5, b1])
self.assertEqual(f1.get_indices(), (4, 5))
self.assertEqual(f2.get_indices(), (1, 6))
self.assertEqual(f3.get_indices(), (7, 8))
# Unpack f3 and move to first
f2.unpack(f3)
menu.move_widget_index(f3, f2)
self.assertEqual(menu._widgets, [f3, b5, b1, f2, b3, b2, f1, b0, b4])
self.assertEqual(f1.get_indices(), (7, 8))
self.assertEqual(f2.get_indices(), (4, 6))
self.assertEqual(f3.get_indices(), (1, 2))
# Remove b5
menu.remove_widget(b5)
self.assertNotIn(b5, f1.get_widgets())
self.assertEqual(b5.get_menu(), b5.get_frame())
# Add again b5, this time this widget is not within menu
f3.pack(b5)
self.assertRaises(AssertionError, lambda: f3.pack(f4))
self.assertIsNone(f4.get_menu())
f3.pack(f2.unpack(b3))
self.assertEqual(f3.get_widgets(unpack_subframes=False), (b1, b5, b3))
menu.move_widget_index(b1, b3)
self.assertEqual(f3.get_widgets(unpack_subframes=False), (b3, b1, b5))
self.assertEqual(f2.get_indices(), (4, 5))
self.assertEqual(f1.get_indices(), (6, 7))
menu.remove_widget(b4)
self.assertEqual(f2.get_indices(), (4, 5))
self.assertEqual(f1.get_indices(), (6, 6))
menu.move_widget_index(b3, b1)
self.assertEqual(f3.get_widgets(unpack_subframes=False), (b1, b5, b3))
self.assertRaises(AssertionError, lambda: menu.move_widget_index(b1, 5))
self.assertRaises(AssertionError, lambda: menu.move_widget_index(b1, 1))
menu.move_widget_index(b3, 1)
f3.pack(b4)
self.assertEqual(f3.get_widgets(unpack_subframes=False), (b3, b1, b5, b4))
self.assertEqual(menu._widgets, [f3, b3, b1, f2, b2, f1, b0])
# Sort two frames, considering non-menu widgets
menu.move_widget_index(f3, f2)
self.assertEqual(menu._widgets, [f2, b2, f1, b0, f3, b3, b1])
self.assertEqual(f3.get_widgets(unpack_subframes=False), (b3, b1, b5, b4))
# Rollback
menu.move_widget_index(f3, f2)
self.assertEqual(menu._widgets, [f3, b3, b1, f2, b2, f1, b0])
# Add non-menu to last frame within frame
f1.pack(f3.unpack(b4))
self.assertEqual(f3.get_widgets(unpack_subframes=False), (b3, b1, b5))
self.assertEqual(f1.get_widgets(unpack_subframes=False), (b0, b4))
# Move again
menu.move_widget_index(f3, f2)
self.assertEqual(menu._widgets, [f2, b2, f1, b0, f3, b3, b1])
menu.move_widget_index(f3, f2)
self.assertEqual(menu._widgets, [f3, b3, b1, f2, b2, f1, b0])
# Move, but 3 frame in same levels
f2.unpack(f1)
self.assertEqual(menu.get_selected_widget(), b0)
menu.move_widget_index(f1, f3)
self.assertEqual(menu._widgets, [f1, b0, f3, b3, b1, f2, b2])
menu.move_widget_index(f2, f3)
self.assertEqual(menu._widgets, [f1, b0, f2, b2, f3, b3, b1])
menu.move_widget_index(f2, f3)
self.assertEqual(menu._widgets, [f1, b0, f3, b3, b1, f2, b2])
menu.move_widget_index(f3, f2)
self.assertEqual(menu._widgets, [f1, b0, f2, b2, f3, b3, b1])
menu.move_widget_index(None)
self.assertEqual(menu._widgets, [f3, b3, b1, f2, b2, f1, b0])
self.assertEqual(menu.get_selected_widget(), b0)
# Add really long nested frames
f_rec = []
n = 10
for i in range(n):
f_rec.append(menu.add.frame_v(100, 100, frame_id=f'f_rec{i}'))
f_rec[i].relax()
if i >= 1:
f_rec[i - 1].pack(f_rec[i])
# Check indices
for i in range(n):
self.assertEqual(f_rec[i].get_indices(), (-1, -1))
self.assertEqual(f_rec[i].get_frame(), None if i == 0 else f_rec[i - 1])
self.assertEqual(menu._widgets, [f3, b3, b1, f2, b2, f1, b0, *f_rec])
# Test frame with none menu as first
self.assertEqual(f1.get_widgets(), (b0, b4))
f1.pack(f1.unpack(b0))
self.assertEqual(f1.get_widgets(), (b4, b0))
self.assertEqual(menu._widgets, [f3, b3, b1, f2, b2, f1, b0, *f_rec])
# Move widgets
menu.move_widget_index(f2, f_rec[0])
self.assertEqual(menu._widgets, [f3, b3, b1, *f_rec, f2, b2, f1, b0])
menu.move_widget_index(f3, f_rec[0])
self.assertEqual(menu._widgets, [*f_rec, f3, b3, b1, f2, b2, f1, b0])
menu.move_widget_index(f3, f2)
self.assertEqual(menu._widgets, [*f_rec, f2, b2, f3, b3, b1, f1, b0])
menu.move_widget_index(f3, f_rec[0])
self.assertEqual(menu._widgets, [f3, b3, b1, *f_rec, f2, b2, f1, b0])
# Add button to deepest frame
f_rec[-1].pack(f3.unpack(b3))
self.assertEqual(menu.get_selected_widget(), b0)
for i in range(n):
self.assertEqual(f_rec[i].get_indices(), (3 + i, 3 + i))
menu.select_widget(b3)
for w in [b1, b0, b2, b3]:
menu._down()
self.assertEqual(menu.get_selected_widget(), w)
# Unpack button from recursive
f3.pack(f_rec[-1].unpack(b3))
for i in range(n):
self.assertEqual(f_rec[i].get_indices(), (-1, -1))
for w in [b1, b0, b2, b3]:
menu._down()
self.assertEqual(menu.get_selected_widget(), w)
for w in [b2, b0, b1, b3]:
menu._up()
self.assertEqual(menu.get_selected_widget(), w)
menu._test_print_widgets()
# noinspection SpellCheckingInspection
def test_scrollarea(self) -> None:
"""
Test scrollarea frame.
"""
menu = MenuUtils.generic_menu(theme=THEME_NON_FIXED_TITLE)
self.assertRaises(AssertionError, lambda: menu.add.frame_v(300, 400, max_width=400))
self.assertRaises(AssertionError, lambda: menu.add.frame_v(300, 400, max_height=500))
self.assertRaises(AssertionError, lambda: menu.add.frame_v(300, 400, max_height=-1))
img = pygame_menu.BaseImage(pygame_menu.baseimage.IMAGE_EXAMPLE_PYGAME_MENU)
frame_sc = menu.add.frame_v(300, 400, max_height=200, background_color=img, frame_id='frame_sc')
frame_scroll = frame_sc.get_scrollarea(inner=True)
frame2 = menu.add.frame_v(400, 200, background_color=(30, 30, 30), padding=25)
menu.add.frame_v(300, 200, background_color=(255, 255, 0))
self.assertIsNone(menu.get_selected_widget())
btn_frame21 = frame2.pack(menu.add.button('Button frame nosc'))
btn_frame22 = frame2.pack(menu.add.button('Button frame nosc 2'))
btn = frame_sc.pack(menu.add.button('Nice', lambda: print('Clicked'), padding=10))
btn2 = frame_sc.pack(menu.add.button('Nice2', lambda: print('Clicked'), padding=10))
btn3 = frame_sc.pack(menu.add.button('Nice3', lambda: print('Clicked'), padding=10))
btn4 = frame_sc.pack(menu.add.button('Nice4', lambda: print('Clicked'), padding=10))
btn5 = frame_sc.pack(menu.add.button('Nice5', lambda: print('Clicked'), padding=10))
btn_real = menu.add.button('Normal button', lambda: print('Clicked'), background_color=(255, 0, 255))
# First, test structure
# btn \
# btn2 |
# btn3 | frame_sc scrollarea enabled
# btn4 |
# btn5 /
# btn_frame21 (x) \ frame2 no scrollarea <-- selected by default
# btn_frame22 /
# btn_real
self.assertTrue(frame_sc.is_scrollable)
self.assertFalse(frame2.is_scrollable)
self.assertEqual(btn.get_frame(), frame_sc)
self.assertEqual(btn2.get_frame(), frame_sc)
self.assertEqual(btn.get_scrollarea(), frame_sc.get_scrollarea(inner=True))
self.assertIsNone(btn_real.get_frame())
self.assertEqual(btn_real.get_scrollarea(), menu.get_scrollarea())
self.assertEqual(btn_frame21.get_frame(), frame2)
self.assertEqual(btn_frame22.get_frame(), frame2)
self.assertTrue(btn_frame21.is_selected())
self.assertEqual(frame_scroll.get_parent(), menu.get_scrollarea())
btn_frame21.active = True
menu._mouse_motion_selection = True
self.assertEqual(
menu._draw_focus_widget(surface, btn_frame21),
{1: ((0, 0), (600, 0), (600, 158 if PYGAME_V2 else 158), (0, 158 if PYGAME_V2 else 158)),
2: ((0, 159 if PYGAME_V2 else 159), (114, 159 if PYGAME_V2 else 159),
(114, 207 if PYGAME_V2 else 208), (0, 207 if PYGAME_V2 else 208)),
3: ((390, 159 if PYGAME_V2 else 159), (600, 159 if PYGAME_V2 else 159),
(600, 207 if PYGAME_V2 else 208), (390, 207 if PYGAME_V2 else 208)),
4: ((0, 208 if PYGAME_V2 else 209), (600, 208 if PYGAME_V2 else 209), (600, 600), (0, 600))}
)
btn_frame21.active = False
# Test scrollareas position
vpos = 0.721
vpos2 = 0.56
vpos3 = 0.997
vpos4 = 0
if PYGAME_V2:
self.assertEqual(menu.get_selected_widget(), btn_frame21)
self.assertAlmostEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_VERTICAL), vpos)
self.assertEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_HORIZONTAL), -1)
self.assertEqual(frame_scroll.get_scroll_value_percentage(ORIENTATION_VERTICAL), 0)
menu.update(PygameEventUtils.key(ctrl.KEY_MOVE_UP, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn_frame22)
self.assertAlmostEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_VERTICAL), vpos)
self.assertEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_HORIZONTAL), -1)
self.assertEqual(frame_scroll.get_scroll_value_percentage(ORIENTATION_VERTICAL), 0)
menu.update(PygameEventUtils.key(ctrl.KEY_MOVE_DOWN, keydown=True))
menu.update(PygameEventUtils.key(ctrl.KEY_MOVE_DOWN, keydown=True))
self.assertEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_VERTICAL), vpos4)
self.assertAlmostEqual(frame_scroll.get_scroll_value_percentage(ORIENTATION_VERTICAL), vpos2)
self.assertEqual(menu.get_selected_widget(), btn5)
menu.update(PygameEventUtils.key(ctrl.KEY_MOVE_DOWN, keydown=True))
self.assertEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_VERTICAL), vpos4)
self.assertAlmostEqual(frame_scroll.get_scroll_value_percentage(ORIENTATION_VERTICAL), vpos2)
self.assertEqual(menu.get_selected_widget(), btn4)
menu.update(PygameEventUtils.key(ctrl.KEY_MOVE_DOWN, keydown=True))
self.assertEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_VERTICAL), vpos4)
self.assertAlmostEqual(frame_scroll.get_scroll_value_percentage(ORIENTATION_VERTICAL), vpos2)
self.assertEqual(menu.get_selected_widget(), btn3)
menu.update(PygameEventUtils.key(ctrl.KEY_MOVE_DOWN, keydown=True))
self.assertEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_VERTICAL), vpos4)
self.assertAlmostEqual(frame_scroll.get_scroll_value_percentage(ORIENTATION_VERTICAL), 0.305)
self.assertEqual(menu.get_selected_widget(), btn2)
menu.update(PygameEventUtils.key(ctrl.KEY_MOVE_DOWN, keydown=True))
self.assertEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_VERTICAL), vpos4)
self.assertAlmostEqual(frame_scroll.get_scroll_value_percentage(ORIENTATION_VERTICAL), 0)
self.assertEqual(menu.get_selected_widget(), btn)
menu.update(PygameEventUtils.key(ctrl.KEY_MOVE_DOWN, keydown=True))
self.assertAlmostEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_VERTICAL), vpos3)
self.assertAlmostEqual(frame_scroll.get_scroll_value_percentage(ORIENTATION_VERTICAL), 0)
self.assertEqual(menu.get_selected_widget(), btn_real)
menu.update(PygameEventUtils.key(ctrl.KEY_MOVE_DOWN, keydown=True))
menu.update(PygameEventUtils.key(ctrl.KEY_MOVE_DOWN, keydown=True))
menu.update(PygameEventUtils.key(ctrl.KEY_MOVE_DOWN, keydown=True))
self.assertEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_VERTICAL), vpos4)
self.assertAlmostEqual(frame_scroll.get_scroll_value_percentage(ORIENTATION_VERTICAL), vpos2)
self.assertEqual(menu.get_selected_widget(), btn5)
else:
menu.select_widget(btn5)
# Test active within scroll
btn5.active = True
self.assertEqual(
menu._draw_focus_widget(surface, btn5),
{1: ((0, 0), (600, 0), (600, 287 if PYGAME_V2 else 285), (0, 287 if PYGAME_V2 else 285)),
2: ((0, 288 if PYGAME_V2 else 286), (137, 288 if PYGAME_V2 else 286), (137, 347), (0, 347)),
3: ((237, 288 if PYGAME_V2 else 286), (600, 288 if PYGAME_V2 else 286), (600, 347), (237, 347)),
4: ((0, 348), (600, 348), (600, 600), (0, 600))}
)
btn5.active = False
btn.select(update_menu=True)
self.assertEqual(btn.get_rect(to_real_position=True), pygame.Rect(138, 156, 82, 61 if PYGAME_V2 else 62))
self.assertEqual(frame_scroll.get_absolute_view_rect(), pygame.Rect(138, 156, 284, 192))
# Move inner scroll by 10%
frame_scroll.scroll_to(ORIENTATION_VERTICAL, 0.1)
self.assertEqual(frame_scroll.get_absolute_view_rect(), pygame.Rect(138, 156, 284, 192))
self.assertEqual(btn.get_rect(to_real_position=True), pygame.Rect(138, 156, 82, 41 if PYGAME_V2 else 42))
# Move menu scroll by 10%
menu.get_scrollarea().scroll_to(ORIENTATION_VERTICAL, 0.1)
self.assertEqual(frame_scroll.get_absolute_view_rect(), pygame.Rect(138, 155, 284, 165))
self.assertEqual(btn.get_rect(to_real_position=True), pygame.Rect(138, 155, 82, 14 if PYGAME_V2 else 15))
# Move menu scroll by 50%
menu.get_scrollarea().scroll_to(ORIENTATION_VERTICAL, 0.5)
self.assertEqual(frame_scroll.get_absolute_view_rect(), pygame.Rect(138, 155, 284, 46 if PYGAME_V2 else 44))
self.assertEqual(btn.get_rect(to_real_position=True), pygame.Rect(138, 155, 0, 0))
menu.get_scrollarea().scroll_to(ORIENTATION_VERTICAL, 1)
self.assertEqual(frame_scroll.get_absolute_view_rect(), pygame.Rect(0, 155, 0, 0))
self.assertEqual(btn.get_rect(to_real_position=True), pygame.Rect(0, 155, 0, 0))
menu.get_scrollarea().scroll_to(ORIENTATION_VERTICAL, 0)
frame_scroll.scroll_to(ORIENTATION_VERTICAL, 0)
self.assertEqual(btn.get_rect(to_real_position=True), pygame.Rect(138, 156, 82, 61 if PYGAME_V2 else 62))
self.assertEqual(frame_scroll.get_absolute_view_rect(), pygame.Rect(138, 156, 284, 192))
# Remove btn
menu.remove_widget(btn)
self.assertFalse(btn.is_selected())
self.assertIsNone(btn.get_menu())
# Hide button 5
btn5.hide()
# Add textinput to frame
# First, test structure
# btn2 \ <-- selected by default
# btn3 | frame_sc scrollarea enabled
# btn4 |
# btn5 |
# text /
# btn_frame21 (x) \ frame2 no scrollarea
# btn_frame22 /
# btn_real
text = frame_sc.pack(menu.add.text_input('text: '))
self.assertEqual(text.get_position(), (8, 187 if PYGAME_V2 else 190))
self.assertEqual(text.get_translate(virtual=True), (-138, 182 if PYGAME_V2 else 185))
self.assertEqual(text.get_translate(), (0, 0))
# Test text events within frame
menu.select_widget(btn2)
menu.select_widget(text)
self.assertFalse(text.active)
self.assertEqual(text.get_value(), '')
menu.update(PygameEventUtils.key(pygame.K_a, char='a', keydown=True))
self.assertTrue(text.active)
self.assertEqual(text.get_value(), 'a')
for i in range(10):
menu.update(PygameEventUtils.key(pygame.K_a, char='a', keydown=True))
menu.draw(surface)
menu.update(PygameEventUtils.key(pygame.K_a, char='a', keydown=True)) # the last one to be added
self.assertRaises(pygame_menu.widgets.widget.frame._FrameSizeException, lambda: menu.mainloop(surface))
text.set_value('')
self.assertTrue(text.active)
menu.update(PygameEventUtils.key(ctrl.KEY_APPLY, keydown=True))
self.assertFalse(text.active)
# Set widgets as floating
# btn4,text, btn2 \
# btn3 | frame_sc scrollarea enabled
# btn6 /
# btn_frame21 (x) \ frame2 no scrollarea
# btn_frame22 /
# btn_real
btn4.set_float()
text.set_float()
btn6 = frame_sc.pack(menu.add.button('btn6'))
if PYGAME_V2:
self.assertEqual(menu._test_widgets_status(), (
(('Frame',
(0, 0, 0, 138, 1, 304, 192, 138, 156, 138, 1),
(0, 0, 0, 1, 1, 0, 0),
(1, 6)),
('Button-Nice2',
(0, 0, 1, 0, 0, 99, 61, 138, 156, 0, 155),
(1, 0, 0, 1, 0, 1, 1)),
('Button-Nice3',
(0, 0, 2, 0, 61, 99, 61, 138, 217, 0, 216),
(1, 0, 0, 1, 0, 1, 1)),
('Button-Nice4',
(0, 0, 3, 0, 0, 99, 61, 138, 156, 0, 155),
(1, 1, 0, 1, 0, 1, 1)),
('Button-Nice5',
(-1, -1, 4, -148, 172, 99, 61, 138, 156, -148, 327),
(1, 0, 0, 0, 0, 1, 1)),
('TextInput-text: ',
(0, 0, 5, 0, 0, 87, 49, 138, 156, 0, 155),
(1, 1, 1, 1, 0, 1, 1),
''),
('Button-btn6',
(0, 0, 6, 0, 122, 80, 49, 138, 278, 0, 277),
(1, 0, 0, 1, 0, 1, 1)),
('Frame',
(0, 1, 7, 90, 193, 400, 200, 90, 348, 90, 193),
(0, 0, 0, 1, 0, 0, 0),
(8, 9)),
('Button-Button frame nosc',
(0, 1, 8, 115, 218, 275, 49, 115, 373, 115, 218),
(1, 0, 0, 1, 0, 1, 1)),
('Button-Button frame nosc 2',
(0, 1, 9, 115, 267, 300, 49, 115, 422, 115, 267),
(1, 0, 0, 1, 0, 1, 1)),
('Frame',
(0, 2, 10, 140, 393, 300, 200, 0, 155, 140, 393),
(0, 0, 0, 1, 0, 0, 0),
(-1, -1)),
('Button-Normal button',
(0, 3, 11, 178, 593, 224, 49, 0, 155, 178, 593),
(1, 0, 0, 1, 0, 0, 0)))
))
# Test widget unpacking within scrollarea
self.assertEqual(btn6.get_scrollarea(), frame_sc.get_scrollarea(inner=True))
frame_sc.unpack(btn6)
self.assertEqual(btn6.get_scrollarea(), menu.get_scrollarea())
# Translate widget within scrollarea
btn3.translate(250, 100)
menu.render()
self.assertEqual(btn3.get_translate(), (250, 100))
# Add another scrollarea within scrollarea
w = frame_sc.clear()
for v in w:
menu.remove_widget(v)
self.assertNotIn(btn6, w)
menu.remove_widget(btn6)
if PYGAME_V2:
self.assertEqual(menu._test_widgets_status(), (
(('Frame',
(0, 0, 0, 138, 1, 304, 192, 0, 155, 138, 1),
(0, 0, 0, 1, 1, 0, 0),
(-1, -1)),
('Frame',
(0, 1, 1, 90, 193, 400, 200, 90, 155, 90, 193),
(0, 0, 0, 1, 0, 0, 0),
(2, 3)),
('Button-Button frame nosc',
(0, 1, 2, 115, 218, 275, 49, 115, 159, 115, 218),
(1, 0, 1, 1, 0, 1, 1)),
('Button-Button frame nosc 2',
(0, 1, 3, 115, 267, 300, 49, 115, 208, 115, 267),
(1, 0, 0, 1, 0, 1, 1)),
('Frame',
(0, 2, 4, 140, 393, 300, 200, 140, 334, 140, 393),
(0, 0, 0, 1, 0, 0, 0),
(-1, -1)),
('Button-Normal button',
(0, 3, 5, 178, 593, 224, 49, 0, 155, 178, 593),
(1, 0, 0, 1, 0, 0, 0)))
))
btn1 = frame_sc.pack(menu.add.button('btn1'))
btn2 = frame_sc.pack(menu.add.button('btn2'))
btn3 = pygame_menu.widgets.Button('btn3')
menu.add.configure_defaults_widget(btn3)
frame_sc.pack(btn3)
frame_rnoscroll = menu.add.frame_v(150, 100, background_color=(160, 0, 60), frame_id='rno')
btn4 = frame_rnoscroll.pack(menu.add.button('btn4', button_id='nice'))
frame_rscroll = menu.add.frame_v(200, 500, max_height=100, background_color=(60, 60, 60), frame_id='r')
frame_sc.pack(frame_rscroll)
frame_sc.pack(frame_rnoscroll)
bnice = menu.add.button('nice', font_color=(255, 255, 255))
btn5 = frame_rscroll.pack(bnice)
frame_sc.translate(-50, 0)
# btn1 \
# btn2 |
# btn3 | frame_sc, frame_scroll
# btn5 > frame_rscroll |
# btn4 > frame_rnoscroll /
# btn_frame21 (x) \ frame2 no scrollarea
# btn_frame22 /
# btn_real
self.assertEqual(btn1.get_scrollarea(), frame_scroll)
self.assertEqual(btn2.get_scrollarea(), frame_scroll)
self.assertEqual(btn3.get_scrollarea(), frame_scroll)
self.assertEqual(frame_rscroll.get_scrollarea(), frame_scroll)
self.assertEqual(btn5.get_scrollarea().get_parent(), frame_scroll)
self.assertEqual(frame_rnoscroll.get_scrollarea(), frame_scroll)
self.assertEqual(btn5.get_scrollarea(), frame_rscroll.get_scrollarea(inner=True))
self.assertEqual(btn4.get_scrollarea(), frame_scroll)
self.assertEqual(frame_rscroll.get_size(), (204, 92))
self.assertEqual(frame_sc.get_scrollarea(inner=True), frame_scroll)
self.assertEqual(frame_rscroll.get_scrollarea(), frame_scroll)
self.assertEqual(frame_rscroll.get_scrollarea(inner=True).get_parent(), frame_rscroll.get_scrollarea())
# Normal frame with inner frames
frame_out = menu.add.frame_v(400, 900, background_color=(0, 200, 0))
nice1 = frame_out.pack(menu.add.button('Nice1'))
frame_out_rnoscroll = menu.add.frame_v(150, 100, background_color=(160, 0, 60))
nice2 = frame_out_rnoscroll.pack(menu.add.button('Nice2'))
frame_out_rnoscroll2 = menu.add.frame_v(150, 100, background_color=(20, 50, 140))
nice3 = frame_out_rnoscroll2.pack(menu.add.button('Nice3'))
frame_out_rnoscroll_rscroll = menu.add.frame_v(200, 500, max_height=100, background_color=(60, 60, 60))
nice4 = frame_out_rnoscroll_rscroll.pack(menu.add.button('Nice4'))
frame_out.pack(frame_out_rnoscroll)
frame_out.pack(frame_out_rnoscroll2)
frame_out.pack(frame_out_rnoscroll_rscroll)
self.assertEqual(nice2.get_scrollarea(), menu.get_scrollarea())
self.assertIn(nice1, frame_out.get_widgets())
self.assertIn(nice3, frame_out.get_widgets())
self.assertIn(nice4, frame_out.get_widgets())
# frame_sc.translate(-50, 0)
def draw_rect() -> None:
"""
Draw absolute rect on surface for testing purposes.
"""
# surface.fill((160, 0, 0), frame_scroll.get_absolute_view_rect())
# surface.fill((60, 0, 60), btn.get_scrollarea().to_real_position(btn.get_rect(), visible=True))
# surface.fill((255, 255, 255), btn.get_rect(to_real_position=True))
# surface.fill((0, 255, 0), nice4.get_rect(to_real_position=True))
# surface.fill((0, 255, 255), btn4.get_rect(to_real_position=True))
return
menu.get_decorator().add_callable(draw_rect, prev=False, pass_args=False)
# Scroll down each subelement
frame_sc.scrollh(1)
frame_sc.scrollv(1)
frame_rscroll.scrollv(1)
frame_out_rnoscroll_rscroll.scrollv(1)
menu.select_widget(btn_real)
if PYGAME_V2:
for v in [0.292, 0.335, 0.419, 0.535, 0.002, 0.002, 0.002, 0.002, 0.002, 0.002, 0.247]:
menu._up()
self.assertAlmostEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_VERTICAL), v)
self.assertEqual(menu.get_selected_widget(), btn_real)
frame_sc.scrollh(1)
frame_sc.scrollv(1)
frame_rscroll.scrollv(1)
frame_out_rnoscroll_rscroll.scrollv(1)
# Now up
if PYGAME_V2:
for v in [0.222, 0.180, 0.002, 0.002, 0.002, 0.002, 0.535, 0.535, 0.535, 0.535, 0.496]:
menu._down()
self.assertAlmostEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_VERTICAL), v)
self.assertEqual(menu.get_selected_widget(), btn_real)
# Select two widgets
btn_frame21.select()
menu._test_print_widgets()
# Check selection
self.assertRaises(pygame_menu.menu._MenuMultipleSelectedWidgetsException, lambda: menu.render())
menu.render()
self.assertEqual(menu.get_selected_widget(), btn_frame21)
def test_scrollarea_frame_within_scrollarea(self) -> None:
"""
Test scrollarea frame within scrollarea's.
"""
menu = MenuUtils.generic_menu(theme=THEME_NON_FIXED_TITLE)
f1 = menu.add.frame_v(450, 400, background_color=(0, 0, 255), frame_id='f1')
f2 = menu.add.frame_v(400, 400, max_height=300, background_color=(255, 0, 0), frame_id='f2')
f3 = menu.add.frame_v(350, 400, max_height=200, background_color=(0, 255, 0), frame_id='f3')
f4 = menu.add.frame_v(300, 400, max_height=100, background_color=(0, 255, 255), frame_id='f4')
f4._pack_margin_warning = False
# Get scrollarea's
s0 = menu.get_scrollarea()
s1 = f2.get_scrollarea(inner=True)
s2 = f3.get_scrollarea(inner=True)
s3 = f4.get_scrollarea(inner=True)
vm = f2.pack(menu.add.vertical_margin(25, margin_id='margin'))
b1 = f1.pack(menu.add.button('btn1', button_id='b1'), margin=(25, 0))
b2 = f2.pack(menu.add.button('btn2', button_id='b2'), margin=(25, 0))
b3 = f3.pack(menu.add.button('btn3', button_id='b3'), margin=(25, 0))
b4 = f4.pack(menu.add.button('btn4', button_id='b4'), margin=(25, 0))
# Pack frames
f1.pack(f2)
f2.pack(f3)
f3.pack(f4)
# Add last button
b5 = menu.add.button('btn5', button_id='b5')
# Test positioning
#
# .------------f1-----------.
# | btn1 s0 |
# | .----------f2---------. |
# | | <25px> s1 ^ |
# | | btn2 | |
# | | .--------f3-------. | |
# | | | btn3 s2 ^ | |
# | | | .------f4-----. | | |
# | | | | btn4 s3 ^ | | |
# | | | | v | | |
# | | | .-------------. v | |
# | | .-----------------. v |
# | .---------------------. |
# .-------------------------.
# btn5
self.assertEqual(b1.get_frame_depth(), 1)
self.assertEqual(b2.get_frame_depth(), 2)
self.assertEqual(b3.get_frame_depth(), 3)
self.assertEqual(b4.get_frame_depth(), 4)
self.assertEqual(b5.get_frame_depth(), 0)
self.assertEqual(menu._update_frames, [f4, f3, f2])
self.assertFalse(f1.is_scrollable)
self.assertTrue(f2.is_scrollable)
self.assertTrue(f3.is_scrollable)
self.assertTrue(f4.is_scrollable)
self.assertIsNone(s0.get_parent())
self.assertEqual(f1.get_scrollarea(), s0)
self.assertEqual(f2.get_scrollarea(), s0)
self.assertEqual(f3.get_scrollarea(), s1)
self.assertEqual(f4.get_scrollarea(), s2)
self.assertEqual(s0.get_depth(), 0)
self.assertEqual(s1.get_depth(), 1)
self.assertEqual(s2.get_depth(), 2)
self.assertEqual(s3.get_depth(), 3)
if PYGAME_V2:
self.assertEqual(s0.get_absolute_view_rect(), pygame.Rect(0, 155, 580, 345))
self.assertEqual(s1.get_absolute_view_rect(), pygame.Rect(73, 208, 384, 292))
self.assertEqual(s2.get_absolute_view_rect(), pygame.Rect(73, 282, 334, 192))
self.assertEqual(s3.get_absolute_view_rect(), pygame.Rect(73, 331, 284, 92))
self.assertEqual(s0.get_parent_position(), (0, 0))
self.assertEqual(s1.get_parent_position(), (0, 154))
self.assertEqual(s2.get_parent_position(), (73, 208))
self.assertEqual(s3.get_parent_position(), (73, 282))
def draw_rect() -> None:
"""
Draw absolute rect on surface for testing purposes.
"""
# surface.fill((0, 0, 0), s3.get_absolute_view_rect())
return
menu.get_decorator().add_callable(draw_rect, prev=False, pass_args=False)
self.assertEqual(menu.get_selected_widget(), b1)
self.assertEqual(f1.get_indices(), (1, 2))
self.assertEqual(f2.get_indices(), (4, 5))
self.assertEqual(f3.get_indices(), (6, 7))
self.assertEqual(f4.get_indices(), (8, 8))
# Scroll all to bottom, test movement
f2.scrollv(1)
f3.scrollv(1)
f4.scrollv(1)
if PYGAME_V2:
self.assertAlmostEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_VERTICAL), 0.01)
menu._down()
self.assertEqual(menu.get_selected_widget(), b5)
self.assertAlmostEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_VERTICAL), 0.99)
self.assertAlmostEqual(f2.get_scroll_value_percentage(ORIENTATION_VERTICAL), 0.99)
self.assertAlmostEqual(f3.get_scroll_value_percentage(ORIENTATION_VERTICAL), 1)
self.assertAlmostEqual(f4.get_scroll_value_percentage(ORIENTATION_VERTICAL), 0.993)
menu._down()
self.assertEqual(menu.get_selected_widget(), b4)
self.assertAlmostEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_VERTICAL), 0)
self.assertAlmostEqual(f2.get_scroll_value_percentage(ORIENTATION_VERTICAL), 0)
self.assertAlmostEqual(f3.get_scroll_value_percentage(ORIENTATION_VERTICAL), 0)
self.assertAlmostEqual(f3.get_scroll_value_percentage(ORIENTATION_VERTICAL), 0)
self.assertEqual(menu._test_widgets_status(), (
(('Frame',
(0, 0, 0, 65, 1, 450, 400, 65, 156, 65, 1),
(0, 0, 0, 1, 0, 0, 0),
(1, 2)),
('Button-btn1',
(0, 0, 1, 98, 5, 80, 49, 98, 160, 98, 5),
(1, 0, 0, 1, 0, 1, 1)),
('Frame',
(0, 0, 2, 73, 54, 404, 292, 73, 209, 73, 54),
(0, 0, 0, 1, 1, 1, 1),
(4, 5)),
('VMargin', (0, 0, 3, 0, 0, 0, 25, 0, 0, 0, 0), (0, 0, 0, 1, 0, 1, 2)),
('Button-btn2',
(0, 0, 4, 25, 25, 80, 49, 98, 234, 25, 180),
(1, 0, 0, 1, 0, 1, 2)),
('Frame',
(0, 0, 5, 0, 74, 354, 192, 73, 283, 0, 229),
(0, 0, 0, 1, 1, 1, 2),
(6, 7)),
('Button-btn3',
(0, 0, 6, 25, 0, 80, 49, 98, 283, 98, 209),
(1, 0, 0, 1, 0, 1, 3)),
('Frame',
(0, 0, 7, 0, 49, 304, 92, 73, 332, 73, 258),
(0, 0, 0, 1, 1, 1, 3),
(8, 8)),
('Button-btn4',
(0, 0, 8, 25, 0, 80, 49, 98, 332, 98, 283),
(1, 0, 1, 1, 0, 1, 4)),
('Button-btn5',
(0, 1, 9, 250, 401, 80, 49, 0, 155, 250, 401),
(1, 0, 0, 1, 0, 0, 0)))
))
def check_all_visible() -> None:
"""
Check all widgets are visible.
"""
self.assertTrue(f1.is_visible())
self.assertTrue(b1.is_visible())
self.assertTrue(b1.is_visible(check_frame=False))
self.assertTrue(f2.is_visible())
self.assertTrue(b2.is_visible())
self.assertTrue(b2.is_visible(check_frame=False))
self.assertTrue(f3.is_visible())
self.assertTrue(b3.is_visible())
self.assertTrue(b3.is_visible(check_frame=False))
self.assertTrue(f4.is_visible())
self.assertTrue(b4.is_visible())
self.assertTrue(b4.is_visible(check_frame=False))
self.assertTrue(b5.is_visible())
self.assertTrue(b5.is_visible(check_frame=False))
# Test hide
f1.hide()
self.assertEqual(menu.get_selected_widget(), b5)
self.assertFalse(f1.is_visible())
self.assertFalse(b1.is_visible())
self.assertTrue(b1.is_visible(check_frame=False))
self.assertFalse(f2.is_visible())
self.assertFalse(b2.is_visible())
self.assertFalse(f3.is_visible())
self.assertFalse(b3.is_visible())
self.assertFalse(f4.is_visible())
self.assertFalse(b4.is_visible())
self.assertTrue(b5.is_visible())
f1.show()
self.assertEqual(menu.get_selected_widget(), b5)
check_all_visible()
f2.hide()
self.assertTrue(f1.is_visible())
self.assertTrue(b1.is_visible())
self.assertFalse(f2.is_visible())
self.assertFalse(b2.is_visible())
self.assertFalse(f3.is_visible())
self.assertFalse(b3.is_visible())
self.assertFalse(f4.is_visible())
self.assertFalse(b4.is_visible())
self.assertTrue(b5.is_visible())
f2.show()
check_all_visible()
f3.hide()
self.assertTrue(f1.is_visible())
self.assertTrue(b1.is_visible())
self.assertTrue(f2.is_visible())
self.assertTrue(b2.is_visible())
self.assertFalse(f3.is_visible())
self.assertFalse(b3.is_visible())
self.assertFalse(f4.is_visible())
self.assertFalse(b4.is_visible())
self.assertTrue(b5.is_visible())
f3.show()
check_all_visible()
f4.hide()
self.assertTrue(f1.is_visible())
self.assertTrue(b1.is_visible())
self.assertTrue(f2.is_visible())
self.assertTrue(b2.is_visible())
self.assertTrue(f3.is_visible())
self.assertTrue(b3.is_visible())
self.assertFalse(f4.is_visible())
self.assertFalse(b4.is_visible())
self.assertTrue(b5.is_visible())
f4.show()
check_all_visible()
menu.get_scrollarea().scroll_to(ORIENTATION_VERTICAL, 0.562)
# Move widgets
menu.select_widget(b4)
self.assertEqual(menu.get_selected_widget(), b4)
self.assertEqual(menu.get_widgets(), (f1, b1, f2, vm, b2, f3, b3, f4, b4, b5))
menu.move_widget_index(f1, b5)
self.assertEqual(menu.get_selected_widget(), b4)
self.assertEqual(menu.get_widgets(), (b5, f1, b1, f2, vm, b2, f3, b3, f4, b4))
# Test scroll on up
f3.scrollv(0)
menu._down()
self.assertEqual(menu.get_selected_widget(), b3)
self.assertAlmostEqual(f3.get_scroll_value_percentage(ORIENTATION_VERTICAL), 0 if PYGAME_V2 else 0.005)
if PYGAME_V2:
self.assertAlmostEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_VERTICAL), 0.467)
f2.scrollv(0)
menu._down()
self.assertEqual(menu.get_selected_widget(), b2)
self.assertAlmostEqual(f2.get_scroll_value_percentage(ORIENTATION_VERTICAL), 0)
if PYGAME_V2:
self.assertAlmostEqual(menu.get_scrollarea().get_scroll_value_percentage(ORIENTATION_VERTICAL), 0.467)
menu._down()
menu._down()
self.assertEqual(menu.get_selected_widget(), b5)
# Check all widgets are non-floating
for w in menu.get_widgets():
self.assertFalse(w.is_floating())
# Pack all widgets within the deepest frame
f4.unpack(b4)
self.assertRaises(AssertionError, lambda: f4.pack(f1.unpack(f1)))
f4.pack(f1.unpack(b1))
menu.remove_widget(vm)
self.assertNotIn(vm, f2.get_widgets())
f4.pack(f2.unpack(b2))
f4.pack(f3.unpack(b3))
f4.pack(b4)
f4.pack(b5)
b5.set_float()
f4w = f4.get_widgets()
for w in f4w:
self.assertTrue(w.is_floating())
self.assertEqual(w.get_position(), f4w[0].get_position())
self.assertEqual(menu.get_selected_widget(), b5)
self.assertEqual(f4.get_widgets(), (b1, b2, b3, b4, b5))
# Unfloat widgets
f4.unfloat()
menu.select_widget(b1)
for w in [b5, b4, b3, b2, b1]:
menu._down()
self.assertEqual(menu.get_selected_widget(), w)
for w in [b2, b3, b4, b5, b1]:
menu._up()
self.assertEqual(menu.get_selected_widget(), w)
menu._test_print_widgets()
# Remove f4 from menu
menu.remove_widget(f4)
self.assertEqual(menu._update_frames, [f3, f2])
def test_menu_support(self) -> None:
"""
Test frame menu support.
"""
# Test frame movement
theme = TEST_THEME.copy()
theme.widget_margin = (0, 0)
theme.widget_font_size = 20
menu = MenuUtils.generic_menu(columns=3, rows=2, theme=theme)
# btn0 | f1(btn2,btn3,btn4,btn5) | f2(btn7,
# | | btn8,
# | | f3(btn9,btn10))
# btn1 | btn6 | f4(btn11,btn12,btn13)
btn0 = menu.add.button('btn0')
btn1 = menu.add.button('btn1')
f1 = menu.add.frame_h(200, 50, frame_id='f1')
btn2 = menu.add.button('btn2 ')
btn3 = menu.add.button('btn3 ')
btn4 = menu.add.button('btn4 ')
btn5 = menu.add.button('btn5 ')
btn6 = menu.add.button('btn6')
f2 = menu.add.frame_v(200, 132, background_color=(100, 0, 0), frame_id='f2')
f3 = menu.add.frame_h(200, 50, background_color=(0, 0, 100), frame_id='f3')
f4 = menu.add.frame_h(260, 50, frame_id='f4')
btn7 = menu.add.button('btn7')
btn8 = menu.add.button('btn8')
btn9 = menu.add.button('btn9 ')
btn10 = menu.add.button('btn10')
btn11 = menu.add.button('btn11 ')
btn12 = menu.add.button('btn12 ')
btn13 = menu.add.button('btn13')
f1.pack((btn2, btn3, btn4, btn5))
f3.pack((btn9, btn10))
f2.pack((btn7, btn8, f3), align=pygame_menu.locals.ALIGN_CENTER)
f4.pack((btn11, btn12, btn13))
menu._test_print_widgets()
# Test min max indices
self.assertEqual(f1.get_indices(), (3, 6))
self.assertEqual(f2.get_indices(), (9, 11))
self.assertEqual(f3.get_indices(), (12, 13))
self.assertEqual(f4.get_indices(), (15, 17))
# Check positioning
self.assertEqual(btn0.get_col_row_index(), (0, 0, 0))
self.assertEqual(btn1.get_col_row_index(), (0, 1, 1))
self.assertEqual(f1.get_col_row_index(), (1, 0, 2))
self.assertEqual(btn6.get_col_row_index(), (1, 1, 7))
self.assertEqual(f2.get_col_row_index(), (2, 0, 8))
self.assertEqual(f4.get_col_row_index(), (2, 1, 14))
self.assertFalse(f1.is_scrollable)
self.assertFalse(f2.is_scrollable)
self.assertFalse(f3.is_scrollable)
self.assertEqual(menu._test_widgets_status(), (
(('Button-btn0',
(0, 0, 0, 13, 82, 42, 28, 13, 237, 13, 82),
(1, 0, 1, 1, 0, 0, 0)),
('Button-btn1',
(0, 1, 1, 13, 110, 42, 28, 13, 265, 13, 110),
(1, 0, 0, 1, 0, 0, 0)),
('Frame',
(1, 0, 2, 84, 82, 200, 50, 84, 237, 84, 82),
(0, 0, 0, 1, 0, 0, 0),
(3, 6)),
('Button-btn2 ',
(1, 0, 3, 84, 82, 47, 28, 84, 237, 84, 82),
(1, 0, 0, 1, 0, 1, 1)),
('Button-btn3 ',
(1, 0, 4, 131, 82, 47, 28, 131, 237, 131, 82),
(1, 0, 0, 1, 0, 1, 1)),
('Button-btn4 ',
(1, 0, 5, 178, 82, 47, 28, 178, 237, 178, 82),
(1, 0, 0, 1, 0, 1, 1)),
('Button-btn5 ',
(1, 0, 6, 225, 82, 47, 28, 225, 237, 225, 82),
(1, 0, 0, 1, 0, 1, 1)),
('Button-btn6',
(1, 1, 7, 163, 132, 42, 28, 163, 287, 163, 132),
(1, 0, 0, 1, 0, 0, 0)),
('Frame',
(2, 0, 8, 351, 82, 200, 132, 351, 237, 351, 82),
(0, 0, 0, 1, 0, 0, 0),
(9, 11)),
('Button-btn7',
(2, 0, 9, 430, 82, 42, 28, 430, 237, 430, 82),
(1, 0, 0, 1, 0, 1, 1)),
('Button-btn8',
(2, 0, 10, 430, 110, 42, 28, 430, 265, 430, 110),
(1, 0, 0, 1, 0, 1, 1)),
('Frame',
(2, 0, 11, 351, 138, 200, 50, 351, 293, 351, 138),
(0, 0, 0, 1, 0, 1, 1),
(12, 13)),
('Button-btn9 ',
(2, 0, 12, 351, 138, 47, 28, 351, 293, 351, 138),
(1, 0, 0, 1, 0, 1, 2)),
('Button-btn10',
(2, 0, 13, 398, 138, 53, 28, 398, 293, 398, 138),
(1, 0, 0, 1, 0, 1, 2)),
('Frame',
(2, 1, 14, 321, 214, 260, 50, 321, 369, 321, 214),
(0, 0, 0, 1, 0, 0, 0),
(15, 17)),
('Button-btn11 ',
(2, 1, 15, 321, 214, 58, 28, 321, 369, 321, 214),
(1, 0, 0, 1, 0, 1, 1)),
('Button-btn12 ',
(2, 1, 16, 379, 214, 58, 28, 379, 369, 379, 214),
(1, 0, 0, 1, 0, 1, 1)),
('Button-btn13',
(2, 1, 17, 437, 214, 53, 28, 437, 369, 437, 214),
(1, 0, 0, 1, 0, 1, 1)))
))
# Arrow keys
self.assertEqual(menu.get_selected_widget(), btn0)
menu.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn2)
menu.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn3)
menu.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn4)
menu.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn5)
menu.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn7)
menu.update(PygameEventUtils.key(ctrl.KEY_RIGHT, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn0)
menu.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn10)
menu.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn9)
menu.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn5)
menu.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn4)
menu.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn3)
menu.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn2)
menu.update(PygameEventUtils.key(ctrl.KEY_LEFT, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn0)
for bt in (btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn10, btn11, btn12, btn13, btn0, btn1):
menu.update(PygameEventUtils.key(ctrl.KEY_MOVE_UP, keydown=True))
self.assertEqual(menu.get_selected_widget(), bt)
for bt in (btn6, btn11, btn12, btn13, btn1):
menu.update(PygameEventUtils.joy_hat_motion(ctrl.JOY_RIGHT))
self.assertEqual(menu.get_selected_widget(), bt)
for bt in (btn0, btn13, btn12, btn11, btn10, btn9, btn8, btn7, btn6, btn5, btn4, btn3, btn2, btn1, btn0):
menu.update(PygameEventUtils.key(ctrl.KEY_MOVE_DOWN, keydown=True))
self.assertEqual(menu.get_selected_widget(), bt)
menu.update(PygameEventUtils.key(ctrl.KEY_MOVE_UP, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn1)
for bt in (btn13, btn12, btn11, btn6, btn1):
menu.update(PygameEventUtils.joy_hat_motion(ctrl.JOY_LEFT))
self.assertEqual(menu.get_selected_widget(), bt)
# Check mouse events
for bt in (btn0, btn13, btn12, btn11, btn10, btn9, btn8, btn7, btn6, btn5, btn4, btn3, btn2, btn1, btn0):
menu.update(PygameEventUtils.middle_rect_click(bt, evtype=pygame.MOUSEBUTTONDOWN))
self.assertEqual(menu.get_selected_widget(), bt)
# btn0 | f1(btn2,btn3,btn4,btn5) | f2(btn7,
# | | btn8)
# btn1 | btn6 | f4(btn11,btn12,btn13)+(floating9,10)
menu.select_widget(btn0)
self.assertEqual(len(f2._widgets), 3)
self.assertEqual(len(f3._widgets), 2)
menu.remove_widget(f3)
self.assertEqual(len(f2._widgets), 2)
self.assertEqual(len(f3._widgets), 0)
self.assertEqual(menu._test_widgets_status(), (
(('Button-btn0',
(0, 0, 0, 13, 82, 42, 28, 13, 237, 13, 82),
(1, 0, 1, 1, 0, 0, 0)),
('Button-btn1',
(0, 1, 1, 13, 110, 42, 28, 13, 265, 13, 110),
(1, 0, 0, 1, 0, 0, 0)),
('Frame',
(1, 0, 2, 84, 82, 200, 50, 84, 237, 84, 82),
(0, 0, 0, 1, 0, 0, 0),
(3, 6)),
('Button-btn2 ',
(1, 0, 3, 84, 82, 47, 28, 84, 237, 84, 82),
(1, 0, 0, 1, 0, 1, 1)),
('Button-btn3 ',
(1, 0, 4, 131, 82, 47, 28, 131, 237, 131, 82),
(1, 0, 0, 1, 0, 1, 1)),
('Button-btn4 ',
(1, 0, 5, 178, 82, 47, 28, 178, 237, 178, 82),
(1, 0, 0, 1, 0, 1, 1)),
('Button-btn5 ',
(1, 0, 6, 225, 82, 47, 28, 225, 237, 225, 82),
(1, 0, 0, 1, 0, 1, 1)),
('Button-btn6',
(1, 1, 7, 163, 132, 42, 28, 163, 287, 163, 132),
(1, 0, 0, 1, 0, 0, 0)),
('Frame',
(2, 0, 8, 351, 82, 200, 132, 351, 237, 351, 82),
(0, 0, 0, 1, 0, 0, 0),
(9, 10)),
('Button-btn7',
(2, 0, 9, 430, 82, 42, 28, 430, 237, 430, 82),
(1, 0, 0, 1, 0, 1, 1)),
('Button-btn8',
(2, 0, 10, 430, 110, 42, 28, 430, 265, 430, 110),
(1, 0, 0, 1, 0, 1, 1)),
('Frame',
(2, 1, 11, 321, 214, 260, 50, 321, 369, 321, 214),
(0, 0, 0, 1, 0, 0, 0),
(12, 14)),
('Button-btn11 ',
(2, 1, 12, 321, 214, 58, 28, 321, 369, 321, 214),
(1, 0, 0, 1, 0, 1, 1)),
('Button-btn12 ',
(2, 1, 13, 379, 214, 58, 28, 379, 369, 379, 214),
(1, 0, 0, 1, 0, 1, 1)),
('Button-btn13',
(2, 1, 14, 437, 214, 53, 28, 437, 369, 437, 214),
(1, 0, 0, 1, 0, 1, 1)),
('Button-btn9 ',
(2, 0, 15, 427, 82, 47, 28, 427, 237, 427, 82),
(1, 1, 0, 1, 0, 0, 0)),
('Button-btn10',
(2, 0, 16, 424, 82, 53, 28, 424, 237, 424, 82),
(1, 1, 0, 1, 0, 0, 0)))
))
menu.select_widget(btn0)
for i in range(14):
menu.update(PygameEventUtils.key(ctrl.KEY_MOVE_UP, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn0)
for i in range(14):
menu.update(PygameEventUtils.key(ctrl.KEY_MOVE_DOWN, keydown=True))
self.assertEqual(menu.get_selected_widget(), btn0)
# noinspection SpellCheckingInspection
def test_mouseover(self) -> None:
"""
Test frame mouse support.
"""
menu = MenuUtils.generic_menu(theme=THEME_NON_FIXED_TITLE)
reset_widgets_over()
self.assertEqual(WIDGET_MOUSEOVER, [None, []])
f1 = menu.add.frame_v(500, 500, background_color='red',
cursor=pygame_menu.locals.CURSOR_HAND, frame_id='f1')
menu.add.vertical_margin(100, margin_id='vbottom')
f1.pack(menu.add.vertical_margin(100, margin_id='vtop'))
f2 = menu.add.frame_v(400, 300, background_color='blue',
cursor=pygame_menu.locals.CURSOR_HAND, frame_id='f2')
b1 = f1.pack(menu.add.button('1', button_id='b1', cursor=pygame_menu.locals.CURSOR_ARROW))
f1.pack(f2)
b2 = f2.pack(menu.add.button('2', button_id='b2', cursor=pygame_menu.locals.CURSOR_ARROW))
f3 = f2.pack(menu.add.frame_v(100, 100, background_color='green',
cursor=pygame_menu.locals.CURSOR_HAND, frame_id='f3'))
b3 = f3.pack(menu.add.button('3', button_id='b3', cursor=pygame_menu.locals.CURSOR_ARROW))
f1._id__repr__ = True
f2._id__repr__ = True
f3._id__repr__ = True
# Get cursors
cur_none = get_cursor()
if cur_none is None:
return
set_pygame_cursor(pygame_menu.locals.CURSOR_ARROW)
cur_arrow = get_cursor()
set_pygame_cursor(pygame_menu.locals.CURSOR_HAND)
cur_hand = get_cursor()
set_pygame_cursor(cur_none)
if PYGAME_V2:
self.assertEqual(menu._test_widgets_status(), (
(('Frame',
(0, 0, 0, 40, 1, 500, 500, 40, 155, 40, 1),
(0, 0, 0, 1, 0, 0, 0),
(2, 3)),
('VMargin', (0, 0, 1, 0, 0, 0, 100, 0, 0, 0, 0), (0, 0, 0, 1, 0, 1, 1)),
('Button-1',
(0, 0, 2, 48, 105, 33, 49, 48, 191, 48, 105),
(1, 0, 1, 1, 0, 1, 1)),
('Frame',
(0, 0, 3, 48, 154, 400, 300, 48, 240, 48, 154),
(0, 0, 0, 1, 0, 1, 1),
(4, 5)),
('Button-2',
(0, 0, 4, 56, 158, 33, 49, 56, 244, 56, 158),
(1, 0, 0, 1, 0, 1, 2)),
('Frame',
(0, 0, 5, 56, 207, 100, 100, 56, 293, 56, 207),
(0, 0, 0, 1, 0, 1, 2),
(6, 6)),
('Button-3',
(0, 0, 6, 64, 211, 33, 49, 64, 297, 64, 211),
(1, 0, 0, 1, 0, 1, 3)),
('VMargin', (0, 1, 7, 0, 0, 0, 100, 0, 0, 0, 0), (0, 0, 0, 1, 0, 0, 0)))
))
# Setup
self.assertTrue(b1.is_selected())
self.assertFalse(menu._mouse_motion_selection)
menu._test_print_widgets()
test = [False, False, False, False, False, False] # f1, b1, f2, b2, f3, b3
print_events = False
def onf1(widget, _) -> None:
"""
f1 event.
"""
self.assertEqual(widget, f1)
test[0] = not test[0]
if print_events:
print(f"{'Enter' if test[0] else 'Leave'} f1")
def onb1(widget, _) -> None:
"""
b1 event.
"""
self.assertEqual(widget, b1)
test[1] = not test[1]
if print_events:
print(f"{'Enter' if test[1] else 'Leave'} b1")
def onf2(widget, _) -> None:
"""
f2 event.
"""
self.assertEqual(widget, f2)
test[2] = not test[2]
if print_events:
print(f"{'Enter' if test[2] else 'Leave'} f2")
def onb2(widget, _) -> None:
"""
b2 event.
"""
self.assertEqual(widget, b2)
test[3] = not test[3]
if print_events:
print(f"{'Enter' if test[3] else 'Leave'} b2")
def onf3(widget, _) -> None:
"""
f3 event.
"""
self.assertEqual(widget, f3)
test[4] = not test[4]
if print_events:
print(f"{'Enter' if test[4] else 'Leave'} f3")
def onb3(widget, _) -> None:
"""
b3 event.
"""
self.assertEqual(widget, b3)
test[5] = not test[5]
if print_events:
print(f"{'Enter' if test[5] else 'Leave'} b3")
f1.set_onmouseover(onf1)
f1.set_onmouseleave(onf1)
b1.set_onmouseover(onb1)
b1.set_onmouseleave(onb1)
f2.set_onmouseover(onf2)
f2.set_onmouseleave(onf2)
b2.set_onmouseover(onb2)
b2.set_onmouseleave(onb2)
f3.set_onmouseover(onf3)
f3.set_onmouseleave(onf3)
b3.set_onmouseover(onb3)
b3.set_onmouseleave(onb3)
# Start moving mouse
#
# .------------f1-----------.
# | vop <100px> |
# | b1 |
# | .----------f2---------. |
# | | b2 | |
# | | .--------f3-------. | |
# | | | b3 | | |
# | | .-----------------. | |
# | .---------------------. |
# .-------------------------.
# vbottom <100px>
self.assertEqual(get_cursor(), cur_none)
menu.update(PygameEventUtils.topleft_rect_mouse_motion(f1))
self.assertEqual(test, [True, False, False, False, False, False])
self.assertEqual(WIDGET_MOUSEOVER, [f1, [f1, cur_none, []]])
self.assertEqual(get_cursor(), cur_hand)
# Move to b1 inside f1
menu.update(PygameEventUtils.topleft_rect_mouse_motion(b1))
self.assertEqual(test, [True, True, False, False, False, False])
self.assertEqual(WIDGET_MOUSEOVER, [b1, [b1, cur_hand, [f1, cur_none, []]]])
self.assertEqual(get_cursor(), cur_arrow)
# Move to f2, inside f1
menu.update(PygameEventUtils.topleft_rect_mouse_motion(f2))
self.assertEqual(test, [True, False, True, False, False, False]) # out from b1
self.assertEqual(WIDGET_MOUSEOVER, [f2, [f2, cur_hand, [f1, cur_none, []]]])
self.assertEqual(get_cursor(), cur_hand)
# Move to b2, inside f2+f1
menu.update(PygameEventUtils.topleft_rect_mouse_motion(b2))
self.assertEqual(test, [True, False, True, True, False, False])
self.assertEqual(WIDGET_MOUSEOVER, [b2, [b2, cur_hand, [f2, cur_hand, [f1, cur_none, []]]]])
self.assertEqual(get_cursor(), cur_arrow)
# Move to f3
menu.update(PygameEventUtils.topleft_rect_mouse_motion(f3))
self.assertEqual(test, [True, False, True, False, True, False]) # out from b2
self.assertEqual(WIDGET_MOUSEOVER, [f3, [f3, cur_hand, [f2, cur_hand, [f1, cur_none, []]]]])
self.assertEqual(get_cursor(), cur_hand)
# Move to b3, inside f3+f2+f1
menu.update(PygameEventUtils.topleft_rect_mouse_motion(b3))
self.assertEqual(test, [True, False, True, False, True, True])
self.assertEqual(WIDGET_MOUSEOVER, [b3, [b3, cur_hand, [f3, cur_hand, [f2, cur_hand, [f1, cur_none, []]]]]])
self.assertEqual(get_cursor(), cur_arrow)
# From b3, move mouse out from window
menu.update(PygameEventUtils.leave_window())
self.assertEqual(test, [False, False, False, False, False, False])
self.assertEqual(WIDGET_MOUSEOVER, [None, []])
self.assertEqual(get_cursor(), cur_none)
# Move from out to inner widget (b3), this should call f1->f2->f3->b3
menu.update(PygameEventUtils.topleft_rect_mouse_motion(b3))
self.assertEqual(test, [True, False, True, False, True, True])
self.assertEqual(WIDGET_MOUSEOVER, [b3, [b3, cur_hand, [f3, cur_hand, [f2, cur_hand, [f1, cur_none, []]]]]])
self.assertEqual(get_cursor(), cur_arrow)
# Move from b3->f2, this should call b3, f3 but not call f2 as this is actually over
menu.update(PygameEventUtils.topleft_rect_mouse_motion(f2))
self.assertEqual(test, [True, False, True, False, False, False])
self.assertEqual(WIDGET_MOUSEOVER, [f2, [f2, cur_hand, [f1, cur_none, []]]])
self.assertEqual(get_cursor(), cur_hand)
# Move from f2->b1, this should call f2
menu.update(PygameEventUtils.topleft_rect_mouse_motion(b1))
self.assertEqual(test, [True, True, False, False, False, False])
self.assertEqual(WIDGET_MOUSEOVER, [b1, [b1, cur_hand, [f1, cur_none, []]]])
self.assertEqual(get_cursor(), cur_arrow)
# Move from b1 to outside the menu
menu.update(PygameEventUtils.topleft_rect_mouse_motion((1, 1)))
self.assertEqual(test, [False, False, False, False, False, False])
self.assertEqual(WIDGET_MOUSEOVER, [None, []])
self.assertEqual(get_cursor(), cur_none)
# Move from out to b2, this should call f1->f2->b2
menu.update(PygameEventUtils.topleft_rect_mouse_motion(b2))
self.assertEqual(test, [True, False, True, True, False, False])
self.assertEqual(WIDGET_MOUSEOVER, [b2, [b2, cur_hand, [f2, cur_hand, [f1, cur_none, []]]]])
self.assertEqual(menu.get_mouseover_widget(), b2)
self.assertEqual(get_cursor(), cur_arrow)
# Unpack b2
f2.unpack(b2)
if test != [False, False, False, False, False, False]:
return
self.assertEqual(WIDGET_MOUSEOVER, [None, []])
self.assertEqual(get_cursor(), cur_none)
# Check b2
menu.scroll_to_widget(b2)
menu.update(PygameEventUtils.topleft_rect_mouse_motion(b2))
self.assertEqual(test, [False, False, False, True, False, False])
self.assertEqual(WIDGET_MOUSEOVER, [b2, [b2, cur_none, []]])
self.assertEqual(get_cursor(), cur_arrow)
# noinspection PyArgumentList,PyTypeChecker
def test_title(self) -> None:
"""
Test frame title.
"""
menu = MenuUtils.generic_menu(theme=THEME_NON_FIXED_TITLE)
pad = 5
frame = menu.add.frame_v(300, 200, background_color=(170, 170, 170), padding=pad, frame_id='f1')
frame.set_cursor(pygame_menu.locals.CURSOR_HAND)
frame._class_id__repr__ = True
self.assertEqual(frame.get_scroll_value_percentage(ORIENTATION_VERTICAL), -1)
frame_prev_rect = frame.get_rect()
# self.assertRaises(ValueError, lambda: frame.get_title())
frame._accepts_title = False
self.assertRaises(pygame_menu.widgets.widget.frame._FrameDoNotAcceptTitle, lambda: frame.set_title('title'))
self.assertRaises(pygame_menu.widgets.widget.frame._FrameDoNotAcceptTitle,
lambda: frame.add_title_button('none', None))
self.assertRaises(pygame_menu.widgets.widget.frame._FrameDoNotAcceptTitle,
lambda: frame.add_title_generic_button(None))
self.assertRaises(pygame_menu.widgets.widget.frame._FrameDoNotAcceptTitle,
lambda: frame.remove_title())
frame._accepts_title = True
self.assertEqual(frame.get_size(), (300, 200))
self.assertEqual(frame.get_title(), '')
frame.set_onmouseover(lambda: print('over frame 1'))
frame.set_onmouseleave(lambda: print('leave frame 1'))
# Add a title
self.assertNotIn(frame, menu._update_frames)
self.assertEqual(frame._title_height(), 0)
frame.set_title(
'epic',
padding_outer=3,
title_font_size=20,
padding_inner=(0, 3),
title_font_color='white',
title_alignment=pygame_menu.locals.ALIGN_CENTER
)
frame_title = frame.set_title(
'epic',
padding_outer=3,
title_font_size=20,
padding_inner=(0, 3),
title_font_color='white',
title_alignment=pygame_menu.locals.ALIGN_CENTER
)
frame_title.set_onmouseover(lambda: print('over title frame 1'))
frame_title.set_onmouseleave(lambda: print('leave title frame 1'))
self.assertIn(frame, menu._update_frames) # Even if not scrollable
self.assertEqual(frame._title_height(), 34)
self.assertTrue(frame._has_title)
self.assertEqual(frame.get_size(), (300, 234))
self.assertEqual(frame.get_position(), (150 + pad, 73 + pad))
self.assertEqual(len(frame._frame_title.get_widgets()), 1) # The title itself
self.assertEqual(frame._frame_title.get_widgets()[0].get_size(), (38, 28))
self.assertEqual(frame._frame_title.get_widgets()[0].get_title(), 'epic')
self.assertEqual(frame.get_title(), 'epic')
self.assertEqual(frame._title_height(), 34)
self.assertEqual(frame.get_position(), (150 + pad, 73 + pad))
self.assertEqual(frame._frame_title.get_position(), (156, 76))
menu.render()
self.assertEqual(frame.get_position(), (150 + pad, 56 + pad))
self.assertEqual(frame._frame_title.get_position(), (156, 59))
frame.pack(menu.add.button('Button', background_color='green'))
# Test frame cannot set to itself
self.assertRaises(AssertionError, lambda: frame_title.set_frame(frame_title))
# Add button to title
test = [False]
def click_button(**kwargs) -> None:
"""
Click button.
"""
f = kwargs.pop('frame')
b = kwargs.pop('button')
self.assertEqual(f, frame)
self.assertIsInstance(b, Button)
test[0] = not test[0]
# print('clicked')
btn1 = frame.add_title_button(pygame_menu.widgets.FRAME_TITLE_BUTTON_CLOSE, click_button)
btn2 = frame.add_title_button(pygame_menu.widgets.FRAME_TITLE_BUTTON_MAXIMIZE, click_button)
btn3 = frame.add_title_button(pygame_menu.widgets.FRAME_TITLE_BUTTON_MINIMIZE, click_button)
self.assertRaises(ValueError, lambda: frame.add_title_button('none', click_button))
self.assertRaises(IndexError, lambda: frame.get_index(btn1))
self.assertEqual(frame._frame_title.get_index(btn1), 1)
self.assertEqual(frame._frame_title.get_index(btn2), 2)
self.assertEqual(frame._frame_title.get_index(btn3), 3)
self.assertFalse(test[0])
menu.update(PygameEventUtils.middle_rect_click(btn1))
self.assertTrue(test[0])
menu.update(PygameEventUtils.middle_rect_click(btn2))
self.assertFalse(test[0])
menu.update(PygameEventUtils.middle_rect_click(btn3))
self.assertTrue(test[0])
# Scrollable widget
# menu.add.vertical_margin(50)
frame2 = menu.add.frame_v(300, 200, max_height=100, background_color='red', padding=pad, frame_id='f2')
frame2._class_id__repr__ = True
frame2.set_onmouseover(lambda: print('over frame 2'))
frame2.set_onmouseleave(lambda: print('leave frame 2'))
frame2_title = frame2.set_title('title',
padding_outer=3,
title_font_size=20,
padding_inner=(0, 3),
cursor=pygame_menu.locals.CURSOR_CROSSHAIR,
title_font_color='white',
title_alignment=pygame_menu.locals.ALIGN_CENTER,
draggable=True)
frame2_title.set_onmouseover(lambda: print('over title frame 2'))
frame2_title.set_onmouseleave(lambda: print('leave title frame 2'))
btn4 = frame2.add_title_button(pygame_menu.widgets.FRAME_TITLE_BUTTON_CLOSE, None)
self.assertEqual(btn4.get_frame(), frame2._frame_title)
self.assertEqual(frame2.get_position(), (135, 235))
self.assertEqual(frame2.get_size(), (310, 124))
self.assertEqual(frame2._frame_title.get_position(), (141, 238))
self.assertEqual(frame2._frame_title.get_size(), (304, 28))
self.assertEqual(frame2.get_translate(), (0, 0))
# Test events
self.assertFalse(frame2._frame_title.has_attribute('drag'))
menu.update(PygameEventUtils.middle_rect_click(frame2._frame_title))
self.assertTrue(frame2._frame_title.has_attribute('drag'))
self.assertFalse(frame2._frame_title.get_attribute('drag'))
menu.update(PygameEventUtils.middle_rect_click(frame2._frame_title, evtype=pygame.MOUSEBUTTONDOWN))
self.assertTrue(frame2._frame_title.get_attribute('drag'))
menu.update(PygameEventUtils.mouse_motion(frame2._frame_title, rel=(10, 0)))
self.assertEqual(frame2.get_translate(), (10, 0))
menu.update(PygameEventUtils.mouse_motion(frame2._frame_title, rel=(0, -500)))
self.assertEqual(frame2.get_translate(), (10, -235)) # Apply top limit
menu.render()
# Test drag with position way over the item
menu.update(PygameEventUtils.mouse_motion(frame2._frame_title, rel=(0, 100), delta=(0, -100)))
self.assertEqual(frame2.get_translate(), (10, -235)) # Apply top limit restriction
menu.update(PygameEventUtils.middle_rect_click(frame2._frame_title))
self.assertFalse(frame2._frame_title.get_attribute('drag'))
# Test hide
self.assertTrue(frame2._frame_title.is_visible())
self.assertTrue(btn4.is_visible())
frame2.hide()
self.assertFalse(frame2.is_visible())
self.assertFalse(frame2._frame_title.is_visible())
self.assertFalse(btn4.is_visible())
frame2.show()
self.assertTrue(frame2.is_visible())
self.assertTrue(frame2._frame_title.is_visible())
self.assertTrue(btn4.is_visible())
# Remove title from frame 1
frame.remove_title()
self.assertEqual(frame._title_height(), 0)
self.assertNotIn(frame, menu._update_frames)
self.assertFalse(frame._has_title)
menu.render()
self.assertEqual(frame.get_rect().width, frame_prev_rect.width)
self.assertEqual(frame.get_rect().height, frame_prev_rect.height)
# Move frame 1 to bottom
menu.update(PygameEventUtils.middle_rect_click(frame2._frame_title, evtype=pygame.MOUSEBUTTONDOWN))
self.assertTrue(frame2._frame_title.get_attribute('drag'))
menu.render()
menu.update(PygameEventUtils.mouse_motion(frame2._frame_title, rel=(0, 350)))
self.assertEqual(frame2.get_translate(), (10, 115))
menu.render()
menu.update(PygameEventUtils.mouse_motion(frame2._frame_title, rel=(0, 100)))
self.assertEqual(frame2.get_translate(), (10, 115))
# Test more title gradients
frame2.set_title('title',
background_color=((10, 36, 106), (166, 202, 240), True, True))
frame2.set_title('title',
background_color=((10, 36, 106), (166, 202, 240), True, False))
frame2.set_title('title',
background_color=((10, 36, 106), (166, 202, 240), False, False))
frame2.set_frame(frame_title)
frame2.set_scrollarea(frame2.get_scrollarea())
def test_resize(self) -> None:
"""
Test resize.
"""
menu = MenuUtils.generic_menu()
# No title, no scrollable
frame = menu.add.frame_v(300, 200, background_color=(170, 170, 170), frame_id='f1')
self.assertEqual(frame.get_size(), (300, 200))
# Resize
frame.resize(400, 400)
self.assertEqual(frame.get_size(), (400, 400))
# No title, scrollable to non-scrollable
frame2 = menu.add.frame_v(300, 200, background_color=(170, 170, 170),
frame_id='f2', max_width=200, max_height=100)
self.assertEqual(frame2.get_size(), (204, 112))
frame2.resize(400, 400) # Now it's not scrollable
self.assertFalse(frame2.is_scrollable)
self.assertEqual(frame2.get_size(), (400, 400))
self.assertRaises(AssertionError, lambda: frame2.resize(400, 400, max_width=300, max_height=200))
# No title, scrollable to scrollable
frame3 = menu.add.frame_v(300, 200, background_color=(170, 170, 170),
frame_id='f3', max_width=200, max_height=100)
self.assertTrue(frame3.is_scrollable)
frame3.resize(400, 400, max_width=300, max_height=300)
self.assertEqual(frame3.get_size(), (320, 320))
self.assertTrue(frame3.is_scrollable)
# Title, no scrollable
frame4 = menu.add.frame_v(300, 200, background_color=(170, 170, 170), frame_id='f4')
frame4title = frame4.set_title('generic title')
btn1 = frame4.add_title_button(pygame_menu.widgets.FRAME_TITLE_BUTTON_CLOSE, lambda: print(''))
btn2 = frame4.add_title_button(pygame_menu.widgets.FRAME_TITLE_BUTTON_MINIMIZE, lambda: print(''))
frame4title_widgets = frame4._frame_title.get_widgets()
label = frame4title_widgets[0]
self.assertEqual(frame4title_widgets, (label, btn1, btn2))
frame4.resize(600, 600)
new_frame4title_widgets = frame4._frame_title.get_widgets()
label = new_frame4title_widgets[0]
self.assertEqual(frame4.get_size(), (600, 641 if PYGAME_V2 else 642)) # Plus title height
self.assertNotEqual(frame4title, frame4._frame_title)
self.assertEqual(new_frame4title_widgets, (label, btn1, btn2))
|
dcartman/pygame-menu | test/__init__.py | <filename>test/__init__.py
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST
This directory contains all project tests files.
"""
|
dcartman/pygame-menu | pygame_menu/widgets/core/__init__.py | <reponame>dcartman/pygame-menu<filename>pygame_menu/widgets/core/__init__.py
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
CORE
This module contains the widget core classes.
"""
from pygame_menu.widgets.core.widget import Widget
from pygame_menu.widgets.core.selection import Selection
|
dcartman/pygame-menu | test/test_sound.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST SOUND
Test sound management.
"""
__all__ = ['SoundTest']
from test._utils import MenuUtils, BaseTest
import copy
import pygame_menu
class SoundTest(BaseTest):
def setUp(self) -> None:
"""
Setup sound engine.
"""
self.sound = pygame_menu.sound.Sound(force_init=True)
def test_copy(self) -> None:
"""
Test sound copy.
"""
sound_src = pygame_menu.sound.Sound()
sound_src.load_example_sounds()
sound = copy.copy(sound_src)
sound_deep = copy.deepcopy(sound_src)
# Check if sounds are different
t = pygame_menu.sound.SOUND_TYPE_CLICK_MOUSE
self.assertNotEqual(sound_src._sound[t]['file'], sound._sound[t]['file'])
self.assertNotEqual(sound_src._sound[t]['file'], sound_deep._sound[t]['file'])
def test_none_channel(self) -> None:
"""
Test none channel.
"""
new_sound = pygame_menu.sound.Sound(uniquechannel=False)
new_sound.load_example_sounds()
new_sound.play_widget_selection()
new_sound._channel = None
new_sound.stop()
new_sound.pause()
new_sound.unpause()
new_sound.play_error()
self.assertEqual(len(new_sound.get_channel_info()), 5)
def test_channel(self) -> None:
"""
Test channel.
"""
new_sound = pygame_menu.sound.Sound(uniquechannel=False)
new_sound.get_channel()
self.sound.get_channel_info()
self.sound.pause()
self.sound.unpause()
self.sound.stop()
def test_load_sound(self) -> None:
"""
Test load sounds.
"""
self.assertFalse(self.sound.set_sound(pygame_menu.sound.SOUND_TYPE_CLICK_MOUSE, None))
self.assertRaises(ValueError, lambda: self.sound.set_sound('none', None))
self.assertRaises(IOError,
lambda: self.sound.set_sound(pygame_menu.sound.SOUND_TYPE_CLICK_MOUSE, 'bad_file'))
self.assertFalse(self.sound._play_sound(None))
self.assertFalse(self.sound.set_sound(pygame_menu.sound.SOUND_TYPE_ERROR, pygame_menu.font.FONT_PT_SERIF))
def test_example_sounds(self) -> None:
"""
Test example sounds.
"""
self.sound.load_example_sounds()
self.sound.play_click_mouse()
self.sound.play_click_touch()
self.sound.play_close_menu()
self.sound.play_error()
self.sound.play_event()
self.sound.play_event_error()
self.sound.play_key_add()
self.sound.play_key_del()
self.sound.play_open_menu()
def test_sound_menu(self) -> None:
"""
Test sounds in menu.
"""
menu = MenuUtils.generic_menu()
submenu = MenuUtils.generic_menu()
menu.add.button('submenu', submenu)
button = menu.add.button('button', lambda: None)
menu.set_sound(self.sound, True)
self.assertEqual(button.get_sound(), self.sound)
# This will remove the sound engine
menu.set_sound(None, True)
self.assertNotEqual(button.get_sound(), self.sound)
self.assertEqual(menu.get_sound(), menu._sound)
|
dcartman/pygame-menu | test/test_widget_scrollbar.py | <filename>test/test_widget_scrollbar.py
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST WIDGET - SCROLLBAR
Test ScrollBar widget.
"""
__all__ = ['ScrollBarWidgetTest']
from test._utils import surface, PygameEventUtils, WINDOW_SIZE, BaseTest, MenuUtils
import pygame
from pygame_menu.locals import ORIENTATION_VERTICAL, POSITION_SOUTHEAST
from pygame_menu.widgets import ScrollBar
from pygame_menu.widgets.core.widget import WidgetTransformationNotImplemented
class ScrollBarWidgetTest(BaseTest):
def test_scrollbar(self) -> None:
"""
Test ScrollBar widget.
"""
screen_size = surface.get_size()
world = pygame.Surface((WINDOW_SIZE[0] * 2, WINDOW_SIZE[1] * 3))
world.fill((200, 200, 200))
for x in range(100, world.get_width(), 200):
for y in range(100, world.get_height(), 200):
pygame.draw.circle(world, (225, 34, 43), (x, y), 100, 10)
# Vertical right scrollbar
thick = 80
length = screen_size[1]
world_range = (50, world.get_height())
x, y = screen_size[0] - thick, 0
sb = ScrollBar(
length, world_range, 'sb2', ORIENTATION_VERTICAL,
slider_pad=2,
slider_color=(210, 120, 200),
page_ctrl_thick=thick,
page_ctrl_color=(235, 235, 230)
)
self.assertEqual(sb.get_thickness(), 80)
self.assertIsNone(sb.get_scrollarea())
sb.set_shadow(color=(245, 245, 245), position=POSITION_SOUTHEAST)
self.assertFalse(sb._font_shadow)
sb.set_position(x, y)
self.assertEqual(sb._orientation, 1)
self.assertEqual(sb.get_orientation(), ORIENTATION_VERTICAL)
self.assertEqual(sb.get_minimum(), world_range[0])
self.assertEqual(sb.get_maximum(), world_range[1])
sb.set_value(80)
self.assertAlmostEqual(sb.get_value(), 80, delta=2) # Scaling delta
sb.update(PygameEventUtils.mouse_click(x + thick / 2, y + 2, evtype=pygame.MOUSEBUTTONDOWN))
self.assertEqual(sb.get_value(), 50)
self.assertEqual(sb.get_value_percentage(), 0)
sb.set_page_step(length)
self.assertAlmostEqual(sb.get_page_step(), length, delta=2) # Scaling delta
sb.draw(surface)
# Test events
sb.update(PygameEventUtils.key(pygame.K_PAGEDOWN, keydown=True))
self.assertEqual(sb.get_value(), 964)
sb.update(PygameEventUtils.key(pygame.K_PAGEUP, keydown=True))
self.assertEqual(sb.get_value(), 50)
self.assertEqual(sb._last_mouse_pos, (-1, -1))
sb.update(PygameEventUtils.enter_window())
self.assertEqual(sb._last_mouse_pos, (-1, -1))
sb.update(PygameEventUtils.leave_window())
self.assertEqual(sb._last_mouse_pos, pygame.mouse.get_pos())
self.assertFalse(sb.scrolling)
sb.update(PygameEventUtils.middle_rect_click(sb.get_slider_rect(), evtype=pygame.MOUSEBUTTONDOWN))
self.assertTrue(sb.scrolling)
sb.update(PygameEventUtils.mouse_click(1, 1))
self.assertFalse(sb.scrolling)
self.assertEqual(sb.get_value(), 50)
sb.update(PygameEventUtils.middle_rect_click(sb.get_rect(to_absolute_position=True),
evtype=pygame.MOUSEBUTTONDOWN))
self.assertEqual(sb.get_value(), 964)
sb.update(PygameEventUtils.middle_rect_click(sb.get_slider_rect(), evtype=pygame.MOUSEBUTTONDOWN))
self.assertTrue(sb.scrolling)
sb.update(PygameEventUtils.middle_rect_click(sb.get_slider_rect(), button=4,
evtype=pygame.MOUSEBUTTONDOWN))
self.assertEqual(sb.get_value(), 875)
sb.update(PygameEventUtils.middle_rect_click(sb.get_slider_rect(), button=5,
evtype=pygame.MOUSEBUTTONDOWN))
self.assertEqual(sb.get_value(), 964)
self.assertEqual(sb.get_value_percentage(), 0.522)
# Test mouse motion while scrolling
sb.update(PygameEventUtils.middle_rect_click(sb.get_slider_rect(), button=5, delta=(0, 50), rel=(0, 10),
evtype=pygame.MOUSEMOTION))
self.assertEqual(sb.get_value_percentage(), 0.547)
sb.update(PygameEventUtils.middle_rect_click(sb.get_slider_rect(), button=5, delta=(0, 50), rel=(0, -10),
evtype=pygame.MOUSEMOTION))
self.assertEqual(sb.get_value_percentage(), 0.522)
sb.update(PygameEventUtils.middle_rect_click(sb.get_slider_rect(), button=5, delta=(0, 50), rel=(0, 999),
evtype=pygame.MOUSEMOTION))
self.assertEqual(sb.get_value_percentage(), 1)
sb.readonly = True
self.assertFalse(sb.update([]))
# Ignore events if mouse outside the region
sb.update(PygameEventUtils.middle_rect_click(sb.get_slider_rect(), button=5, delta=(0, 999), rel=(0, -10),
evtype=pygame.MOUSEMOTION))
self.assertIn(sb.get_value_percentage(), (0.976, 1))
# Test remove onreturn
sb = ScrollBar(length, world_range, 'sb', ORIENTATION_VERTICAL, onreturn=-1)
self.assertIsNone(sb._onreturn)
self.assertTrue(sb._kwargs.get('onreturn', 0))
# Scrollbar ignores scaling
self.assertRaises(WidgetTransformationNotImplemented, lambda: sb.scale(2, 2))
self.assertFalse(sb._scale[0])
self.assertRaises(WidgetTransformationNotImplemented, lambda: sb.resize(2, 2))
self.assertFalse(sb._scale[0])
self.assertRaises(WidgetTransformationNotImplemented, lambda: sb.set_max_width(10))
self.assertIsNone(sb._max_width[0])
self.assertRaises(WidgetTransformationNotImplemented, lambda: sb.set_max_height(10))
self.assertIsNone(sb._max_height[0])
sb._apply_font()
sb.set_padding(10)
self.assertEqual(sb._padding[0], 0)
self.assertRaises(WidgetTransformationNotImplemented, lambda: sb.rotate(10))
self.assertEqual(sb._angle, 0)
self.assertRaises(WidgetTransformationNotImplemented, lambda: sb.flip(True, True))
self.assertFalse(sb._flip[0])
self.assertFalse(sb._flip[1])
# Set minimum
sb.set_minimum(0.5 * sb._values_range[1])
# Test hide
sb._mouseover = True
sb.hide()
def test_value(self) -> None:
"""
Test scrollbar value.
"""
menu = MenuUtils.generic_menu()
sb = menu.get_scrollarea()._scrollbars[0]
self.assertEqual(sb._default_value, 0)
self.assertEqual(sb.get_value(), 0)
self.assertFalse(sb.value_changed())
sb.set_value(1)
self.assertEqual(sb.get_value(), 1)
self.assertTrue(sb.value_changed())
sb.reset_value()
self.assertEqual(sb.get_value(), 0)
self.assertFalse(sb.value_changed())
|
dcartman/pygame-menu | test/test_widget_menubar.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST WIDGET - MENUBAR
Test MenuBar widget.
"""
__all__ = ['MenuBarWidgetTest']
from test._utils import MenuUtils, surface, PygameEventUtils, BaseTest
import pygame
import pygame_menu
import pygame_menu.controls as ctrl
from pygame_menu.locals import POSITION_NORTH, POSITION_SOUTH, POSITION_EAST, \
POSITION_WEST, POSITION_SOUTHWEST
from pygame_menu.widgets import MENUBAR_STYLE_ADAPTIVE, MENUBAR_STYLE_NONE, \
MENUBAR_STYLE_SIMPLE, MENUBAR_STYLE_UNDERLINE, MENUBAR_STYLE_UNDERLINE_TITLE, \
MENUBAR_STYLE_TITLE_ONLY, MENUBAR_STYLE_TITLE_ONLY_DIAGONAL
from pygame_menu.widgets import MenuBar
from pygame_menu.widgets.core.widget import WidgetTransformationNotImplemented
class MenuBarWidgetTest(BaseTest):
# noinspection PyTypeChecker,PyArgumentEqualDefault
def test_menubar(self) -> None:
"""
Test menubar widget.
"""
menu = MenuUtils.generic_menu()
for mode in (MENUBAR_STYLE_ADAPTIVE, MENUBAR_STYLE_NONE, MENUBAR_STYLE_SIMPLE,
MENUBAR_STYLE_UNDERLINE, MENUBAR_STYLE_UNDERLINE_TITLE,
MENUBAR_STYLE_TITLE_ONLY, MENUBAR_STYLE_TITLE_ONLY_DIAGONAL):
mb = MenuBar('Menu', 500, (0, 0, 0), back_box=True, mode=mode)
menu.add.generic_widget(mb)
mb = MenuBar('Menu', 500, (0, 0, 0), back_box=True)
mb.set_backbox_border_width(2)
self.assertRaises(AssertionError, lambda: mb.set_backbox_border_width(1.5))
self.assertRaises(AssertionError, lambda: mb.set_backbox_border_width(0))
self.assertRaises(AssertionError, lambda: mb.set_backbox_border_width(-1))
self.assertEqual(mb._backbox_border_width, 2)
menu.draw(surface)
menu.disable()
# Test unknown mode
mb = MenuBar('Menu', 500, (0, 0, 0), back_box=True, mode='unknown')
mb.set_menu(menu)
self.assertRaises(ValueError, lambda: mb._render())
# Check margins
mb = MenuBar('Menu', 500, (0, 0, 0), back_box=True, mode=MENUBAR_STYLE_ADAPTIVE)
self.assertEqual(mb.get_scrollbar_style_change(POSITION_SOUTH), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_EAST), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_WEST), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_NORTH), (0, (0, 0)))
mb.set_menu(menu)
mb._render()
self.assertEqual(mb.get_scrollbar_style_change(POSITION_SOUTHWEST), (0, (0, 0)))
# Test displacements
theme = pygame_menu.themes.THEME_DEFAULT.copy()
theme.title_bar_style = MENUBAR_STYLE_TITLE_ONLY
menu = MenuUtils.generic_menu(theme=theme, title='my title')
mb = menu.get_menubar()
self.assertEqual(mb.get_scrollbar_style_change(POSITION_SOUTH), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_EAST), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_WEST), (-55, (0, 55)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_NORTH), (0, (0, 55)))
# Test with close button
menu = MenuUtils.generic_menu(theme=theme, title='my title',
onclose=pygame_menu.events.CLOSE,
touchscreen=True)
theme.widget_border_inflate = 0
mb = menu.get_menubar()
self.assertEqual(mb.get_scrollbar_style_change(POSITION_SOUTH), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_EAST), (-33, (0, 33)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_WEST), (-55, (0, 55)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_NORTH), (0, (0, 55)))
# Hide the title, and check
mb.hide()
self.assertEqual(mb.get_scrollbar_style_change(POSITION_SOUTH), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_EAST), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_WEST), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_NORTH), (0, (0, 0)))
mb.show()
self.assertEqual(mb.get_scrollbar_style_change(POSITION_SOUTH), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_EAST), (-33, (0, 33)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_WEST), (-55, (0, 55)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_NORTH), (0, (0, 55)))
# Floating
mb.set_float(True)
self.assertEqual(mb.get_scrollbar_style_change(POSITION_SOUTH), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_EAST), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_WEST), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_NORTH), (0, (0, 0)))
mb.set_float(False)
self.assertEqual(mb.get_scrollbar_style_change(POSITION_SOUTH), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_EAST), (-33, (0, 33)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_WEST), (-55, (0, 55)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_NORTH), (0, (0, 55)))
# Fixed
mb.fixed = False
self.assertEqual(mb.get_scrollbar_style_change(POSITION_SOUTH), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_EAST), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_WEST), (0, (0, 0)))
self.assertEqual(mb.get_scrollbar_style_change(POSITION_NORTH), (0, (0, 0)))
# Test menubar
self.assertFalse(mb.update(PygameEventUtils.middle_rect_click(mb._rect)))
self.assertTrue(mb.update(PygameEventUtils.middle_rect_click(mb._backbox_rect)))
self.assertTrue(mb.update(PygameEventUtils.middle_rect_click(
mb._backbox_rect, evtype=pygame.FINGERUP, menu=menu)))
self.assertFalse(mb.update(PygameEventUtils.middle_rect_click(
mb._backbox_rect, evtype=pygame.MOUSEBUTTONDOWN)))
self.assertTrue(mb.update(PygameEventUtils.joy_button(ctrl.JOY_BUTTON_BACK)))
mb.readonly = True
self.assertFalse(mb.update(PygameEventUtils.joy_button(ctrl.JOY_BUTTON_BACK)))
mb.readonly = False
# Test none methods
self.assertRaises(WidgetTransformationNotImplemented, lambda: mb.rotate(10))
self.assertEqual(mb._angle, 0)
self.assertRaises(WidgetTransformationNotImplemented, lambda: mb.resize(10, 10))
self.assertFalse(mb._scale[0])
self.assertEqual(mb._scale[1], 1)
self.assertEqual(mb._scale[2], 1)
self.assertRaises(WidgetTransformationNotImplemented, lambda: mb.scale(100, 100))
self.assertFalse(mb._scale[0])
self.assertEqual(mb._scale[1], 1)
self.assertEqual(mb._scale[2], 1)
self.assertRaises(WidgetTransformationNotImplemented, lambda: mb.flip(True, True))
self.assertFalse(mb._flip[0])
self.assertFalse(mb._flip[1])
self.assertRaises(WidgetTransformationNotImplemented, lambda: mb.set_max_width(100))
self.assertIsNone(mb._max_width[0])
self.assertRaises(WidgetTransformationNotImplemented, lambda: mb.set_max_height(100))
self.assertIsNone(mb._max_height[0])
# Ignore others
mb.set_padding()
mb.set_border()
mb.set_selection_effect()
menu.add.button('nice')
def test_empty_title(self) -> None:
"""
Test empty title.
"""
title = MenuBar('', 500, (0, 0, 0), back_box=True)
p = title._padding
self.assertEqual(title.get_width(), p[1] + p[3])
self.assertEqual(title.get_height(), p[0] + p[2])
def test_value(self) -> None:
"""
Test menubar value.
"""
mb = MenuBar('Menu', 500, (0, 0, 0), back_box=True)
self.assertRaises(ValueError, lambda: mb.get_value())
self.assertRaises(ValueError, lambda: mb.set_value('value'))
self.assertFalse(mb.value_changed())
mb.reset_value()
|
dcartman/pygame-menu | pygame_menu/widgets/selection/none.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
NONE
No selection effect.
"""
__all__ = ['NoneSelection']
import pygame
import pygame_menu
from pygame_menu.widgets.selection.simple import SimpleSelection
class NoneSelection(SimpleSelection):
"""
No selection effect.
"""
def __init__(self) -> None:
super(NoneSelection, self).__init__()
self.widget_apply_font_color = False
# noinspection PyMissingOrEmptyDocstring
def draw(self, surface: 'pygame.Surface', widget: 'pygame_menu.widgets.Widget') -> 'NoneSelection':
return self
|
dcartman/pygame-menu | pygame_menu/examples/__init__.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
EXAMPLES
Example file directory.
"""
__all__ = ['create_example_window']
import pygame
import sys
from typing import Tuple
_PYGAME_ICON = [None]
# noinspection PyTypeChecker
def create_example_window(
title: str,
window_size: Tuple[int, int],
pygame_menu_icon: bool = True,
init_pygame: bool = True,
center_window: bool = True,
**kwargs
) -> 'pygame.Surface':
"""
Set pygame window.
:param title: Window title
:param window_size: Window size
:param pygame_menu_icon: Use pygame menu icon
:param init_pygame: Init pygame
:param center_window: Center the window
:param kwargs: Optional keyword arguments received by display set_mode
:return: Pygame surface from created display
"""
assert len(title) > 0, 'title cannot be empty'
assert len(window_size) == 2, 'window size shape must be (width, height)'
assert isinstance(window_size[0], int), 'width must be an integer'
assert isinstance(window_size[1], int), 'height must be an integer'
from pygame_menu.baseimage import IMAGE_EXAMPLE_PYGAME_MENU, BaseImage
import os
if init_pygame:
pygame.init()
if center_window:
os.environ['SDL_VIDEO_CENTERED'] = '1'
# Create pygame screen and objects
if sys.platform == 'darwin':
kwargs = {}
try:
surface = pygame.display.set_mode(window_size, **kwargs)
except TypeError:
surface = pygame.display.set_mode(window_size)
pygame.display.set_caption(title)
if pygame_menu_icon:
# noinspection PyBroadException
try:
if _PYGAME_ICON[0] is not None:
pygame.display.set_icon(_PYGAME_ICON[0])
else:
icon = BaseImage(IMAGE_EXAMPLE_PYGAME_MENU).get_surface(new=False)
pygame.display.set_icon(icon)
_PYGAME_ICON[0] = icon
except BaseException: # lgtm [py/catch-base-exception]
pass
return surface
|
dcartman/pygame-menu | pygame_menu/events.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
EVENTS
Menu events definition and locals.
"""
__all__ = [
# Class
'MenuAction',
# Utils
'is_event',
# Menu events
'BACK',
'CLOSE',
'EXIT',
'NONE',
'RESET',
# Last menu events
'MENU_LAST_DISABLE_UPDATE',
'MENU_LAST_FRAMES',
'MENU_LAST_JOY_REPEAT',
'MENU_LAST_MENU_BACK',
'MENU_LAST_MENU_CLOSE',
'MENU_LAST_MENUBAR',
'MENU_LAST_MOUSE_ENTER_MENU',
'MENU_LAST_MOUSE_ENTER_WINDOW',
'MENU_LAST_MOUSE_LEAVE_MENU',
'MENU_LAST_MOUSE_LEAVE_WINDOW',
'MENU_LAST_MOVE_DOWN',
'MENU_LAST_MOVE_LEFT',
'MENU_LAST_MOVE_RIGHT',
'MENU_LAST_MOVE_UP',
'MENU_LAST_NONE',
'MENU_LAST_QUIT',
'MENU_LAST_SCROLL_AREA',
'MENU_LAST_SELECTED_WIDGET_BUTTON_UP',
'MENU_LAST_SELECTED_WIDGET_EVENT',
'MENU_LAST_SELECTED_WIDGET_FINGER_UP',
'MENU_LAST_WIDGET_DISABLE_ACTIVE_STATE',
'MENU_LAST_WIDGET_SELECT',
'MENU_LAST_WIDGET_SELECT_MOTION',
# Pygame events
'PYGAME_QUIT',
'PYGAME_WINDOWCLOSE'
]
from typing import Any
import pygame.locals as __locals
class MenuAction(object):
"""
Pygame-menu events.
:param action: Action identifier
"""
_action: int
def __init__(self, action: int) -> None:
assert isinstance(action, int)
self._action = action
def __eq__(self, other: 'MenuAction') -> bool:
if isinstance(other, MenuAction):
return self._action == other._action
return False
def is_event(event: Any) -> bool:
"""
Check if event is pygame_menu event type.
:param event: Event
:return: ``True`` if it's an event
"""
return isinstance(event, MenuAction) or \
str(type(event)) == "<class 'pygame_menu.events.MenuAction'>"
# Events
BACK = MenuAction(0) # Menu back
CLOSE = MenuAction(1) # Close Menu
EXIT = MenuAction(3) # Menu exit program
NONE = MenuAction(4) # None action. It's the same as 'None'
RESET = MenuAction(5) # Menu reset
# Pygame events
PYGAME_QUIT = __locals.QUIT
PYGAME_WINDOWCLOSE = -1
if hasattr(__locals, 'WINDOWCLOSE'):
PYGAME_WINDOWCLOSE = __locals.WINDOWCLOSE
elif hasattr(__locals, 'WINDOWEVENT_CLOSE'):
PYGAME_WINDOWCLOSE = __locals.WINDOWEVENT_CLOSE
# Menu last event types. Returned by menu.get_last_update_mode()
MENU_LAST_DISABLE_UPDATE = 'DISABLE_UPDATE'
MENU_LAST_FRAMES = 'FRAMES'
MENU_LAST_JOY_REPEAT = 'JOY_REPEAT'
MENU_LAST_MENU_BACK = 'MENU_BACK'
MENU_LAST_MENU_CLOSE = 'MENU_CLOSE'
MENU_LAST_MENUBAR = 'MENUBAR'
MENU_LAST_MOUSE_ENTER_MENU = 'MOUSE_ENTER_MENU'
MENU_LAST_MOUSE_ENTER_WINDOW = 'MOUSE_ENTER_WINDOW'
MENU_LAST_MOUSE_LEAVE_MENU = 'MOUSE_LEAVE_MENU'
MENU_LAST_MOUSE_LEAVE_WINDOW = 'MOUSE_LEAVE_WINDOW'
MENU_LAST_MOVE_DOWN = 'MOVE_DOWN'
MENU_LAST_MOVE_LEFT = 'MOVE_LEFT'
MENU_LAST_MOVE_RIGHT = 'MOVE_RIGHT'
MENU_LAST_MOVE_UP = 'MOVE_UP'
MENU_LAST_NONE = 'NONE'
MENU_LAST_QUIT = 'QUIT'
MENU_LAST_SCROLL_AREA = 'SCROLL_AREA'
MENU_LAST_SELECTED_WIDGET_BUTTON_UP = 'SELECTED_WIDGET_BUTTON_UP'
MENU_LAST_SELECTED_WIDGET_EVENT = 'SELECTED_WIDGET_EVENT'
MENU_LAST_SELECTED_WIDGET_FINGER_UP = 'SELECTED_WIDGET_FINGER_UP'
MENU_LAST_WIDGET_DISABLE_ACTIVE_STATE = 'WIDGET_DISABLE_ACTIVE_STATE'
MENU_LAST_WIDGET_SELECT = 'WIDGET_SELECT'
MENU_LAST_WIDGET_SELECT_MOTION = 'WIDGET_SELECT_MOTION'
|
dcartman/pygame-menu | pygame_menu/__pyinstaller/__init__.py | <reponame>dcartman/pygame-menu<filename>pygame_menu/__pyinstaller/__init__.py
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
PYINSTALLER
Module for pyinstaller.
"""
__all__ = ['get_hook_dirs']
import os
from typing import List
def get_hook_dirs() -> List[str]:
"""
Return hook dirs to PyInstaller.
:return: Hook dir list
"""
return [os.path.dirname(__file__)]
|
dcartman/pygame-menu | test/test_base.py | <gh_stars>0
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST BASE
Test base class.
"""
__all__ = ['BaseTest']
from test._utils import BaseTest as _BaseTest
# noinspection PyProtectedMember
from pygame_menu._base import Base
class BaseTest(_BaseTest):
def test_counter(self) -> None:
"""
Test counter.
"""
obj = Base('')
self.assertEqual(obj.get_counter_attribute('count', 1), 1)
self.assertEqual(obj.get_counter_attribute('count', 1), 2)
self.assertEqual(obj.get_counter_attribute('count', 1), 3)
self.assertEqual(obj.get_counter_attribute('count', 1), 4)
self.assertEqual(obj.get_counter_attribute('count', 1), 5)
self.assertEqual(obj.get_counter_attribute('count', 1), 6)
self.assertAlmostEqual(obj.get_counter_attribute('count_epic', 1, '3.14'), 4.14)
self.assertAlmostEqual(obj.get_counter_attribute('count_epic', 1, '3.14'), 5.14)
self.assertAlmostEqual(obj.get_counter_attribute('count_epic', 1, '3.14'), 6.14)
# Test check instance
self.assertEqual(obj.get_counter_attribute('count1', 1, '1'), 2)
self.assertEqual(obj.get_counter_attribute('count1', 1, '1'), 3)
# Test check instance
self.assertEqual(obj.get_counter_attribute('count2', 1.0, '1'), 2.0)
self.assertEqual(obj.get_counter_attribute('count2', 1.0, '1'), 3.0)
def test_classid(self) -> None:
"""
Test class id.
"""
obj = Base('id')
self.assertEqual(obj.get_class_id(), 'Base<"id">')
def test_attributes(self) -> None:
"""
Test attributes.
"""
obj = Base('')
self.assertFalse(obj.has_attribute('epic'))
self.assertRaises(IndexError, lambda: obj.remove_attribute('epic'))
obj.set_attribute('epic', True)
self.assertTrue(obj.has_attribute('epic'))
self.assertTrue(obj.get_attribute('epic'))
obj.set_attribute('epic', False)
self.assertFalse(obj.get_attribute('epic'))
obj.remove_attribute('epic')
self.assertFalse(obj.has_attribute('epic'))
self.assertEqual(obj.get_attribute('epic', 420), 420)
def test_repr(self) -> None:
"""
Test base repr.
"""
obj = Base('id')
self.assertNotIn('["id"]', str(obj))
obj._id__repr__ = True
self.assertIn('["id"]', str(obj))
obj = Base('id2')
obj._class_id__repr__ = True
self.assertEqual(str(obj), 'Base<"id2">')
|
dcartman/pygame-menu | pygame_menu/widgets/widget/__init__.py | <filename>pygame_menu/widgets/widget/__init__.py
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
WIDGET
This module contains the widgets of pygame-menu.
"""
from pygame_menu.widgets.widget.button import Button
from pygame_menu.widgets.widget.colorinput import ColorInput
from pygame_menu.widgets.widget.dropselect import DropSelect
from pygame_menu.widgets.widget.dropselect_multiple import DropSelectMultiple
from pygame_menu.widgets.widget.frame import Frame
from pygame_menu.widgets.widget.hmargin import HMargin
from pygame_menu.widgets.widget.image import Image
from pygame_menu.widgets.widget.label import Label
from pygame_menu.widgets.widget.menubar import MenuBar
from pygame_menu.widgets.widget.menulink import MenuLink
from pygame_menu.widgets.widget.none import NoneWidget
from pygame_menu.widgets.widget.progressbar import ProgressBar
from pygame_menu.widgets.widget.rangeslider import RangeSlider
from pygame_menu.widgets.widget.scrollbar import ScrollBar
from pygame_menu.widgets.widget.selector import Selector
from pygame_menu.widgets.widget.surface import SurfaceWidget
from pygame_menu.widgets.widget.table import Table
from pygame_menu.widgets.widget.textinput import TextInput
from pygame_menu.widgets.widget.toggleswitch import ToggleSwitch
from pygame_menu.widgets.widget.vmargin import VMargin
|
dcartman/pygame-menu | pygame_menu/examples/other/dynamic_button_append.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
EXAMPLE - DYNAMIC BUTTON
Menu with dynamic buttons.
"""
__all__ = ['main']
import pygame_menu
from pygame_menu.examples import create_example_window
from random import randrange
surface = create_example_window('Example - Dynamic Button Append', (600, 400))
menu = pygame_menu.Menu(
height=300,
theme=pygame_menu.themes.THEME_BLUE,
title='Welcome',
width=400
)
def add_dynamic_button() -> 'pygame_menu.widgets.Button':
"""
Append a button to the menu on demand.
:return: Appended button
"""
print(f'Adding a button dynamically, total: {len(menu.get_widgets()) - 2}')
btn = menu.add.button(randrange(0, 10))
def _update_button() -> None:
count = btn.get_counter_attribute('count', 1, btn.get_title())
btn.set_title(str(count))
btn.update_callback(_update_button)
return btn
menu.add.text_input('Name: ', default='<NAME>')
menu.add.button('Play', add_dynamic_button)
menu.add.button('Quit', pygame_menu.events.EXIT)
def main(test: bool = False) -> None:
"""
Main function.
:param test: Indicate function is being tested
"""
menu.mainloop(surface, disable_loop=test)
if __name__ == '__main__':
main()
|
dcartman/pygame-menu | test/test_examples.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST EXAMPLES
Test example files.
"""
__all__ = ['ExamplesTest']
from test._utils import BaseRSTest, MenuUtils, PygameEventUtils, \
test_reset_surface
import pygame
import pygame_menu
import pygame_menu.examples.game_selector as game_selector
import pygame_menu.examples.multi_input as multi_input
import pygame_menu.examples.scroll_menu as scroll_menu
import pygame_menu.examples.simple as simple
import pygame_menu.examples.timer_clock as timer_clock
import pygame_menu.examples.window_resize as window_resize
import pygame_menu.examples.other.calculator as calculator
import pygame_menu.examples.other.dynamic_button_append as dynamic_button
import pygame_menu.examples.other.dynamic_widget_update as dynamic_widget
import pygame_menu.examples.other.image_background as image_background
import pygame_menu.examples.other.maze as maze
import pygame_menu.examples.other.scrollbar as scrollbar
import pygame_menu.examples.other.scrollbar_area as scrollbar_area
import pygame_menu.examples.other.ui_solar_system as ui_solarsystem
import pygame_menu.examples.other.widget_positioning as widget_positioning
# Reset the surface as some example could have changed it
test_reset_surface()
class ExamplesTest(BaseRSTest):
def test_example_game_selector(self) -> None:
"""
Test game selector example.
"""
game_selector.main(test=True)
font = MenuUtils.load_font(MenuUtils.random_font(), 5)
game_selector.play_function(['EASY'], font, test=True)
pygame.event.post(PygameEventUtils.keydown(pygame.K_ESCAPE, inlist=False))
game_selector.play_function(['MEDIUM'], font, test=True)
pygame.event.post(PygameEventUtils.keydown(pygame.K_ESCAPE, inlist=False))
game_selector.play_function(['HARD'], font, test=True)
self.assertRaises(ValueError,
lambda: game_selector.play_function(['U'], font, test=True))
game_selector.change_difficulty(('HARD', 1), 'HARD')
def test_example_multi_input(self) -> None:
"""
Test multi-input example.
"""
multi_input.main(test=True)
multi_input.check_name_test('name')
multi_input.update_menu_sound(('sound', None), True)
multi_input.update_menu_sound(('sound', None), False)
# Test methods within submenus
settings = multi_input.main_menu.get_submenus()[0]
settings.get_widget('store').apply()
# Check range slider has event
rslider = settings.get_widget('range_slider')
self.assertIsNotNone(rslider._onchange)
self.assertEqual(rslider.get_value(), 50)
rslider.set_value(69)
rslider.change()
self.assertEqual(settings.get_widget('progress').get_value(), 69)
more_settings = multi_input.main_menu.get_submenus()[1]
# noinspection PyTypeChecker
hex_color_widget: 'pygame_menu.widgets.ColorInput' = more_settings.get_widget('hex_color')
hex_color_widget.apply()
@staticmethod
def test_example_scroll_menu() -> None:
"""
Test scroll menu example.
"""
scroll_menu.main(test=True)
scroll_menu.on_button_click('pygame-menu', 'epic')
scroll_menu.on_button_click('pygame-menu')
@staticmethod
def test_example_simple() -> None:
"""
Test example simple.
"""
sel = simple.menu.get_widgets()[1]
sel.change(sel.get_value())
btn = simple.menu.get_widgets()[2]
btn.apply()
def test_example_resizable_window(self) -> None:
"""
Test resizable window.
"""
window_resize.on_resize()
self.assertEqual(window_resize.menu.get_window_size(), (600, 600))
self.assertEqual(window_resize.menu.get_size(), (450, 420))
@staticmethod
def test_example_timer_clock() -> None:
"""
Test timer clock example.
"""
pygame.event.post(PygameEventUtils.keydown(pygame.K_ESCAPE, inlist=False))
timer_clock.main(test=True)
timer_clock.mainmenu_background()
timer_clock.reset_timer()
timer_clock.TestCallClassMethod.update_game_settings()
color = (-1, -1, -1)
timer_clock.change_color_bg((color, 'random',), color, write_on_console=True)
def test_example_other_calculator(self) -> None:
"""
Test calculator example.
"""
app = calculator.main(test=True)
# Process events
app.process_events(PygameEventUtils.keydown([pygame.K_1, pygame.K_2, pygame.K_3, pygame.K_4,
pygame.K_5, pygame.K_PLUS]))
self.assertEqual(app.prev, '12345')
self.assertEqual(app.op, '+')
app.process_events(PygameEventUtils.keydown([pygame.K_6, pygame.K_7, pygame.K_8, pygame.K_9,
pygame.K_0]))
self.assertEqual(app.curr, '67890')
app.process_events(PygameEventUtils.keydown(pygame.K_EQUALS))
self.assertEqual(app.op, '')
self.assertEqual(app.curr, '80235')
self.assertEqual(app.prev, '')
app.process_events(PygameEventUtils.keydown([pygame.K_x, pygame.K_2]))
self.assertEqual(app.op, 'x')
self.assertEqual(app.curr, '2')
self.assertEqual(app.prev, '80235')
app.process_events(PygameEventUtils.keydown([pygame.K_x]))
self.assertEqual(app.op, 'x')
self.assertEqual(app.curr, '')
self.assertEqual(app.prev, '160470')
app.process_events(PygameEventUtils.keydown([pygame.K_PLUS, pygame.K_3, pygame.K_0]))
self.assertEqual(app.op, '+')
self.assertEqual(app.curr, '30')
self.assertEqual(app.prev, '160470')
app.process_events(PygameEventUtils.keydown(pygame.K_EQUALS))
self.assertEqual(app.op, '')
self.assertEqual(app.curr, '160500')
self.assertEqual(app.prev, '')
app.process_events(PygameEventUtils.keydown([pygame.K_SLASH, pygame.K_5, pygame.K_MINUS]))
self.assertEqual(app.op, '-')
self.assertEqual(app.curr, '')
self.assertEqual(app.prev, '32100')
app.process_events(PygameEventUtils.keydown([pygame.K_3, pygame.K_2, pygame.K_1, pygame.K_0, pygame.K_EQUALS]))
self.assertEqual(app.op, '')
self.assertEqual(app.curr, '28890')
self.assertEqual(app.prev, '')
app.process_events(PygameEventUtils.keydown([pygame.K_9, pygame.K_BACKSPACE]))
self.assertEqual(app.op, '')
self.assertEqual(app.curr, '')
self.assertEqual(app.prev, '')
# Test methods
self.assertRaises(ValueError, lambda: app._format('n'))
self.assertEqual(app._format('1.2'), '1')
self.assertEqual(app._format('2.0'), '2')
# Test selection
app.menu._test_print_widgets()
b1 = app.menu.get_widgets()[4]
b1d = b1.get_decorator()
lay = b1.get_attribute('on_layer')
self.assertFalse(b1d.is_enabled(lay))
b1.select()
self.assertTrue(b1d.is_enabled(lay))
b1.select(False)
self.assertFalse(b1d.is_enabled(lay))
def test_example_other_dynamic_button_append(self) -> None:
"""
Test dynamic button example.
"""
btn = dynamic_button.add_dynamic_button()
self.assertEqual(btn.get_counter_attribute('count'), 0)
btn.apply()
self.assertEqual(btn.get_counter_attribute('count'), 1)
dynamic_button.main(test=True)
@staticmethod
def test_example_other_dynamic_widget_update() -> None:
"""
Test dynamic widget update example.
"""
app = dynamic_widget.App()
app.current = 3
app.animate_quit_button(app.quit_button, app.menu)
dynamic_widget.main(test=True)
app.fake_quit()
app._on_selector_change(3, 3)
@staticmethod
def test_example_other_image_background() -> None:
"""
Test background image example.
"""
image_background.main(test=True)
def test_example_other_maze(self) -> None:
"""
Test maze app example.
"""
app = maze.MazeApp(rows=10)
btn = app._menu.get_widget('clear')
app._path_found = True
btn.apply()
self.assertFalse(app._path_found)
app._visualize = False
# noinspection PyTypeChecker
gen: 'pygame_menu.widgets.DropSelect' = app._menu.get_widget('generator')
# noinspection PyTypeChecker
sol: 'pygame_menu.widgets.DropSelect' = app._menu.get_widget('solver')
for i in range(4):
gen.set_value(i)
sol.set_value(i)
app._run_generator()
app._run_solver()
@staticmethod
def test_example_other_scrollbar() -> None:
"""
Test scrollbar example.
"""
pygame.event.post(PygameEventUtils.keydown(pygame.K_v, inlist=False))
pygame.event.post(PygameEventUtils.keydown(pygame.K_h, inlist=False))
scrollbar.main(test=True)
scrollbar.h_changed(1)
scrollbar.v_changed(1)
@staticmethod
def test_example_other_scrollbar_area() -> None:
"""
Test scrollbar area example.
"""
pygame.event.post(PygameEventUtils.keydown(pygame.K_ESCAPE, inlist=False))
scrollbar_area.main(test=True)
def test_example_other_ui_solar_system(self) -> None:
"""
Test solar system.
"""
app = ui_solarsystem.main(test=True)
self.assertFalse(app.menu._disable_draw)
app.process_events(PygameEventUtils.keydown([pygame.K_p]), app.menu)
self.assertTrue(app.menu._disable_draw)
app.process_events(PygameEventUtils.keydown([pygame.K_p, pygame.K_q, pygame.K_e, pygame.K_s, pygame.K_c]),
app.menu)
self.assertFalse(app.menu._disable_draw)
def test_example_other_widget_positioning(self) -> None:
"""
Test widget positioning.
"""
widget_positioning.menu.render()
self.assertTrue(widget_positioning.f.is_floating())
self.assertTrue(widget_positioning.b1.is_floating())
self.assertTrue(widget_positioning.b2.is_floating())
|
dcartman/pygame-menu | pygame_menu/examples/window_resize.py | <reponame>dcartman/pygame-menu
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
EXAMPLE - WINDOW RESIZE
Resize the menu when the window is resized.
"""
import pygame
import pygame_menu
pygame.init()
surface = pygame.display.set_mode((600, 400), pygame.RESIZABLE)
pygame.display.set_caption("Example resizable window")
menu = pygame_menu.Menu(
height=100,
theme=pygame_menu.themes.THEME_BLUE,
title='Welcome',
width=100
)
def on_resize() -> None:
"""
Function checked if the window is resized.
"""
window_size = surface.get_size()
new_w, new_h = 0.75 * window_size[0], 0.7 * window_size[1]
menu.resize(new_w, new_h)
print(f'New menu size: {menu.get_size()}')
menu.add.label('Resize the window!')
user_name = menu.add.text_input('Name: ', default='<NAME>', maxchar=10)
menu.add.selector('Difficulty: ', [('Hard', 1), ('Easy', 2)])
menu.add.button('Quit', pygame_menu.events.EXIT)
menu.enable()
on_resize() # Set initial size
if __name__ == '__main__':
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
break
if event.type == pygame.VIDEORESIZE:
# Update the surface
surface = pygame.display.set_mode((event.w, event.h),
pygame.RESIZABLE)
# Call the menu event
on_resize()
# Draw the menu
surface.fill((25, 0, 50))
menu.update(events)
menu.draw(surface)
pygame.display.flip()
|
dcartman/pygame-menu | pygame_menu/widgets/widget/none.py | <gh_stars>0
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
NONE WIDGET
None widget definition.
"""
__all__ = [
'NoneWidget',
'NoneWidgetManager'
]
import pygame
import pygame_menu
from abc import ABC
from pygame_menu.utils import make_surface
from pygame_menu.widgets.core.widget import Widget, WidgetTransformationNotImplemented, \
AbstractWidgetManager
from pygame_menu._types import Optional, NumberType, EventVectorType
# noinspection PyMissingOrEmptyDocstring
class NoneWidget(Widget):
"""
None widget. Useful if used for filling column/row layout. None widget don't
accept values, padding, margin, cursors, position, sound, controls, and
cannot be selected. Also, none widget cannot accept callbacks, except draw
and update callbacks.
.. note::
NoneWidget does not accept any transformation.
:param widget_id: ID of the widget
"""
def __init__(
self,
widget_id: str = ''
) -> None:
super(NoneWidget, self).__init__(widget_id=widget_id)
self.is_selectable = False
self._surface = make_surface(0, 0, alpha=True)
def _apply_font(self) -> None:
pass
def set_padding(self, *args, **kwargs) -> 'NoneWidget':
return self
def get_selected_time(self) -> NumberType:
return 0
def set_title(self, *args, **kwargs) -> 'NoneWidget':
return self
def get_rect(self, *args, **kwargs) -> 'pygame.Rect':
return pygame.Rect(0, 0, 0, 0)
def set_background_color(self, *args, **kwargs) -> 'NoneWidget':
return self
def _draw_background_color(self, *args, **kwargs) -> None:
pass
def _draw_border(self, *args, **kwargs) -> None:
pass
def set_selection_effect(self, *args, **kwargs) -> 'NoneWidget':
return self
def apply(self, *args) -> None:
pass
def change(self, *args) -> None:
pass
def _draw(self, *args, **kwargs) -> None:
pass
def _render(self, *args, **kwargs) -> Optional[bool]:
pass
def set_margin(self, *args, **kwargs) -> 'NoneWidget':
return self
def _apply_transforms(self, *args, **kwargs) -> None:
pass
def set_font(self, *args, **kwargs) -> 'NoneWidget':
return self
def update_font(self, *args, **kwargs) -> 'NoneWidget':
return self
def set_position(self, *args, **kwargs) -> 'NoneWidget':
return self
def scale(self, *args, **kwargs) -> 'NoneWidget':
raise WidgetTransformationNotImplemented()
def resize(self, *args, **kwargs) -> 'NoneWidget':
raise WidgetTransformationNotImplemented()
def set_max_width(self, *args, **kwargs) -> 'NoneWidget':
raise WidgetTransformationNotImplemented()
def set_max_height(self, *args, **kwargs) -> 'NoneWidget':
raise WidgetTransformationNotImplemented()
def rotate(self, *args, **kwargs) -> 'NoneWidget':
raise WidgetTransformationNotImplemented()
def flip(self, *args, **kwargs) -> 'NoneWidget':
raise WidgetTransformationNotImplemented()
def translate(self, *args, **kwargs) -> 'NoneWidget':
raise WidgetTransformationNotImplemented()
def set_alignment(self, *args, **kwargs) -> 'NoneWidget':
return self
def select(self, *args, **kwargs) -> 'NoneWidget':
return self
def set_font_shadow(self, *args, **kwargs) -> 'NoneWidget':
return self
def set_sound(self, *args, **kwargs) -> 'NoneWidget':
return self
def set_cursor(self, *args, **kwargs) -> 'NoneWidget':
return self
def set_controls(self, *args, **kwargs) -> 'NoneWidget':
return self
def set_border(self, *args, **kwargs) -> 'NoneWidget':
return self
def _check_mouseover(self, *args, **kwargs) -> bool:
self._mouseover = False
return False
def mouseleave(self, *args, **kwargs) -> 'NoneWidget':
return self
def mouseover(self, *args, **kwargs) -> 'NoneWidget':
return self
def set_onchange(self, *args, **kwargs) -> 'NoneWidget':
self._onchange = None
return self
def set_onreturn(self, *args, **kwargs) -> 'NoneWidget':
self._onreturn = None
return self
def set_onmouseleave(self, *args, **kwargs) -> 'NoneWidget':
self._onmouseleave = None
return self
def set_onmouseover(self, *args, **kwargs) -> 'NoneWidget':
self._onmouseover = None
return self
def set_onselect(self, *args, **kwargs) -> 'NoneWidget':
self._onselect = None
return self
def set_tab_size(self, *args, **kwargs) -> 'NoneWidget':
return self
def shadow(self, *args, **kwargs) -> 'NoneWidget':
return self
def update(self, events: EventVectorType) -> bool:
self.apply_update_callbacks(events)
return False
class NoneWidgetManager(AbstractWidgetManager, ABC):
"""
NoneWidget manager.
"""
def none_widget(
self,
widget_id: str = ''
) -> 'pygame_menu.widgets.NoneWidget':
"""
Add a none widget to the Menu.
.. note::
This widget is useful to fill column/rows layout without compromising
any visuals. Also, it can be used to store information or even to add
a ``draw_callback`` function to it for being called on each Menu draw.
.. note::
This is applied only to the base Menu (not the currently displayed,
stored in ``_current`` pointer); for such behaviour apply to
:py:meth:`pygame_menu.menu.Menu.get_current` object.
:param widget_id: Widget ID
:return: Widget object
:rtype: :py:class:`pygame_menu.widgets.NoneWidget`
"""
attributes = self._filter_widget_attributes({})
widget = NoneWidget(widget_id=widget_id)
self._configure_widget(widget=widget, **attributes)
self._append_widget(widget)
return widget
|
dcartman/pygame-menu | docs/generate_resources.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
GENERATE RESOURCES
Generate resources for docs.
"""
__all__ = ['save_font_image', 'generate_fonts_doc']
import pygame
import pygame_menu
pygame.init()
def save_font_image(
font_name: str,
text: str,
filename: str,
font_size: int = 50,
image_height: int = 26
) -> None:
"""
Generate a font image and save as a png.
:param font_name: Font name
:param text: Text to render
:param filename: File to save the font
:param font_size: Font size
:param image_height: Image size in px
"""
assert isinstance(font_size, int)
assert isinstance(image_height, int)
assert font_size > 0 and image_height > 0
font = pygame_menu.font.get_font(font_name, font_size)
surf = font.render(text, True, (0, 0, 0))
h, w = surf.get_height(), surf.get_width()
new_width = int(w * (float(image_height) / h))
surf2 = pygame.transform.smoothscale(surf, (new_width, image_height))
pygame.image.save(surf2, filename)
def generate_fonts_doc() -> None:
"""
Generate images for all fonts.
"""
text = 'pygame menu'
save_font_image(pygame_menu.font.FONT_8BIT, text, '_static/font_8bit.png')
save_font_image(pygame_menu.font.FONT_BEBAS, text, '_static/font_bebas.png')
save_font_image(pygame_menu.font.FONT_COMIC_NEUE, text, '_static/font_comic_neue.png')
save_font_image(pygame_menu.font.FONT_DIGITAL, text, '_static/font_digital.png')
save_font_image(pygame_menu.font.FONT_FIRACODE, text, '_static/font_firacode.png')
save_font_image(pygame_menu.font.FONT_FIRACODE_BOLD, text, '_static/font_firacode_bold.png')
save_font_image(pygame_menu.font.FONT_FIRACODE_BOLD_ITALIC, text, '_static/font_firacode_bold_italic.png')
save_font_image(pygame_menu.font.FONT_FIRACODE_ITALIC, text, '_static/font_firacode_italic.png')
save_font_image(pygame_menu.font.FONT_FRANCHISE, text, '_static/font_franchise.png')
save_font_image(pygame_menu.font.FONT_HELVETICA, text, '_static/font_helvetica.png')
save_font_image(pygame_menu.font.FONT_MUNRO, text, '_static/font_munro.png')
save_font_image(pygame_menu.font.FONT_NEVIS, text, '_static/font_nevis.png')
save_font_image(pygame_menu.font.FONT_OPEN_SANS, text, '_static/font_open_sans.png')
save_font_image(pygame_menu.font.FONT_OPEN_SANS_BOLD, text, '_static/font_open_sans_bold.png')
save_font_image(pygame_menu.font.FONT_OPEN_SANS_ITALIC, text, '_static/font_open_sans_italic.png')
save_font_image(pygame_menu.font.FONT_OPEN_SANS_LIGHT, text, '_static/font_open_sans_light.png')
save_font_image(pygame_menu.font.FONT_PT_SERIF, text, '_static/font_pt_serif.png')
if __name__ == '__main__':
generate_fonts_doc()
|
dcartman/pygame-menu | pygame_menu/widgets/selection/right_arrow.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
RIGHT ARROW CLASS
Selector with a right arrow on the item.
"""
__all__ = ['RightArrowSelection']
import pygame
import pygame_menu
from pygame_menu.widgets.selection.arrow_selection import ArrowSelection
from pygame_menu._types import Tuple2IntType, NumberType, NumberInstance
class RightArrowSelection(ArrowSelection):
"""
Widget selection right arrow class. Creates an arrow to the right of the
selected Menu item.
:param arrow_size: Size of arrow on x-axis and y-axis (width, height) in px
:param arrow_left_margin: Distance from the arrow to the widget (px)
:param arrow_vertical_offset: Vertical offset of the arrow (px)
:param blink_ms: Milliseconds between each blink; if ``0`` blinking is disabled
"""
_arrow_left_margin: int
def __init__(
self,
arrow_size: Tuple2IntType = (10, 15),
arrow_left_margin: int = 3,
arrow_vertical_offset: int = 0,
blink_ms: NumberType = 0
) -> None:
assert isinstance(arrow_left_margin, NumberInstance)
assert arrow_left_margin >= 0, 'margin cannot be negative'
super(RightArrowSelection, self).__init__(
margin_left=0,
margin_right=arrow_size[0] + arrow_left_margin,
margin_top=0,
margin_bottom=0,
arrow_vertical_offset=arrow_vertical_offset,
blink_ms=blink_ms
)
self._arrow_left_margin = arrow_left_margin
# noinspection PyMissingOrEmptyDocstring
def draw(self, surface: 'pygame.Surface', widget: 'pygame_menu.widgets.Widget') -> 'RightArrowSelection':
# /A
# widget B
# \ C
# <------>
# margin
rect = widget.get_rect()
a = (rect.topright[0] + self._arrow_size[0] + self._arrow_left_margin,
int(rect.midright[1] - self._arrow_size[1] / 2 + self._arrow_vertical_offset))
b = (rect.midright[0] + self._arrow_left_margin,
rect.midright[1] + self._arrow_vertical_offset)
c = (rect.bottomright[0] + self._arrow_size[0] + self._arrow_left_margin,
int(rect.midright[1] + self._arrow_size[1] / 2 + self._arrow_vertical_offset))
super(RightArrowSelection, self)._draw_arrow(surface, widget, a, b, c)
return self
|
dcartman/pygame-menu | pygame_menu/widgets/widget/image.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
IMAGE
Image widget class, adds a simple image.
"""
__all__ = [
'Image',
'ImageManager'
]
from abc import ABC
from io import BytesIO
from pathlib import Path
import pygame
import pygame_menu
from pygame_menu.baseimage import BaseImage
from pygame_menu.utils import assert_vector
from pygame_menu.widgets.core.widget import Widget, AbstractWidgetManager
from pygame_menu._types import Union, NumberType, CallbackType, Tuple2NumberType, \
Optional, NumberInstance, EventVectorType, Callable, Vector2NumberType, Any
# noinspection PyMissingOrEmptyDocstring
class Image(Widget):
"""
Image widget.
.. note::
Image accepts all transformations.
:param image_path: Path of the image, BytesIO object, or :py:class:`pygame_menu.baseimage.BaseImage` object. If :py:class:`pygame_menu.baseimage.BaseImage` object is provided drawing mode is not considered
:param image_id: Image ID
:param angle: Angle of the image in degrees (clockwise)
:param onselect: Function when selecting the widget
:param scale: Scale of the image on x-axis and y-axis (x, y) in px
:param scale_smooth: Scale is smoothed
"""
_image: 'BaseImage'
def __init__(
self,
image_path: Union[str, 'BaseImage', 'Path', 'BytesIO'],
angle: NumberType = 0,
image_id: str = '',
onselect: CallbackType = None,
scale: Tuple2NumberType = (1, 1),
scale_smooth: bool = True
) -> None:
assert isinstance(image_path, (str, Path, BaseImage, BytesIO))
assert isinstance(image_id, str)
assert isinstance(angle, NumberInstance)
assert isinstance(scale_smooth, bool)
assert_vector(scale, 2)
super(Image, self).__init__(
onselect=onselect,
widget_id=image_id
)
if isinstance(image_path, BaseImage):
self._image = image_path
else:
self._image = BaseImage(image_path)
self._image.rotate(angle)
self._image.scale(scale[0], scale[1], smooth=scale_smooth)
def set_title(self, title: str) -> 'Image':
return self
def get_image(self) -> 'BaseImage':
"""
Gets the :py:class:`pygame_menu.baseimage.BaseImage` object from widget.
:return: Widget image
"""
return self._image
def get_angle(self) -> NumberType:
"""
Return the image angle.
:return: Angle in degrees
"""
return self._image.get_angle()
def set_image(self, image: 'BaseImage') -> None:
"""
Set the :py:class:`pygame_menu.baseimage.BaseImage` object from widget.
:param image: Image object
"""
self._image = image
self._surface = None
self._render()
def _apply_font(self) -> None:
pass
def _update_surface(self) -> 'Image':
"""
Updates surface and renders.
:return: Self reference
"""
self._surface = None
self._render()
return self
def scale(self, width: NumberType, height: NumberType, smooth: bool = False) -> 'Image':
self._image.scale(width, height, smooth)
return self._update_surface()
def resize(self, width: NumberType, height: NumberType, smooth: bool = False) -> 'Image':
self._image.resize(width, height, smooth)
self._surface = None
return self._update_surface()
def set_max_width(self, width: Optional[NumberType], scale_height: NumberType = False,
smooth: bool = True) -> 'Image':
if width is not None and self._image.get_width() > width:
sx = width / self._image.get_width()
height = self._image.get_height()
if scale_height:
height *= sx
self._image.resize(width, height, smooth)
return self._update_surface()
return self
def set_max_height(self, height: Optional[NumberType], scale_width: NumberType = False,
smooth: bool = True) -> 'Image':
if height is not None and self._image.get_height() > height:
sy = height / self._image.get_height()
width = self._image.get_width()
if scale_width:
width *= sy
self._image.resize(width, height, smooth)
return self._update_surface()
return self
def rotate(self, angle: NumberType) -> 'Image':
self._image.rotate(angle)
return self._update_surface()
def flip(self, x: bool, y: bool) -> 'Image':
assert isinstance(x, bool)
assert isinstance(y, bool)
self._flip = (x, y)
if x or y:
self._image.flip(x, y)
return self._update_surface()
return self
def _draw(self, surface: 'pygame.Surface') -> None:
surface.blit(self._surface, self._rect.topleft)
def _render(self) -> Optional[bool]:
if self._surface is not None:
return True
self._surface = self._image.get_surface(new=False)
self._rect.width, self._rect.height = self._surface.get_size()
if not self._render_hash_changed(self._visible):
return True
self.force_menu_surface_update()
def update(self, events: EventVectorType) -> bool:
self.apply_update_callbacks(events)
for event in events:
if self._check_mouseover(event):
break
return False
class ImageManager(AbstractWidgetManager, ABC):
"""
Image manager.
"""
def image(
self,
image_path: Union[str, 'Path', 'pygame_menu.BaseImage', 'BytesIO'],
angle: NumberType = 0,
image_id: str = '',
onselect: Optional[Callable[[bool, 'Widget', 'pygame_menu.Menu'], Any]] = None,
scale: Vector2NumberType = (1, 1),
scale_smooth: bool = True,
selectable: bool = False,
**kwargs
) -> 'pygame_menu.widgets.Image':
"""
Add a simple image to the Menu.
If ``onselect`` is defined, the callback is executed as follows, where
``selected`` is a boolean representing the selected status:
.. code-block:: python
onselect(selected, widget, menu)
kwargs (Optional)
- ``align`` (str) – Widget `alignment <https://pygame-menu.readthedocs.io/en/latest/_source/themes.html#alignment>`_
- ``background_color`` (tuple, list, str, int, :py:class:`pygame.Color`, :py:class:`pygame_menu.baseimage.BaseImage`) – Color of the background. ``None`` for no-color
- ``background_inflate`` (tuple, list) – Inflate background on x-axis and y-axis (x, y) in px
- ``border_color`` (tuple, list, str, int, :py:class:`pygame.Color`) – Widget border color. ``None`` for no-color
- ``border_inflate`` (tuple, list) – Widget border inflate on x-axis and y-axis (x, y) in px
- ``border_position`` (str, tuple, list) – Widget border positioning. It can be a single position, or a tuple/list of positions. Only are accepted: north, south, east, and west. See :py:mod:`pygame_menu.locals`
- ``border_width`` (int) – Border width in px. If ``0`` disables the border
- ``cursor`` (int, :py:class:`pygame.cursors.Cursor`, None) – Cursor of the widget if the mouse is placed over
- ``float`` (bool) - If ``True`` the widget don't contribute width/height to the Menu widget positioning computation, and don't add one unit to the rows
- ``float_origin_position`` (bool) - If ``True`` the widget position is set to the top-left position of the Menu if the widget is floating
- ``margin`` (tuple, list) – Widget (left, bottom) margin in px
- ``padding`` (int, float, tuple, list) – Widget padding according to CSS rules. General shape: (top, right, bottom, left)
- ``selection_color`` (tuple, list, str, int, :py:class:`pygame.Color`) – Color of the selected widget; only affects the font color
- ``selection_effect`` (:py:class:`pygame_menu.widgets.core.Selection`) – Widget selection effect. Applied only if ``selectable`` is ``True``
- ``shadow_color`` (tuple, list, str, int, :py:class:`pygame.Color`) – Color of the widget shadow
- ``shadow_radius`` (int) - Border radius of the shadow
- ``shadow_type`` (str) - Shadow type, it can be ``'rectangular'`` or ``'ellipse'``
- ``shadow_width`` (int) - Width of the shadow. If ``0`` the shadow is disabled
.. note::
All theme-related optional kwargs use the default Menu theme if not
defined.
.. note::
This is applied only to the base Menu (not the currently displayed,
stored in ``_current`` pointer); for such behaviour apply to
:py:meth:`pygame_menu.menu.Menu.get_current` object.
:param image_path: Path of the image (file) or a BaseImage object. If BaseImage object is provided the angle and scale are ignored
:param angle: Angle of the image in degrees (clockwise)
:param image_id: ID of the image
:param onselect: Callback executed when selecting the widget; only executed if ``selectable`` is ``True``
:param scale: Scale of the image on x-axis and y-axis (x, y)
:param scale_smooth: Scale is smoothed
:param selectable: Image accepts user selection
:param kwargs: Optional keyword arguments
:return: Widget object
:rtype: :py:class:`pygame_menu.widgets.Image`
"""
assert isinstance(selectable, bool)
# Remove invalid keys from kwargs
for key in list(kwargs.keys()):
if key not in ('align', 'background_color', 'background_inflate',
'border_color', 'border_inflate', 'border_width',
'cursor', 'margin', 'padding', 'selection_color',
'selection_effect', 'border_position', 'float',
'float_origin_position', 'shadow_color', 'shadow_radius',
'shadow_type', 'shadow_width'):
kwargs.pop(key, None)
# Filter widget attributes to avoid passing them to the callbacks
attributes = self._filter_widget_attributes(kwargs)
widget = Image(
angle=angle,
image_id=image_id,
image_path=image_path,
onselect=onselect,
scale=scale,
scale_smooth=scale_smooth
)
widget.is_selectable = selectable
self._check_kwargs(kwargs)
self._configure_widget(widget=widget, **attributes)
self._append_widget(widget)
return widget
|
dcartman/pygame-menu | test/test_font.py | """
pygame-menu
https://github.com/ppizarror/pygame-menu
TEST FONT
Test font management.
"""
__all__ = ['FontTest']
from pathlib import Path
from test._utils import MenuUtils, BaseTest
import pygame
import pygame_menu
class FontTest(BaseTest):
def test_font_load(self) -> None:
"""
Load a font from a file.
"""
font = MenuUtils.get_font(pygame_menu.font.FONT_8BIT, 5)
self.assertTrue(font is not None)
self.assertEqual(font, pygame_menu.font.get_font(font, 5))
self.assertRaises(ValueError, lambda: MenuUtils.get_font('', 0))
self.assertRaises(ValueError, lambda: MenuUtils.get_font('sys', 0))
def test_pathlib(self) -> None:
"""
Test font load with pathlib.
"""
path_font = Path(pygame_menu.font.FONT_8BIT)
self.assertRaises(ValueError, lambda: pygame_menu.font.get_font(path_font, 0))
font = pygame_menu.font.get_font(path_font, 10)
assert font is not None
def test_system_load(self) -> None:
"""
Test fonts from system.
"""
font_sys = MenuUtils.random_system_font()
font = MenuUtils.get_font(font_sys, 5)
self.assertTrue(font is not None)
# Modify the system font and load, this will raise an exception
self.assertRaises(ValueError, lambda: MenuUtils.get_font('invalid font', 5))
def test_font_argument(self) -> None:
"""
Test font pass as argument.
"""
menu = MenuUtils.generic_menu()
f0 = pygame.font.SysFont(pygame.font.get_fonts()[0], 20)
# Widget with custom font
text = menu.add.text_input('First name: ', default='John', font_name=f0)
self.assertEqual(text.get_font_info()['name'], f0)
# Test widgets with default font, check are equal
text2 = menu.add.text_input('First name: ', default='John')
self.assertEqual(text2.get_font_info()['name'], menu.get_theme().widget_font)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.