text
stringlengths
0
1.05M
meta
dict
#$Id$ class BankRule: """This class is used to create object for bank rules.""" def __init__(self): """Initialize parameters for Bank rules.""" self.rule_id = '' self.rule_name = '' self.rule_order = 0 self.apply_to = '' self.target_account_id = '' self.apply_to = '' self.criteria_type = '' self.criterion = [] self.record_as = '' self.account_id = '' self.account_name = '' self.tax_id = '' self.reference_number = '' self.customer_id = '' self.customer_name = '' def set_rule_id(self, rule_id): """Set rule id. Args: rule_id(str): Rule id. """ self.rule_id = rule_id def get_rule_id(self): """Get rule id. Returns: str: Rule id. """ return self.rule_id def set_rule_name(self, rule_name): """Set rule name. Args: rule_name(str): Rule name. """ self.rule_name = rule_name def get_rule_name(self): """Get rule name. Returns: str:Rule name. """ return self.rule_name def set_rule_order(self, rule_order): """Set rule order. Args: rule_order(int): Rule order. """ self.rule_order = rule_order def get_rule_order(self): """Get rule order. Returns: int: Rule order. """ return self.rule_order def set_apply_to(self, apply_to): """Set apply to. Args: apply_to(str): Apply to. """ self.apply_to = apply_to def get_apply_to(self): """Get apply to. Returns: str: Apply to. """ return self.apply_to def set_criteria_type(self, criteria_type): """Set criteria type. Args: criteria_type(str): Criteria type. """ self.criteria_type = criteria_type def get_criteria_type(self): """Get criteria type. Returns: str: Criteria type. """ return self.criteria_type def set_target_account_id(self, target_account_id): """Set target account id. Args: target_account_id(str): Target account id. """ self.target_account_id = target_account_id def get_target_account_id(self): """Get target account id. Returns: str: Target account id. """ return self.target_account_id def set_criterion(self, criteria): """Set criterion. Args: criteria(instance): Criteria object. """ self.criterion.append(criteria) def get_criterion(self): """Get criterion. Returns: list of instance: List of criteria object. """ return self.criterion def set_record_as(self, record_as): """Set record as. Args: record_as(str): Record as. """ self.record_as = record_as def get_record_as(self): """Get record as. Returns: str: Record as. """ return self.record_as def set_account_id(self, account_id): """Set account id. Args: account_id(str): Account id. """ self.account_id = account_id def get_account_id(self): """Get account id. Returns: str: Account id. """ return self.account_id def set_account_name(self, account_name): """Set account name. Args: account_name(str): Account name. """ self.account_name = account_name def get_account_name(self): """Get account name. Returns: str: Account name. """ return self.account_name def set_tax_id(self, tax_id): """Set tax id. Args: tax_id(str): Tax id. """ self.tax_id = tax_id def get_tax_id(self): """Get tax id. Returns: str:Tax id. """ return self.tax_id def set_reference_number(self, reference_number): """Set reference number. Args: reference_number(str): Reference number. """ self.reference_number = reference_number def get_reference_number(self): """Get reference number. Returns: str: Reference number. """ return self.reference_number def set_customer_id(self, customer_id): """Set customer id. Args: customer_id(str): Customer id. """ self.customer_id = customer_id def get_customer_id(self): """Get customer id. Returns: str: Customer id. """ return self.customer_id def set_customer_name(self, customer_name): """Set customer name. Args: customer_name(str): Customer name. """ self.customer_name = '' def get_customer_name(self): """Get customer name. Returns: str: Customer name. """ return self.customer_name def to_json(self): """This method is used to convert bills object to json object. Returns: dict: Dictionary containing json object for bank rules. """ data = {} if self.rule_name != '': data['rule_name'] = self.rule_name if self.target_account_id != '': data['target_account_id'] = self.target_account_id if self.apply_to != '': data['apply_to'] = self.apply_to if self.criteria_type != '': data['criteria_type'] = self.criteria_type if self.criterion: data['criterion'] = [] for value in self.criterion: criteria = value.to_json() data['criterion'].append(criteria) if self.record_as != '': data['record_as'] = self.record_as if self.account_id != '': data['account_id'] = self.account_id if self.tax_id != '': data['tax_id'] = self.tax_id if self.reference_number != '': data['reference_number'] = self.reference_number if self.customer_id != '': data['customer_id'] = self.customer_id return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/BankRule.py", "copies": "1", "size": "6521", "license": "mit", "hash": -6088579880555392000, "line_mean": 20.3104575163, "line_max": 70, "alpha_frac": 0.496549609, "autogenerated": false, "ratio": 4.14821882951654, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00808975573681456, "num_lines": 306 }
#$Id$ class BaseCurrencyAdjustment: """This class is used to create object for Base Currency adjustment.""" def __init__(self): """Initialize parameters for Base currency adjustment.""" self.base_currency_adjustment_id = '' self.adjustment_date = '' self.exchange_rate = 0.0 self.exchange_rate_formatted = '' self.currency_id = '' self.currency_code = '' self.notes = '' self.gain_or_loss = 0.0 self.adjustment_date_formatted = '' self.accounts = [] def set_base_currency_adjustment_id(self, base_currency_adjustment_id): """Set base currency adjustment id. Args: base_currency_adjustment_id(str): Base currency adjustment id. """ self.base_currency_adjustment_id = base_currency_adjustment_id def get_base_currency_adjustment_id(self): """Get base currency adjustment id. Returns: str: Base currency adjustment id. """ return self.base_currency_adjustment_id def set_adjustment_date(self, adjustment_date): """Set adjustment date. Args: adjustment_date(str): Adjustment date. """ self.adjustment_date = adjustment_date def get_adjustment_date(self): """Get adjustment date. Returns: str: Adjustment date. """ return self.adjustment_date def set_exchange_rate(self, exchange_rate): """Set exchaneg rate. Args: exchaneg_rate(float): Exchange rate. """ self.exchange_rate = exchange_rate def get_exchange_rate(self): """Get exchange rate. Returns: float: Exchange rate. """ return self.exchange_rate def set_exchange_rate_formatted(self, exchange_rate_formatted): """Set exchange rate formatted. Args: exchange_rate_formatted(str): Exchange rate formatted. """ self.exchange_rate_formatted = exchange_rate_formatted def get_exchange_rate_formatted(self): """Get exchange rate formatted. Returns: str: Exchange rate formatted. """ return self.exchange_rate_formatted def set_currency_id(self, currency_id): """Set currency id. Args: currency_id(str): Currency id. """ self.currency_id = currency_id def get_currency_id(self): """Get currency id. Returns: str: Currency id. """ return self.currency_id def set_currency_code(self, currency_code): """Set currency code. Args: currency_code(str): Currency code. """ self.currency_code = currency_code def get_currency_code(self): """Get currecny code. Returns: str: Currency code. """ return self.currency_code def set_notes(self, notes): """Set notes. Args: notes(str): Notes. """ self.notes = notes def get_notes(self): """Get notes. Returns: str: Notes. """ return self.notes def set_gain_or_loss(self, gain_or_loss): """Set gain or loss. Args: gain_or_loss(float): Gain or loss. """ self.gain_or_loss = gain_or_loss def get_gain_or_loss(self): """Get gain or loss. Returns: float: Gain or loss. """ return self.gain_or_loss def set_adjustment_date_formatted(self, adjustment_date_formatted): """Set adjustment date formatted. Args: adjustment_date_formatted(str): Adjustment date formatted. """ self.adjustment_date_formatted = adjustment_date_formatted def get_adjustment_date_foramtted(self): """Get adjustment date formatted. Returns: str: Adjustment date formatted. """ return self.adjustment_date_formatted def set_accounts(self, accounts): """Set accounts. Args: accounts(instance): Accounts. """ self.accounts.append(accounts) def get_accounts(self): """Get accounts. Returns: instance: Accounts. """ return self.accounts def to_json(self): """This method is used to convert base currency adjusment object in json format. Returns: dict: Dictionary containing json object for base currency adjustment. """ data = {} if self.currency_id != '': data['currency_id'] = self.currency_id if self.adjustment_date != '': data['adjustment_date'] = self.adjustment_date if self.exchange_rate > 0: data['exchange_rate'] = self.exchange_rate if self.notes != '': data['notes'] = self.notes return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/BaseCurrencyAdjustment.py", "copies": "1", "size": "5019", "license": "mit", "hash": 5451036193072059000, "line_mean": 22.453271028, "line_max": 88, "alpha_frac": 0.554293684, "autogenerated": false, "ratio": 4.410369068541301, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.54646627525413, "avg_score": null, "num_lines": null }
#$Id$ class BillPayment: """This class is used to create object for payments.""" def __init__(self): """Initialize parameters for Payments object.""" self.payment_id = '' self.bill_id = '' self.bill_payment_id = '' self.payment_mode = '' self.description = '' self.date = '' self.reference_number = '' self.exchange_rate = 0.0 self.amount = 0.0 self.paid_through_account_id = '' self.paid_through_account_name = '' self.is_single_bill_payment = None self.amount_applied = 0.0 self.vendor_id = '' self.vendor_name = '' self.paid_through = "" def set_paid_through(self, paid_through): """Set paid through. Args: paid_through(str): Paid through. """ self.paid_through = paid_through def get_paid_through(self): """Get paid through. Returns: str: Paid through. """ return self.paid_through def set_vendor_name(self, vendor_name): """Set vendor name. Args: vendor_name(str): Vendor name. """ self.vendor_name = vendor_name def get_vendor_name(self): """Get vendor name. Returns: str: Vendor name. """ return self.vendor_name def set_vendor_id(self, vendor_id): """Set vendor id. Args: vendor_id(str): Vendor id. """ self.vendor_id = vendor_id def get_vendor_id(self): """Get vendor id. Returns: str: Vendor id. """ return self.vendor_id def set_amount_applied(self, amount_applied): """Set amount applied. Args: amount_applied(float): Amount applied. """ self.amount_applied = amount_applied def get_amount_applied(self): """Get amount applied. Returns: float: Amount applied. """ return self.amount_applied def set_payment_id(self, payment_id): """Set payment id. Args: payment_id(str): Payment id. """ self.payment_id = payment_id def get_payment_id(self): """Get payment id. Returns: str: Payment id. """ return self.payment_id def set_bill_id(self, bill_id): """Set bill id. Args: bill_id(str): Bill id. """ self.bill_id = bill_id def get_bill_id(self): """Get bill id. Returns: str: Bill id. """ return bill_id def set_bill_payment_id(self, bill_payment_id): """Set bill payment id. Args: bill_payment_id(str): Bill payment id. """ self.bill_payment_id = bill_payment_id def get_bill_payment_id(self): """Get bill payment id. Returns: str: Bill payment id. """ return self.bill_payment_id def set_payment_mode(self, payment_mode): """Set payment id. Args: payment_mode(str): Payment mode. """ self.payment_mode = payment_mode def get_payment_mode(self): """Get payment mode. Returns: str: Payment mode. """ return self.payment_mode def set_description(self, description): """Set description. Args: description(str): Description. """ self.description = description def get_description(self): """Get description. Returns: str: Description. """ return self.description def set_date(self, date): """Set date. Args: date(str): Date. """ self.date = date def get_date(self): """Get date. Returns: str: Date. """ return self.date def set_reference_number(self, reference_number): """Set reference number. Args: reerence_number(str): Refference number. """ self.reference_number = reference_number def get_reference_number(self): """Get reference number. Returns: str: Reference number. """ return self.reference_number def set_exchange_rate(self, exchange_rate): """Set exchange rate. Args: exchange_rate(float): Exchange rate. """ self.exchange_rate = exchange_rate def get_exchange_rate(self): """Get exchange rate. Returns: float: Exchange rate. """ return self.exchange_rate def set_amount(self, amount): """Set amount. Args: amount(float): Amount. """ self.amount = amount def get_amount(self): """Get amount. Returns: float: Amount. """ return self.amount def set_paid_through_account_id(self, paid_through_account_id): """Set paid through account id. Args: paid_through_account_id(str): Paid through account id. """ self.paid_through_account_id = paid_through_account_id def get_paid_through_account_id(self): """Get paid through account id. Returns: str: Paid through account id. """ return self.paid_through_account_id def set_paid_through_account_name(self, paid_through_account_name): """Set paid through account name. Args: paid_through_account_name(str): Paid through account name. """ self.paid_through_account_name = paid_through_account_name def get_paid_through_account_name(self, paid_through_acount_name): """Get paid through account name. Returns: str: Paid through account name. """ return self.paid_through_account_name def set_is_single_bill_payment(self, is_single_bill_payment): """Set whether it is single payment bill. Args: is_single_bill_payment(bool): True if it is single bill payment. """ self.is_single_bill_payment = is_single_bill_payment def get_is_single_bill_payment(self): """Get whether it is single payment bill. Returns: bool: True if it is single bill payment. """ return self.is_single_bill_payment
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/BillPayment.py", "copies": "1", "size": "6550", "license": "mit", "hash": -693976398031561900, "line_mean": 19.9265175719, "line_max": 76, "alpha_frac": 0.5244274809, "autogenerated": false, "ratio": 4.1455696202531644, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.022581781672567483, "num_lines": 313 }
#$Id$ class ChartOfAccount: """Create object for Chart of Accounts.""" def __init__(self): """Initialize parameters for Chart of accounts.""" self.account_id = '' self.account_name = '' self.is_active = None self.account_type = '' self.account_type_formatted = '' self.currency_id = '' self.description = '' self.is_user_created = None self.is_involved_in_transaction = None self.is_system_account = None #self.current_balance = 0.0 #Not mentioned def set_account_id(self, account_id): """Set account id. Args: account_id(str): Account id. """ self.account_id = account_id def get_account_id(self): """Get account id. Returns: str: Account id. """ return self.account_id def set_account_name(self, account_name): """Set account name. Args: account_name(str): Account name. """ self.account_name = account_name def get_account_name(self): """Get account name. Returns: str: Account name. """ return self.account_name def set_is_active(self, is_active): """Set whether the account is active or not. Args: is_active(bool): True if active else False. """ self.is_active = is_active def get_is_active(self): """Get whether is active. Returns: bool: True if active else false. """ return self.is_active def set_account_type(self, account_type): """Set account type. Args: account_type(str): Account type. """ self.account_type = account_type def get_account_type(self): """Get account type. Returns: str: Account type. """ return self.account_type def set_account_type_formatted(self, account_type_formatted): """Set account type formatted. Args: account_type_formatted(str): Account type formatted. """ self.account_type_formatted = account_type_formatted def get_account_type_formatted(self): """Get acccount type formatted. Returns: str: Account type formatted. """ return self.account_type_formatted def set_currency_id(self, currency_id): """Set currency id. Args: currency_id(str): Currency id. """ self.currency_id = currency_id def get_currency_id(self): """Get currency id. Returns: str: Currency id. """ return self.currency_id def set_description(self, description): """Set descripiton. Args: description(str): Description. """ self.description = description def get_description(self): """Get description. Returns: str: Description. """ return self.description def set_is_user_created(self, is_user_created): """Set whether the account is user created. Args: is_user_created(bool): True if user created else False. """ self.is_user_created = is_user_created def get_is_user_created(self): """Get whether the account is user created. Returns: bool: True if user created else False. """ return self.is_user_created def set_is_involved_in_transaction(self, is_involved_in_transaction): """Set Whether the account is involved in transactions. Args: is_involved_in_transaction(bool): True if the account is involved in transactions else False. """ self.is_involved_in_transaction = is_involved_in_transaction def get_is_involved_in_transaction(self): """Get whether the account is involved in transactions. Returns: bool: True if the account is involved in transaction. """ return self.is_involved_in_transaction def set_is_system_account(self, is_system_account): """Set whether the account is system account. Args: is_system_account(bool): True if system account else False. """ self.is_system_account = is_system_account def get_is_system_account(self): """Get whether the account is system account. Returns: bool: True if system account else False. """ return self.is_system_account '''def set_current_balance(self, current_balance): """Set current balance. Args: current_balance(float): Current balance. """ self.current_balance = current_balance def get_current_balance(self): """Get current balance. Returns: float: Current balance. """ return self.current_balance''' def to_json(self): """This method is used to convert chart of accounts object to json object. Returns: dict: Dictionary containing json object for chart of accounts. """ data = {} if self.account_name != '': data['account_name'] = self.account_name if self.account_type != '': data['account_type'] = self.account_type if self.currency_id != '': data['currency_id'] = self.currency_id if self.description != '': data['description'] = self.description return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/ChartOfAccount.py", "copies": "1", "size": "5623", "license": "mit", "hash": 2818978555257500000, "line_mean": 22.9276595745, "line_max": 105, "alpha_frac": 0.5577094078, "autogenerated": false, "ratio": 4.3826968043647705, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.544040621216477, "avg_score": null, "num_lines": null }
#$Id$ class Comment: """This class is used to create object for comment.""" def __init__(self): """Initialize parameters for comment object.""" self.id = 0 self.content = "" self.posted_by = "" self.posted_person = "" self.post_date = "" self.post_date_long = 0 self.added_by = "" self.added_person = "" self.created_time_format = "" self.created_time = "" self.created_time_long = 0 def set_id(self, id): """Set id. Args: id(long): Comment id. """ self.id = id def get_id(self): """Get id. Returns: long: Comment id. """ return self.id def set_content(self, content): """Set content. Args: content(str): Content. """ self.content = content def get_content(self): """Get content. Returns: str: Content. """ return self.content def set_posted_by(self, posted_by): """Set posted by. Args: posted_by(str): Posted by. """ self.posted_by = posted_by def get_posted_by(self): """Get posted by. Returns: str: Posted by. """ return self.posted_by def set_posted_person(self, posted_person): """Set posted person. Args: posted_person(str): Posted person. """ self.posted_person = posted_person def get_posted_person(self): """Get posted person. Returns: str: Posted person. """ return self.posted_person def set_post_date(self, post_date): """Set post date. Args: post_date(str): Post date. """ self.post_date = post_date def get_post_date(self): """Get post date. Returns: str: Post date. """ return self.post_date def set_post_date_long(self, post_date_long): """Set post date long. Args: post_date_long(long): Post date long. """ self.post_date_long = post_date_long def get_post_date_long(self): """Get post_date_long(self): Returns: long: Post date long. """ return self.post_date_long def set_added_by(self, added_by): """ Set the comment added by. Args: added_by(str): Comment added by. """ self.added_by = added_by; def get_added_by(self): """ Get the comment added by. Returns: str: Returns the the comment added by. """ return self.added_by; def set_added_person(self, added_person): """ Set the comment added person. Args: added_person(str): Comment added person. """ self.added_person = added_person; def get_added_person(self): """ Get the comment added person. Returns: str: Returns the comment added person. """ return self.added_person; def set_created_time_format(self, created_time_format): """ Set the comment created time format. Args: created_time_format(str): Comment created time format. """ self.created_time_format = created_time_format; def get_created_time_format(self): """ Get the comment created time format. Returns: str: Returns the comment created time format. """ return self.created_time_format; def set_created_time(self, created_time): """ Set the comment created time. Args: created_time(str): Comment created time. """ self.created_time = created_time; def get_created_time(self): """ Get the comment created time. Returns: str: Returns the comment created time. """ return self.created_time; def set_created_time_long(self, created_time_long): """ Set the comment created time long. Args: created_time_long(long): Comment created time long. """ self.created_time_long = created_time_long; def get_created_time_long(self): """ Get the comment created time long. Returns: long: Returns the comment created time long. """ return self.created_time_long;
{ "repo_name": "zoho/projects-python-wrappers", "path": "projects/model/Comment.py", "copies": "1", "size": "4664", "license": "mit", "hash": 4151800672727371000, "line_mean": 17.7309236948, "line_max": 60, "alpha_frac": 0.5019296741, "autogenerated": false, "ratio": 3.925925925925926, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9292294060773681, "avg_score": 0.1271123078504489, "num_lines": 249 }
#$Id$ class Comment: """This class is used to create object for comments.""" def __init__(self): """Initialize parameters for comments.""" self.comment_id = '' self.contact_id = '' self.contact_name = '' self.description = '' self.commented_by_id = '' self.commented_by = '' self.date = '' self.date_description = '' self.time = '' self.transaction_id = '' self.transaction_type = '' self.is_entity_deleted = None self.operation_type = '' self.estimate_id = '' self.comment_type = '' self.invoice_id = '' self.payment_expected_date = '' self.show_comment_to_clients = None self.recurring_invoice_id = '' self.creditnote_id = '' self.expense_id = '' self.recurring_expense_id = '' self.bill_id = '' self.project_id = '' self.is_current_user = None def set_is_current_user(self, is_current_user): """Set whether it is current user or not. Args: is_current_user(bool): True if it is current user else false. """ self.is_current_user = is_current_user def get_is_current_user(self): """Get whether it is current user or not. Returns: bool: True if it is current user else false. """ return self.is_current_user def set_comment_id(self, comment_id): """Set comment id. Args: comment_id(str): Comment id. """ self.comment_id = comment_id def get_comment_id(self): """Get comment id. Returns: str: Comment id. """ return self.comment_id def set_contact_id(self, contact_id): """Set contact id. Args: contact_id(str): Contact id. """ self.contact_id = contact_id def get_contact_id(self): """Get contact id. Returns: str: Contact id. """ return self.contact_id def set_contact_name(self, contact_name): """Set contact name. Args: contact_name(str): Contact name. """ self.contact_name = contact_name def get_contact_name(self): """Get contact name. Returns: str: Contact name. """ return self.contact_name def set_description(self, description): """Set description. Args: description(str): Description. """ self.description = description def get_description(self): """Get descritpion. Returns: str: Description. """ return self.description def set_commented_by_id(self, commented_by_id): """Set commented by id. Args: commented_by_id(str): Commented by id. """ self.commented_by_id = commented_by_id def get_commented_by_id(self): """Get commented by id. Returns: str: Commented by id. """ return self.commented_by_id def set_commented_by(self, commented_by): """Set commented by. Args: commented_by(str): Commented by. """ self.commented_by = commented_by def get_commented_by(self): """Get commented by. Returns: str: Commented by. """ return self.commented_by def set_date(self, date): """Set date. Args: date(str): Date. """ self.date = date def get_date(self): """Get date. Returns: str: Date. """ return self.date def set_date_description(self, date_description): """Set date description. Args: date_description(str): Date description. """ self.date_description = date_description def get_date_description(self): """Get date description. Returns: str: Date description. """ return self.date_description def set_time(self, time): """Set time. Args: time(str): Time. """ self.time = time def get_time(self): """Get time. Returns: str: Time. """ return self.time def set_transaction_id(self, transaction_id): """Set transaction id. Args: transaction_id(str): Transaction id. """ self.transaction_id = transaction_id def get_transaction_id(self): """Get transaction id. Returns: str: Transaction id. """ return self.transaction_id def set_transaction_type(self, transaction_type): """Set transaction type. Args: transaction_type(str): Transaction type. """ self.transaction_type = transaction_type def get_transaction_type(self): """Get transaction type. Returns: str: Transaction type. """ return self.transaction_type def set_is_entity_deleted(self, is_entity_deleted): """Set whether entity is deleted or not. Args: is_entity_deleted(bool): True if entity is deleted else False. """ self.is_entity_deleted = is_entity_deleted def get_is_entity_deleted(self): """Get whether entity is deleted or not. Returns: bool: True if entity is deleted else False. """ return self.is_entity_deleted def set_operation_type(self, operation_type): """Set operation type. Args: operatipon_type(str): Operation type. """ self.operation_type = operation_type def get_operation_type(self): """Get operation type. Returns: str: Operation type. """ return self.operation_type def set_comment_type(self, comment_type): """Set comment type. Args: comment_type(Str): Comment type. """ self.comment_type = comment_type def get_comment_type(self): """Get comment type. Returns: str: Comment type. """ return self.comment_type def set_estimate_id(self, estimate_id): """Set estimate id. Args: estimate_id(str): Estimate id. """ self.estimate_id = estimate_id def get_estimate_id(self): """Get estimate id. Returns: str: Estimate id. """ return self.estimate_id def set_invoice_id(self, invoice_id): """Set invoice id. Args: invoice_id(str): Invoice id. """ self.invoice_id = invoice_id def get_invoice_id(self): """Get invoice id. Returns: str: Invoice id. """ return self.invoice_id def set_payment_expected_date(self, payment_expected_date): """Set payment expected date. Args: payment_expected_date(str): Payment expected date. """ self.payment_expected_date = payment_expected_date def get_payment_expected_date(self): """Get payment expected date. Returns: str: Payment expected date. """ return self.payment_expected_date def set_show_comment_to_clients(self, show_comment_to_clients): """Set whether to show comment to clients. Args: show_comment_to_client(bool): True to show comment to clients else False. """ self.show_comment_to_clients = show_comment_to_clients def get_show_comment_to_clients(self): """Get whether to show comment to clients. Returns: bool: True to show comment to clients else False. """ return self.show_comment_to_clients def set_recurring_invoice_id(self, recurring_invoice_id): """Set recurring invoice id. Args: recurring_invoice_id(str): Recurring invoice id. """ self.recurring_invoice_id = recurring_invoice_id def get_recurring_invoice_id(self): """Get recurring invoice id. Returns: str: Recurring invoice id. """ return self.recurring_invoice_id def set_creditnote_id(self, creditnote_id): """Set creditnote id. Args: creditnote_id (str): Creditnote id. """ self.creditnote_id = creditnote_id def get_creditnote_id(self): """Get creditnote id. Args: str: Creditnote id. """ return self.creditnote_id def set_expense_id(self, expense_id): """Set expense id. Args: expense_id(str): Expense id. """ self.expense_id = expense_id def get_expense_id(self): """Get expense id. Returns: str: Expense id. """ return self.expense_id def set_recurring_expense_id(self, recurring_expense_id): """Set recurring expense id. Args: recurring_expense_id(str): Recurring expense id. """ self.recurring_expense_id = recurring_expense_id def get_recurring_expense_id(self): """Get recurring expense id. Returns: str: Recurring expense id. """ return self.recurring_expense_id def set_bill_id(self, bill_id): """Set bill id. Args: bill_id(str): Bill id. """ self.bill_id = bill_id def get_bill_id(self): """Get bill id. Returns: str: Bill id. """ return self.bill_id def set_project_id(self, project_id): """Set project id. Args: project_id(str): Project id. """ self.project_id = project_id def get_project_id(self): """Get project id. Returns: str: Project id. """ return self.project_id
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Comment.py", "copies": "1", "size": "10376", "license": "mit", "hash": 293105543607664700, "line_mean": 20.4380165289, "line_max": 74, "alpha_frac": 0.5169622205, "autogenerated": false, "ratio": 4.207623682076237, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5224585902576236, "avg_score": null, "num_lines": null }
#$Id$ class ContactPerson: """This class is used to create model for contact person.""" def __init__(self): """Initialize the parameters for contact person.""" self.contact_person_id = '' self.salutation = '' self.first_name = '' self.last_name = '' self.email = '' self.phone = '' self.mobile = '' self.is_primary_contact = None self.contact_id = '' def set_contact_person_id(self, contact_person_id): """Set contact person id. Args: contact_person_id(str): Contact person id. """ self.contact_person_id = contact_person_id def get_contact_person_id(self): """Get contact person id. Returns: str: Contact person id. """ return self.contact_person_id def set_salutation(self, salutation): """Set salutation. Args: salutation(str): Salutation. """ self.salutation = salutation def get_salutation(self): """Get salutation. Returns: str: Salutation. """ return self.salutation def set_first_name(self, first_name): """Set first name. Args: first_name(str): First name. """ self.first_name = first_name def get_first_name(self): """Get first name. Returns: str: First name. """ return self.first_name def set_last_name(self, last_name): """Set last name. Args: last_name(str): Last name. """ self.last_name = last_name def get_last_name(self): """Get last name. Returns: str: Last name. """ return self.last_name def set_email(self, email): """Set email. Args: email(str): Email. """ self.email = email def get_email(self): """Get email. Returns: str: Email. """ return self.email def set_phone(self, phone): """Set phone. Args: phone(str): Phone. """ self.phone = phone def get_phone(self): """Get phone. Returns: str: Phone. """ return self.phone def set_mobile(self, mobile): """Set mobile. Args: mobile(str): Mobile. """ self.mobile = mobile def get_mobile(self): """Get mobile. Args: mobile(str): Mobile. """ return self.mobile def set_is_primary_contact(self, is_primary_contact): """Set whether it is primary contact or not. Args: is_primary_contact(bool): True if it is primary contact. Allowed value is true only. """ self.is_primary_contact = is_primary_contact def get_is_primary_contact(self): """Get whether it is primary contact or not. Returns: bool: True if it os primary contact else False. """ return self.is_primary_contact def set_contact_id(self, contact_id): """Set contact id. Args: contact_id(str): Contact id. """ self.contact_id = contact_id def get_contact_id(self): """Get contact id. Returns: str: Contact id. """ return self.contact_id def to_json(self): """This method is used to convert the contact person object to JSON object. Returns: dict: Dictionary containing details of contact person object. """ contact_person = {} if self.salutation != '': contact_person['salutation'] = self.salutation if self.first_name != '': contact_person['first_name'] = self.first_name if self.last_name != '': contact_person['last_name'] = self.last_name if self.email != '': contact_person['email'] = self.email if self.phone != '': contact_person['phone'] = self.phone if self.mobile != '': contact_person['mobile'] = self.mobile if self.is_primary_contact != False: contact_person['is_primary_contact'] = str(\ self.is_primary_contact).lower() if self.contact_id != '': contact_person['contact_id'] = self.contact_id return contact_person
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/ContactPerson.py", "copies": "1", "size": "4579", "license": "mit", "hash": 8104365254950759000, "line_mean": 21.3365853659, "line_max": 83, "alpha_frac": 0.5038217952, "autogenerated": false, "ratio": 4.271455223880597, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5275277019080596, "avg_score": null, "num_lines": null }
#$Id$ class CreditNoteRefund: """This class is used to create object for creditnotes refund.""" def __init__(self): """Initialize parameters for creditnotes refund object.""" self.date = '' self.refund_mode = '' self.reference_number = '' self.amount = 0.0 self.exchange_rate = 0.0 self.from_account_id = '' self.from_account_name = '' self.description = '' self.creditnote_refund_id = '' self.creditnote_id = '' self.creditnote_number = '' self.customer_name = '' self.amount_bcy = '' self.amount_fcy = '' def set_date(self, date): """Set the date at which the credit note is created. Args: date(str): Date. """ self.date = date def get_date(self): """Get date at which the credit note is created. Returns: str: Date. """ return self.date def set_refund_mode(self, refund_mode): """Set the mode of refund for the credit note refund amount. Args: refund_mode(str): Refund mode . """ self.refund_mode = refund_mode def get_refund_mode(self): """Get the mode of refund for the credit note refund amount. Returns: str: Refund mode. """ return self.refund_mode def set_reference_number(self, reference_number): """Set reference number for the refund recorded. Args: reference_number(str): Reference number. """ self.reference_number = reference_number def get_reference_number(self): """Get reference number for the refund recorded. Returns: str: Reference number. """ return self.reference_number def set_amount(self, amount): """Set amount refunded from the credit note. Args: amount(float): Amount. """ self.amount = amount def get_amount(self): """Get amount refunded from the credit note. Returns: float: Amount. """ return self.amount def set_exchange_rate(self, exchange_rate): """Set exchange rate of the currency. Args: exchange_rate(float): Exchange rate. """ self.exchange_rate = exchange_rate def get_exchange_rate(self): """Get exchange rate of the currency. Returns: float: Exchange rate. """ return self.exchange_rate def set_from_account_id(self, from_account_id): """Set the account id from which credit note is refunded. Args: from_account_id(str): The account id from which credit note is refunded. """ self.from_account_id = from_account_id def get_from_account_id(self): """Get the account id from which credit note is refunded. Returns: str: The account id from which credit note is refunded. """ return self.from_account_id def set_description(self, description): """Set description for the refund. Args: description(str): Description for the refund. """ self.description = description def get_description(self): """Get descriptioon for the refund. Returns: str: Description for the refund. """ return self.description def set_creditnote_refund_id(self, creditnote_refund_id): """Set creditnote refund id. Args: creditnote_refund(str): Id of the creditnote refund. """ self.creditnote_refund_id = creditnote_refund_id def get_creditnote_refund_id(self): """Get creditnote refund id. Returns: str: Id of the creditnote refund. """ return self.creditnote_refund_id def set_creditnote_id(self, creditnote_id): """Set credit note id. Args: creditnote_id(str): Id of the creditnote. """ self.creditnote_id = creditnote_id def get_creditnote_id(self): """Get Id of the credit note. Returns: str: Id of the creditnote. """ return self.creditnote_id def set_from_account_name(self, from_account_name): """Set account name from which credit note is refunded. Args: from_account_name(str): Account name from which credit note is refunded. """ self.from_account_name = from_account_name def get_from_account_name(self): """Get account name from which credit note is refunded. Returns: str: Account name from which credit note is refunded. """ return self.from_account_name def set_creditnote_number(self, creditnote_number): """Set creditnote number of the creditnote. Args: creditnote_number(str): Creditnote number of creditnote. """ self.creditnote_number = creditnote_number def get_creditnote_number(self): """Get creditnote number of the creditnote. Returns: str: Creditnote number of creditnote. """ return self.creditnote_number def set_customer_name(self, customer_name): """Set customer name. Args: customer_name(str): Customer name. """ self.customer_name = customer_name def get_customer_name(self): """Get customer name. Returns: str: Customer name. """ return self.customer_name def set_amount_bcy(self, amount_bcy): """Set amount bcy. Args: amount_bcy(str): Amount_bcy. """ self.amount_bcy = amount_bcy def get_amount_bcy(self): """Get amount bcy. Returns: str: Amount_bcy. """ return self.amount_bcy def set_amount_fcy(self, amount_fcy): """Set amount fcy. Args: amount_fcy(str): Amount fcy. """ self.amount_fcy = amount_fcy def get_amount_fcy(self): """Get amount fcy. Returns: str: Amount fcy. """ return self.amount_fcy def to_json(self): """This method is used to convert creditnote refund object to json object. Returns: dict: Dictionary containing json object for credit note refund. """ data = {} if self.date != '': data['date'] = self.date if self.refund_mode != '': data['refund_mode'] = self.refund_mode if self.reference_number != '': data['reference_number'] = self.reference_number if self.amount > 0: data['amount'] = self.amount if self.exchange_rate > 0 : data['exchange_rate'] = self.exchange_rate if self.from_account_id != '': data['from_account_id'] = self.from_account_id if self.description != '': data['description'] = self.description if self.creditnote_id != '': data['creditnote_id'] = self.creditnote_id return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/CreditNoteRefund.py", "copies": "1", "size": "7615", "license": "mit", "hash": -7577912090061715000, "line_mean": 24.1320132013, "line_max": 82, "alpha_frac": 0.5290873276, "autogenerated": false, "ratio": 4.389048991354467, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.053232881389253625, "num_lines": 303 }
#$Id$ class CreditnoteSetting: """This class is used to create object for creditnotes settings.""" def __init__(self): """Initialize parameters for creditnotes settings.""" self.auto_generate = None self.prefix_string = "" self.reference_text = "" self.next_number = "" self.notes = "" self.terms = "" def set_auto_generate(self, auto_generate): """Set whether auto number generation is enabled. Args: auto_generate(bool): True to enable auto number genration else false. """ self.auto_generate = auto_generate def get_auto_generate(self): """Set whether auto number generation is enabled. Returns: bool: True to enable auto number genration else false. """ return self.auto_generate def set_prefix_string(self, prefix_string): """Set prefix string. Args: prefix_string(str): Prefix string. """ self.prefix_string = prefix_string def get_prefix_string(self): """Get prefix string. Returns: str: Prefix string. """ return self.prefix_string def set_reference_text(self, reference_text): """Set reference text. Args: reference_text(str): Reference text. """ self.reference_text = reference_text def get_reference_text(self): """Get reference text. Returns: str: Reference text. """ return self.reference_text def set_next_number(self, next_number): """Set reference number. Args: reference_number(str): Reference number. """ self.next_number = next_number def get_next_number(self): """Get next number. Returns: str: Next number. """ return self.next_number def set_notes(self, notes): """Set notes. Args: notes(str): Notes. """ self.notes = notes def get_notes(self): """Get notes. Returns: str: Notes. """ return self.notes def set_terms(self, terms): """Set terms. Args: terms(str): Terms. """ self.terms = terms def get_terms(self): """Get terms. Returns: str: Terms. """ return self.terms def to_json(self): """This method is used to convert creditnote setting object to json objcet. Returns: dict: Dictionary containing json object for credit note setting. """ data = {} if self.auto_generate is not None: data['auto_generate'] = self.auto_generate if self.prefix_string != '': data['prefix_string'] = self.prefix_string if self.reference_text != '': data['reference_text'] = self.reference_text if self.next_number != '': data['next_number'] = self.next_number if self.notes != '': data['notes'] = self.notes if self.terms != '': data['terms'] = self.terms return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/CreditnoteSetting.py", "copies": "1", "size": "3249", "license": "mit", "hash": -6191426246393403000, "line_mean": 21.8802816901, "line_max": 83, "alpha_frac": 0.5278547245, "autogenerated": false, "ratio": 4.475206611570248, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5503061336070247, "avg_score": null, "num_lines": null }
#$Id$ class Criteria: """This class is used to create object for criteria.""" def __init__(self): """Initialize parameters for criteria object.""" self.criteria_id = '' self.field = '' self.comparator = '' self.value = 0.0 def set_criteria_id(self, criteria_id): """Set criteria id. Args: criteria_id(str): Criteria id. """ self.criteria_id = criteria_id def get_criteria_id(self): """Get criteria id. Returns: str: Criteria id. """ return self.criteria_id def set_field(self, field): """Set field. Args: field(str): Field. """ self.field = field def get_field(self): """Get field. Returns: str: Field. """ return self.field def set_comparator(self, comparator): """Set comparator. Args: comparator(str): Comparator. """ self.comparator = comparator def get_comparator(self): """Get comparator. Returns: str: Comparator. """ return self.comparator def set_value(self, value): """Set value. Args: value(float): Value. """ self.value = value def get_value(self): """Get value. Returns: float: Value. """ return self.value def to_json(self): """This method is used to convert criteria object to json object. Returns: dict: Dictionary containing json object for criteria. """ data = {} if self.field != '': data['field'] = self.field if self.comparator != '': data['comparator'] = self.comparator if self.value > 0: data['value'] = self.value return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Criteria.py", "copies": "1", "size": "1950", "license": "mit", "hash": -6699669022595363000, "line_mean": 18.5, "line_max": 73, "alpha_frac": 0.4851282051, "autogenerated": false, "ratio": 4.513888888888889, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.014798608254490609, "num_lines": 100 }
#$Id$ class Currency: """This class is used to create object for currency. """ def __init__(self): """Initialize parameters for currency object.""" self.currency_id = '' self.currency_code = '' self.currency_name = '' self.currency_symbol = '' self.price_precision = 0 self.currency_format = '' self.is_base_currency = None self.exchange_rate = 0.0 self.effective_date = '' def set_currency_id(self, currency_id): """Set currency id. Args: currency_id(str): Currency id. """ self.currency_id = currency_id def get_currency_id(self): """Get currency id. Returns: str: Currency id. """ return self.currency_id def set_currency_code(self, currency_code): """Set currency code. Args: currency_code(str): Currency code. """ self.currency_code = currency_code def get_currency_code(self): """Get currency code. Returns: str: Currency code. """ return self.currency_code def set_currency_name(self, currency_name): """Set currency name. Args: currency_name(str): Currency name. """ self.currency_name = currency_name def get_currency_name(self): """Get currency name. Returns: str: Currency name. """ return self.currency_name def set_currency_symbol(self, currency_symbol): """Set currency symbol. Args: currency_symbol(str): Currency symbol. """ self.currency_symbol = currency_symbol def get_currency_symbol(self): """Get currency symbol. Returns: str: Currency symbol. """ return self.currency_symbol def set_price_precision(self, price_precision): """Set price precision. Args: price_precision(int): Price precision. """ self.price_precision = price_precision def get_price_precision(self): """Get price precision. Returns: int: Price precision. """ return self.price_precision def set_currency_format(self, currency_format): """Set currency format. Args: currency_format(str): Currency format. """ self.currency_format = currency_format def get_currency_format(self): """Get currency format. Returns: str: Currency fromat. """ return self.currency_format def set_is_base_currency(self, is_base_currency): """Set whether the currency is base currency. Args: is_base_currency(bool): True if it is base currency else False. """ self.is_base_currency = is_base_currency def get_is_base_currency(self): """Get whether the currency is base currency. Returns: bool: True if it is base currency else false. """ return self.is_base_currency def set_exchange_rate(self, exchange_rate): """Set exchange rate. Args: exchange_rate(float): Exchange rate. """ self.exchange_rate = exchange_rate def get_exchange_rate(self): """Get exchange rate. Returns: float: Exchange rate. """ return self.exchange_rate def set_effective_date(self, effective_date): """Set effective date. Args: effective_date(str): Effective date. """ self.effective_date = effective_date def get_effective_date(self): """Get effective date. Returns: str: Effective date. """ return self.effective_date def to_json(self): """This method is used to create json object for currency. Returns: dict: Dictionary containing json object for currency. """ data = {} if self.currency_code != '': data['currency_code'] = self.currency_code if self.currency_symbol != '': data['currency_symbol'] = self.currency_symbol if self.price_precision > 0: data['price_precision'] = self.price_precision if self.currency_format != '': data['currency_format'] = self.currency_format return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Currency.py", "copies": "1", "size": "4486", "license": "mit", "hash": -2628652742961089000, "line_mean": 22.0051282051, "line_max": 75, "alpha_frac": 0.5479268836, "autogenerated": false, "ratio": 4.437190900098912, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.009824916159757788, "num_lines": 195 }
#$Id$ class CustomerPayment: """This class is used to create object for customer payments.""" def __init__(self): """Initialize parameters for customer payments.""" self.customer_id = '' self.invoices = [] self.payment_mode = '' self.description = '' self.date = '' self.reference_number = '' self.exchange_rate = 0.0 self.amount = 0.0 self.bank_charges = 0.0 self.tax_account_id = '' self.account_id = '' self.payment_id = '' self.payment_number = '' self.invoice_numbers = '' self.bcy_amount = 0 self.unused_amount = 0 self.bcy_unused_amount = 0 self.account_name = '' self.customer_name = '' self.created_time = '' self.last_modified_time = '' self.tax_account_name = '' self.tax_amount_withheld = 0.0 def set_customer_id(self, customer_id): """Set customer id. Args: customer_id(str): Customer id. """ self.customer_id = customer_id def get_customer_id(self): """Get customer id. Returns: str: Customer id. """ return self.customer_id def set_invoices(self, invoice): """Set invoices. Args: invoice(list) : List of invoice object. """ self.invoices.extend(invoice) def get_invoices(self): """Get invoices. Returns: list: List of invoices. """ return self.invoices def set_payment_mode(self, payment_mode): """Set mode of payment for the payment received. Args: payment_mode(str): Mode of payment. """ self.payment_mode = payment_mode def get_payment_mode(self): """Get mode of payment of the payment received. Returns: str: Mode of payment. """ return self.payment_mode def set_description(self, description): """Set description for the customer payment. Args: description(str): Description for the customer payment. """ self.description = description def get_description(self): """Get description of the customer payment. Returns: str: Description of the customer payment. """ return self.description def set_date(self, date): """Set date at which the payment is made. Args: date(str): Date at which payment is made. """ self.date = date def get_date(self): """Get date at which payment is made. Returns: str: Date at which payment is made. """ return self.date def set_reference_number(self, reference_number): """Set reference number for the customer payment. Args: reference_number(str): Reference number for the customer payment. """ self.reference_number = reference_number def get_reference_number(self): """Get reference number of the customer payment. Returns: str: Reference number of the customer payment. """ return self.reference_number def set_exchange_rate(self, exchange_rate): """Set exchange rate for the currency. Args: exchange_rate(float): Exchange rate for thee currency. """ self.exchange_rate = exchange_rate def get_exchange_rate(self): """Get exchange rate of the currency. Returns: float: Exchange rate of the currency. """ return self.exchange_rate def set_amount(self, amount): """Set payment amount made by the customer. Args: amount(float): Payment amount made by the customer. """ self.amount = amount def get_amount(self): """Get payment amount made by the customer. Returns: float: Payment amount made by the customer. """ return self.amount def set_bank_charges(self, bank_charges): """Set bank charges incurred. Args: bank_charges(float): Bank charges incurred. """ self.bank_charges = bank_charges def get_bank_charges(self): """Get bank charges incurred. Returns: float: Bank charges incurred. """ return self.bank_charges def set_tax_account_id(self, tax_account_id): """Set id for the tax account incase of withholding tax. Args: tax_account_id(str): Id for the tax account. """ self.tax_account_id = tax_account_id def get_tax_account_id(self): """Get id of the tax account. Returns: str: Id of the tax account. """ return self.tax_account_id def set_account_id(self, account_id): """Set ID for the cash/ bank account to which the payment has to be deposited. Args: account_id(str): Id for the cash or bank account. """ self.account_id = account_id def get_account_id(self): """Get ID of the cash/ bank account to which the payment has to be deposited. Returns: str: Id of the cash or bank account. """ return self.account_id def set_payment_id(self, payment_id): """Set payment id. Args: payment_id(str): Payment id. """ self.payment_id = payment_id def get_payment_id(self): """Get payment id. Returns: str: Payment id. """ return self.payment_id def set_payment_number(self, payment_number): """Set payment number. Args: payment_number(str): Payment number. """ self.payment_number = payment_number def get_payment_number(self): """Get payment number. Returns: str: Payment number. """ return self.payment_number def set_invoice_numbers(self, invoice_numbers): """Set invoice numbers. Args: invoice_numbers(str): invoice_numbers """ self.invoice_numbers = invoice_numbers def get_invoice_numbers(self): """Get invoice numbers. Returns: str: Invoice numbers """ return self.invoice_numbers def set_bcy_amount(self, bcy_amount): """Set bcy amount. Args: bcy_amount(int): bcy amount. """ self.bcy_amount = bcy_amount def get_bcy_amount(self): """Get bcy amount. Returns: int: bcy amount. """ return self.bcy_amount def set_unused_amount(self, unused_amount): """Set unused amount. Args: unused_amount(int): Unused amount. """ self.unused_amount = unused_amount def get_unused_amount(self): """Get unused amount. Returns: int: Unused amount. """ return self.unused_amount def set_bcy_unused_amount(self, bcy_unused_amount): """Set bcy unused amount. Args: bcy_unused_amount(int): bcy unused amount. """ self.bcy_unused_amount = bcy_unused_amount def get_bcy_unused_amount(self): """Get bcy unused amount. Returns: int: bcy unused amount. """ return self.bcy_unused_amount def set_account_name(self, account_name): """Set account name. Args: account_name(str): Account name. """ self.account_name = account_name def get_account_name(self): """Get account name. Returns: str: Account name. """ return self.account_name def set_customer_name(self, customer_name): """Set customer name. customer_name(str): Customer name. """ self.customer_name = customer_name def get_customer_name(self): """Get customer name. Returns: str: Customer name. """ return self.customer_name def set_created_time(self, created_time): """Set created time. Args: created_time(str): Created time. """ self.created_time = created_time def get_created_time(self): """Get created time. Returns: str: Created time. """ return self.created_time def set_last_modified_time(self, last_modified_time): """Set last modified time. Args: last_modified_time(str): Last modified time. """ self.last_modified_time = last_modified_time def get_last_modified_time(self): """Get last modified time. Returns: str: Last modified time. """ return self.last_modified_time def set_tax_account_name(self, tax_account_name): """Set tax account name. Args: tax_account_name(str): Tax Account name. """ self.tax_account_name = tax_account_name def get_tax_account_name(self): """Get tax account name. Returns: str: Tax account name. """ return self.tax_account_name def set_tax_amount_withheld(self, tax_amount_withheld): """Set amount withheld for tax. Args: tax_amount_withheld(float): Amount withheld for tax. """ self.tax_amount_withheld = tax_amount_withheld def get_tax_amount_withheld(self): """Get amount withheld for tax. Returns: float: Amount withheld for tax. """ return self.tax_amount_withheld def to_json(self): """This method is used to convert customer payment object to json object. Returns: dict: Dictionary containing json object for customer payments. """ data = {} if self.customer_id != '': data['customer_id'] = self.customer_id if self.invoices: data['invoices'] = [] for value in self.invoices: invoice = value.to_json() data['invoices'].append(invoice) if self.payment_mode != '': data['payment_mode'] = self.payment_mode if self.description != '': data['description'] = self.description if self.date != '': data['date'] = self.date if self.reference_number != '': data['reference_number'] = self.reference_number if self.exchange_rate > 0: data['exchange_rate'] = self.exchange_rate if self.amount > 0: data['amount'] = self.amount if self.bank_charges > 0: data['bank_charges'] = self.bank_charges if self.tax_account_id != '': data['tax_account_id'] = self.tax_account_id if self.account_id != '': data['account_id'] = self.account_id return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/CustomerPayment.py", "copies": "1", "size": "11242", "license": "mit", "hash": -8828575926023331000, "line_mean": 22.5681341719, "line_max": 81, "alpha_frac": 0.5384273261, "autogenerated": false, "ratio": 4.285932138772398, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.024181783893901975, "num_lines": 477 }
#$Id$ class CustomField: """This class is used to create custom field.""" def __init__(self): """Initialize the parameters for custom field object""" self.index = 0 self.show_on_pdf = None self.value = '' self.label = '' def set_index(self, index): """Set index for custom field. Args: index(int): Index for custom field. """ self.index = index def get_index(self): """Get index for custom field. Returns: int: Index for custom field. """ return self.index def set_show_on_pdf(self, show_on_pdf): """Set whether to show as pdf or not. Args: show_on_pdf(bool): True to show as pdf else False. """ self.show_on_pdf = show_on_pdf def get_show_on_pdf(self): """Get whether to show as pdf or not. Returns: bool: True to show as pdf else False. """ return self.show_on_pdf def set_value(self, value): """Set value for custom field. Args: value(str): Value for custom field. """ self.value = value def get_value(self): """Get value of custom field. Returns: str: Value for custom field. """ return self.value def set_label(self, label): """Set label for custom field. Args: label(str): Label for custom field. """ self.label = label def get_label(self): """Get label of custom field. Returns: str: Label of custom field. """ return self.label def set_invoice(self, invoice): """Set invoice. Args: invoice(instance): Invoice custom field. """ self.invoice.append(invoice) def get_invoice(self): """Get invoice. Returns: list of instance: List of Invoice custom field. """ return self.invoice def set_contact(self, contact): """Set cocntact. Args: contact(instance): Contact custom field. """ self.contact.append(contact) def get_contact(self): """Get contact. Returns: list of instance: List of Contact custom field. """ return self.custom_field def set_estimate(self, estimate): """Set estimate. Args: estimate(instance): Estimate custom field. """ self.estimate.append(estimate) def get_estimate(self): """Get estimate. Returns: list of instance: List of estimate custom field. """ return self.estimate def to_json(self): """This method is used to convert custom field object to json object. Returns: dict: Dictionary containing json object for custom field. """ data = {} #if self.index != None: #data['index'] = self.index if self.value != '': data['value'] = self.value return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/CustomField.py", "copies": "1", "size": "3198", "license": "mit", "hash": 866816066794086500, "line_mean": 20.32, "line_max": 77, "alpha_frac": 0.5109443402, "autogenerated": false, "ratio": 4.4978902953586495, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5508834635558649, "avg_score": null, "num_lines": null }
#$Id$ class Customfield: ''' Customfield object is used to create an object for the project custom field. ''' def __init__(self): ''' Initialize the parameters of the Customfield object. ''' self.label_name = ""; self.column_name = ""; self.default_Value = ""; self.picklist_values = []; def set_label_name(self, label_name): ''' Set the label name of the custom field. Args: label_name(str): Label name of the custom field. ''' self.label_name = label_name; def get_label_name(self): ''' Get the label name of the custom field. Returns: str: Returns the label name. ''' return self.label_name; def set_column_name(self, column_name): ''' Set the column name of the custom field. Args: column_name(str): Column name of the custom field. ''' self.column_name = column_name; def get_column_name(self): ''' Get the column name of the custom field. Returns: str: Returns the column name. ''' return self.column_name; def set_default_value(self, default_Value): ''' Set the default value of the custom field. Args: default_Value(str): Default value of the custom field. ''' self.default_Value = default_Value; def get_default_value(self): ''' Get the default value of the custom field. Returns: str: Returns the default value. ''' return self.default_Value; def set_picklist_values(self, picklist_values): ''' Set the picklist values of the custom field. Args: picklist_values(array): Array of picklist values. ''' self.picklist_values = picklist_values; def get_picklist_values(self): ''' Get the picklist values of the custom field. Returns: array : Returns array of picklist values. ''' return self.picklist_values;
{ "repo_name": "zoho/projects-python-wrappers", "path": "projects/model/Customfield.py", "copies": "1", "size": "1860", "license": "mit", "hash": 5986238668109387000, "line_mean": 15.6071428571, "line_max": 77, "alpha_frac": 0.6322580645, "autogenerated": false, "ratio": 3.2804232804232805, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.44126813449232805, "avg_score": null, "num_lines": null }
#$Id$ class Date: """This class is used to create object for date.""" def __init__(self): """Initialize parameters for date object.""" self.total_hours = "" self.display_format = "" self.date_long = 0 self.task_log = [] self.bug_log = [] self.general_log = [] def set_total_hours(self, total_hours): """Set total hours. Args: total_hours(str): Total hours. """ self.total_hours = total_hours def get_total_hours(self): """Get total hours. Returns: str: Total hours. """ return self.total_hours def set_display_format(self, display_format): """Set display format. Args: display_format(str): Display format. """ self.display_format = display_format def get_display_format(self): """Get display format. Returns: str: Display format. """ return self.display_format def set_date_long(self, date_long): """Set date long. Args: date_long(long): date long. """ self.date_long = date_long def get_date_long(self): """Get date long. Returns: long: Date long. """ return self.date_long def set_task_logs(self, task_log): """Set task log. Args: task_log(instance): Task log. """ self.task_log.append(task_log) def get_task_logs(self): """Get task log. Returns: list of instance:List of Task log object. """ return self.task_log def set_bug_logs(self, bug_log): """Set bug log. Args: bug_log(instance): Bug log. """ self.bug_log.append(bug_log) def get_bug_logs(self): """Get bug log. Returns: list of instance:List of bug log object. """ return self.bug_log def set_general_logs(self, general_log): """Set general log. Args: general_log(instance): General log. """ self.general_log.append(general_log) def get_general_logs(self): """Get general log. Returns: list of instaance:List of General log object. """ return self.general_log
{ "repo_name": "zoho/projects-python-wrappers", "path": "projects/model/Date.py", "copies": "1", "size": "2413", "license": "mit", "hash": -6262563467049923000, "line_mean": 18.6178861789, "line_max": 57, "alpha_frac": 0.5043514298, "autogenerated": false, "ratio": 4.076013513513513, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5080364943313513, "avg_score": null, "num_lines": null }
#$Id$ class Defaultfield: ''' Defaultfield is used to create an object for project default field. ''' def __init__(self): ''' Initialize parameters for Defaultfiled object. ''' self.severity_details = []; self.status_deatils = []; self.module_details = []; self.priority_details = []; self.classification_details = []; def set_severity_details(self, severity_details): ''' Set the severity details of the project. Args: severity_details(list): Severity details of the project. ''' self.severity_details = severity_details; def get_severity_details(self): ''' Get the severity details of the project. Returns: list: Returns list of severity details. ''' return self.severity_details; def set_status_deatils(self, status_deatils): ''' Set the status details of the project. Args: status_deatils(list): List of status deatils of the project. ''' self.status_deatils = status_deatils; def get_status_deatils(self): ''' Get the status deatils of the project. Returns: list: Returns list of status deatils. ''' return self.status_deatils; def set_module_details(self, module_details): ''' Set the module details of the project. Args: module_details(list): List of module details of the project. ''' self.module_details = module_details; def get_module_details(self): ''' Get the module details of the project. Returns: list : Returns list of module details. ''' return self.module_details; def set_priority_details(self, priority_details): ''' Set the priority details of the project. Args: priority_details(list) : List of priority details of the project. ''' self.priority_details = priority_details; def get_priority_details(self): ''' Get the priority details of the project. Returns: list: Returns list of priority details. ''' return self.priority_details; def set_classification_details(self, classification_details): ''' Set the classification details of the project. Args: classification_details(list): List of classification details of the project. ''' self.classification_details = classification_details; def get_classification_details(self): ''' Get the classification details of the project. Returns: list : Returns list of classification details. ''' return self.classification_details;
{ "repo_name": "zoho/projects-python-wrappers", "path": "projects/model/Defaultfield.py", "copies": "1", "size": "2503", "license": "mit", "hash": -7440482696929800000, "line_mean": 17.2700729927, "line_max": 79, "alpha_frac": 0.6652017579, "autogenerated": false, "ratio": 3.6014388489208633, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47666406068208633, "avg_score": null, "num_lines": null }
#$Id$ class DefaultTemplate: """This class is used to create object for default templates.""" def __init__(self): """Initialize the parameters for default temmplates.""" self.invoice_template_id = '' self.invoice_template_name = '' self.estimate_template_id = '' self.estimate_template_name = '' self.creditnote_template_id = '' self.creditnote_template_name = '' self.invoice_email_template_id = '' self.invoice_email_template_name = '' self.estimate_email_template_id = '' self.estimate_email_template_name = '' self.creditnote_email_template_id = '' self.creditnote_email_template_name = '' def set_invoice_template_id(self, invoice_template_id): """Set default invoice template id used for this contact while creating invoice. Args: invoice_template_id(str): Default invoice template id used for this contact while creating invoice. """ self.invoice_template_id = invoice_template_id def get_invoice_template_id(self): """Get default invoice template id used for this contact while creating invoice. Returns: str: Default invoice template id used for this contact while creating invoice. """ return self.invoice_template_id def set_invoice_template_name(self, invoice_template_name): """Set default invoice template name used for this contact while creating invoice. Args: invoice_template_name(str): Default invoice template name used for this contact while creating invoice. """ self.invoice_template_name = invoice_template_name def get_invoice_template_name(self): """Get default invoice template name used for this contact while creating invoice. Returns: str: Default invoice template name used for this contact while creating invoice. """ return self.invoice_template_name def set_estimate_template_id(self, estimate_template_id): """Set default estimate template id used for this contact while creating estimate. Args: estimate_template_id(str): Default estimate template id used for this contact while creating estimate. """ self.estimate_template_id = estimate_template_id def get_estimate_template_id(self): """Get default estimate template id used for this contact while creating estimate. Returns: str: Default estimate template id used for this contact while creating estimate. """ return self.estimate_template_id def set_estimate_template_name(self, estimate_template_name): """Set default estimate template name used for this contact while creating estimate. Args: estimate_template_name(str): Default estimate template name used for this contact while creating estimate. """ self.estimate_template_name = estimate_template_name def get_estimate_template_name(self): """Get default estimate template name used for this contact while creating estimate. Returns: str: Default estimate template name used for this contact while creating estimate. """ return self.estimate_template_name def set_creditnote_template_id(self, creditnote_template_id): """Set default creditnote template id used for this contact while creating creditnote. Args: creditnote_template_id(str): Default creditnote template id used for this contact while creating creditnote. """ self.creditnote_template_id = creditnote_template_id def get_creditnote_template_id(self): """Get default creditnote template id used for this contact while creating creditnote. Returns: str: Default creditnote template id used for this contact while creating creditnote. """ return self.creditnote_template_id def set_creditnote_template_name(self, creditnote_template_name): """Set default creditnote template name used for this contact while creating creditnote. Args: creditnote_template_name(str): Default creditnote template name used for this contact while creating creditnote. """ self.creditnote_template_name = creditnote_template_name def get_creditnote_template_name(self): """Get default creditnote template id used for this contact while creating creditnote. Returns: str: Default creditnote template id used for this contact while creating creditnote. """ return self.creditnote_template_name def set_invoice_email_template_id(self, invoice_email_template_id): """Set default invoice email template id used for this contact while creating invoice. Args: invoice_email_template_id(str): Default invoice template id used for this contact while creating invoice """ self.invoice_email_template_id = invoice_email_template_id def get_invoice_email_template_id(self): """Get default invoice email template id used for this contact while creating invoice. Returns: str: Default invoice email template id used for this contact while creating invoice. """ return self.invoice_email_template_id def set_invoice_email_template_name(self, invoice_email_template_name): """Set default invoice email template name used for this contact while creating invocie. Args: invoice_email_template_name(str): Default invoice email template name used for this contact while creating invocie. """ self.invoice_email_template_name = invoice_email_template_name def get_invoice_email_template_name(self): """Get default invoice email template name used for this contact while creating invoice. Returns: str: Default invoice email template name used for this contact while creating invoice. """ return self.invoice_email_template_name def set_estimate_email_template_id(self, estimate_email_template_id): """Set default estimate template id used for this contact while creating estimate. Args: estimate_email_template_id(str): Default estimate template id used for this cotnact while creating estimate. """ self.estimate_email_template_id = estimate_email_template_id def get_estimate_email_template_id(self): """Get default estimate email template id used for this contact while creating estimate. Returns: str: Default estimate template id used for this cotnact while creating estimate. """ return self.estimate_email_template_id def set_estimate_email_template_name(self, estimate_email_template_name): """Set default estimate email template name used for this contact while creating estimate. Args: estimate_email_template_name(str): Default estimate email template name used for this contact while ccreating estimate. """ self.estimate_email_template_name = estimate_email_template_name def get_estimate_email_template_name(self): """Get default estimate email template name used for this contact while creating estimate. Returns: str: Default estimate email template name used for this contact while creating estimate. """ return self.estimate_email_template_name def set_creditnote_email_template_id(self, creditnote_email_template_id): """Set default creditnote email template id used for this contact while creating creditnote. Args: creditnote_email_template_id(str): Default creditnote email template id used for this contact while creating creditnote. """ self.creditnote_email_template_id = creditnote_email_template_id def get_creditnote_email_template_id(self): """Get default creditnote email template id used for this contact while creating creditnote. Returns: str: Default creditnote email template id used for this contact while creating creditnote. """ return self.creditnote_email_template_id def set_creditnote_email_template_name(self, creditnote_email_template_name): """Set default creditnote email template name used for this contact while creating creditnote. Args: creditnote_email_template_name(str): Default creditnote email template name used for this contact while creating creditnote. """ self.creditnote_email_template_name = creditnote_email_template_name def get_creditnote_email_template_name(self): """Get default creditnote email template name used for this contact while creating creditnote. Returns: str: Default creditnote email template name used for this contact while creating creditnote. """ return self.creditnote_email_template_name
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/DefaultTemplate.py", "copies": "1", "size": "10073", "license": "mit", "hash": 1813725376093645800, "line_mean": 33.9756944444, "line_max": 81, "alpha_frac": 0.6156060756, "autogenerated": false, "ratio": 5.049122807017544, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.06529036224867103, "num_lines": 288 }
#$Id$ class EmailHistory: """This class is used to create an object for Email history.""" def __init__(self): """Initialize the parameters for Email hstory object.""" self.mailhistory_id = '' self.from_mail_id = '' self.to_mail_ids = '' self.subject = '' self.date = '' self.type = 0 def set_mailhistory_id(self, mailhistory_id): """Set mail history id. Args: mailhistory_id(str): Mail history id. """ self.mailhistory_id = mailhistory_id def get_mailhistory_id(self): """Get mail history id. Returns: str: Mail history id. """ return self.mailhistory_id def set_from(self, from_mail_id): """Set from mail id. Args: from_mail_id(str): From mail id. """ self.from_mail_id = from_mail_id def get_from(self): """Get from mail id. Returns: str: From mail id. """ return self.from_mail_id def set_to_mail_ids(self, to_mail_ids): """Set to mail id. Args: to_mail_ids(str): To mail ids. """ self.to_mail_ids = to_mail_ids def get_to_mail_ids(self): """Get to mail ids. Returns: str: To mail ids. """ return self.to_mail_ids def set_subject(self, subject): """Set subject. Args: subjecct(str): Subject. """ self.subject = subject def get_subject(self): """Get subject. Returns: str: Subject. """ return self.subject def set_date(self, date): """Set date. Args: date(str): Date. """ self.date = date def get_date(self): """Get date. Returns: str: Date. """ return self.date def set_type(self, email_type): """Set type. Args: type(int): Type. """ self.type = email_type def get_type(self): """Get type. Returns: int: Type. """ return self.type
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/EmailHistory.py", "copies": "1", "size": "2217", "license": "mit", "hash": 8584623841151164000, "line_mean": 17.1721311475, "line_max": 67, "alpha_frac": 0.4727108705, "autogenerated": false, "ratio": 3.9731182795698925, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49458291500698925, "avg_score": null, "num_lines": null }
#$Id$ class EmailTemplate: """This class is used to create object for email templates.""" def __init__(self): """Initialize parameters for email templates.""" self.selected = None self.name = '' self.email_template_id = '' def set_selected(self, selected): """Set whether to select or not. Args: selected(bool): True to select else False. """ self.selected = selected def get_selected(self): """Get whether to select or not. Returns: bool: True to select else False. """ return self.selected def set_name(self, name): """Set name. Args: name(str): Name. """ self.name = name def get_name(self): """Get name. Returns: str: Name. """ return self.name def set_email_template_id(self, email_template_id): """Set email template id. Args: email_template_id(str): Email template id. """ self.email_template_id = email_template_id def get_email_template_id(self): """Get email template id. Returns: str: Email template id. """ return self.email_template_id
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/EmailTemplate.py", "copies": "1", "size": "1307", "license": "mit", "hash": -8430492837022829000, "line_mean": 19.1076923077, "line_max": 66, "alpha_frac": 0.5179801071, "autogenerated": false, "ratio": 4.385906040268456, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.02666666666666667, "num_lines": 65 }
#$Id$ class EstimateSetting: """This class is used to create object for estimate settings.""" def __init__(self): """Initialize parameters for estimate settings.""" self.auto_generate = None self.prefix_string = "" self.start_at = 0 self.next_number = "" self.quantity_precision = 0 self.discount_type = "" self.is_discount_before_tax = None self.reference_text = "" self.notes = "" self.terms = "" self.terms_to_invoice = None self.notes_to_invoice = None self.warn_estimate_to_invoice = None self.is_sales_person_required = None self.default_template_id = "" def set_default_template_id(self, default_template_id): """Set default template id. Args: default_template_id(str): Default template id. """ self.default_template_id = default_template_id def get_default_template_id(self): """Get default template id. Returns: str: Default template id. """ return self.default_template_id def set_auto_generate(self, auto_generate): """Set whether to enable or disable auto number generation. Args: auto_generate(bool): True to enable auto number generation. """ self.auto_generate = auto_generate def get_auto_generate(self): """Get whether to enable or disable auto number generation. Returns: bool: True to enable auto number generation. """ return self.auto_generate def set_prefix_string(self, prefix_string): """Set prefix string. Args: prefix_string(str): Prefix string. """ self.prefix_string = prefix_string def get_prefix_string(self): """Get prefix string. Returns: str: Prefix string. """ return self.prefix_string def set_start_at(self, start_at): """Set start at. Args: start_at(int): Start at. """ self.start_at = start_at def get_start_at(self): """Get start at. Returns: str: Get start at. """ return self.start_at def set_next_number(self, next_number): """Set next number. Args: next_number(str): Next number. """ self.next_number = next_number def get_next_number(self): """Get next number. Returns: str: Next number. """ return self.next_number def set_quantity_precision(self, quantity_precision): """Set quantity precision. Args: quantity_precision(int): Quantity precision. """ self.quantity_precision = quantity_precision def get_quantity_precision(self): """Get quantity precision. Returns: int: Quantity precision. """ return self.quantity_precision def set_discount_type(self, discount_type): """Set discount type. Args: discount_type(str): Discount type. """ self.discount_type = discount_type def get_discount_type(self): """Get discount type. Returns: str: Discount type. """ return self.discount_type def set_is_discount_before_tax(self, is_discount_before_tax): """Set whether to discount before tax. Args: is_discount_before_tax(bool): True to discount before tax. """ self.is_discount_before_tax = is_discount_before_tax def get_is_discount_before_tax(self): """Get whether to discount before tax. Returns: bool: True to discount before tax else false. """ return self.is_discount_before_tax def set_reference_text(self, reference_text): """Set reference text. Args: reference_text(str): Reference text. """ self.reference_text = reference_text def get_reference_text(self): """Get reference text. Returns: str: Reference text. """ return self.reference_text def set_notes(self, notes): """Set notes. Args: notes(str): Notes. """ self.notes = notes def get_notes(self): """Get notes. Returns: str: Notes. """ return self.notes def set_terms(self, terms): """Set terms. Args: terms(str): Terms. """ self.terms = terms def get_terms(self): """Get terms. Returns: str: Terms. """ return self.terms def set_terms_to_invoice(self, terms_to_invoice): """Set terms to invoice. Args: terms_to_invoice(bool): True to determine whether terms and conditions field is to be copied from estimate to invoice else False. """ self.terms_to_invoice = terms_to_invoice def get_terms_to_invoice(self): """Get terms to invoice. Returns: bool: True to determine whether terms and conditions field is to be copied from estimate to invoice else False. """ return self.terms_to_invoice def set_notes_to_invoice(self, notes_to_invoice): """Set notes to invoice. Args: notes_to_invoice(bool): True to determine whether customer notes field is to be copied from estimate to invoice. """ self.notes_to_invoice = notes_to_invoice def get_notes_to_invoice(self): """Get notes to invoice. Returns: bool: True to determine whether customer notes field is to be copied from estimate to invoice. """ return self.notes_to_invoice def set_warn_estimate_to_invoice(self, warn_estimate_to_invoice): """Set whether to warn while converting from estimate to invoice. Args: warn_estimate_to_invoice(bool): True to warn while converting from estiamte to invoice. """ self.warn_estimate_to_invoice = warn_estimate_to_invoice def get_warn_estimate_to_invoice(self): """Get whether to warn while converting form estimate to invoice. Returns: bool: True to warn while converting from estimate to invoice. """ return self.warn_estimate_to_invoice def set_is_sales_person_required(self, is_sales_person_required): """Set whether sales person is required. Args: is_sales_person_required(bool): True if sales person is required else false. """ self.is_sales_person_required = is_sales_person_required def get_is_sales_person_required(self): """Get whether sales person is required. Returns: bool: True if sales person is required. """ return self.is_sales_person_required def to_json(self): """This method is used to convert estimate setting object to json object. Returns: dict: Dictionary containing json object for estimate setting. """ data = {} if self.auto_generate != None: data['auto_generate'] = self.auto_generate if self.prefix_string != "": data['prefix_string'] = self.prefix_string if self.start_at > 0: data['start_at'] = self.start_at if self.next_number != '': data['next_number'] = self.next_number if self.quantity_precision > 0: data['quantity_precision'] = self.quantity_precision if self.discount_type != '': data['discount_type'] = self.discount_type if self.reference_text != '': data['reference_text'] = self.reference_text if self.default_template_id != '': data['default_template_id'] = self.default_template_id if self.notes != '': data['notes'] = self.notes if self.terms != '': data['terms'] = self.terms if self.terms_to_invoice is not None: data['terms_to_invoice'] = self.terms_to_invoice if self.notes_to_invoice is not None: data['notes_to_invoice'] = self.notes_to_invoice if self.warn_estimate_to_invoice is not None: data['warn_estimate_to_invoice'] = self.warn_estimate_to_invoice if self.is_sales_person_required is not None: data['is_sales_person_required'] = self.is_sales_person_required return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/EstimateSetting.py", "copies": "1", "size": "8661", "license": "mit", "hash": 1861906017328479000, "line_mean": 25.3252279635, "line_max": 141, "alpha_frac": 0.5687564946, "autogenerated": false, "ratio": 4.324013979031453, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.013048295877669841, "num_lines": 329 }
#$Id$ class Event: """This class is used to create object for Event.""" def __init__(self): """Initialize parameters for Event object.""" self.id = 0 self.title = "" self.location = "" self.scheduled_on = "" self.scheduled_on_long = 0 self.reminder = "" self.repeat = "" self.occurrences = 0 self.occured = 0 self.duration_hour = "" self.duration_minutes = "" self.is_open = None self.participants = [] self.hour = "" self.minutes = "" self.ampm = "" def set_id(self, id): """Set id. Args: id(long): Event id. """ self.id = id def get_id(self): """Get id. Returns: long: Event id. """ return self.id def set_title(self, title): """Set title. Args: title(str): Title. """ self.title = title def get_title(self): """Get title. Returns: str: Title. """ return self.title def set_location(self, location): """Set location. Args: location(str): Location. """ self.location = location def get_location(self): """Get location. Returns: str: Location. """ return self.location def set_scheduled_on(self, scheduled_on): """Set scheduled on. Args: scheduled_on(str): Scheduled on. """ self.scheduled_on = scheduled_on def get_scheduled_on(self): """Get scheduled on. Returns: str: Scheduled on. """ return self.scheduled_on def set_scheduled_on_long(self, scheduled_on_long): """Set scheduled on long. Args: scheduled_on_long(long): Scheduled on long. """ self.scheduled_on_long = scheduled_on_long def get_scheduled_on_long(self): """Get scheduled on long. Returns: long: Scheduled on long. """ return self.scheduled_on_long def set_reminder(self, reminder): """Set reminder. Args: reminder(str): Reminder. """ self.reminder = reminder def get_reminder(self): """Get reminder. Returns: str: Reminder. """ return self.reminder def set_repeat(self, repeat): """Set repeat. Args: repeat(str): Repeat. """ self.repeat = repeat def get_repeat(self): """Get repeat. Returns: str: Repeat. """ return self.repeat def set_occurrences(self, occurrences): """Set occurrences. Args: occurrences(int): Occurrences. """ self.occurrences = occurrences def get_occurrences(self): """Get occurrences. Returns: int: Occurrences. """ return self.occurrences def set_occurred(self, occurred): """Set occurred. Args: occurred(int): Occurred. """ self.occurred = occurred def get_occurred(self): """Get occurred. Returns: int: Occurred. """ return self.occurred def set_duration_hour(self, duration_hour): """Set duration hour. Args: duration_hour(str): Duration hour. """ self.duration_hour = duration_hour def get_duration_hour(self): """Get duration hour. Returns: str: Duration hour. """ return self.duration_hour def set_duration_minutes(self, duration_minutes): """Set duration minutes. Args: duration_minutes(str): Duration minutes. """ self.duration_minutes = duration_minutes def get_duration_minutes(self): """Get duration minutes. Returns: str: Duration minutes. """ return self.duration_minutes def set_is_open(self, is_open): """Set whether the event is open or not. Args: is_open(bool): True if open else False. """ self.is_open = is_open def get_is_open(self): """Get whether the event is open or not. Returns: bool: True if open else false. """ return self.is_open def set_participants(self, participant): """Set participant. Args: participant(instance): Participant object. """ self.participants.append(participant) def get_participants(self): """Get participants. Returns: list of instance: List of participant object. """ return self.participants def set_hour(self, hour): """Set hour. Args: hour(str): Hour. """ self.hour = hour def get_hour(self): """Get hour. Returns: str: Hour. """ return self.hour def set_minutes(self, minutes): """Set minutes. Args: minutes(str): Minutes. """ self.minutes = minutes def get_minutes(self): """Get minutes. Returns: str: Minutes. """ return self.minutes def set_ampm(self, ampm): """Set am or pm. Args: ampm(str): Am or pm . """ self.ampm = ampm def get_ampm(self): """Get am or pm. Returns: str: Am or pm. """ return self.ampm
{ "repo_name": "zoho/projects-python-wrappers", "path": "projects/model/Event.py", "copies": "1", "size": "5751", "license": "mit", "hash": 6057440014975055000, "line_mean": 17.3738019169, "line_max": 57, "alpha_frac": 0.4884367936, "autogenerated": false, "ratio": 4.340377358490566, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.006985063215095164, "num_lines": 313 }
#$Id$ class ExchangeRate: """This class is used to create object for Exchange rate.""" def __init__(self): """Initialize parameters for exchange rate.""" self.exchange_rate_id = '' self.currency_id = '' self.currency_code = '' self.effective_date = '' self.rate = 0.0 def set_exchange_rate_id(self, exchange_rate_id): """Set exchange rate id. Args: exchange_rate_id(str): Exchange rate id. """ self.exchange_rate_id = exchange_rate_id def get_exchange_rate_id(self): """Get exchange rate id. Returns: str: Exchange rate id. """ return self.exchange_rate_id def set_currency_id(self, currency_id): """Set currency id. Args: currency_id(str): Currency id. """ self.currency_id = currency_id def get_currency_id(self): """Get currency id. Returns: str: Currency id. """ return self.currency_id def set_currency_code(self, currency_code): """Set currency code. Args: currency_code(str): Currency code. """ self.currency_code = currency_code def get_currency_code(self): """Get currency code. Returns: str: Currency code. """ return self.currency_code def set_effective_date(self, effective_date): """Set effective date. Args: effective_date(str): Effective date. """ self.effective_date = effective_date def get_effective_date(self): """Get effective date. Returns: str: Effective date. """ return self.effective_date def set_rate(self, rate): """Set rate. Args: rate(float): Rate. """ self.rate = rate def get_rate(self): """Get rate. Returns: float: Rate. """ return self.rate def to_json(self): """This method is used to create json object for exchange rate. Returns: dict: Dictionary containing json object for exchange rate. """ data = {} if self.currency_id != '': data['currency_id'] = self.currency_id if self.currency_code != '': data['currency_code'] = self.currency_code if self.effective_date != '': data['effective_date'] = self.effective_date if self.rate > 0: data['rate'] = self.rate if self.effective_date != '': data['effective_date'] = self.effective_date return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/ExchangeRate.py", "copies": "1", "size": "2720", "license": "mit", "hash": 1838665718556411000, "line_mean": 21.479338843, "line_max": 71, "alpha_frac": 0.5202205882, "autogenerated": false, "ratio": 4.256651017214398, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.018939393939393936, "num_lines": 121 }
#$Id$ class Expense: """This class is used to create objecct for expenses.""" def __init__(self): """Initialize parameters for Expenses object.""" self.account_id = '' self.paid_through_account_id = '' self.date = '' self.amount = 0.0 self.tax_id = '' self.is_inclusive_tax = None self.is_billable = None self.customer_id = '' self.vendor_id = '' self.currency_id = '' self.exchange_rate = 0.0 self.project_id = '' self.expense_id = '' self.expense_item_id = '' self.account_name = '' self.paid_through_account_name = '' self.vendor_name = '' self.tax_name = '' self.tax_percentage = 0.0 self.currency_code = '' self.tax_amount = 0.0 self.sub_total = 0.0 self.total = 0.0 self.bcy_total = 0.0 self.reference_number = '' self.description = '' self.customer_name = '' self.expense_receipt_name = '' self.created_time = '' self.last_modified_time = '' self.status = '' self.invoice_id = '' self.invoice_number = '' self.project_name = '' self.recurring_expense_id = '' def set_account_id(self, account_id): """Set account id. Args: account_id(str): Account id. """ self.account_id = account_id def get_account_id(self): """Get account id. Returns: str: Account id. """ return self.account_id def set_paid_through_account_id(self, paid_through_account_id): """Set paid through account id. Args: paid_through_account_id(str): Paid through account id. """ self.paid_through_account_id = paid_through_account_id def get_paid_through_account_id(self): """Get paid through account id. Returns: str: Paid through account id. """ return self.paid_through_account_id def set_date(self, date): """Set date. Args: date(str): Date. """ self.date = date def get_date(self): """Get date. Returns: str: Date. """ return self.date def set_amount(self, amount): """Set amount. Args: amount(float): Amount. """ self.amount = amount def get_amount(self): """Get amount. Returns: float: Amount. """ return self.amount def set_tax_id(self, tax_id): """Set tax id. Args: tax_id(str): Tax id. """ self.tax_id = tax_id def get_tax_id(self): """Get tax id. Returns: str: Tax id. """ return self.tax_id def set_is_inclusive_tax(self, is_inclusive_tax): """Set whether tax is inclusive. Args: is_inclusive_tax(bool): True if tax is inclusive else False. """ self.is_inclusive_tax = is_inclusive_tax def get_is_inclusive_tax(self): """Get whether tax is inclusive. Returns: bool: True if tax is inclusive else False. """ return self.is_inclusive_tax def set_is_billable(self, is_billable): """Set whether expenses are billable. Args: is_billable(bool): True if billable else False. """ self.is_billable = is_billable def get_is_billable(self): """Get whether expenses are billable. Returns: bool: True if billable else False. """ return self.is_billable def set_customer_id(self, customer_id): """Set customer id. Args: customer_id(str): Customer id. """ self.customer_id = customer_id def get_customer_id(self): """Get customer id. Returns: str: Customer id. """ return self.customer_id def set_vendor_id(self, vendor_id): """Set vendor id. Args: vendor_id(str): Vendor id. """ self.vendor_id = vendor_id def get_vendor_id(self): """Get vendor id. Returns: str: Vendor id. """ return self.vendor_id def set_currency_id(self, currency_id): """Set currency id. Args: currency_id(str): Currency id. """ self.currency_id = currency_id def get_currency_id(self): """Get currency idd. Returns: str: Currency id. """ return self.currency_id def set_exchange_rate(self, exchange_rate): """Set exchange rate. Args: exchange_rate(float): Exchange rate. """ self.exchange_rate = exchange_rate def get_exchange_rate(self): """Get exchange rate. Returns: float: Exchangge rate. """ return self.exchange_rate def set_project_id(self, project_id): """Set project id. Args: project_id(str): Project id. """ self.project_id = project_id def get_project_id(self): """Get project id. Returns: str: Project id. """ return self.project_id def set_expense_id(self, expense_id): """Set expense id. Args: expense_id(str): Expense id. """ self.expense_id = expense_id def get_expense_id(self): """Get expense id. Returns: str: Expense id. """ return self.expense_id def set_expense_item_id(self, expense_item_id): """Set expense item id. Args: expense_item_id(str): Expense item id. """ self.expense_item_id = expense_item_id def get_expense_item_id(self): """Get expense item id. Returns: str: Expense item id. """ return self.expense_item_id def set_account_name(self, account_name): """Set account name. Args: account_name(str): Account name. """ self.account_name = account_name def get_account_name(self): """Get account name. Returns: str: Account name. """ return self.account_name def set_paid_through_account_name(self, paid_through_account_name): """Set paid through account name. Args: paid_through_account_name(str): Paid through account name. """ self.paid_through_account_name = paid_through_account_name def get_paid_through_account_name(self): """Get paid through account name. Returns: str: Paid through account name. """ return self.paidf_through_account_name def set_vendor_name(self, vendor_name): """Set vendor name. Args: vendor_name(str): Vendor name. """ self.vendor_name = vendor_name def get_vendor_name(self): """Get vendor name. Returns: str: Vendor name. """ return self.vendor_name def set_tax_name(self, tax_name): """Set tax name. Args: tax_name(str): Tax name. """ self.tax_name = tax_name def get_tax_name(self): """Get tax name. Returns: str: Tax name. """ return self.tax_name def set_tax_percentage(self, tax_percentage): """Set tax percentage. Args: tax_percentage(float): Tax percentage. """ self.tax_percentage = tax_percentage def get_tax_percentage(self): """Get tax percentage. Returns: float: Tax percentage. """ return self.tax_percentage def set_currency_code(self, currency_code): """Set currency code. Args: currency_code(str): Currency code. """ self.currency_code = currency_code def get_currency_code(self): """Get currency code. Returns: str: Currency code. """ return self.currency_code def set_tax_amount(self, tax_amount): """Set tax amount. Args: tax_amount(float): Tax amount. """ self.tax_amount = tax_amount def get_tax_amount(self): """Get tax amount. Returns: float: Tax amount. """ return self.tax_amount def set_sub_total(self, sub_total): """Set sub total. Args: sub_total(float): Sub total. """ self.sub_total = sub_total def get_sub_total(self): """Get sub total. Returns: float: Sub total. """ return self.sub_total def set_total(self, total): """Set total. Args: total(float): Total. """ self.total = total def get_total(self): """Get total. Returns: float: Total. """ return self.total def set_bcy_total(self, bcy_total): """Set bcy total. Args: bcy_total(float): Bcy total. """ self.bcy_total = bcy_total def get_bcy_total(self): """Get bcy total. Returns: float: Bcy total. """ return self.bcy_total def set_reference_number(self, reference_number): """Set reference number. Args: reference_number(str): Reference number. """ self.reference_number = reference_number def get_reference_number(self): """Get reference_number. Returns: str: Reference number. """ return self.reference_number def set_description(self, description): """Set description. Args: description(str): Description """ self.description = description def get_description(self): """Get description. Returns: str: Description. """ return self.description def set_customer_name(self, customer_name): """Set customer name. Args: customer_name(str): Customer name. """ self.customer_name = customer_name def get_customer_name(self): """Get customer name. Returns: str: Customer name. """ return self.customer_name def set_expense_receipt_name(self, expense_receipt_name): """Set expense receipt name. Args: expense_receipt_name(str): Expense receipt name. """ self.expense_receipt_name = expense_receipt_name def get_expense_receipt_name(self): """Get expense receipt name. Returns: str: Expense receipt name. """ return self.expense_receipt_name def set_created_time(self, created_time): """Set created time. Args: created_time(str): Created time. """ self.created_time = created_time def get_created_time(self): """Get created time. Returns: str: Created time. """ return self.created_time def set_last_modified_time(self, last_modified_time): """Set last modified time. Args: last_modified_time(str): Last modified time. """ self.last_modified_time = last_modified_time def get_last_modified_time(self): """Get last modified time. Returns: str: Last modified time. """ return self.last_modified_time def set_status(self, status): """Set status. Args: status(str): Status. """ self.status = status def get_status(self): """Get status. Returns: str: Status. """ return status def set_invoice_id(self, invoice_id): """Set invoice id. Args: invoice_id(str): Invoice id. """ self.invoice_id = invoice_id def get_invoice_id(self): """Get invoice id. Returns: str: Invoice id. """ def set_invoice_number(self, invoice_number): """Set invoice number. Args: invoice_number(str): Invoice number. """ self.invoice_number = invoice_number def get_invoice_number(self): """Get invoice number. Returns: str: Invoice number. """ return self.invoice_number def set_project_name(self, project_name): """Set project name. Args: project_name(str): Project name. """ self.project_name = project_name def get_project_name(self): """Get project name. Returns: str: Project name. """ return self.project_name def set_recurring_expense_id(self, recurring_expense_id): """Set recurring expense id. Args: recurring_expense_id(str): Recurring expense id. """ self.recurring_expense_id = recurring_expense_id def get_recurring_expense_id(self): """Get recurring expense id. Returns: str: Recurring expense id. """ return self.recurring_expense_id def to_json(self): """This method is used to convert expense object to json object. Returns: dict: Dictionary containing json object for expenses. """ data = {} if self.account_id != '': data['account_id'] = self.account_id if self.paid_through_account_id != '': data['paid_through_account_id'] = self.paid_through_account_id if self.date != '': data['date'] = self.date if self.amount > 0: data['amount'] = self.amount if self.tax_id != '': data['tax_id'] = self.tax_id if self.is_inclusive_tax is not None: data['is_inclusive_tax'] = self.is_inclusive_tax if self.reference_number != '': data['reference_number'] = self.reference_number if self.description != '': data['description'] = self.description if self.is_billable is not None: data['is_billable'] = self.is_billable if self.customer_id != '': data['customer_id'] = self.customer_id if self.vendor_id != '': data['vendor_id'] = self.vendor_id if self.currency_id != '': data['currency_id'] = self.currency_id if self.exchange_rate > 0: data['exchange_rate'] = self.exchange_rate if self.recurring_expense_id != '': data['recurring_expense_id'] = self.recurring_expense_id if self.project_id != '': data['project_id'] = self.project_id return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Expense.py", "copies": "1", "size": "15182", "license": "mit", "hash": -695551894355073500, "line_mean": 20.2633053221, "line_max": 74, "alpha_frac": 0.5153471216, "autogenerated": false, "ratio": 4.146954384048074, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5162301505648075, "avg_score": null, "num_lines": null }
#$Id$ class Folder: """This class is used to create object for Folder.""" def __init__(self): """Initialize parameters for folder object.""" self.id = 0 self.name = "" self.is_discussion = None self.url = "" def set_id(self, id): """Set id. Args: id(str): Folder id. """ self.id = id def get_id(self): """Get id. Returns: str: Id. """ return self.id def set_name(self, name): """Set name. Args: name(str): Name. """ self.name = name def get_name(self): """Get name. Returns: str: Name. """ return self.name def set_is_discussion(self, is_discussion): """Set whether discussion or not. Args: is_discussion(bool): True if discussion else false. """ self.is_discussion = is_discussion def get_is_discussion(self): """Get whether discussion or not. Returns: bool: True if discussion else false. """ return self.is_discussion def set_url(self, url): """Set url. Args: url(str): Url. """ self.url = url def get_url(self): """Get url. Returns: str: Url. """ return self.url
{ "repo_name": "zoho/projects-python-wrappers", "path": "projects/model/Folder.py", "copies": "1", "size": "1440", "license": "mit", "hash": 4199912420831940600, "line_mean": 15.5517241379, "line_max": 63, "alpha_frac": 0.4527777778, "autogenerated": false, "ratio": 4.260355029585799, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.007316719791364821, "num_lines": 87 }
#$Id$ class Forum: """This class is used to create object for forum.""" def __init__(self): """Initialize parameters for forum object.""" self.id = 0 self.name = "" self.content = "" self.is_sticky_post = None self.is_announcement_post = None self.posted_by = "" self.posted_person = "" self.posted_date = "" self.posted_date_long = 0 self.url = "" self.category_id = 0 self.upload_file = [] self.notify = "" def set_id(self, id): """Set id. Args: id(long): Forum id. """ self.id = id def get_id(self): """Get id. Returns: long: Forum id. """ return self.id def set_name(self, name): """Set name. Args: name(str): Name. """ self.name = name def get_name(self): """Get name. Returns: str: Name. """ return self.name def set_content(self, content): """Set content. Args: content(str): Content. """ self.content = content def get_content(self): """Get content. Returns: str: Content. """ return self.content def set_is_sticky_post(self, is_sticky_post): """Set whether it is sticky post or not. Args: is_sticky_post(bool): True if it is sticky post else False. """ self.is_sticky_post = is_sticky_post def get_sticky_post(self): """Get whether it is sticky post or not. Returns: bool: True if it is sticky post else false. """ return self.is_sticky_post def set_is_announcement_post(self, is_announcement_post): """Set whether it is announcement post or not. Args: is_announcement_post(bool): True if announcement post else false. """ self.is_announcement_post = is_announcement_post def get_is_announcement_post(self): """Get announcement post. Returns: bool: True if announcement post else false. """ return self.is_announcement_post def set_posted_by(self, posted_by): """Set posted by. Args: posted_by(str): Posted by. """ self.posted_by = posted_by def get_posted_by(self): """Get posted by. Returns: str: Posted by. """ return self.posted_by def set_posted_person(self, posted_person): """Set posted person. Args: posted_person(str): Posted person. """ self.posted_person = posted_person def get_posted_person(self): """Get posted person. Returns: str: Posted person. """ return self.posted_person def set_post_date(self, post_date): """Set post date. Args: post_date(str): Post date. """ self.post_date = post_date def get_post_date(self): """Get post date. Returns: str: Post date. """ return self.post_date def set_post_date_long(self, post_date_long): """Set post date long. Args: post_date_long(long): Post date long. """ self.post_date_long = post_date_long def get_post_date_long(self): """Get post date long. Returns: long: Post date long. """ return self.post_date_long def set_url(self, url): """Set url. Args: url(str): Self url. """ self.url = url def get_url(self): """Get url. Returns: str: Self url. """ return self.url def set_category_id(self, category_id): """Set category id. Args: category_id(long): Category id. """ self.category_id = category_id def get_category_id(self): """Get category id. Returns: long: Category id. """ return self.category_id def set_upload_file(self, upload_file): """Set upload file. Args: upload_file(list): List of files to be uploaded. """ self.upload_file = upload_file def get_upload_file(self): """Get upload file. Returns: list of file: List of files to be uploaded. """ return self.upload_file def set_notify(self, notify): """Set notify. Args: notify(str):Notify. """ self.notify = notify def get_notify(self): """Get notify. Returns: str: Notify. """ return self.notify
{ "repo_name": "zoho/projects-python-wrappers", "path": "projects/model/Forum.py", "copies": "1", "size": "4916", "license": "mit", "hash": -3715918896199240000, "line_mean": 17.9076923077, "line_max": 77, "alpha_frac": 0.4894222945, "autogenerated": false, "ratio": 4.124161073825503, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5113583368325503, "avg_score": null, "num_lines": null }
#$Id$ class FromEmail: """This class is used to create object for FromEmails.""" def __init__(self): """Initialize parameters for FromEmails.""" self.user_name = '' self.selected = None self.email = '' self.is_org_email_id = None def set_user_name(self, user_name): """Set the user name. Args: user_name(str): User name. """ self.user_name = user_name def get_user_name(self): """Get the user name. Returns: str: User name. """ return self.user_name def set_selected(self, selected): """Set selected. Args: selected(bool): True if selected else False. """ self.selected = selected def get_selected(self): """Get selected. Returns: bool: True if selected else False. """ return self.selected def set_email(self, email): """Set email address. Args: email(str): Email address. """ self.email = email def get_email(self): """Get email address. Returns: str: Email address. """ return self.email def set_is_org_email_id(self, is_org_email_id): """Set whether it is organization's email id or not. Args: is_org_email_id(bool): True if it is organization's mail id else False. """ self.is_org_email_id = is_org_email_id def get_is_org_email_id(self): """Get whether it is organization's mail id or not. Returns: bool: True if it is organization's mail id else False. """ return self.is_org_email_id
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/FromEmail.py", "copies": "1", "size": "1850", "license": "mit", "hash": 2620019852506380300, "line_mean": 21.5609756098, "line_max": 69, "alpha_frac": 0.4956756757, "autogenerated": false, "ratio": 4.195011337868481, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.519068701356848, "avg_score": null, "num_lines": null }
#$Id$ class Instrumentation: """This class is used tocreate object for instrumentation.""" def __init__(self): """Initialize parameters for Instrumentation object.""" self.query_execution_time = '' self.request_handling_time = '' self.response_write_time = '' self.page_context_write_time = '' def set_query_execution_time(self, query_execution_time): """Set query execution time. Args: query_execution_time(str): Query execution time. """ self.query_execution_time = query_execution_time def get_query_execution_time(self): """Get query execution time. Returns: str: Query execution time. """ return self.query_execution_time def set_request_handling_time(self, request_handling_time): """Set request handling time. Args: request_handling_time(str): Request handling time. """ self.request_handling_time = request_handling_time def get_request_handling_time(self): """Get request handling time. Returns: str: Request handling time. """ return self.request_handling_time def set_response_write_time(self, response_write_time): """Set response write time. Args: response_write_time(str): Response write time. """ self.response_write_time = response_write_time def get_response_write_time(self): """Get response write time. Returns: str: Response write time. """ return self.response_write_time def set_page_context_write_time(self, page_context_write_time): """Set page context write time. Args: page_context_write_time(str): Page context write time. """ self.page_context_write_time = page_context_write_time def get_page_context_write_time(self): """Get page context write time. Returns: str: Page context write time. """ return self.page_context_write_time
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Instrumentation.py", "copies": "1", "size": "2136", "license": "mit", "hash": 8238827201165372000, "line_mean": 24.734939759, "line_max": 67, "alpha_frac": 0.5880149813, "autogenerated": false, "ratio": 4.368098159509202, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.029383668540295046, "num_lines": 83 }
#$Id$ class InvoiceCredited: """This class is used to create objecctfor Invoices Credited.""" def __init__(self): """Initialize parameters for Invoices credited.""" self.creditnote_id = '' self.invoice_id = '' self.creditnotes_invoice_id = '' self.date = '' self.invoice_number = '' self.creditnotes_number = '' self.credited_amount = 0.0 self.credited_date = '' self.amount_applied = 0.0 def set_creditnote_id(self, creditnote_id): """Set credit note id. Args: creditnote_id(str): Credit note id. """ self.creditnote_id = creditnote_id def get_creditnote_id(self): """Get credit note id. Returns: str: Credit note id. """ return self.creditnote_id def set_invoice_id(self, invoice_id): """Set invoice id. Args: invoice_id(str): Invoice id. """ self.invoice_id = invoice_id def get_invoice_id(self): """Get invoice id. Returns: str: Invoice id. """ return self.invoice_id def set_creditnotes_invoice_id(self, creditnotes_invoice_id): """Set credit note invoice id. Args: creditnotes_invoice_id(str): Credditnote invoice id. """ self.creditnotes_invoice_id = creditnotes_invoice_id def get_creditnotes_invoice_id(self): """Get creditnotes invoice id. Returns: str: Creditnotes invoice id. """ return self.creditnotes_invoice_id def set_date(self, date): """Set date. Args: date(str): Date. """ self.date = date def get_date(self): """Get date. Returns: str: Date. """ return self.date def set_invoice_number(self, invoice_number): """Set invoice number. Args: invoice_number(str): Invoice number. """ self.invoice_number = invoice_number def get_invoice_number(self): """Get invoice number. Returns: str: Invoice number. """ return self.invoice_number def set_creditnotes_number(self, creditnotes_number): """Set creditnote number. Args: creditnote_number(str): Creditnote number. """ self.creditnotes_number = creditnotes_number def get_creditnotes_number(self): """Get creditnote number. Returns: str: Creditnote number. """ return self.creditnotes_number def set_credited_amount(self, credited_amount): """Set credited amount. Args: credited_amount(float): Credited amount. """ self.credited_amount = credited_amount def get_credited_amount(self): """Get credited amount. Returns: float: Credited amount. """ return self.credited_amount def set_credited_date(self, credited_date): """Set credited date. Args: credited_date(str): Credited date. """ self.credited_date = credited_date def get_credited_date(self): """Get credited date. Returns: str: Credited date. """ return self.credited_date def set_amount_applied(self, amount_applied): """Set amount applied. Args: amount_applied(float): Amount applied. """ self.amount_applied = amount_applied def get_amount_applied(self): """Get amount applied. Returns: float: Amount applied. """ return self.amount_applied
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/InvoiceCredited.py", "copies": "1", "size": "3801", "license": "mit", "hash": -6333936865016023000, "line_mean": 20.2346368715, "line_max": 68, "alpha_frac": 0.5377532228, "autogenerated": false, "ratio": 4.109189189189189, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5146942411989189, "avg_score": null, "num_lines": null }
#$Id$ class Invoice: """This class is used to create object for invoice.""" def __init__(self): """Initialize parameters for Invoice object.""" self.invoice_id = '' self.invoice_number = '' self.date = '' self.status = '' self.payment_terms = 0 self.payment_terms_label = '' self.due_date = '' self.payment_expected_date = '' self.last_payment_date = '' self.reference_number = '' self.customer_id = '' self.customer_name = '' self.contact_persons = [] self.currency_id = '' self.currency_code = '' self.exchange_rate = 0.00 self.discount = '' self.is_discount_before_tax = None self.discount_type = '' self.recurring_invoice_id = '' self.line_items = [] self.shipping_charge = 0.00 self.adjustment = 0.0 self.adjustment_description = '' self.sub_total = 0.0 self.tax_total = 0.0 self.total = 0.0 self.taxes = [] self.payment_reminder_enabled = None self.payment_made = 0.0 self.credits_applied = 0.0 self.tax_amount_withheld = 0.0 self.balance = 0.0 self.write_off_amount = 0.0 self.allow_partial_payments = None self.price_precision = 2 self.payment_options = { 'payment_gateways': [] } self.is_emailed = False self.reminders_sent = 0 self.last_reminder_sent_date = '' self.billing_address = '' self.shipping_address = '' self.notes = '' self.terms = '' self.custom_fields = [] self.template_id = '' self.template_name = '' self.created_time = '' self.last_modified_time = '' self.attachment_name = '' self.can_send_in_mail = None self.salesperson_id = '' self.salesperson_name = '' self.invoice_url = '' self.invoice_payment_id = '' self.due_days = '' self.custom_body = '' self.custom_subject = '' self.invoiced_estimate_id = '' self.amount_applied = '' self.name = '' self.value = '' def set_name(self, name): """Set name. Args: name(str): Name. """ self.name = name def get_name(self): """Get name. Returns: str: Name. """ return self.name def set_value(self,value): """Set value. Args: value(str): Value. """ self.value = value def get_value(self): """Get value. Returns: str: Value. """ return self.value def set_invoice_id(self, invoice_id): """Set invoice id. Args: invoice_id(str): Invoice id. """ self.invoice_id = invoice_id def get_invoice_id(self): """Get invoice id. Returns: str: Invoice id. """ return self.invoice_id def set_invoice_number(self, invoice_number): """Set invoice number. Args: invoice_numeber(str): Invoice number. """ self.invoice_number = invoice_number def get_invoice_number(self): """Get invoice number. Returns: str: Invoice number. """ return self.invoice_number def set_date(self, date): """Set date at which the invoice is created. Args: date(str): Date at which invoice is created. """ self.date = date def get_date(self): """Get date at which invoice is created. Returns: str: Date at which invoice is created. """ return self.date def set_status(self, status): """Set status. Args: status(str): Status. """ self.status = status def get_status(self): """Get status. Returns: str: Status. """ return self.status def set_payment_terms(self, payment_terms): """Set payment terms in days.Invoice due date will be calculated based on this. Args: payment_terms(int): Payment terms in days.Eg 15, 30, 60. """ self.payment_terms = payment_terms def get_payment_terms(self): """Get payment terms. Returns: int: Payment terms in days. """ return self.payment_terms def set_payment_terms_label(self, payment_terms_label): """Set Payments terms label. Args: payment_terms_label(str): Payment terms label. Default value for 15 days is "Net 15". """ self.payment_terms_label = payment_terms_label def get_payment_terms_label(self): """Get payment terms label. Returns: str: PAyment terms label. """ return self.payment_terms_label def set_due_date(self, due_date): """Set due date for invoice. Args: due_date(str): Due date for invoice. Format is yyyy-mm-dd. """ self.due_date = due_date def get_due_date(self): """Get due date of invoice. Returns: str: Due date dor invoice. """ return self.due_date def set_payment_expected_date(self, payment_expected_date): """Set payment expected date. Args: payment_expected_date(str): Payment expected date. """ self.payment_expected_date = payment_expected_date def get_payment_expected_date(self): """Get payment expected date. Returns: str: Payment expected date. """ return self.payment_expected_date def set_last_payment_date(self, last_payment_date): """Set last payment date. Args: last_payment_date(str): last_payment_date """ self.last_payment_date = last_payment_date def get_last_payment_date(self): """Get last payment date. Returns: str: last payment date. """ return self.last_payment_date def set_reference_number(self, reference_number): """Set reference number for the customer payment. Args: reference_number(str): Reference number. """ self.reference_number = reference_number def get_reference_number(self): """Get reference number for the customer payment. Returns: str: Reference number. """ return self.reference_number def set_customer_id(self, customer_id): """Set customer id. Args: customer_id(str): Customer id. """ self.customer_id = customer_id def get_customer_id(self): """Get customer id. Returns: str: Customer id. """ return self.customer_id def set_customer_name(self, customer_name): """Set customer name. Args: customer_name(str): Customer name. """ self.customer_name = customer_name def get_customer_name(self): """Get customer name. Returns: str: Customer name. """ return self.customer_name def set_contact_persons(self, contact_person): """Set the list of ID of contact persons for which thank you mail has to be sent. Args: contact_peson(list): Id of contact persons for which thank you mail has to be sent. """ self.contact_persons.extend(contact_person) def get_contact_persons(self): """Get the Id of contact persons for which thank you mail has to be sent. Returns: list: List of ID of contact persons. """ return self.contact_persons def set_currency_id(self, currency_id): """Set currency id. Args: currency_id(str): Currency id. """ self.currency_id = currency_id def get_currency_id(self): """Get currency id. Returns: str: Currency id. """ return self.currency_id def set_currency_code(self, currency_code): """Set currency code. Args: currency_code(str): Currency code. """ self.currency_code = currency_code def get_currency_code(self): """Get currency code. Returns: str: Currency code. """ return self.currency_code def set_exchange_rate(self, exchange_rate): """Set exchange rate for the currency. Args: exchange_rate(int): Exchange rate. """ self.exchange_rate = exchange_rate def get_exchange_rate(self): """Get exchange rate of the currency. Returns: int: Exchange rate. """ return self.exchange_rate def set_discount(self, discount): """Set discount applied to the invoice. Args: discount(str): Discount. It can be either in % or in amount. """ self.discount = discount def get_discount(self): """Get discount applied to the invoice. Returns: str: Discount. """ return self.discount def set_is_discount_before_tax(self, is_discount_before_tax): """Set whether to discount before tax or after tax. Args: is_discount_before_tax(bool): True to discount before tax else False to discount after tax. """ self.is_discount_before_tax = is_discount_before_tax def get_is_discount_before_tax(self): """Get whether to discount before tax or after tax. Returns: bool: True to discount before tax else False to discount after tax. """ return self.is_discount_before_tax def set_discount_type(self, discount_type): """Set how the discount should be specified. Args: discount_type: Discount type. Allowed values are entity_level or item_level """ self.discount_type = discount_type def get_discount_type(self): """Get discount type. Returns: str: Discount type. """ return self.discount_type def set_recurring_invoice_id(self, recurring_invoice_id): """Set id of the recurring invoice from which the invoice is created. Args: recurring_invoice_id(str): Recurring invoice id. """ self.recurring_invoice_id = recurring_invoice_id def get_recurring_invoice_id(self): """Get id of the recurring invoice from which the invoice is created. Returns: str: Recurring invoice id. """ return self.recurring_invoice_id def set_line_items(self, line_item): """Set line items for an invoice. Args: instance: Line item object. """ self.line_items.append(line_item) def get_line_items(self): """Get line items of an invoice. Returns: list: List of line items object """ return self.line_items def set_shipping_charge(self, shipping_charge): """Set shipping charge for the invoice. Args: shipping_charge(float): Shipping charge. """ self.shipping_charge = shipping_charge def get_shipping_charge(self): """Get shipping charge for the invoice. Returns: float: Shipping charge. """ return self.shipping_charge def set_adjustment(self, adjustment): """Set adjustments made to the invoice. Args: adjustment(float): Adjustments made. """ self.adjustment = adjustment def get_adjustment(self): """Get adjustments made to the invoice. Returns: float: Adjustments made. """ return self.adjustment def set_adjustment_description(self, adjustment_description): """Set to customize adjustment description. Args: adjustment_description(str): Adjustment description. """ self.adjustment_description = adjustment_description def get_adjustment_description(self): """Get adjustment description. Returns: str: Adjustment description. """ return self.adjustment_description def set_sub_total(self, sub_total): """Set sub total. Args: sub_total(float): Sub total. """ self.sub_total = sub_total def get_sub_total(self): """Get sub total. Returns: float: Sub total. """ return self.sub_total def set_tax_total(self, tax_total): """Set tax total. Args: tax_total(float): Tax total. """ self.tax_total = tax_total def get_tax_total(self): """Get tax total. Returns: float: Tax total. """ return self.tax_total def set_total(self, total): """Set total. Args: total(float): Total amount. """ self.total = total def get_total(self): """Get total. Returns: float: Total amount. """ return self.total def set_taxes(self, taxes): """Set taxes. Args: taxes(instance): Taxes. """ self.taxes.append(tax) def get_taxes(self): """Get taxes. Returns: list: List of tax objects. """ return self.taxes def set_payment_reminder_enabled(self, payment_reminder_enabled): """Set whether to enable payment reminder or not. Args: payment_reminder_enabled(bool): True to enable payment reminder else False. """ self.payment_reminder_enabled = payment_reminder_enabled def get_payment_reminder_enabled(self): """Get whether payment reminder is enabled or not. Returns: bool: True if payment reminder is enabled else False. """ return self.payment_reminder_enabled def set_payment_made(self, payment_made): """Set payment made. Args: payment_made(float): Payments made. """ self.payment_made = payment_made def get_payment_made(self): """Get payments made. Returns: float: Payments made. """ return self.payment_made def set_credits_applied(self, credits_applied): """Set credits applied. Args: credits_applied(float): Credits applied. """ self.credits_applied = credits_applied def get_credits_applied(self): """Get credits applied. Returns: float: Credits applied. """ return self.credits_applied def set_tax_amount_withheld(self, tax_amount_withheld): """Set tax amount withheld. Args: tax_amount_withheld(float): Tax amount withheld. """ self.tax_amount_withheld = tax_amount_withheld def get_tax_amount_withheld(self): """Get tax amount withheld. Returns: float: Tax amount withheld. """ return self.tax_amount_withheld def set_balance(self, balance): """Set balance. Args: balance(float): Balance. """ self.balance = balance def get_balance(self): """Get balance. Returns: float: Balance. """ return self.balance def set_write_off_amount(self, write_off_amount): """Set write off amount. Args: write_off_amount(float): Write off amount. """ self.write_off_amount = write_off_amount def get_write_off_amount(self): """Get write off amount. Returns: float: Write off amount. """ return self.write_off_amount def set_allow_partial_payments(self, allow_partial_payments): """Set whether to allow partial payments or not. Args: allow_partial_payments(bool): True to allow partial payments else False. """ self.allow_partial_payments = allow_partial_payments def get_allow_partial_payments(self): """Get whether to allow partial payments. Returns: bool: True if partial payments are allowed else False. """ return self.allow_partial_payments def set_price_precision(self, price_precision): """Set price precision. Args: price_precision(int): Price precision. """ self.price_precision = price_precision def get_price_precision(self): """Get price precision. Returns: int: Price precision. """ return self.price_precision def set_payment_options(self, payment_gateways): """Set payment options. Args: payment_gateways(instance): Online payment gateways through which payment can be made. """ self.payment_options['payment_gateways'].append(payment_gateways) def get_payment_options(self): """Get payment options. Returns: dict: Payment options for the invoice. """ return self.payment_options def set_is_emailed(self, is_emailed): """Set whether to email or not. Args: is_emailed(bool): True to email else False. """ self.is_emailed = is_emailed def get_is_emailed(self): """Get whether to email. Returns: bool: True to email else False. """ return self.is_emailed def set_reminders_sent(self, reminders_sent): """Set reminders sent. Args: reminders_sent(int): Reminders sent. """ self.reminders_sent = reminders_sent def get_reminders_sent(self): """Get reminders sent. Returns: int: Reminders sent. """ return self.reminders_sent def set_last_reminder_sent_date(self, last_reminder_sent_date): """Set last reminder sent date. Args: last_reminder_sent_date(str): Last reminder sent date """ self.last_reminder_sent_date = last_reminder_sent_date def get_last_reminder_sent_date(self): """Get last reminder sent date. Returns: str: Last reminder sent date. """ return self.last_reminder_sent_date def set_billing_address(self, billing_address): """Set billing address. Args: billing_address(instance): Billing address object. """ self.billing_address = billing_address def get_billing_address(self): """Get billing address. Returns: instance: Billing address object. """ return self.billing_address def set_shipping_address(self, shipping_address): """Set shipping address. Args: shipping_address(instance): Shipping address object. """ self.shipping_address = shipping_address def get_shipping_address(self): """Get shipping address. Returns: instance: Shipping address object. """ return self.shipping_address def set_notes(self, notes): """Set notes. Args: notes(str): Notes. """ self.notes = notes def get_notes(self): """Get notes. Returns: str: Notes """ return self.notes def set_terms(self, terms): """Set terms. Args: terms(str): Terms. """ self.terms = terms def get_terms(self): """Get terms. Returns: str: Terms. """ return self.terms def set_custom_fields(self, custom_field): """Set custom fields. Args: custom_field(instance): custom field object. """ self.custom_fields.append(custom_field) def get_custom_fields(self): """Get custom field. Returns: instance: custom field object. """ return self.custom_fields def set_template_id(self, template_id): """Set template id. Args: template_id(str): Template id. """ self.template_id = template_id def get_template_id(self): """Get template id. Returns: str: Template id. """ return self.template_id def set_template_name(self, template_name): """Set template name. Args: template_name(str): Template name. """ self.template_name = template_name def get_template_name(self): """Get template name. Returns: str: Template name. """ return self.template_name def set_created_time(self, created_time): """Set created time. Args: created_time(str): Created time. """ self.created_time = created_time def get_created_time(self): """Get created time. Returns: str: Created time. """ return self.created_time def set_last_modified_time(self, last_modified_time): """Set last modified time. Args: last_modified_time(str): Last modified time. """ self.last_modified_time = last_modified_time def get_last_modified_time(self): """Get last modified time. Returns: str: Last modified time. """ return self.last_modified_time def set_attachment_name(self, attachment_name): """Set attachment name. Args: attachment_name(str): Attachment name. """ self.attachment_name = attachment_name def get_attachment_name(self): """Get attachment name. Returns: str: Attachment name. """ return self.attachment_name def set_can_send_in_mail(self, can_send_in_mail): """Set whether the invoice can be sent in mail or not. Args: can_send_in_mail(bool): True if it can be sent in mail else False. """ self.can_send_in_mail = can_send_in_mail def get_can_send_in_mail(self): """Get whether the invoice can be sent in mail or not. Returns: bool: True if it can be sent in mail else False. """ return self.can_send_in_mail def set_salesperson_id(self, salesperson_id): """Set salesperson id. Args: salesperson_id(str): Salesperson id. """ self.salesperson_id = salesperson_id def get_salesperson_id(self): """Get salesperson id. Returns: str: Salesperson id. """ return self.salesperson_id def set_salesperson_name(self, salesperson_name): """Set salesperson name. Args: salesperson_name(str): Salesperson name. """ self.salesperson_name = salesperson_name def get_salesperson_name(self): """Get salesperson name. Returns: str: Salesperson name. """ return self.salesperson_name def set_invoice_url(self, invoice_url): """Set invoice url. Args: invoice_url(str): Invoice url. """ self.invoice_url = invoice_url def get_invoice_url(self): """Get invoice url. Returns: str: Invoice url. """ return self.invoice_url def set_due_days(self, due_days): """Set due days. Args: due_days(str): Due days. """ self.due_days = due_days def get_due_days(self): """Get due days. Returns: str: Due days. """ return self.due_days def set_custom_body(self, custom_body): """Set custom body. Args: custom_body(str): Custom body. """ self.custom_body = custom_body def get_custom_body(self): """Get custom body. Returns: str: Custom body. """ return self.custom_body def set_custom_subject(self, custom_subject): """Set custom subject. Args: custom_subject(str): Custom subject. """ self.custom_subjecct = custom_subject def get_custom_subject(self): """Get custom subject. Returns: str: Custom subject. """ return self.custom_subject def set_invoiced_estimate_id(self, invoiced_estimate_id): """Set invoiced estimate id. Args: invoiced_estimate_id(str): Invoiced estimate id. """ self.invoiced_estimate_id = invoiced_estimate_id def get_invoiced_estimate_id(self): """Get invoiced estimate id. Returns: str: Invoiced estimate id. """ return self.invoiced_estimate_id def set_amount_applied(self, amount_applied): """Set amount applied. Args: amount_applied(str): Amount applied. """ self.amount_applied = amount_applied def get_amount_applied(self): """Get amount applied. Returns: str: Amount applied. """ return self.amount_applied def set_invoice_payment_id(self, invoice_payment_id): """Set invoice payment id. Args: invoice_payment_id(str): Invoice payment id. """ self.invoice_payment_id = invoice_payment_id def get_invoice_payment_id(self): """Get invoice payment id. Returns: str: Invoice payment id. """ return self.invoice_payment_id def to_json(self): """This method is used to convert invoice object to json object. Returns: dict: Dictionary containing json object for invoices. """ data = {} if self.customer_id != '': data['customer_id'] = self.customer_id if self.contact_persons: data['contact_persons'] = self.contact_persons if self.reference_number != '': data['reference_number'] = self.reference_number if self.template_id != '': data['template_id'] = self.template_id if self.date != '': data['date'] = self.date if self.payment_terms > 0: data['payment_terms'] = self.payment_terms if self.payment_terms_label != '': data['payment_terms_label'] = self.payment_terms_label if self.due_date != '': data['due_date'] = self.due_date if self.discount != '': data['discount'] = self.discount if self.is_discount_before_tax is not None: data['is_discount_before_tax'] = self.is_discount_before_tax if self.discount_type != '': data['discount_type'] = self.discount_type if self.exchange_rate > 0: data['exchange_rate'] = self.exchange_rate if self.recurring_invoice_id != '': data['recurring_invoice_id'] = self.recurring_invoice_id if self.invoiced_estimate_id != '': data['invoiced_estimate_id'] = self.invoiced_estimate_id if self.salesperson_name != '': data['salesperson_name'] = self.salesperson_name if self.custom_fields: data['custom_fields'] = [] for value in self.custom_fields: custom_field = value.to_json() data['custom_fields'].append(custom_field) if self.line_items: data['line_items'] = [] for value in self.line_items: line_item = value.to_json() data['line_items'].append(line_item) if self.payment_options['payment_gateways']: data['payment_options'] = {'payment_gateways':[]} for value in self.payment_options['payment_gateways']: payment_gateway = value.to_json() data['payment_options']['payment_gateways'].append(payment_gateway) if self.allow_partial_payments != None: data['allow_partial_payments'] = self.allow_partial_payments if self.custom_body != '': data['custom_body'] = self.custom_body if self.custom_subject != '': data['custom_subject'] = self.custom_subject if self.notes != '': data['notes'] = self.notes if self.terms != '': data['terms'] = self.terms if self.shipping_charge > 0: data['shipping_charge'] = self.shipping_charge if self.adjustment > 0: data['adjustment'] = self.adjustment if self.adjustment_description != '': data['adjustment_description'] = self.adjustment_description if self.invoice_number != '': data['invoice_number'] = self.invoice_number return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Invoice.py", "copies": "1", "size": "29831", "license": "mit", "hash": -1729967105434840800, "line_mean": 22.6942017474, "line_max": 103, "alpha_frac": 0.5380979518, "autogenerated": false, "ratio": 4.300273893613954, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.03385213827049668, "num_lines": 1259 }
#$Id$ class InvoicePayment: """This class is used to create object for Invoice Payments.""" def __init__(self): """Initialize parameters for Invoice payments.""" self.invoice_payment_id = '' self.payment_id = '' self.invoice_id = '' self.amount_used = 0.0 self.amount_applied = 0.0 self.payment_number = '' self.payment_mode = '' self.description = '' self.date = '' self.reference_number = '' self.exchange_rate = 0.00 self.amount = 0.00 self.tax_amount_withheld = 0.0 self.is_single_invoice_payment = None def set_invoice_payment_id(self, invoice_payment_id): """Set invoice payment id. Args: invoice_payment_id(str): Invoice payment id. """ self.invoice_payment_id = invoice_payment_id def get_invoice_payment_id(self): """Get invoice payment id. Returns: str: Invoice payment id. """ return self.invoice_payment_id def set_invoice_id(self, invoice_id): """Set invoice id. Args: invoice_id(str): Invoice id. """ self.invoice_id = invoice_id def get_invoice_id(self): """Get invoice id. Returns: str: Invoice id. """ return self.invoice_id def set_payment_id(self, payment_id): """Set payment id. Args: payment_id(str): Payment id. """ self.payment_id = payment_id def get_payment_id(self): """Get payment id. Returns: str: Payment id. """ return self.payment_id def set_amount_applied(self, amount_applied): """Set amount applied. Args: amount_applied(float): Amount applied. """ self.amount_applied = amount_applied def get_amount_applied(self): """Get amount applied. Returns: float: Amount applied. """ return self.amount_applied def set_amount_used(self, amount_used): """Set amount used. Args: amount_used(float): Amount used. """ self.amount_used = amount_used def get_amount_used(self): """Get amount used. Returns: float: Amount used. """ return self.amount_used def set_payment_number(self, payment_number): """Set payment number. Args: payment_number(str): Payment number. """ self.payment_number = payment_number def get_payment_number(self): """Get payment number. Returns: str: Payment number. """ return self.payment_number def set_payment_mode(self, payment_mode): """Set payment mode. Args: payment_mode(str): Payment mode. """ self.payment_mode = payment_mode def get_payment_mode(self): """Get payment mode. Returns: str: Payment mode. """ return self.payment_mode def set_description(self, description): """Set description. Args: description(str): Description. """ self.description = description def get_description(self): """Get description. Returns: str: Description. """ return self.description def set_date(self, date): """Set date. Args: date(str): Date. """ self.date = date def get_date(self): """Get date. Returns: str: Date. """ return self.date def set_reference_number(self, reference_number): """Set reference number. Args: reference_number(str): Reference number. """ self.reference_number = reference_number def get_reference_number(self): """Get reference number. Returns: str: Reference number. """ return self.reference_number def set_exchange_rate(self, exchange_rate): """Set exchange rate. Args: exchange_rate(float): Exchange rate. """ self.exchange_rate = exchange_rate def get_exchange_rate(self): """Get exchange rate. Returns: float: Exchange rate. """ return self.exchange_rate def set_amount(self, amount): """Set amount. Args: amount(float): Amount. """ self.amount = amount def get_amount(self): """Get amount. Returns: float: Amount. """ return self.amount def set_tax_amount_withheld(self, tax_amount_withheld): """Set tax amount withheld. Args: tax_amount_withheld(float): Tax amount withheld. """ self.tax_amount_withheld = tax_amount_withheld def get_tax_amount_withheld(self): """Get tax amount withheld. Returns: float: Tax amount withheld. """ return self.tax_amount_withheld def set_is_single_invoice_payment(self, is_single_invoice_payment): """Set whether it is single invoice payment. Args: is_single_invoice_payment(bool): True if it is single invoice payment else False. """ self.is_single_invoice_payment = is_single_invoice_payment def get_is_single_invoice_payment(self): """Get whether it is single invoice payment. Returns: bool: True if it is single invoice payment else False. """ return self.is_single_invoice_payment
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/InvoicePayment.py", "copies": "1", "size": "5813", "license": "mit", "hash": 5634009573624588000, "line_mean": 20.2153284672, "line_max": 74, "alpha_frac": 0.5293308103, "autogenerated": false, "ratio": 4.390483383685801, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.01868962394053635, "num_lines": 274 }
#$Id$ class InvoiceSetting: """This class is used to create object for invoice settings.""" def __init__(self): """Initialize parameters for Invoice settings.""" self.auto_generate = None self.prefix_string = '' self.start_at = 0 self.next_number = '' self.quantity_precision = 0 self.discount_type = '' self.is_discount_before_tax = None self.reference_text = '' self.default_template_id = '' self.notes = '' self.terms = '' self.is_shipping_charge_required = None self.is_adjustment_required = None self.is_open_invoice_editable = None self.warn_convert_to_open = None self.warn_create_creditnotes = None self.attach_expense_receipt_to_invoice = '' self.invoice_item_type = '' self.is_sales_person_required = None self.is_show_invoice_setup = None self.discount_enabled = None def set_discount_enabled(self, discount_enabled): """Set discount enabled. Args: discount_enabled(str): Discount enabled. """ self.discount_enabled = discount_enabled def get_discount_enabled(self): """Get discount enabled. Returns: str: Discount enabled. """ return self.discount_enabled def set_default_template_id(self, default_template_id): """Set default template id. Args: default_template_id(str): Default template id. """ self.default_template_id = default_template_id def get_default_template_id(self): """Get default template id. Returns: str: Default template id. """ return self.default_template_id def set_auto_generate(self, auto_generate): """Set auto generate. Args: auto_generate(bool): Auto generate. """ self.auto_generate = auto_generate def get_auto_generate(self): """Get auto generate. Returns: bool: Auto generate. """ return self.auto_generate def set_prefix_string(self, prefix_string): """Set prefix string. Args: prefix_string(str): Prefix string. """ self.prefix_string = prefix_string def get_prefix_string(self): """Get prefix string. Returns: str: Prefix string. """ return self.prefix_string def set_start_at(self, start_at): """Set start at. Args: start_at(int): Start at. """ self.start_at = start_at def get_start_at(self): """Get start at. Returns: int: Start at. """ return self.start_at def set_next_number(self, next_number): """Set next number. Args: next_number(str): Next number. """ self.next_number = next_number def get_next_number(self): """Get next number. Returns: str: Next number. """ return self.next_number def set_quantity_precision(self, quantity_precision): """Set quantity precision. Args: quantity_precision(int): Quantity precision. """ self.quantity_precision = quantity_precision def get_quantity_precision(self): """Get quantity precision. Returns: int: Quantity precision. """ return self.quantity_precision def set_discount_type(self, discount_type): """Set discount type. Args: discount_type(str): Discount type. """ self.discount_type = discount_type def get_discount_type(self): """Get discount type. Returns: str: Discount type. """ return self.discount_type def set_is_discount_before_tax(self, is_discount_before_tax): """Set whether it is discount before tax. Args: is_discount_before_tax(bool): True to discount before tax. """ self.is_discount_before_tax = is_discount_before_tax def get_is_discount_before_tax(self): """Get whether to discount before tax. Returns: bool: True to discount before tax else false. """ return self.is_discount_before_tax def set_reference_text(self, reference_text): """Set reference text. Args: reference_text(str): Reference text. """ self.reference_text = reference_text def get_reference_text(self): """Get reference text. Returns: str: Reference text. """ return self.reference_text def set_notes(self, notes): """Set notes. Args: notes(str): Notes. """ self.notes = notes def get_notes(self): """Get notes. Returns: str: Notes. """ return self.notes def set_terms(self, terms): """Set terms. Args: terms(str): Terms. """ self.terms = terms def get_terms(self): """Get terms. Returns: str: Terms. """ return self.terms def set_is_shipping_charge_required(self, is_shipping_charge_required): """Set whether shipping charge is required or not. Args: is_shipping_charge_required(bool): True if shipping charge is required else false. """ self.is_shipping_charge_required = is_shipping_charge_required def get_is_shipping_charge_required(self): """Get whether shipping charge is required or not. Returns: bool: True if shipping charge is required or not. """ return self.is_shipping_charge_required def set_is_adjustment_required(self, is_adjustment_required): """Set whether adjustment is required. Args: is_adjustment_required(bool): True if adjustment is required else false. """ self.is_adjustment_required = is_adjustment_required def get_is_adjustment_required(self): """Get whether adjustment is required. Returns: bool: True if adjustment is required. """ return self.is_adjustment_required def set_is_open_invoice_editable(self, is_open_invoice_editable): """Set whether open invoice editable. Args: is_open_invoice_editable(bool): True if open invoice editable else false. """ self.is_open_invoice_editable = is_open_invoice_editable def get_is_open_invoice_editable(self): """Get whether open invoice editable. Returns: bool: True if open invoice editable else false. """ return self.is_open_invoice_editable def set_warn_convert_to_open(self, warn_convert_to_open): """Set whether to enable warning while converting to open. Args: warn_convert_to_open(bool): True to warn while converting to open else false. """ self.warn_convert_to_open = warn_convert_to_open def get_warn_convert_to_open(self): """Get whether to enable warning while converting to open. Returns: bool: True if warning while converting to open is enabled else false. """ return self.warn_convert_to_open def set_warn_create_creditnotes(self, warn_create_creditnotes): """Set whether to enable warning while creating creditnotes. Args: warn_create_creditnotes(bool): True to warn while creating creditnotes else false. """ self.warn_create_creditnotes = warn_create_creditnotes def get_warn_create_creditnotes(self): """Get whether warning while creating creditnotes is enabled or not. Returns: bool: True to warn while creating creditnotes else false. """ return self.warn_create_creditnotes def set_attach_expense_receipt_to_invoice(self, \ attach_expense_receipt_to_invoice): """Set attach expense receipt to invoice. Args: attach_expense_receipt_to_invoice(str): Attach expense receipt to invoice. """ self.attach_expense_receipt_to_invoice = \ attach_expense_receipt_to_invoice def get_attach_expense_receipt_to_invoice(self): """Get attach expense receipt to invoice. Returns: str: Attach expense receipt to invoice. """ return self.attach_expense_receipt_to_invoice def set_is_open_invoice_editable(self, is_open_invoice_editable): """Set whether to open invoice editable. Args: is_open_invoice_editable(bool): True to open invoice editable else false. """ self.is_open_invoice_editable = is_open_invoice_editable def get_is_open_invoice_editable(self): """Get whether to open invoice editable. Returns: bool: True to open invoice editable else false. """ return self.is_open_invoice_editable def set_is_sales_person_required(self, is_sales_person_required): """Set whether sales person is required or not. Args: is_sales_person_required(bool): True if sales person is required else false. """ self.is_sales_person_required = is_sales_person_required def get_is_sales_person_required(self): """Get whether sales person is required or not. Returns: bool: True if sales person is required else false. """ return self.is_sales_person_required def set_is_show_invoice_setup(self, is_show_invoice_setup): """Set whether to show invoice setup. Args: is_show_invoice_setup(bool): True to show invoice setup. """ self.is_show_invoice_setup = is_show_invoice_setup def get_is_show_invoice_setup(self): """Get whether to show invoice setup. Returns: bool: True to show invoice setup. """ return self.is_show_invoice_setup def set_invoice_item_type(self, invoice_item_type): """Set invoice item type. Args: invoice_item_type(str): Invoice item type. """ self.invoice_item_type = invoice_item_type def get_invoice_item_type(self): """Get invoice item type. Returns: str: Invoice item type. """ return self.invoice_item_type def to_json(self): """This method is used to convert invoice settings in json format. Returns: dict: Dictionary containing json object for invoice settings. """ data = {} if self.auto_generate is not None: data['auto_generate'] = self.auto_generate if self.prefix_string != None: data['prefix_string'] = self.prefix_string if self.start_at > 0: data['start_at'] = self.start_at if self.next_number != '': data['next_number'] = self.next_number if self.quantity_precision > 0: data['quantity_precision'] = self.quantity_precision if self.discount_enabled is not None: data['discount_enabled'] = self.discount_enabled if self.reference_text != '': data['reference_text'] = self.reference_text if self.default_template_id != '': data['default_template_id'] = self.default_template_id if self.notes != '': data['notes'] = self.notes if self.terms != '': data['terms'] = self.terms if self.is_shipping_charge_required is not None: data['is_shipping_charge_required'] = \ self.is_shipping_charge_required if self.is_adjustment_required is not None: data['is_adjustment_required'] = \ self.is_adjustment_required if self.invoice_item_type != '': data['invoice_item_type'] = self.invoice_item_type if self.discount_type != '': data['discount_type'] = self.discount_type if self.warn_convert_to_open is not None: data['warn_convert_to_open'] = self.warn_convert_to_open if self.warn_create_creditnotes is not None: data['warn_create_creditnotes'] = self.warn_create_creditnotes if self.is_open_invoice_editable is not None: data['is_open_invoice_editable'] = self.is_open_invoice_editable if self.is_sales_person_required is not None: data['is_sales_person_required'] = self.is_sales_person_required return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/InvoiceSetting.py", "copies": "1", "size": "12982", "license": "mit", "hash": 2888429994730160000, "line_mean": 25.8223140496, "line_max": 79, "alpha_frac": 0.5737174549, "autogenerated": false, "ratio": 4.343258614921378, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.007058914631239031, "num_lines": 484 }
#$Id$ class Item: """This class is used to create object for item.""" def __init__(self): """Initialize parameters for Item object.""" self.item_id = '' self.name = '' self.status = '' self.description = '' self.rate = 0.0 self.unit = '' self.account_id = '' self.account_name = '' self.tax_id = '' self.tax_name = '' self.tax_percentage = 0.0 self.tax_type = '' def set_item_id(self, item_id): """Set item id. Args: item_id(str): Item id. """ self.item_id = item_id def get_item_id(self): """Get item id. Returns: str: Item id. """ return self.item_id def set_name(self, name): """Set name. Args: name(str): Name. """ self.name = name def get_name(self): """Get name. Returns: str: Name. """ return self.name def set_status(self, status): """Set status. Args: status(str): Status. """ self.status = status def get_status(self): """Get status. Returns: str: Status. """ return self.status def set_description(self,description): """Set description. Args: descritpion(str): Description. """ self.description = description def get_description(self): """Get description. Returns: str: Descritpion. """ return self.description def set_rate(self, rate): """Set rate. Args: rate(float): Rate. """ self.rate = rate def get_rate(self): """Get rate. Returns: float: Rate. """ return self.rate def set_unit(self, unit): """Set unit. Args: unit(float): Unit. """ self.unit = unit def get_unit(self): """Get unit. Returns: float: Unit. """ return self.unit def set_account_id(self, account_id): """Set account id. Args: account_id(str): Account id. """ self.account_id = account_id def get_account_id(self): """Get account id. Returns: str: Account id. """ return self.account_id def set_account_name(self, account_name): """Set account name. Args: str: Account name. """ self.account_name = account_name def get_account_name(self): """Get account name. Returns: str: Account name. """ return self.account_name def set_tax_id(self, tax_id): """Set tax id. Args: tax_id(str): Tax id. """ self.tax_id = tax_id def get_tax_id(self): """Get tax id. Returns: str: Tax id. """ return self.tax_id def set_tax_name(self, tax_name): """Set tax name. Args: tax_name(str): Tax name. """ self.tax_name = tax_name def get_tax_name(self): """Get tax name. Returns: str: Tax name. """ return self.tax_name def set_tax_percentage(self, tax_percentage): """Set tax percentage. Args: tax_percentage(float): Tax percentage. """ self.tax_percentage = tax_percentage def get_tax_percentage(self): """Get tax percentage. Returns: float: Tax percentage. """ return self.tax_percentage def set_tax_type(self, tax_type): """Set tax type. Args: tax_type(str): Tax type. """ self.tax_type = tax_type def get_tax_type(self): """Get tax type. Returns: str: Tax type. """ return self.tax_type def to_json(self): """This method is used to create json object for items. Returns: dict: Dictionary containing json object for items. """ data = {} if self.name != '': data['name'] = self.name if self.description != '': data['description'] = self.description if self.rate > 0: data['rate'] = self.rate if self.account_id != '': data['account_id'] = self.account_id if self.tax_id != '': data['tax_id'] = self.tax_id return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Item.py", "copies": "1", "size": "4692", "license": "mit", "hash": 8126653452674430000, "line_mean": 17.4, "line_max": 63, "alpha_frac": 0.4603580563, "autogenerated": false, "ratio": 4.174377224199288, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00979303556047742, "num_lines": 255 }
#$Id$ class Journal: """This class is used to create object for Journals.""" def __init__(self): """Initilaize parameters for journals object.""" self.journal_date = '' self.reference_number = '' self.notes = '' self.line_items = [] self.journal_id = '' self.entry_number = '' self.currency_id = '' self.currency_symbol = '' self.journal_date = '' self.line_item_total = 0.0 self.total = 0.0 self.price_precision = 0 self.taxes = [] self.created_time = '' self.last_modified_time = '' def set_journal_date(self, journal_date): """Set journal date. Args: journal_date(str): Journal date. """ self.journal_date = journal_date def get_journal_date(self): """Get journal date. Returns: str: Journal date. """ return self.journal_date def set_reference_number(self, reference_number): """Set reference date. Args: reference_number(str): Reference number. """ self.reference_number = reference_number def get_reference_number(self): """Get reference number. Returns: str: Reference number. """ return self.reference_number def set_notes(self, notes): """Set notes. Args: notes(str): Notes. """ self.note = notes def get_notes(self): """Get notes. Returns: str: Notes. """ return self.notes def set_line_items(self, line_item): """Set line items. Args: line_items(instance): Line items. """ self.line_items.append(line_item) def get_line_items(self): """Get line items. Returns: list of instance: List of instance object. """ return self.line_items def set_journal_id(self, journal_id): """Set journal id. Args: journal_id(str): Journal id. """ self.journal_id = journal_id def get_journal_id(self): """Get journal id. Returns: str: Journal id. """ return self.journal_id def set_entry_number(self, entry_number): """Set entry number. Args: entry_number(str): Entry number. """ self.entry_number = entry_number def get_entry_number(self): """Get entry number. Returns: str: Entry number. """ return self.entry_number def set_currency_id(self, currency_id): """Set currecny id. Args: currency_id(str): Currency id. """ self.currency_id = currency_id def get_currency_id(self): """Get currency id. Returns: str: Currency id. """ return self.currency_id def set_currency_symbol(self, currency_symbol): """Set currency symbol. Args: currency_symbol(str): Currency symbol. """ self.currency_symbol = currency_symbol def get_currency_symbol(self): """Get currency symbol. Returns: str: Currency symbol. """ return self.currency_symbol def set_journal_date(self, journal_date): """Set journal date. Args: journal_date(str): Journal date. """ self.journal_date = journal_date def get_journal_date(self): """Get journal date. Returns: str: Journal date. """ return self.journal_date def set_line_item_total(self, line_item_total): """Set line item total. Args: lin_item_total(float): Line item total. """ self.line_item_total = line_item_total def get_line_item_total(self): """Get line item total. Returns: float: Line item total. """ return self.line_item_total def set_total(self, total): """Set total. Args: total(float): Total. """ self.total = total def get_total(self): """Get total. Returns: float: Total. """ return self.total def set_price_precision(self, price_precision): """Set price precision. Args: price_precision(int): Price precision. """ self.price_precision = price_precision def get_price_precision(self): """Get price precision. Returns: int: Price precision. """ return self.price_precision def set_taxes(self, tax): """Set taxes. Args: tax(instance): Tax. """ self.taxes.append(tax) def get_taxes(self): """Get taxes. Returns: list of instance: List of tax object. """ return self.taxes def set_created_time(self, created_time): """Set created time. Args: created_time(str): Created time. """ self.created_time = created_time def get_created_time(self): """Get created time. Returns: str: Created time. """ return self.created_time def set_last_modified_time(self, last_modified_time): """Set last modified time. Args: last_modified_time(str): Last modified time. """ self.last_modified_time = last_modified_time def get_last_modified_time(self): """Get last modified time. Returns: str: Last modified time. """ return self.last_modified_time def to_json(self): """This method is used to create json object for journals. Returns: dict: Response containing json object for journals. """ data = {} if self.journal_date != '': data['journal_date'] = self.journal_date if self.reference_number != '': data['reference_number'] = self.reference_number if self.notes != '': data['notes'] = self.notes if self.line_items: data['line_items'] = [] for value in self.line_items: line_item = value.to_json() data['line_items'].append(line_item) return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Journal.py", "copies": "1", "size": "6534", "license": "mit", "hash": 5291190513102269000, "line_mean": 19.875399361, "line_max": 66, "alpha_frac": 0.5116314662, "autogenerated": false, "ratio": 4.312871287128713, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.011861187493262896, "num_lines": 313 }
#$Id$ class LineItem: """This class is used to create object for line items.""" def __init__(self): """Initialize the parameters for line items.""" self.item_id = '' self.line_item_id = '' self.name = '' self.description = '' self.item_order = 0 self.bcy_rate = 0.0 self.rate = 0.00 self.quantity = 0 self.unit = '' self.discount = 0.00 self.tax_id = '' self.tax_name = '' self.tax_type = '' self.tax_percentage = 0.0 self.item_total = 0.0 self.expense_id = '' self.expense_item_id = '' self.expense_receipt_name = '' self.time_entry_ids = '' self.project_id = '' self.account_id = '' self.account_name = '' self.line_id = '' self.debit_or_credit = '' self.amount = 0.0 self.discount_amount = 0.0 def set_item_id(self,item_id): """Set item id. Args: item_id(str): Item id. """ self.item_id = item_id def get_item_id(self): """Get item id. Returns: str: Item id. """ return self.item_id def set_line_item_id(self,line_item_id): """Set line item id. Args: line_item_id(str): line_item_id """ self.line_item_id = line_item_id def get_line_item_id(self): """Get line item id. Returns: str: line item id. """ return self.line_item_id def set_name(self,name): """Set name of the line item. Args: name(str): Name of the line item. """ self.name = name def get_name(self): """Get name of the line item. Returns: str: Name of the line item. """ return self.name def set_description(self,description): """Set description of the line item. Args: description(str): Description of the line item. """ self.description = description def get_description(self): """Get description of the line item. Returns: str: Descritpion of the line item. """ return self.description def set_item_order(self,item_order): """Set item order. Args: item_order(int): Item order. """ self.item_order = item_order def get_item_order(self): """Get item order. Returns: int: Item order. """ return self.item_order def set_bcy_rate(self,bcy_rate): """Set bcy rate. Args: bcy_rate(float): Bcy rate. """ self.bc_rate = bcy_rate def get_bcy_rate(self): """Get bcy rate. Returns: float: Bcy rate. """ return self.bcy_rate def set_rate(self,rate): """Set rate. Args: rate(float): Rate. """ self.rate = rate def get_rate(self): """Get rate. Returns: float: Rate. """ return self.rate def set_quantity(self,quantity): """Set quantity. Args: quantity(float): Quantity. """ self.quantity = quantity def get_quantity(self): """Get quantity. Returns: float: Quantity. """ return self.quantity def set_unit(self,unit): """Set unit. Args: unit(str): Unit. """ self.unit = unit def get_unit(self): """Get unit. Returns: str: Unit. """ return self.unit def set_discount(self,discount): """Set discount. Args: discount(float): Discount. """ self.discount = discount def get_discount(self): """Get discount. Returns: float: Discount. """ return self.discount def set_tax_id(self,tax_id): """Set tax id. Args: tax_id(str): Tax id. """ self.tax_id = tax_id def get_tax_id(self): """Get tax id. Returns: str: Tax id. """ return self.tax_id def set_tax_name(self,tax_name): """Set tax name. Args: tax_name(str): Tax name. """ self.tax_name = tax_name def get_tax_name(self): """Get tax name. Returns: str: Tax name. """ return self.tax_name def set_tax_type(self,tax_type): """Set tax type. Args: tax_type(str): Tax type. """ self.tax_type = tax_type def get_tax_type(self): """Get tax type. Returns: str: Tax type. """ return self.tax_type def set_tax_percentage(self,tax_percentage): """Set tax percentage. Args: tax_percentage(str): Tax percentage. """ self.tax_percentage = tax_percentage def get_tax_percentage(self): """Get tax percentage. Returns: str: Tax percentage. """ return self.tax_percentage def set_item_total(self,item_total): """Set item total. Args: item_total(int): Item total. """ self.item_total = item_total def get_item_total(self): """Get item total. Returns: int: Item total. """ return self.item_total def set_expense_id(self,expense_id): """Set expense id. Args: expense_id(str): Expense id. """ self.expense_id = expense_id def get_expense_id(self): """Get expense id. Args: expense_id(str): Expense id. """ return self.expense_id def set_expense_item_id(self,expense_item_id): """Set expense item id. Args: expense_item_id(str): Expense item id. """ self.expense_item_id = expense_item_id def get_expense_item_id(self): """Get expense item id. Returns: str: Expense item id. """ return self.expense_item_id def set_expense_receipt_name(self,expense_receipt_name): """Set expense receipt name. Args: expense_receipt_name(str): Expense receipt name. """ self.expense_receipt_name = expense_receipt_name def get_expense_receipt_name(self): """Get expense receipt name. Returns: str: Expense receipt name. """ return self.expense_receipt_name def set_time_entry_ids(self,time_entry_ids): """Set time entry ids. Args: time_entry_ids(str): Time entry ids. """ self.time_entry_ids = time_entry_ids def get_time_entry_ids(self): """Get time entry ids. Returns: str: Time entry ids. """ return self.time_entry_ids def set_project_id(self,project_id): """Set project id. Args: project_id(str): Project id. """ self.project_id = project_id def get_project_id(self): """Get project id. Returns: str: Project id. """ return self.project_id def set_account_id(self,account_id): """Set account id. Args: account_id(str): Account id. """ self.account_id = account_id def get_account_id(self): """Get account id. Returns: str: Account id. """ return self.account_id def set_account_name(self,account_name): """Set account name. Args: account_name(str): Account name. """ self.account_name = account_name def get_account_name(self): """Get account name. Returns: str: Account name. """ return self.account_name def set_line_id(self,line_id): """Set line id. Args: line_id(str): Line id. """ self.line_id = line_id def get_line_id(self): """Get line id. Returns: str: Line id. """ return self.line_id def set_debit_or_credit(self,debit_or_credit): """Set debit or credit. Args: debit_or_credit(str): Debit or credit. """ self.debit_or_credit = debit_or_credit def get_debit_or_credit(self): """Get debit or credit. Returns: str: Debit or credit. """ return self.debit_or_credit def set_amount(self, amount): """Set amount. Args: amount(float): Amount. """ self.amount = amount def get_amount(self): """Get amount. Returns: float: Amount. """ return self.amount def set_discount_amount(self,discount_amount): """Set discount amount. Args: discount_amount(float): Discount amount. """ self.discount_amount = discount_amount def get_discount_amount(self): """Get discount amount. Returns: float: Discount amount. """ return self.discount_amount def to_json(self): """This method is used to create json object for line items. Returns: dict: Dictionary containing json object for line items. """ line_item = {} if self.item_id != '': line_item['item_id'] = self.item_id if self.account_id != '': line_item['account_id'] = self.account_id if self.name != '': line_item['name'] = self.name if self.description != '': line_item['description'] = self.description if self.unit != '': line_item['unit'] = self.unit if self.rate != None: line_item['rate'] = self.rate if self.item_order != None: line_item['item_order'] = self.item_order if self.quantity != None: line_item['quantity'] = self.quantity if self.discount is not None: line_item['discount'] = self.discount if self.tax_id != '': line_item['tax_id'] = self.tax_id if self.amount > 0: line_item['amount'] = self.amount if self.debit_or_credit != '': line_item['debit_or_credit'] = self.debit_or_credit return line_item
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/LineItem.py", "copies": "1", "size": "10767", "license": "mit", "hash": 996749187577651000, "line_mean": 19.1629213483, "line_max": 68, "alpha_frac": 0.4881582614, "autogenerated": false, "ratio": 4.031074503931112, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.989938177325635, "avg_score": 0.02397019841495233, "num_lines": 534 }
#$Id$ class Log: """This class is used to create object for log.""" def __init__(self): """Initialize parameters for logs.""" self.id = "" self.notes = "" self.log_date = "" self.log_date_long = 0 self.log_date_format = "" self.hours = 0 self.minutes = 0 self.hours_display = "" self.total_minutes = 0 self.owner_id = "" self.owner_name = "" self.bill_status = "" self.url = "" def set_id(self, id): """Set id. Args: id(str): Id. """ self.id = id def get_id(self): """Get id. Returns: str: Id. """ return self.id def set_notes(self, notes): """Set notes. Args: notes(str): Notes. """ self.notes = notes def get_notes(self): """Get notes. Returns: str: Notes. """ return self.notes def set_log_date(self, log_date): """Set log date. Args: log_date(str): Log date. """ self.log_date = log_date def get_log_date(self): """Get log date. Returns: str: Log date. """ return self.log_date def set_log_date_long(self, log_date_long): """Set log date long. Args: long: Log date long. """ self.log_date_long = log_date_long def get_log_date_long(self): """Get log date long. Returns: long: Log date long. """ return self.log_date_long def set_log_date_format(self, log_date_format): """Set log date format. Args: log_date_format(str): Log date format. """ self.log_date_format = log_date_format def get_log_date_format(self): """Get log date format. Returns: str: Log date format. """ return self.log_date_format def set_hours(self, hours): """Set hours. Args: hours(int): Hours. """ self.hours = hours def get_hours(self): """Get hours. Returns: int: Hours. """ return self.hours def set_minutes(self, minutes): """Set minutes. Args: minutes(int): Minutes. """ self.minutes = minutes def get_minutes(self): """Get minutes. Returns: int: Minutes. """ return self.minutes def set_hours_display(self, hours_display): """Set hours display. Args: hours_display(str): Hours display. """ self.hours_display = hours_display def get_hours_display(self): """Get hours display. Returns: str: Hours display. """ return self.hours_display def set_total_minutes(self, total_minutes): """Set total minutes. Args: total_minutes(int): Total minutes. """ self.total_minutes = total_minutes def get_total_minutes(self): """Get total minutes. Returns: int: Total minutes. """ return self.total_minutes def set_owner_id(self, owner_id): """Set owner id. Args: owner_id(str): Owner id. """ self.owner_id = owner_id def get_owner_id(self): """Get owner id. Returns: str: Owner id. """ return self.owner_id def set_owner_name(self, owner_name): """Set owner name. Args: owner_name(str): Owner name. """ self.owner_name = owner_name def get_owner_name(self): """Get owner name. Returns: str: Owner name. """ return self.owner_name def set_bill_status(self, bill_status): """Set bill status. Args: bill_status(str): Bill status. """ self.bill_status = bill_status def get_bill_status(self): """Get bill status. Returns: str: Bill status. """ return self.bill_status def set_url(self, url): """Set url. Args: url(str): Url """ self.url = url def get_url(self): """Get url. Returns: str: Url. """ return self.url
{ "repo_name": "zoho/projects-python-wrappers", "path": "projects/model/Log.py", "copies": "1", "size": "4550", "license": "mit", "hash": -1099473329300122500, "line_mean": 16.7734375, "line_max": 54, "alpha_frac": 0.4630769231, "autogenerated": false, "ratio": 4.066130473637176, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.005153496490442055, "num_lines": 256 }
#$Id$ class Milestone: """This class is used to create object for Milestone.""" def __init__(self): """Initialize parameters for milestone object.""" self.id = 0 self.url = "" self.status_url = "" self.name = "" self.owner_name = "" self.owner_id = "" self.flag = "" self.start_date = "" self.start_date_long = 0 self.end_date = "" self.end_date_long = 0 self.status = "" self.completed_date = "" self.completed_date_long = 0 self.start_date_format = "" self.end_date_format = "" def set_id(self, id): """Set id. Args: id(long): Milestone id. """ self.id = id def get_id(self): """Get id. Returns: long: Milestone id. """ return self.id def set_url(self, url): """Set url. Args: url(str): Url. """ self.url = url def get_url(self): """Get url. Returns: str: Url. """ return self.url def set_status_url(self, url): """Set status url. Args: url(str): Status url. """ self.status_url = url def get_status_url(self): """Get status url. Returns: str: Status url. """ return self.status_url def set_name(self, name): """Set name. Args: name(str): Name. """ self.name = name def get_name(self): """Get name. Returns: str: Name. """ return self.name def set_owner_name(self, owner_name): """Set owner name. Args: owner_name(str): Owner name. """ self.owner_name = owner_name def get_owner_name(self): """Get owner name. Returns: str: Owner name. """ return self.owner_name def set_owner_id(self, owner_id): """Set owner id. Args: owner_id(str): Owner id. """ self.owner_id = owner_id def get_owner_id(self): """Get owner id. Returns: str: Owner id. """ return self.owner_id def set_flag(self, flag): """Set flag. Args: flag(str): Flag. """ self.flag = flag def get_flag(self): """Get flag. Returns: str: Flag. """ return self.flag def set_start_date(self, start_date): """Set start date. Args: start_date(str): Start date. """ self.start_date = start_date def get_start_date(self): """Get start date. Returns: str: Start date. """ return self.start_date def set_start_date_long(self, start_date_long): """Set start date long. Args: start_date_long(long): Start date long. """ self.start_date_long = start_date_long def get_start_date_long(self): """Get start date long. Returns: long: Start date long. """ return self.start_date_long def set_end_date(self, end_date): """Set end date. Args: end_date(str): End date. """ self.end_date = end_date def get_end_date(self): """Get end date. Returns: str: End date. """ return self.end_date def set_end_date_long(self, end_date_long): """Set end date long. Args: end_date_long(long): End date long. """ self.end_date_long = end_date_long def get_end_date_long(self): """Get end date long. Returns: long: End date long. """ return self.end_date_long def set_status(self, status): """Set status. Args: status(str): Status. """ self.status = status def get_status(self): """Get status. Returns: str: Status. """ return self.status def set_completed_date(self, completed_date): """Set comleted date. Args: completed_date(str): Comleted date. """ self.completed_date = completed_date def get_completed_date(self): """Get completed date. Returns: str: Completed date. """ return self.completed_date def set_completed_date_long(self, completed_date_long): """Set completed date long. Args: completed_date_long(long): Completed date long. """ self.completed_date_long = completed_date_long def get_completed_date_long(self): """Get completed date long. Returns: long: Completed date long. """ return self.completed_date_long def set_start_date_format(self, start_date_format): """Set start date format. Args: start_date_format(str): Start date format. """ self.start_date_format = start_date_format def get_start_date_format(self): """Get start date format. Returns: str: Start date format. """ return self.start_date_format def set_end_date_format(self, end_date_format): """Set end date format. Args: end_date_format(str): End date format. """ self.end_date_format = end_date_format def get_end_date_format(self): """Get end date format. Returns: str: End date format. """ return self.end_date_format
{ "repo_name": "zoho/projects-python-wrappers", "path": "projects/model/Milestone.py", "copies": "1", "size": "5824", "license": "mit", "hash": -7700956639996711000, "line_mean": 17.607028754, "line_max": 60, "alpha_frac": 0.4800824176, "autogenerated": false, "ratio": 4.027662517289073, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9924281894557023, "avg_score": 0.01669260806640998, "num_lines": 313 }
#$Id$ class NotesAndTerms: """This class is used to create object for notes and terms.""" def __init__(self): """Initialize parameters for notes and terms.""" self.notes = '' self.terms = '' def set_notes(self, notes): """Set notes. Args: notes(str): Notes. """ self.notes = notes def get_notes(self): """Get notes. Returns: str: Notes. """ return self.notes def set_terms(self, terms): """Set terms. Args: terms(str): Terms. """ self.terms = terms def get_terms(self): """Get terms. Returns: str: Terms. """ return self.terms def to_json(self): """This method is used to convert notes and terms object to json form. Returns: dict: Dictionary containing json object for notes and terms. """ data = {} if self.notes != '': data['notes'] = self.notes if self.terms != '': data['terms'] = self.terms return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/NotesAndTerms.py", "copies": "1", "size": "1148", "license": "mit", "hash": 8433471978212807000, "line_mean": 18.7931034483, "line_max": 78, "alpha_frac": 0.4790940767, "autogenerated": false, "ratio": 4.415384615384616, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5394478692084616, "avg_score": null, "num_lines": null }
#$Id$ class OpeningBalance: """This class is used to create object for opening balance.""" def __init__(self): """Initialize parameters for opening balance.""" self.opening_balance_id = '' self.date = '' self.accounts = [] def set_opening_balance_id(self, opening_balance_id): """Set opening balance id. Args: opening_balance_id(str): Opening balance id. """ self.opening_balance_id = opening_balance_id def get_opening_balance_id(self): """Get opening balance id. Returns: str: Opening balancce id. """ return self.opening_balance_id def set_date(self, date): """Set date. Args: date(str): Date. """ self.date = date def get_date(self): """Get date. Returns: str: Date. """ return self.date def set_accounts(self, account): """Set accounts. Args: account(instance): Account object. """ self.accounts.append(account) def get_accounts(self): """Get accounts. Returns: list of instance: List of accounts object. """ return self.accounts def to_json(self): """This method is used to convert opening balance object to json object. Returns: dict: Dictionary containing json object for opening balance. """ data = {} if self.date != '': data['date'] = self.date if self.accounts: data['accounts'] = [] for value in self.accounts: account = value.to_json() data['accounts'].append(account) return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/OpeningBalance.py", "copies": "1", "size": "1811", "license": "mit", "hash": 8332991411463216000, "line_mean": 21.6375, "line_max": 80, "alpha_frac": 0.5135284373, "autogenerated": false, "ratio": 4.561712846347607, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5575241283647607, "avg_score": null, "num_lines": null }
#$Id$ class PageContext: """This class is used to create object for page context.""" def __init__(self): """Initialize parameters for page context.""" self.page = 0 self.per_page = 0 self.has_more_page = None self.applied_filter = '' self.sort_column = '' self.sort_order = '' self.report_name = '' self.search_criteria = [] self.from_date = '' self.to_date = '' def set_page(self, page): """Set page number for the list. Args: page(int): Page number for list. """ self.page = page def get_page(self): """Get page number for the list. Returns: int: Page number for the list. """ return self.page def set_per_page(self, per_page): """Set details per page. Args: per_page(int): Details per page. """ self.per_page = per_page def get_per_page(self): """Get details per page. Returns: int: Details per page. """ return self.per_page def set_has_more_page(self, has_more_page): """Set has more page. Args: has_more_page(bool): Has more page. """ self.has_more_page = has_more_page def get_has_more_page(self): """Get has more page. Returns: bool: Has more page. """ return self.has_more_page def set_applied_filter(self, applied_filter): """Set applied filter for the report. Args: applied_filter(str): Applied filter for the report. """ self.applied_filter = applied_filter def get_applied_filter(self): """Get applied filter for the report. Returns: str: Applied filter for the report. """ return self.applied_filter def set_sort_column(self, sort_column): """Set sort column. Args: sort_column(str): Sort column. """ self.sort_column = sort_column def get_sort_column(self): """Get sort column. Returns: str: Sort column. """ return self.sort_column def set_sort_order(self, sort_order): """Set sort order. Args: sort_order(str): Sort order. """ self.sort_order = sort_order def get_sort_order(self): """Get sort order. Returns: str: Sort order. """ return self.sort_order def set_report_name(self, report_name): """Set report name. Args: report_name(str): Report name. """ self.report_name = report_name def get_report_name(self): """Get report name. Returns: str: Report name. """ return self.report_name def set_search_criteria(self, search_criteria): """Set search criteria. Args: search_criteria(instance): Search criteria object. """ self.search_criteria.append(search_criteria) def get_search_criteria(self): """Get search criteria. Returns: list of instance: List of search criteria object. """ return self.search_criteria def set_from_date(self, from_date): """Set from date. Args: from_date(str): From date. """ self.from_date = from_date def get_from_date(self): """Get from date. Returns: str: From date. """ return self.from_date def set_to_date(self, to_date): """Set to date. Args: to_date(str): To date. """ self.to_date = to_date def get_to_date(self): """Get to date. Returns: to_date(str): To date. """ return self.to_date
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/PageContext.py", "copies": "1", "size": "4058", "license": "mit", "hash": -7892011146345250000, "line_mean": 19.4949494949, "line_max": 63, "alpha_frac": 0.4955643174, "autogenerated": false, "ratio": 4.153531218014329, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5149095535414329, "avg_score": null, "num_lines": null }
#$Id$ class PaymentGateway: """This class is used to create object for payment gateway object.""" def __init__(self): """Initialize parameters for Payment gateway object.""" self.gateway_name = '' self.gateway_name_formatted = '' self.identifier = '' self.additional_field1 = '' self.additional_field2 = '' self.additional_field3 = '' self.deposit_to_account_id = '' self.deposit_to_account_name = '' self.configured = None def set_gateway_name(self, gateway_name): """Set gateway name associated with recurring profile. Args: gateway_name(str): Gateway name associated with recurring profile. Allowed values are paypal, authorize_net, payflow_pro, stripe, 2checkout and braintree. """ self.gateway_name = gateway_name def get_gateway_name(self): """Get gateway name. Returns: str: Gateway name associated with recurring profile. """ return self.gateway_name def set_gateway_name_formatted(self, gateway_name_formatted): """Set gateway name formatted. Args: gateway_name_formatted(str): Gateway name formatted. """ self.gateway_name_formatted = gateway_name_formatted def get_gateway_name_formatted(self): """Get gateway name formatted. Returns: str: Gateway name formatted. """ return self.gateway_name_formatted def set_identifier(self, identifier): """Set identifier. Args: identifier(str): Identifier. """ self.identifier = identifier def get_identifier(self): """Get identifier. Returns: str: Identifier. """ return self.identifier def set_additional_field1(self, additional_field1): """Set additional field1. Args: additional_field1(str): Paypal payment method.Allowed values are standard and adaptive. """ self.additional_field1 = additional_field1 def get_additional_field1(self): """Get additional field1. Returns: str: Paypal payment method. """ return self.additional_field1 def set_additional_field2(self, additional_field2): """Set additional field2. Args: additional_field2(str): Paypal payment method.Allowed values are standard and adaptive. """ self.additional_field2 = additional_field2 def get_additional_field2(self): """Get additional field2. Returns: str: Paypal payment method. """ return self.additional_field2 def set_additional_field3(self, additional_field3): """Set additional field3. Args: additional_field3(str): Paypal payment method.Allowed values are standard and adaptive. """ self.additional_field3 = additional_field3 def get_additional_field3(self): """Get additional fiield3. Returns: str: Paypal payment method. """ return self.additional_field3 def set_deposit_to_account_id(self, deposit_to_account_id): """Set deposit to account id. Args: deposit_to_account_id(str): Deposit to account id. """ self.deposit_to_account_id = deposit_to_account_id def get_deposit_to_account_id(self): """Get deposit to account id. Returns: str: Deposit to account id. """ return self.deposit_to_account_id def set_deposit_to_account_name(self, deposit_to_account_name): """Set deposit to account name. Args: deposit_to_account_name(str): Deposit to account name. """ self.deposit_to_account_name = deposit_to_account_name def get_deposit_to_account_name(self): """Get deposit to account name. Returns: str: Deposit to account name. """ return self.deposit_to_account_name def set_configured(self, configured): """Set Whether to configure or not. Args: configured(bool): Configured. """ self.configured = configured def get_configured(self): """Get configured. Returns: bool: Configured. """ return self.configured def to_json(self): """This method is used to convert payment gateway object to json object. Returns: dict: Dictionary containing json object for payment gatewqay. """ data = {} if self.gateway_name != '': data['gateway_name'] = self.gateway_name if self.additional_field1 != '': data['additional_field1'] = self.additional_field1 return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/PaymentGateway.py", "copies": "1", "size": "5037", "license": "mit", "hash": -82913449795984600, "line_mean": 24.6989795918, "line_max": 80, "alpha_frac": 0.5709747866, "autogenerated": false, "ratio": 4.414548641542506, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5485523428142506, "avg_score": null, "num_lines": null }
#$Id$ class Portal: """This class is used to create object for Portal.""" def __init__(self): """Initialize parameters for portal object.""" self.id = 0 self.id_string = "" self.name = "" self.default = None self.gmt_time_zone = "" self.role = "" self.company_name = "" self.website_url = "" self.time_zone = "" self.date_format = "" self.code = "" self.language = "" self.country = "" self.project_url = "" def set_id(self, id): """Set id. Args: id(long): Id. """ self.id = id def get_id(self): """Get id. Returns: long: Id. """ return self.id def set_id_string(self, id_string): """ Set the portal id as string. Args: id_string(str): Portal id as string. """ self.id_string = id_string def get_id_string(self): """ Get the portal id as string. Returns: str: Returns the portal id as string. """ return self.id_string def set_name(self, name): """Set name. Args: name(str): Name. """ self.name = name def get_name(self): """Get name. Returns: str: Name. """ return self.name def set_default(self, default): """Set default. Args: default(bool): Default. """ self.default = default def get_default(self): """Get default. Returns: bool: Default. """ return self.default def set_gmt_time_zone(self, gmt_time_zone): """Set gmt time zone. Args: gmt_time_zone(str): Gmt time zone. """ self.gmat_time_zone = gmt_time_zone def get_gmt_time_zone(self): """Get gmt time zone. Returns: str: Gmt time zone. """ return self.gmt_time_zone def set_role(self, role): """Set role. Args: role(str): Role. """ self.role = role def get_role(self): """Get role. Returns: str: Role. """ return self.role def set_company_name(self, company_name): """Set company name. Args: company_name(str): Company name. """ self.company_name = company_name def get_company_name(self): """Get company name. Returns: str: Company name. """ return self.company_name def set_website_url(self, website_url): """Set website url. Args: website_url(str): Website url. """ self.website_url = website_url def get_website_url(self): """Get website url. Returns: str: Website url. """ return self.website_url def set_time_zone(self, time_zone): """Set time zone. Args: time_zone(str): Time zone. """ self.time_zone = time_zone def get_time_zone(self): """Get time zone. Returns: str: Time zone. """ return self.time_zone def set_date_format(self, date_format): """Set date format. Args: date_format(str): Date format. """ self.date_format = date_format def get_date_format(self): """Get date format. Returns: str: Date format. """ return self.date_format def set_code(self, code): """Set code. Args: code(str): Code. """ self.code = code def get_code(self): """Get code. Returns: str: Code. """ return self.code def set_language(self, language): """Set language. Args: language(str): LAnguage. """ self.language = language def get_language(self): """Get language. Returns: str: Language. """ return self.language def set_country(self, country): """Set country. Args: country(str): Country. """ self.country = country def get_country(self): """Get country. Returns: str: Country. """ return self.country def set_project_url(self, project_url): """Set project url. Args: project_url(str): Project url. """ self.project_url = project_url def get_project_url(self): """Get project url. Returns: str: Project url. """ return self.project_url
{ "repo_name": "zoho/projects-python-wrappers", "path": "projects/model/Portal.py", "copies": "1", "size": "4887", "license": "mit", "hash": 6417567809342566000, "line_mean": 16.5161290323, "line_max": 57, "alpha_frac": 0.4618375281, "autogenerated": false, "ratio": 4.11017661900757, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.507201414710757, "avg_score": null, "num_lines": null }
#$Id$ class Project: """This class is used to create object for project.""" def __init__(self): """Initialize parameters for project object.""" self.id = 0 self.id_string = "" self.open_task_count = 0 self.closed_task_count = 0 self.open_milestone_count = 0 self.closed_milestone_count = 0 self.open_bug_count = 0 self.closed_bug_count = 0 self.name = "" self.template_id = 0 self.status = "" self.created_date = "" self.created_date_long = 0 self.description = "" self.owner_name = "" self.owner_id = 0 self.forum_url = "" self.status_url = "" self.task_url = "" self.url = "" self.tasklist_url = "" self.milestone_url = "" self.folder_url = "" self.document_url = "" self.event_url = "" self.bug_url = "" self.timesheet_url = "" self.user_url = "" self.activity_url = "" self.created_date_format = "" def set_id(self, id): """Set id. Args: id(str): Id. """ self.id = id def get_id(self): """Get id. Returns: str: Id. """ return self.id def set_id_string(self, id_string): """ Set the project id as string. Args: id_string(str): Project id as string. """ self.id_string = id_string def get_id_string(self): """ Get the project id as string. Returns: str: Returns the project id as string. """ def set_open_task_count(self, count): """Set task count. Args: count(int): Task count. """ self.open_task_count = count def get_open_task_count(self): """Get open task count. Returns: int: Open task count. """ return self.open_task_count def set_closed_task_count(self, count): """Set closed task count. Args: count(int): Closed task count. """ self.closed_task_count = count def get_closed_task_count(self): """Get closed task count. Returns: int: Closed task count. """ return self.closed_task_count def set_open_milestone_count(self, count): """Set open milestone count. Args: count(int): Open milestone count. """ self.open_milestone_count = count def get_open_milestone_count(self): """Get open milestone count. Returns: int: Open milestone count. """ return self.open_milestone_count def set_closed_milestone_count(self, count): """Set closed milestone count. Args: count(int): Closed milestone count. """ self.closed_milestone_count = count def get_closed_milestone_count(self): """Get closed milestone count. Returns: int: Closed milestone count. """ return self.closed_milestone_count def set_open_bug_count(self, count): """Set open bug count. Args: count(int): Open bug count. """ self.open_bug_count = count def get_open_bug_count(self): """Get open bug count. Returns: int: Open bug count. """ return self.open_bug_count def set_closed_bug_count(self, count): """Set closed bug count. Args: count(int): Closed bug count. """ self.closed_bug_count = count def get_closed_bug_count(self): """Get closed bug count. Returns: int: Closed bug count. """ return self.closed_bug_count def set_name(self, name): """Set name. Args: name(str): Name. """ self.name = name def get_name(self): """Get name. Returns: str: Name. """ return self.name def set_template_id(self, template_id) """ Set the template id of the project. Args: template_id(long): ID of the template. """ self.template_id = template_id def get_template_id(self) """ Get the template id of the project. Returns: long: Returns the template id. """ return self.template_id def set_status(self, status): """Set status. Args: status(str): Status. """ self.status = status def get_status(self): """Get status. Returns: str: Status. """ return self.status def set_created_date(self, created_date): """Set created date. Args: created_date(str): Created date. """ self.created_date = created_date def get_created_date(self): """Get created date. Returns: str: Created date. """ return self.created_date def set_created_date_long(self, created_date_long): """Set created date long. Args: created_date_long(long); Created date long. """ self.created_date_long = created_date_long def get_created_date_long(self): """Get created date long. Returns: long: Created date long. """ return self.created_date_long def set_description(self, description): """Set description. Args: description(str): Description. """ self.description = description def get_description(self): """Get description. Returns: str: Description. """ return self.description def set_owner_name(self, owner_name): """Set owner name. Args: owner_name(str): Owner name. """ self.owner_name = owner_name def get_owner_name(self): """Get owner name. Returns: str: Owner name. """ return self.owner_name def set_owner_id(self, owner_id): """Set owner id. Args: owner_id(long): Owner id. """ self.owner_id = owner_id def get_owner_id(self): """Get owner id. Returns: long: Owner id. """ return self.owner_id def set_forum_url(self, url): """Set forum url. Args: url(str): Forum url. """ self.forum_url = url def get_forum_url(self): """Get forum url. Returns: str: Forum url. """ return self.forum_url def set_status_url(self, url): """Set status url. Args: url(str): Status url. """ self.status_url = url def get_status_url(self): """Get status url. Returns: str: Status url. """ return self.status_url def set_task_url(self, url): """Set task url. Args: url(str): Task url. """ self.task_url = url def get_task_url(self): """Get task url. Returns: str: Task url. """ return self.task_url def set_url(self, url): """Set url. Args: url(str): Self url. """ self.url = url def get_url(self): """Get url. Returns: str: Self url. """ return self.url def set_tasklist_url(self, tasklist_url): """Set task list url. Args: tasklist_url(str): Tasklist url. """ self.tasklist_url = tasklist_url def get_tasklist_url(self): """Get tasklist url. Returns: str: Task list url. """ return self.tasklist_url def set_milestone_url(self, url): """Set milestone url. Args: url(str): Milestone url. """ self.milestone_url = url def get_milestone_url(self): """Get milestone url. Returns: str: Milestone url. """ return self.milestone_url def set_folder_url(self, folder_url): """Set folder url. Args: folder_url(str): Folder url. """ self.folder_url = folder_url def get_folder_url(self): """Get folder url. Returns: str: Folder url. """ return self.folder_url def set_document_url(self, document_url): """Set document url. Args: document_url(str): Document url. """ self.document_url = document_url def get_document_url(self): """Get document url. Returns: str: Document url. """ return self.document_url def set_event_url(self, event_url): """Set event url. Args: event_url(str): Event url. """ self.event_url = event_url def get_event_url(self): """Get event url. Returns: str: Event url. """ return self.event_url def set_bug_url(self, bug_url): """Set bug url. Args: bug_url(str): Bug url. """ self.bug_url = bug_url def get_bug_url(self): """Get bug url. Returns: str: Bug url. """ return self.bug_url def set_timesheet_url(self, timesheet_url): """Set timesheet url. Args: timesheet_url(str): Timesheet url. """ self.timesheet_url = timesheet_url def get_timesheet_url(self): """Get timesheet url. Returns: str: Timesheet url. """ return self.timesheet_url def set_user_url(self, user_url): """Set user url. Args: user_url(str): User url. """ self.user_url = user_url def get_user_url(self): """Get user url. Returns: str: User url. """ return self.user_url def set_activity_url(self, activity_url): """Set activity url. Args: activity_url(str): Activity url. """ self.activity_url = activity_url def get_activity_url(self): """Get activity url. Returns: str: Activity url. """ return self.activity_url def set_created_date_format(self, created_date_format): """Set created date format. Args: created_date_format(str): Created date format. """ self.created_date_format = created_date_format def get_created_date_format(self): """Get created date format. Returns: str: Created date format. """ return self.created_date_format
{ "repo_name": "zoho/projects-python-wrappers", "path": "projects/model/Project.py", "copies": "1", "size": "11111", "license": "mit", "hash": 7672466902991077000, "line_mean": 17.8962585034, "line_max": 59, "alpha_frac": 0.4895148951, "autogenerated": false, "ratio": 4.084926470588235, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9958398154424906, "avg_score": 0.02320864225266614, "num_lines": 588 }
#$Id$ class Project: """This class is used to create object for Projects.""" def __init__(self): """Initialize the parameters for projects object.""" self.project_id = '' self.project_name = '' self.customer_id = '' self.customer_name = '' self.currency_code = '' self.description = '' self.status = '' self.billing_type = '' self.rate = 0.0 self.budget_type = '' self.budget_hours = 0 self.budget_amount = 0.0 self.total_hours = '' self.billed_hours = '' self.un_billed_hours = '' self.created_time = '' self.tasks = [] self.users = [] def set_project_id(self, project_id): """Set project_id. Args: project_id(str): Project id. """ self.project_id = project_id def get_project_id(self): """Get project id. Returns: str: Project id. """ return self.project_id def set_project_name(self, project_name): """Set project name. Args: project_name(str): Project name. """ self.project_name = project_name def get_project_name(self): """Get project name. Returns: str: Project name. """ return self.project_name def set_customer_id(self, customer_id): """Set customer id. Args: customer_id(str): Customer id. """ self.customer_id = customer_id def get_customer_id(self): """Get customer id. Returns: str: Customer id. """ return self.customer_id def set_customer_name(self, customer_name): """Set customer name. Args: customer_name(str): Customer name. """ self.customer_name = customer_name def get_customer_name(self): """Get customer name. Returns: str: Customer name. """ return self.customer_name def set_currency_code(self, currency_code): """Set currency code. Args: currency_code(str): Currency code. """ self.currency_code = currency_code def get_currency_code(self): """Get currency_code. Returns: str: Currency code. """ return self.currency_code def set_description(self, description): """Set description. Args: description(str): Description. """ self.description = description def get_description(self): """Get description. Returns: str: Description. """ return self.description def set_status(self, status): """Set status. Args: status(str): Status. """ self.status = status def get_status(self): """Get status. Returns: str: Status. """ return self.status def set_billing_type(self, billing_type): """Set billing type. Args: billing_type(str): Billing type. """ self.billing_type = billing_type def get_billing_type(self): """Get billing type. Returns: str: Billing type. """ return self.billing_type def set_budget_type(self, budget_type): """Set budget type. Args: budget_type(str): Budget type. """ self.budget_type = budget_type def get_budget_type(self): """Get budget type. Returns: str: Budget type. """ return self.budget_type def set_total_hours(self, total_hours): """Set total hours. Args: total_hours(str): Total hours. """ self.total_hours = total_hours def get_total_hours(self): """Get total hours. Returns: str: Total hours. """ return self.total_hours def set_billed_hours(self, billed_hours): """Set billed hours. Args: billed_hours(str): Billed hours. """ self.billed_hours = billed_hours def get_billed_hours(self): """Get billed hours. Returns: str: Billed hours. """ return self.billed_hours def set_un_billed_hours(self, un_billed_hours): """Set unbilled hours. Args: un_billed_hours(str): Unbilled hours. """ self.un_billed_hours = un_billed_hours def get_un_billed_hours(self): """Get unbilled hours. Returns: str: Unbilled hours. """ return self.un_billed_hours def set_created_time(self, created_time): """Set created time. Args: created_time(str): Created time. """ self.created_time = created_time def get_created_time(self): """Get created time. Returns: str: Created time. """ return self.created_time def set_tasks(self, task): """Set task. Args: task(instance): Task object. """ self.tasks.append(task) def get_tasks(self): """Get tasks. Returns: list of instance: List of task object. """ return self.tasks def set_users(self, user): """Set User. Args: user(instance): User object. """ self.users.append(user) def get_users(self): """Get user. Returns: list of object: User object. """ return self.users def set_rate(self, rate): """Set rate. Args: rate(float): Rate. """ self.rate = rate def get_rate(self): """Get rate. Returns: float: Rate. """ return self.rate def set_budget_hours(self, budget_hours): """Set budget hours. Args: budget_hours(str): Budget hours. """ self.budget_hours = budget_hours def get_budget_hours(self): """Get budget hours. Returns: str: Budget hours. """ return self.budget_hours def set_budget_amount(self, budget_amount): """Set budget amount. Args: budget_amount(float): Budget amount. """ self.budget_amount = budget_amount def get_budget_amount(self): """Get budget amount. Returns: float: Budget amount. """ return self.budget_amount def to_json(self): """This method is used to convert projects object to json format. Returns: dict: Dictionary containing json for projects. """ data = {} if self.project_name != '': data['project_name'] = self.project_name if self.customer_id != '': data['customer_id'] = self.customer_id if self.description != '': data['description'] = self.description if self.billing_type != '': data['billing_type'] = self.billing_type if self.rate > 0: data['rate'] = self.rate if self.budget_type != '': data['budget_type'] = self.budget_type if self.budget_hours != '': data['budget_hours'] = self.budget_hours if self.budget_amount > 0: data['budget_amount'] = self.budget_amount if self.users: data['users'] = [] print self.users for value in self.users: print value user = value.to_json() data['users'].append(user) if self.tasks: data['tasks'] = [] for value in self.tasks: task = value.to_json() data['tasks'].append(task) return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Project.py", "copies": "1", "size": "8026", "license": "mit", "hash": -7973795500675921000, "line_mean": 19.792746114, "line_max": 73, "alpha_frac": 0.4997508099, "autogenerated": false, "ratio": 4.226434965771459, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5226185775671458, "avg_score": null, "num_lines": null }
#$Id$ class RecurringExpense: """This class is used to create object for Recurring Expenses.""" def __init__(self): """Initialize parameters for Recurring expenses.""" self.account_id = '' self.paid_through_account_id = '' self.recurrence_name = '' self.start_date = '' self.end_date = '' self.recurrence_frequency = '' self.repeat_every = 0 self.repeat_frequency = '' self.amount = 0.0 self.tax_id = '' self.is_inclusive_tax = None self.is_billable = None self.customer_id = '' self.vendor_id = '' self.project_id = '' self.currency_id = '' self.exchange_rate = 0.0 self.recurring_expense_id = '' self.last_created_date = '' self.next_expense_date = '' self.account_name = '' self.paid_through_account_name = '' self.vendor_name = '' self.currency_code = '' self.tax_name = '' self.tax_percentage = 0 self.tax_amount = 0.0 self.sub_total = 0.0 self.total = 0.0 self.bcy_total = 0.0 self.description = '' self.customer_name = '' self.status = '' self.created_time = '' self.last_modified_time = '' self.project_name = '' def set_account_id(self, account_id): """Set account id. Args: account_id(str): Account id. """ self.account_id = account_id def get_account_id(self): """Get account id. Returns: str: Account id. """ return self.account_id def set_paid_through_account_id(self, paid_through_account_id): """Set paid through account id. Args: paid_through_account_id(str): Paid through account id. """ self.paid_through_account_id = paid_through_account_id def get_paid_through_account_id(self): """Get paid through account id. Returns: str: Paid through account id. """ return self.paid_through_account_id def set_recurrence_name(self, recurrence_name): """Set recurrence name. Args: recurrence_name(str): Recurrence name. """ self.recurrence_name = recurrence_name def get_recurrence_name(self): """Get recurrence name. Returns: str: Recurrence name. """ return self.recurrence_name def set_start_date(self, start_date): """Set start date. Args: start_date(str): Start date. """ self.start_date = start_date def get_start_date(self): """Get start date. Returns: str: Start date. """ return self.start_date def set_end_date(self, end_date): """Set end date. Args: end_date(str): End date. """ self.end_date = end_date def get_end_date(self): """Get end date. Returns: str: End date. """ return self.end_date def set_recurrence_frequency(self, recurrence_frequency): """Set recurrence frequency. Args: recurrence_frequency(str): Recurrence frequency. """ self.recurrence_frequency = recurrence_frequency def get_recurrence_frequency(self): """Get recurrence frequency. Returns: str: Recurrence frequency. """ return self.recurrence_frequency def set_repeat_every(self, repeat_every): """Set repeat every. Args: repeat_every(int): Repeat every. """ self.repeat_every = repeat_every def get_repeat_every(self): """Get repeat every. Returns: int: Repeat every. """ return self.repeat_every def set_repeat_frequency(self, repeat_frequency): """Set repeat frequency. Args: repeat_frequency(str): Repeat frequency. """ self.repeat_frequency = repeat_frequency def get_repeat_frequency(self): """Get repeat frequency. Returns: str: Repeat frequency. """ return self.repeat_frequency def set_amount(self, amount): """Set amount. Args: amount(float): Amount. """ self.amount = amount def get_amount(self): """Get amount. Returns: float: Amount. """ return self.amount def set_tax_id(self, tax_id): """Set tax id. Args: tax_id(str): Tax id. """ self.tax_id = tax_id def get_tax_id(self): """Get tax id. Returns: str: Tax id. """ return self.tax_id def set_is_inclusive_tax(self, is_inclusive_tax): """Set whether tax is inclusive. Args: is_inclusive_tax(bool): True if tax is inclusive else False. """ self.is_inclusive_tax = is_inclusive_tax def get_is_inclusive_tax(self): """Get whether tax is inclusive. Returns: bool: True if tax is inclusive else False. """ return self.is_inclusive_tax def set_is_billable(self, is_billable): """Set whether Recurring Expense is billable. Args: is_billable(bool): True if billable else False. """ self.is_billable = is_billable def get_is_billable(self): """Get whether Recurring Expense is billable. Returns: bool: True if billable else False. """ return self.is_billable def set_customer_id(self, customer_id): """Set customer id. Args: customer_id(str): Customer id. """ self.customer_id = customer_id def get_customer_id(self): """Get customer id. Returns: str: Customer id. """ return self.customer_id def set_vendor_id(self, vendor_id): """Set vendor id. Args: vendor_id(str): Vendor id. """ self.vendor_id = vendor_id def get_vendor_id(self): """Get vendor id. Returns: str: Get vendor id. """ return self.vendor_id def set_project_id(self, project_id): """Set project id. Args: project_id(str): Project id. """ self.project_id = project_id def get_project_id(self): """Get project id. Returns: str: Project id. """ return self.project_id def set_currency_id(self, currency_id): """Set currency id. Args: currency_id(str): Currency id. """ self.currency_id = currency_id def get_currency_id(self): """Get currency id. Returns: str: Currency id. """ return self.currency_id def set_exchange_rate(self, exchange_rate): """Set exchange rate. Args: exchange_rate(float): Exchange rate. """ self.exchange_rate = exchange_rate def get_exchange_rate(self): """Get exchange rate. Returns: float: Exchange rate. """ return self.exchange_rate def set_recurring_expense_id(self, recurring_expense_id): """Set recurring expense id. Args: recurring_expense_id(str): Recurring expense id. """ self.recurring_expense_id = recurring_expense_id def get_recurring_expense_id(self): """Get recurring expense id. Returns: str: Recurring expense id. """ return self.recurring_expense_id def set_last_created_date(self, last_created_date): """Set last created date. Args: last_created_date(str): Last created date. """ self.last_created_date = last_created_date def get_last_created_date(self): """Get last created date. Returns: str: Last created date. """ return self.last_created_date def set_next_expense_date(self, next_expense_date): """Set next expense date. Args: next_expense_date(str): Next expense date. """ self.next_expense_date = next_expense_date def get_next_expense_date(self): """Get next expense date. Returns: str: Next expense date. """ return self.next_expense_date def set_account_name(self, account_name): """Set account name. Args: account_name(str): Account name. """ self.account_name = account_name def get_account_name(self): """Get account name. Return: str: Account name. """ return self.account_name def set_paid_through_account_name(self, paid_through_account_name): """Set paid through account name. Args: paid_through_account_name(str): Paid through account name. """ self.paid_through_account_name = paid_through_account_name def get_paid_through_account_name(self): """Get paid through account name. Returns: str: Paid through account name. """ return self.paid_through_account_name def set_vendor_name(self, vendor_name): """Set vendor name. Args: vendor_name(str): Vendor name. """ self.vendor_name = vendor_name def get_vendor_name(self): """Get vendor name. Returns: str: Vendor name. """ return self.vendor_name def set_currency_code(self, currency_code): """Set currency code. Args: currency_code(str): Currency code. """ self.currency_code = currency_code def get_currency_code(self): """Get currency code. Returns: str: Currency code. """ return self.currency_code def set_tax_name(self, tax_name): """Set tax name. Args: tax_name(str): Tax name. """ self.tax_name = tax_name def get_tax_name(self): """Get tax name. Returns: str: Tax name. """ return self.tax_name def set_tax_percentage(self, tax_percentage): """Set tax percentage. Args: tax_percentage(int): Tax percentage. """ self.tax_percentage = tax_percentage def set_tax_amount(self, tax_amount): """Set tax amount. Args: tax_amount(float): Tax amount. """ self.tax_amount = tax_amount def get_tax_amount(self): """Get tax amount. Returns: float: Tax amount. """ return self.tax_amount def set_sub_total(self, sub_total): """Set sub total. Args: sub_total(float): Sub total. """ self.sub_total = sub_total def get_sub_total(self): """Get sub total. Returns: float: Sub total. """ return self.sub_total def set_total(self, total): """Set total. Args: total(float): Total. """ self.total = total def get_total(self): """Get total. Returns: float: Total. """ return self.total def set_bcy_total(self, bcy_total): """Set bcy total. Args: bcy_total(float): Bcy total. """ self.bcy_total = bcy_total def get_bcy_total(self): """Get bcy total. Returns: float: Bcy total. """ return self.bcy_total def set_description(self, description): """Set description. Args: description(str): Description. """ self.description = description def get_description(self): """Get description. Returns: str: Description. """ return self.description def set_customer_name(self, customer_name): """Set customer name. Args: customer_name(str): Customer name. """ self.customer_name = customer_name def get_customer_name(self): """Get customer name. Returns: str: Customer name. """ return self.customer_name def set_status(self, status): """Set status. Args: status(str): Status. """ self.status = '' def get_status(self): """Get status. Returns: str: Status. """ return self.status def set_created_time(self, created_time): """Set created time. Args: created_time(str): Created time. """ self.created_time = created_time def get_created_time(self): """Get created time. Returns: str: Created time. """ return self.created_time def set_last_modified_time(self, last_modified_time): """Set last modified time. Args: last_modified_time(str): Last modified time. """ self.last_modified_time = last_modified_time def get_last_modified_time(self): """Get last modified time. Returns: str: Last modified time. """ return self.last_modified_time def set_project_name(self, project_name): """Set project name. Args: project_name(str): Project name. """ self.project_name = project_name def get_project_name(self): """Get project name. Returns: str: Project name. """ return self.project_name def to_json(self): """This method is used to convert recurring expenses object to json object. Returns: dict: Dictionary coontaining json object for recurring expenses. """ data = {} if self.account_id != '': data['account_id'] = self.account_id if self.paid_through_account_id != '': data['paid_through_account_id'] = self.paid_through_account_id if self.recurrence_name != '': data['recurrence_name'] = self.recurrence_name if self.start_date != '': data['start_date'] = self.start_date if self.end_date != '': data['end_date'] = self.end_date if self.recurrence_frequency != '': data['recurrence_frequency'] = self.recurrence_frequency if self.repeat_every > 0: data['repeat_every'] = self.repeat_every if self.amount > 0: data['amount'] = self.amount if self.tax_id != '': data['tax_id'] = self.tax_id if self.is_inclusive_tax is not None: data['is_inclusive_tax'] = self.is_inclusive_tax if self.is_billable is not None: data['is_billable'] = self.is_billable if self.customer_id != '': data['customer_id'] = self.customer_id if self.vendor_id != '': data['vendor_id'] = self.vendor_id if self.project_id != '': data['project_id'] = self.project_id if self.currency_id != '': data['currency_id'] = self.currency_id if self.exchange_rate > 0: data['exchange_rate'] = self.exchange_rate return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/RecurringExpense.py", "copies": "1", "size": "15775", "license": "mit", "hash": -8707576081268855000, "line_mean": 20.7586206897, "line_max": 83, "alpha_frac": 0.5201267829, "autogenerated": false, "ratio": 4.138247639034628, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5158374421934628, "avg_score": null, "num_lines": null }
#$Id$ class SearchCriteria: """This class is used to create object for Criteria.""" def __init__(self): """Initialize parameter for search criteria.""" self.column_name = '' self.search_text = '' self.comparator = '' def set_column_name(self, column_name): """Set column name. Args: column_name(str): Column name. """ self.column_name = column_name def get_column_name(self): """Get column name. Returns: str: Column name. """ return self.column_name def set_search_text(self, search_text): """Set search text. Args: search_text(str): Search text. """ self.search_text = search_text def get_search_text(self): """Get search text. Returns: str: Search text. """ return self.search_text def set_comparator(self, comparator): """Set comparator. Args: comparator(str): Comparator. """ self.comparator = comparator def get_comparator(self): """Get compparator. Returns: str: Comparator. """ return self.comparator
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/SearchCriteria.py", "copies": "1", "size": "1260", "license": "mit", "hash": -6269701408765418000, "line_mean": 18.6875, "line_max": 59, "alpha_frac": 0.5174603175, "autogenerated": false, "ratio": 4.359861591695502, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5377321909195502, "avg_score": null, "num_lines": null }
#$Id$ class Status: """This class is used to create object for status.""" def __init__(self): """Initialize parameters for status object.""" self.id = 0 self.content = "" self.posted_by = "" self.posted_person = "" self.posted_time = "" self.posted_time_long = 0 def set_id(self, id): """Set id. Args: id(long):Status Id. """ self.id = id def get_id(self): """Get id. Returns: long: Status id. """ return self.id def set_content(self, content): """Set content. Args: content(str): Content. """ self.content = content def get_content(self): """Get content. Returns: str: Content. """ return self.content def set_posted_by(self, posted_by): """Set posted by. Args: posted_by(str): Posted by. """ self.posted_by = posted_by def get_posted_by(self): """Get posted by. Returns: str: Posted by. """ return self.posted_by def set_posted_person(self, posted_person): """Set posted person. Args: posted_person(str): Posted person. """ self.posted_person = posted_person def get_posted_person(self): """Get posted person. Returns: str: Posted person. """ return self.posted_person def set_posted_time(self, posted_time): """Set posted time. Args: posted_time(str): Posted time. """ self.posted_time = posted_time def get_posted_time(self): """Get posted time. Returns: str: Posted time. """ return self.posted_time def set_posted_time_long(self, posted_time_long): """Set posted time long. Args: posted_time_long(long): Posted time long. """ self.posted_time_long = posted_time_long def get_posted_time_long(self): """Get posted time long. Returns: long: Posted time long. """ return self.posted_time_long
{ "repo_name": "zoho/projects-python-wrappers", "path": "projects/model/Status.py", "copies": "1", "size": "2280", "license": "mit", "hash": 7183220424019940000, "line_mean": 17.5365853659, "line_max": 57, "alpha_frac": 0.4899122807, "autogenerated": false, "ratio": 4.1454545454545455, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5135366826154546, "avg_score": null, "num_lines": null }
#$Id$ class Task: """This class is used to create object for tasks.""" def __init__(self): """Initialize parameters for tasks object.""" self.task_id = '' self.task_name = '' self.description = '' self.rate = 0.0 self.budget_hours = 0 self.total_hours = '' self.billed_hours= '' self.unbilled_hours = '' self.project_id = '' self.project_name = '' self.currency_id = '' self.customer_id = '' self.customer_name = '' self.log_time = '' def set_task_id(self, task_id): """Set task id. Args: task_id(str): Task id. """ self.task_id = task_id def get_task_id(self): """Get task id. Returns: str: Task id. """ return self.task_id def set_task_name(self, task_name): """Set task name. Args: task_name(str): Task name. """ self.task_name = task_name def get_task_name(self): """Get task name. Returns: str: Task name. """ return self.task_name def set_description(self, description): """Set description. Args: description(str): Description. """ self.description = description def get_description(self): """Get description Returns: str: Description. """ return self.description def set_rate(self, rate): """Set rate. Args: rate(float): Rate. """ self.rate = rate def get_rate(self): """Get rate. Returns: float: Rate. """ return self.rate def set_budget_hours(self, budget_hours): """Set budget hours. Args: budget_hours(int): Budget hours. """ self.budget_hours = budget_hours def get_budget_hours(self): """Get budget_hours. Returns: int: Budget hours. """ return self.budget_hours def set_total_hours(self, total_hours): """Set total hours. Args: total_hours(str): Total hours. """ self.total_hours = total_hours def get_total_hours(self): """Get total hours. Returns: str: Total hours. """ return self.total_hours def set_billed_hours(self, billed_hours): """Set billed hours. Args: billed_hours(str): Billed hours. """ self.billed_hours = billed_hours def get_billed_hours(self): """Get billed hours. Args: str: billed hours. """ return self.billed_hours def set_un_billed_hours(self, un_billed_hours): """Set unbilled hours. Args: un_billed_hours(str): Unbilled hours. """ self.un_billed_hours = un_billed_hours def get_un_billed_hours(self): """Get unbilled hours. Returns: str: Unbilled hours. """ return self.un_billed_hours def set_project_id(self, project_id): """Set project_id. Args: project_id(str): Project id. """ self.project_id = project_id def get_project_id(self): """Get project id. Returns: str: Project id. """ return self.project_id def set_project_name(self, project_name): """Set project name. Args: project_name(str): Project name. """ self.project_name = project_name def get_project_name(self): """Get project name. Returns: str: Project name. """ return self.project_name def set_currency_id(self, currency_id): """Set currency id. Args: currency_id(str): Currency id. """ self.currency_id = currency_id def get_currency_id(self): """Get currency id. Returns: str: Currency id. """ return self.currency_id def set_customer_id(self, customer_id): """Set customer id. Args: customer_id(str): Customer id. """ self.customer_id = customer_id def get_customer_id(self): """Get customer id. Returns: str: Customer id. """ return self.customer_id def set_customer_name(self, customer_name): """Set customer name. Args: customer_name(str): Customer name. """ self.customer_name = customer_name def get_customer_name(self): """Get customer name. Returns: str: Customer name. """ return self.customer_name def set_log_time(self, log_time): """Set log time. Args: log_time(str): Log time. """ self.log_time = log_time def get_log_time(self): """Get log time. Returns: str: Log time. """ return self.log_time def to_json(self): """This method is used to convert task object to jsno format. Returns: dict: Dictionary containing json object for task. """ data = {} if self.task_name != '': data['task_name'] = self.task_name if self.description != '': data['description'] = self.description if self.rate > 0: data['rate'] = self.rate if self.budget_hours > 0: data['budget_hours'] = self.budget_hours return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Task.py", "copies": "1", "size": "5745", "license": "mit", "hash": 749764716455477200, "line_mean": 18.8103448276, "line_max": 69, "alpha_frac": 0.4924281984, "autogenerated": false, "ratio": 4.100642398286938, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5093070596686938, "avg_score": null, "num_lines": null }
#$Id$ class TaxGroup: """This class is used to create object for tax group.""" def __init__(self): """Initialize parameters for tax group. """ self.tax_group_id = '' self.tax_group_name = '' self.tax_group_percentage = 0 self.taxes = '' def set_tax_group_id(self, tax_group_id): """Set tax group id. Args: tax_group_id(str): Tax group id. """ self.tax_group_id = tax_group_id def get_tax_group_id(self): """Get tax group id. Returns: str: Tax group id. """ return self.tax_group_id def set_tax_group_name(self, tax_group_name): """Set tax group name. Args: tax_group_name(str): Tax group name. """ self.tax_group_name = tax_group_name def get_tax_group_name(self): """Get tax group name. Returns: str: Tax group name. """ return self.tax_group_name def set_tax_group_percentage(self, tax_group_percentage): """Set tax group percentage. Args: tax_group_percentage(int): Tax group percentage. """ self.tax_group_percentage = tax_group_percentage def get_tax_group_percentage(self): """Get tax group percentage. Returns: int: Tax group percentage. """ return self.tax_group_percentage def set_taxes(self, taxes): """Set taxes. Args: taxes(str): Taxes. """ self.taxes = taxes def get_taxes(self): """Get taxes. Returns: str: Taxes. """ return self.taxes def to_json(self): """This method is used to create json object for tax group. Returns: dict: Dictionary containing json object for tax group. """ data = {} if self.tax_group_name != '': data['tax_group_name'] = self.tax_group_name if self.taxes != '': data['taxes'] = self.taxes return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/TaxGroup.py", "copies": "1", "size": "2101", "license": "mit", "hash": 8365240971431508000, "line_mean": 20.8854166667, "line_max": 67, "alpha_frac": 0.516420752, "autogenerated": false, "ratio": 4.048169556840077, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.008547008547008546, "num_lines": 96 }
#$Id$ class Tax: """This class is used to create an object for tax.""" def __init__(self): """Initialize parameters for tax.""" self.tax_name = '' self.tax_amount = 0.0 self.tax_id = '' self.tax_percentage = 0.0 self.tax_type = '' def set_tax_id(self, tax_id): """Set tax id. Args: tax_id(str): Tax id. """ self.tax_id = tax_id def get_tax_id(self): """Get tax id. Returns: str: Tax id. """ return self.tax_id def set_tax_percentage(self, tax_percentage): """Set tax percentage. Args: tax_percentage(float): Tax percentage. """ self.tax_percentage = tax_percentage def get_tax_percentage(self): """Get tax percentage. Args: float: Tax percentage. """ return self.tax_percentage def set_tax_type(self, tax_type): """Set tax type. Args: tax_type(str): Tax type. """ self.tax_type = tax_type def get_tax_type(self): """Get tax type. Returns: str: Tax type. """ return self.tax_type def set_tax_name(self, tax_name): """Set tax name. Args: tax_name(str): Tax name. """ self.tax_name = tax_name def get_tax_name(self): """Get tax name. Returns: str: Tax name. """ return self.tax_name def set_tax_amount(self, tax_amount): """Set tax amount. Args: tax_amount(float): Tax amount. """ self.tax_amount = tax_amount def get_tax_amount(self): """Get tax amount. Returns: float: Tax amount. """ return self.tax_amount def to_json(self): """This method is used to convert tax object to json format. Returns: dict: Dictionary containing json object for tax. """ data = {} if self.tax_name != '': data['tax_name'] = self.tax_name if self.tax_percentage > 0: data['tax_percentage'] = self.tax_percentage if self.tax_type != '': data['tax_type'] = self.tax_type return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Tax.py", "copies": "1", "size": "2355", "license": "mit", "hash": -707129205512776300, "line_mean": 18.7899159664, "line_max": 68, "alpha_frac": 0.4815286624, "autogenerated": false, "ratio": 3.9780405405405403, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.495956920294054, "avg_score": null, "num_lines": null }
#$Id$ class Template: """This class is used to create object for templates.""" def __init__(self): """Initialize the parameters for templates object.""" self.template_name = '' self.template_id = '' self.template_type = '' def set_template_name(self, template_name): """Set template name. Args: template_name(str): Template name. """ self.template_name = template_name def get_template_name(self): """Get template name. Returns: str: Template name. """ return self.template_name def set_template_id(self, template_id): """Set template id. Args: template_id(str): Template id. """ self.template_id = template_id def get_template_id(self): """Get template id. Returns: str: Template id. """ return self.template_id def set_template_type(self, template_type): """Set template type. Args: template_type(str): Template type. """ self.template_type = template_type def get_template_type(self): """Get template type. Returns: str: Template type. """ return self.template_type
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Template.py", "copies": "1", "size": "1330", "license": "mit", "hash": 6243268605620555000, "line_mean": 19.4615384615, "line_max": 61, "alpha_frac": 0.5255639098, "autogenerated": false, "ratio": 4.403973509933775, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.03373626373626374, "num_lines": 65 }
#$Id$ class Term: """This class is used to create object for terms.""" def __init__(self): """Initialize parameters for terms.""" self.invoice_terms = '' self.estimate_terms = '' self.creditnotes_terms = '' def set_invoice_terms(self, invoice_terms): """Set invoice terms. Args: invoice_terms(str): Invoice terms. """ self.invoice_terms = invoice_terms def get_invoice_terms(self): """Get invoice terms. Returns: str: Invoice terms. """ return self.invoice_terms def set_estimate_terms(self, estimate_terms): """Set estimate terms. Args: estimate_terms(str): Estimate terms. """ self.estimate_terms = estimate_terms def set_creditnote_terms(self, creditnote_terms): """Set creditnote terms. Args: creditnote_terms(str): Creditnote terms. """ self.creditnote_terms = creditnote_terms def get_creditnote_terms(self): """Get creditnote terms. Returns: str: Creditnote terms. """ return self.creditnote_terms
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Term.py", "copies": "1", "size": "1205", "license": "mit", "hash": -1114756810520991400, "line_mean": 20.9090909091, "line_max": 56, "alpha_frac": 0.5526970954, "autogenerated": false, "ratio": 4.350180505415162, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5402877600815162, "avg_score": null, "num_lines": null }
#$Id$ class TimeEntry: """This class is used to create object for Time Entry.""" def __init__(self): """Initialize parameters for Time entry object.""" self.time_entry_id = '' self.project_id = '' self.project_name = '' self.task_id = '' self.task_name = '' self.user_id = '' self.user_name = '' self.is_current_user = None self.log_date = '' self.begin_time = '' self.end_time = '' self.log_time = '' self.billed_status = '' self.notes = '' self.time_started_at = '' self.timer_duration_in_minutes = 0 self.created_time = '' self.customer_id = '' self.customer_name = '' self.start_timer = None def set_start_timer(self, start_timer): """Set start timer. Args: start_timer(bool): Start timer. """ self.start_timer = start_timer def get_start_timer(self): """Get start timer. Returns: bool: Start timer. """ return self.start_timer def set_time_entry_id(self, time_entry_id): """Set time entry id. Args: time_entry_id(str): Time entry id. """ self.time_entry_id = time_entry_id def get_time_entry_id(self): """Get time entry id. Returns: str: Time entry id. """ return self.time_entry_id def set_project_id(self, project_id): """Set project id. Args: project_id(str): Project id. """ self.project_id = project_id def get_project_id(self): """Get project id. Returns: str: Project id. """ return self.project_id def set_project_name(self, project_name): """Set project name. Args: project_name(str):Project name. """ self.project_name = project_name def get_project_name(self): """Get project name. Returns: str: Project name. """ return self.project_name def set_task_id(self, task_id): """Set task id. Args: task_id(str): Task id. """ self.task_id = task_id def get_task_id(self): """Get task id. Returns: str: Task id. """ return self.task_id def set_task_name(self, task_name): """Set task name. Args: task_name(str): Task name. """ self.task_name = task_name def get_task_name(self): """Get task name. Returns: str: Task name. """ return self.task_name def set_user_id(self, user_id): """Set user id. Args: user_id(str): User id. """ self.user_id = user_id def get_user_id(self): """Get user id. Returns: str: User id. """ return self.user_id def set_user_name(self, user_name): """Set user name. Args: user_name(str): User name. """ self.user_name = user_name def get_user_name(self): """Get user name. Returns: str: User name. """ return self.user_name def set_is_current_user(self, is_current_user): """Set whether it is current user or not. Args: is_current_user(bool): True if it is a current user else false. """ self.is_current_user = is_current_user def get_is_current_user(self): """Get whether it is current user or not. Returns: bool: True if it is current user else False. """ return self.is_current_user def set_log_date(self, log_date): """Set log date. Args: log_date(str): Log date. """ self.log_date = log_date def get_log_date(self): """Get log date. Returns: str: Log date. """ return self.log_date def set_begin_time(self, begin_time): """Set begin time. Args: begin_time(str): Begin time. """ self.begin_time = begin_time def get_begin_time(self): """Get begin time. Returns: str: Begin time. """ return self.begin_time def set_end_time(self, end_time): """Set end time. Args: end_time(str): End time. """ self.end_time = end_time def get_end_time(self): """Get end time. Returns: str: End time """ return self.end_time def set_log_time(self, log_time): """Set log time. Args: log_time(str): Log time. """ self.log_time = log_time def get_log_time(self): """Get log time. Returns: str: Log time. """ return self.log_time def set_billed_status(self, billed_status): """Set billed status. Args: billed_status(str): Billed status. """ self.billed_status = billed_status def get_billed_status(self): """Get billed status. Returns: str: Billed status. """ return self.billed_status def set_notes(self, notes): """Set notes. Args: notes(str): Notes. """ self.notes = notes def get_notes(self): """Get notes. Returns: str: Notes. """ return self.notes def set_timer_started_at(self, timer_started_at): """Set timer started at. Args: timer_started_at(str): Timer started at. """ self.timer_started_at = timer_started_at def get_timer_started_at(self): """Get timer started at. Returns: str: Timer started at. """ return self.timer_started_at def set_timer_duration_in_minutes(self, timer_duration_in_minutes): """Set timer duration in minutes. Args: timer_duration_in_minutes(int): Timer duration in minutes. """ self.timer_duration_in_minutes = timer_duration_in_minutes def get_timer_duration_in_minutes(self): """Get timer duration in minutes. Returns: str: Timer duration in minutes. """ return self.timer_duration_in_minutes def set_created_time(self, created_time): """Set created time. Args: created_time(str): Created time. """ self.created_time = created_time def get_created_time(self): """Get created time. Returns: str: Created time. """ return self.created_time def set_customer_id(self, customer_id): """Set customer id. Args: customer_id(str): Customer id. """ self.customer_id = customer_id def get_customer_id(self): """Get customer id. Returns: str: Customer id. """ return self.customer_id def set_customer_name(self, customer_name): """Set customer name. Args: customer_name(str): Customer name. """ self.customer_name = customer_name def get_customer_name(self): """Get customer name. Returns: str: Customer name. """ return self.customer_name def to_json(self): """This method is used to convert time entry object to json format. Returns: dict: Dictionary containing json object for time entry. """ data = {} if self.project_id != '': data['project_id'] = self.project_id if self.task_id != '': data['task_id'] = self.task_id if self.user_id != '': data['user_id'] = self.user_id if self.log_date != '': data['log_date'] = self.log_date if self.begin_time != '': data['begin_time'] = self.begin_time if self.end_time != '': data['end_time'] = self.end_time if self.log_time != '': data['log_time'] = self.log_time if self.notes != '': data['notes'] = self.notes if self.start_timer != '': data['start_timer'] = self.start_timer return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/TimeEntry.py", "copies": "1", "size": "8584", "license": "mit", "hash": 7271550929050448000, "line_mean": 19.7342995169, "line_max": 76, "alpha_frac": 0.4931267474, "autogenerated": false, "ratio": 4.011214953271028, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5004341700671029, "avg_score": null, "num_lines": null }
#$Id$ class Timelog: """This class is used to create object for time log.""" def __init__(self): """Initialize parameters for timelog.""" self.grandtotal = "" self.role = "" self.date = [] def set_grandtotal(self, grandtotal): """Set grand total. Args: grandtotal(str): Grand total. """ self.grandtotal = grandtotal def get_grandtotal(self): """Get grand total. Returns: str: Grand total. """ return self.grandtotal def set_role(self, role): """Set role. Args: role(str): Role. """ self.role = role def get_role(self): """Get role. Returns: str: Role. """ return self.role def set_date(self, date): """Set date. Args: date(instance): Date object. """ self.date.append(date) def get_date(self): """Get date. Returns: list of instance: List of Date object. """ return self.date
{ "repo_name": "zoho/projects-python-wrappers", "path": "projects/model/Timelog.py", "copies": "1", "size": "1138", "license": "mit", "hash": 4484984123238393300, "line_mean": 15.9850746269, "line_max": 59, "alpha_frac": 0.4683655536, "autogenerated": false, "ratio": 4.29433962264151, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.526270517624151, "avg_score": null, "num_lines": null }
#$Id$ class ToContact: """This class is used to create object for to Contacts.""" def __init__(self): """Initialize parameters for to contacts.""" self.first_name = '' self.selected = None self.phone = '' self.email = '' self.last_name = '' self.salutation = '' self.contact_person_id = '' self.mobile = '' def set_first_name(self, first_name): """Set first name. Args: first_name(str): First name. """ self.first_name = first_name def get_first_name(self): """Get first name. Returns: str: First name. """ return self.first_name def set_selected(self, selected): """Set selected. Args: selected(bool): Selected. """ self.selected = selected def get_selected(self): """Get selected. Returns: bool: Selected. """ return self.selected def set_phone(self, phone): """Set phone. Args: phone(str): Phone. """ self.phone = phone def get_phone(self): """Get phone. Returns: str: Phone. """ return self.phone def set_email(self, email): """Set email. Args: email(str): Email. """ self.email = email def get_email(self): """Get email. Returns: str: Email. """ return self.email def set_last_name(self, last_name): """Set last name. Args: last_name(str): Last name. """ self.last_name = last_name def get_last_name(self): """Get last name. Returns: str: Last name. """ return self.last_name def set_salutation(self, salutation): """Set salutation. Args: salutation(str): Salutation. """ self.salutation = salutation def get_salutation(self): """Get salutation. Returns: str: Salutation. """ return self.salutation def set_contact_person_id(self, contact_person_id): """Set contact person id. Args: contact_person_id(str): Contact person id. """ self.contact_person_id = contact_person_id def get_contact_person_id(self): """Get person id. Returns: str: Contact person id. """ return self.contact_person_id def set_mobile(self, mobile): """Set mobile. Args: mobile(str): Mobile. """ self.mobile = mobile def get_mobile(self): """Get mobile. Returns: str: Mobile. """ return self.mobile
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/ToContact.py", "copies": "1", "size": "2988", "license": "mit", "hash": 4369171642278946300, "line_mean": 17.4444444444, "line_max": 62, "alpha_frac": 0.4621820616, "autogenerated": false, "ratio": 4.311688311688312, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5273870373288312, "avg_score": null, "num_lines": null }
#$Id$ class Transaction: """This class is used to create object for transaction.""" def __init__(self): """Initialize parameters for transactions object.""" self.transaction_id = '' self.debit_or_credit = '' self.date = '' self.customer_id = '' self.payee = '' self.reference_number = '' self.transaction_type = '' self.amount = '' self.status = '' self.date_formatted = '' self.transaction_type_formatted = '' self.amount_formatted = '' self.customer_name = '' self.from_account_id = '' self.from_account_name = '' self.to_account_id = '' self.to_account_name = '' self.currency_id = '' self.currency_code = '' self.payment_mode = '' self.exchange_rate = 0.0 self.reference_number = '' self.description = '' self.imported_transaction_id = '' self.associated_transactions = [] self.categorized_transaction_id = '' self.transaction_date = '' self.account_id = '' self.entry_number = '' self.offset_account_name = '' self.reconcile_status = '' self.debit_amount = 0.0 self.credit_amount = 0.0 self.source = '' self.imported_transactions = [] self.status_formatted = '' def set_imported_transaction_id(self, imported_transaction_id): """Set imported transaction id. Args: imported_transaction_id(str): Imported transaction id. """ self.imported_transaction_id = imported_transaction_id def get_imported_transaction_id(self): """Get imported transaction id. Returns: str: Imported transaction id. """ return self.imported_transaction_id def set_transaction_id(self, transaction_id): """Set transaction id. Args: transaction_id(str): Transaction_id. """ self.transaction_id = transaction_id def get_transaction_id(self): """Get transaction id. Returns: str: Transaction id. """ return self.transaction_id def set_debit_or_credit(self, debit_or_credit): """Set whether debit or credit. Args: debit_or_credit(str): Debit or credit. """ self.debit_or_credit = debit_or_credit def get_debit_or_credit(self): """Get whether debit or credit. Returns: str: Debit or credit. """ return self.debit_or_credit def set_date(self, date): """Set date. Args: date(str): Date. """ self.date = date def get_date(self): """Get date. Returns: str: Date. """ return self.date def set_customer_id(self, customer_id): """Set customer id. Args: customer_id(self): Customer id. """ self.customer_id = customer_id def get_customer_id(self): """Get customer id. Returns: str: Customer id. """ return self.customer_id def set_payee(self, payee): """Set payee. Args: payee(str): Payee. """ self.payee = payee def get_payee(self): """Get payee. Returns: str: Payee. """ return self.payee def set_reference_number(self, reference_number): """Set reference number. Args: reference_number(str): Reference number. """ self.reference_number = reference_number def get_reference_number(self): """Get reference number. Returns: str: Reference number. """ return self.reference_number def set_transaction_type(self, transaction_type): """Set transaction type. Args: transaction_type(str): Transaction type. """ self.transaction_type = transaction_type def get_transaction_type(self): """Get transaction type. Returns: str: Transaction type. """ return self.transaction_type def set_amount(self, amount): """Set amount. Args: amount(float): Amount. """ self.amount = amount def get_amount(self): """Get amount. Returns: float: Amount. """ return self.amount def set_status(self, status): """Set status. Args: status(str): Status. """ self.status = status def get_status(self): """Get status. Returns: str: Status. """ return self.status def set_date_formatted(self, date_formatted): """Set date formatted. Args: date_formatted(str): Date formatted. """ self.date_formatted = date_formatted def get_date_formatted(self): """Get date formatted. Returns: str: Date formatted. """ def set_transaction_type_formatted(self, transaction_type_formatted): """Set transaction type formatted. Args: transaction_type_formatted(str): Transaction type formatted. """ self.transaction_type_formatted = transaction_type_formatted def get_transaction_type_formatted(self): """Get transaction type formatted. Returns: str: Transaction type formatted. """ return self.transaction_type_formatted def set_amount_formatted(self, amount_formatted): """Set amount formatted. Args: amount_formatted(str): Amount formatted. """ self.amount_formatted = amount_formatted def get_amount_formatted(self): """Get amount formatted. Returns: str: Amount formatted. """ return self.amount_formatted def set_customer_name(self, customer_name): """Set customer name. Args: customer_name(str): Customer name. """ self.customer_name = customer_name def get_customer_name(self): """Get customer name. Returns: str: Customer name. """ return self.customer_name def set_from_account_id(self, from_account_id): """Set from account id. Args: from_account_id(str): From account id. """ self.from_account_id = from_account_id def get_from_account_id(self): """Get from account id. Returns: str: From account id. """ return self.from_account_id def set_from_account_name(self, from_account_name): """Set from account name. Args: from_account_name(str): From account name. """ self.from_account_name = from_account_name def get_from_account_name(self): """Get from account name. Returns: str: From account name. """ return self.from_account_name def set_to_account_id(self, to_account_id): """Set to account id. Args: to_account_id(str): To account id. """ self.to_account_id = to_account_id def get_to_account_id(self): """Get to account id. Returns: str: To account id. """ return self.to_account_id def set_to_account_name(self, to_account_name): """Set to account name. Args: to_account_name(str): To account name. """ self.to_account_name = to_account_name def get_to_account_name(self): """Get to account name. Returns: str: To account name. """ return self.to_account_name def set_currency_id(self, currency_id): """Set currency id. Args: currency_id(str): Currency id. """ self.currecny_id = currency_id def get_currency_id(self): """Get currency id. Returns: str: Currecny id. """ return self.currency_id def set_currency_code(self, currency_code): """Set currecny code. Args: currency_code(str): Currecny code. """ self.currecy_code = currency_code def get_currency_code(self): """Get currecny code. Returns: str: Currecny code. """ return self.currecny_code def set_payment_mode(self, payment_mode): """Set payment mode. Args: payment_mode(str): Payment mode. """ self.payment_mode = payment_mode def get_payment_mode(self): """Get payment mode. Returns: str: Payment mode. """ return self.payment_mode def set_exchange_rate(self, exchange_rate): """Set exchange rate. Args: exchaneg_rate(float): Exchange rate. """ self.exchange_rate = exchange_rate def get_exchange_rate(self): """Get exchange rate. Returns: float: Exchange rate. """ return self.exchange_rate def set_description(self, description): """Set description. Args: description(str): Description. """ self.description = description def get_description(self): """Get description. Returns: str: Description. """ return self.description def set_currency_id(self, currency_id): """Set currency id. Args: currency_id(str): Currency id. """ self.currecny_id = currency_id def get_currency_id(self): """Get currecny id. Returns: str: Currency id. """ return self.currency_id def set_currency_code(self, currency_code): """Set currency code. Args: currency_code(str): Currency code. """ self.currency_code = currency_code def get_currecny_code(self): """Get currecny code. Returns: str: Currency code. """ return self.currency_code def set_payment_mode(self, payment_mode): """Set payment mode. Args: payment_mode(str): Payment mode. """ self.payment_mode = payment_mode def get_payment_mode(self): """Get payment mode. Returns: str: Payment mode. """ return self.payment_mode def set_exchange_rate(self, exchange_rate): """Set exchange rate. Args: exchange_rate(float): Exchange rate. """ self.exchange_rate = exchange_rate def get_exchange_rate(self): """Get exchange rate. Returns: float: Exchange rate. """ return self.exchange_rate def set_associated_transactions(self, transactions): """Set associated transacctions. Args: transactions(instance): Transaction object. """ self.associated_transactions.append(transactions) def get_associated_transactions(self): """Get associated transactions. Returns: list of instance: List of transactions object. """ return self.associated_transactions def set_categorized_transaction_id(self, categorized_transaction_id): """Set categorized transaction id. Args: categorized_transaction_id(str): Categorized transaction id. """ self.categorized_transaction_id = categorized_transaction_id def get_categorized_transaction_id(self): """Get categorized transaction id. Returns: str: Categorized transaction id. """ return self.categorized_transaction_id def set_transaction_date(self, transaction_date): """Set transaction date. Args: transaction_date(str): Transaction date. """ self.transaction_date = transaction_date def get_transaction_date(self): """Get transaction date. Returns: str: Transaction date. """ return self.transaction_date def set_account_id(self, account_id): """Set account id. Args: account_id(str): Account id. """ self.account_id = account_id def get_account_id(self): """Get account id. Returns: str: Account id. """ return self.account_id def set_entry_number(self, entry_number): """Set entry number. Args: entry_number(str): Entry number. """ self.entry_number = entry_number def get_entry_number(self): """Get entry number. Returns: str: Entry number. """ return self.entry_number def set_offset_account_name(self, offset_account_name): """Set offset account name. Args: offset_account_name(str): Offset account name. """ self.offset_account_name = offset_account_name def get_offset_account_name(self): """Get offset_account_name. Returns: str: Offset account name. """ return self.offset_account_name def set_reconcile_status(self, reconcile_status): """Set reconcile status. Args: reconcile_status(str): Reconcile status. """ self.reconcile_status = reconcile_status def get_reconcile_status(self): """Get reconcile status. Returns: str: Reconcile status. """ return self.reconcile_status def set_debit_amount(self, debit_amount): """Set debit amount. Args: debit_amount(float): Debit amount. """ self.debit_amount = debit_amount def get_debit_amount(self): """Get debit amount. Returns: float: Debit amount. """ return self.debit_amount def set_credit_amount(self, credit_amount): """Set ccredit amount. Args: credit_amount(flaot): Credit amount. """ self.credit_amount = credit_amount def get_credit_amount(self): """Get credit amount. Returns: float: Credit amount. """ return self.credit_amount def set_source(self, source): """Set source. Args: source(str): Source. """ self.source = source def get_source(self): """Get source. Returns: str: Source. """ return self.source def set_imported_transaction(self, imported_transactions): """Set imported transactions. Args: imported_transaction: Imported transaction. """ self.imported_transactions.append(imported_transactions) def get_imported_transaction(self): """Get imported transactions. Returns: list: List of imported transactions. """ return self.imported_transactions def set_status_formatted(self, status_formatted): """Set status formatted. Args: status_formatted(str): Status formatted. """ self.status_formatted = status_formatted def get_status_formatted(self): """Get status formatted. Returns: str: Status formatted. """ return self.status_formatted def to_json(self): """This method is used to convert taransaction object to json format. Returns: dict: Dictionary containing json object for transaction. """ data = {} if self.from_account_id != '': data['from_account_id'] = self.from_account_id if self.to_account_id != '': data['to_account_id'] = self.to_account_id if self.transaction_type != '': data['transaction_type'] = self.transaction_type if self.amount > 0: data['amount'] = self.amount if self.payment_mode != '': data['payment_mode'] = self.payment_mode if self.exchange_rate > 0: data['exchange_rate'] = self.exchange_rate if self.date != '': data['date'] = self.date if self.customer_id != '': data['customer_id'] = self.customer_id if self.reference_number != '': data['reference_number'] = self.reference_number if self.description != '': data['description'] = self.description if self.currency_id != '': data['currency_id'] = self.currency_id return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/Transaction.py", "copies": "1", "size": "16998", "license": "mit", "hash": -3423598206455031000, "line_mean": 20.8483290488, "line_max": 77, "alpha_frac": 0.5374161666, "autogenerated": false, "ratio": 4.408195020746888, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5445611187346888, "avg_score": null, "num_lines": null }
#$Id$ class User: """This class is used to create object for user.""" def __init__(self): """Initialize parameters for user object.""" self.id = "" self.name = "" self.email = "" self.role = "" def set_id(self, id): """Set id. Args: id(str): User id. """ self.id = id def get_id(self): """Get id. Returns: str: User id. """ return self.id def set_name(self, name): """Set name. Args: name(str): Name. """ self.name = name def get_name(self): """Get name. Returns: str: Name. """ return self.name def set_email(self, email): """Set email. Args: email(str): Email. """ self.email = email def get_email(self): """Get email. Returns: str: Email. """ return self.email def set_role(self, role): """Set role. Args: role(str): Role. """ self.role = role def get_role(self): """Get role. Returns: str: Role. """ return self.role
{ "repo_name": "zoho/projects-python-wrappers", "path": "projects/model/User.py", "copies": "1", "size": "1291", "license": "mit", "hash": 334228193418828740, "line_mean": 14.1882352941, "line_max": 55, "alpha_frac": 0.405112316, "autogenerated": false, "ratio": 4.17799352750809, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9915486795889042, "avg_score": 0.033523809523809525, "num_lines": 85 }
#$Id$ class User: """This class is used to create object for Users.""" def __init__(self): """Initialize parameters for Users object.""" self.user_id = '' self.is_current_user = None self.user_name = '' self.email = '' self.user_role = '' self.status = '' self.rate = 0.0 self.budget_hours = 0 self.total_hours = '' self.billed_hours = '' self.un_billed_hours = '' self.project_id = '' self.created_time = '' self.email_ids = [] self.role_id = '' self.name = '' self.photo_url = '' def set_photo_url(self, photo_url): """Set photo url. Args: photo_url(str): Photo url. """ self.photo_url = photo_url def get_photo_url(self): """Get photo url. Returns: str: Photo url. """ return self.photo_url def set_name(self, name): """Set name. Args: name(str): Name. """ self.name = name def get_name(self): """Get name. Returns: str: Name. """ return self.name def set_project_id(self, project_id): """Set project id. Args: project_id(str): Project id. """ self.project_id = project_id def get_project_id(self): """Get project id. Returns: str: Project id. """ return self.project_id def set_user_id(self, user_id): """Set user id. Args: user_id(str): User id. """ self.user_id = user_id def get_user_id(self): """Get user id. Returns: str: User id. """ return self.user_id def set_is_current_user(self, is_current_user): """Set whether it is current user or not. Args: is_current_user(bool): True if it is current user else False. """ self.is_current_user = is_current_user def get_is_current_user(self): """Get whether it is current user. Returns: bool: True if it is a current user else False. """ return self.is_current_user def set_user_name(self, user_name): """Set user name. Args: user_name(str): User name. """ self.user_name = user_name def get_user_name(self): """Get user name. Returns: str: User name """ return self.user_name def set_email(self, email): """Set email. Args: email(str): Email. """ self.email = email def get_email(self): """Get email. Returns: str: Email. """ return self.email def set_user_role(self, user_role): """Set user role. Args: user_role(str): User role. """ self.user_role = user_role def get_user_role(self): """Get user role. Returns: str: User role. """ return self.user_role def set_status(self, status): """Set status. Args: status(str): Status. """ self.status = status def get_status(self): """Get status. Returns: str: Status. """ return self.status def set_rate(self, rate): """Set rate. Args: rate(float): Rate. """ self.rate = rate def get_rate(self): """Get rate. Returns: float: Rate. """ return self.rate def set_budget_hours(self, budget_hours): """Set budget hours. Args: budget_hours(int): Budget hours. """ self.budget_hours = budget_hours def get_budget_hours(self): """Get budget hours. Returns: int: Budget hours. """ return self.budget_hours def set_total_hours(self, total_hours): """Set total hours. Args: total_hours(str): Total hours. """ self.total_hours = total_hours def get_total_hours(self): """Get total hours. Returns: str: Total hours. """ return self.total_hours def set_billed_hours(self, billed_hours): """Set billed hours. Args: billed_hours(str): Billed hours. """ self.billed_hours = billed_hours def get_billed_hours(self): """Get billed hours. Returns: str: Billed hours. """ return self.billed_hours def set_status(self, status): """Set status. Args: status(str): Status. """ self.status = status def get_status(self): """Get status. Returns: str: Status. """ return self.status def set_rate(self, rate): """Set rate. Args: rate(float): Rate """ self.rate = rate def get_rate(self): """Get rate. Returns: float: Rate. """ return self.rate def budget_hours(self, budget_hours): """Set budget hours. Args: budget_hours(str): Budget hours. """ self.budget_hours = budget_hours def get_budget_hours(self): """Get budget hours. Returns: str: Budget hours. """ return self.budget_hours def set_total_hours(self, total_hours): """Set total hours. Args: total_hours(str): Total hours. """ self.total_hours = total_hours def get_total_hours(self): """Get total hours. Returns: str: Total hours. """ return self.total_hours def set_billed_hours(self, billed_hours): """Set billed hours. Args: billed_hours(str): Billed hours. """ self.billed_hours = billed_hours def get_billed_hours(self): """Get billed hours. Returns: str: Billed hours. """ return self.billed_hours def set_un_billed_hours(self, un_billed_hours): """Set unbilled hours. Args: un_billed_hours(str): Un billed hours. """ self.un_billed_hours = un_billed_hours def get_un_billed_hours(self): """Get unbilled hours. Returns: str: Unbilled hours. """ return self.un_billed_hours def set_created_time(self, created_time): """Set created time. Args: created_time(str): Created time. """ self.created_time = created_time def get_created_time(self): """Get created time. Returns: str: Created time. """ return self.created_time def set_email_ids(self, email_ids): """Set email ids. Args: email_ids(instance): Email ids object. """ self.email_ids = email_ids def get_email_ids(self): """Get email ids. Returns: list of instance: list of Email ids object. """ return self.email_ids def set_role_id(self, role_id): """Set role id. Args: role_id(str): Role id. """ self.role_id = role_id def get_role_id(self): """Get role id. Returns: str: Role id. """ return self.role_id def to_json(self): """This method is used to convert user object to json format. Returns: dict: Dictionary containing json object for user. """ data = {} if self.user_id != '': data['user_id'] = self.user_id if self.rate > 0: data['rate'] = self.rate if self.budget_hours > 0: data['budget_hours'] = self.budget_hours if self.user_name != '': data['user_name'] = self.user_name if self.email != '': data['email'] = self.email if self.user_role != '': data['user_role'] = self.user_role if self.name != '': data['name'] = self.name return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/User.py", "copies": "1", "size": "8482", "license": "mit", "hash": 4149750330197514000, "line_mean": 18.1036036036, "line_max": 73, "alpha_frac": 0.4757132752, "autogenerated": false, "ratio": 4.040971891376846, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9973897592964966, "avg_score": 0.008557514722375904, "num_lines": 444 }
#$Id$ class VendorPayment: """This class is used to create object for Vendor payments.""" def __init__(self): """Initialize parameters for Vendor payments.""" self.payment_id = '' self.vendor_id = '' self.vendor_name = '' self.payment_mode = '' self.description = '' self.date = '' self.reference_number = '' self.exchange_rate = 0.0 self.amount = 0.0 self.currency_symbol = '' self.paid_through_account_id = '' self.paid_through_account_name = '' self.bills = [] self.balance = 0.0 def set_payment_id(self, payment_id): """Set payment id. Args: payment_id(str): Payment id. """ self.payment_id = payment_id def get_payment_id(self): """Get payment id. Returns: str: Payment id. """ return self.payment_id def set_vendor_id(self, vendor_id): """Set vendor id. Args: vendor_id(str): Vendor id. """ self.vendor_id = vendor_id def get_vendor_id(self): """Get vendor id. Returns: str: Vendor id. """ return self.vendor_id def set_vendor_name(self, vendor_name): """Set vendor name. Args: vendor_name(str): Vendor name. """ self.vendor_name = vendor_name def get_vendor_name(self): """Get vendor name. Returns: str: Vendor name. """ return self.vendor_name def set_payment_mode(self, payment_mode): """Set payment mode. Args: payment_mode(str): Payment mode. """ self.payment_mode = payment_mode def get_payment_mode(self): """Get payment mode. Returns: str: Payment mode. """ return self.payment_mode def set_description(self, description): """Set description. Args: description(str): Description. """ self.description = description def get_description(self): """Get description. Returns: str: Description. """ return self.description def set_date(self, date): """Set date. Args: date(str): Date. """ self.date = date def get_date(self): """Get date. Returns: str: Date. """ return self.date def set_reference_number(self, reference_number): """Set reference number. Args: reference_number(str): Reference number. """ self.reference_number = reference_number def get_reference_number(self): """Get reference number. Returns: str: Reference number. """ return self.reference_number def set_exchange_rate(self, exchange_rate): """Set exchange rate. Args: exchange_rate(float): Exchange rate. """ self.exchange_rate = exchange_rate def get_exchange_rate(self): """Get exchange rate. Returns: float: Exchange rate. """ return self.exchange_rate def set_amount(self, amount): """Set amount. Args: amount(float): Amount. """ self.amount = amount def get_amount(self): """Get amount. Returns: float: Amount. """ return self.amount def set_currency_symbol(self, currency_symbol): """Set currency symbol. Args: currency_symbol(str): Currency symbol. """ self.currency_symbol = currency_symbol def get_currency_symbol(self): """Get currency symbol. Returns: str: Currency symbol. """ return self.currency_symbol def set_paid_through_account_id(self, paid_through_account_id): """Set paid through account id. Args: paid_through_account_id(str): Paid through account id. """ self.paid_through_account_id = paid_through_account_id def get_paid_through_account_id(self): """Get paid through account id. Returns: str: Paid through acount id. """ return self.paid_through_account_id def set_paid_through_account_name(self, paid_through_account_name): """Set paid through account name. Args: paid_through_account_name(str): Paid through account name. """ self.paid_through_account_name = paid_through_account_name def get_paid_through_account_name(self): """Get paid through account name. Returns: str: Paid through account name. """ return self.paid_through_account_name def set_bills(self, bill): """Set bills. Args: bills(instance): Bills object. """ self.bills.append(bill) def get_bills(self): """Get bills. Returns: list of instance: List of bills object. """ return self.bills def set_balance(self, balance): """Set balance. Args: balance(float): Balance. """ self.balance = balance def get_balance(self): """Get balance. Returns: float: Balance. """ return self.balance def to_json(self): """This method is used to convert vendor payments object to json object. Returns: dict: Dictionary containing json object for vendor payments. """ data = {} if self.vendor_id != '': data['vendor_id'] = self.vendor_id if self.bills: data['bills'] = [] for value in self.bills: bill = value.to_json() data['bills'].append(bill) if self.payment_mode != '': data['payment_mode'] = self.payment_mode if self.description != '': data['description'] = self.description if self.date != '': data['date'] = self.date if self.reference_number != '': data['reference_number'] = self.reference_number if self.exchange_rate > 0: data['exchange_rate'] = self.exchange_rate if self.amount > 0: data['amount'] = self.amount if self.paid_through_account_id != '': data['paid_through_account_id'] = self.paid_through_account_id return data
{ "repo_name": "zoho/books-python-wrappers", "path": "books/model/VendorPayment.py", "copies": "1", "size": "6674", "license": "mit", "hash": 3273949323260421000, "line_mean": 20.8819672131, "line_max": 80, "alpha_frac": 0.5185795625, "autogenerated": false, "ratio": 4.2974887314874435, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5316068293987444, "avg_score": null, "num_lines": null }
#$Id$ class Version: """This class is used to create object for Version.""" def __init__(self): """Initialize parameters for version.""" self.id = "" self.uploaded_by = "" self.description = "" self.file_size = "" self.version = "" self.uploaded_date = "" self.uploaded_date_long = 0 def set_id(self, id): """Set id. Args: id(long): Id. """ self.id = id def get_id(self): """Get id. Returns: long: Id. """ return self.id def set_uploaded_by(self, uploaded_by): """Set uploaded by. Args: uploaded_by(str): Uploaded by. """ self.uploaded_by = uploaded_by def get_uploaded_by(self): """Get uploaded by. Returns: str: Uploaded by. """ return self.uploaded_by def set_description(self, description): """Set description. Args: description(str): Description. """ self.description = description def get_description(self): """Get description. Returns: str: Description. """ return self.description def set_file_size(self, file_size): """Set file size. Args: file_size(str): File size. """ self.file_size = file_size def get_file_size(self): """Get file size. Returns: str: File size. """ return self.file_size def set_version(self, version): """Set version. Args: version(str): Version. """ self.version = version def get_version(self): """Get version. Returns: str: Version. """ return self.version def set_uploaded_date(self, uploaded_date): """Set uploaded date. Args: uploaded_date(str): Uploaded date. """ self.uploaded_date = uploaded_date def get_uploaded_date(self): """Get uploaded date. Returns: str: Uploaded date. """ return self.uploaded_date def set_uploaded_date_long(self, uploaded_date_long): """Set uploaded date long. Args: uploaded_date_long(long): Uploaded date long. """ self.uploaded_date_long = uploaded_date_long def get_uploaded_date_long(self): """Get uploaded date long. Returns: long: Uploaded date long. """ return self.uploaded_date_long
{ "repo_name": "zoho/projects-python-wrappers", "path": "projects/model/Version.py", "copies": "1", "size": "2664", "license": "mit", "hash": -5722505533406240000, "line_mean": 17.7605633803, "line_max": 58, "alpha_frac": 0.4947447447, "autogenerated": false, "ratio": 4.360065466448445, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.010777787538350918, "num_lines": 142 }
""" a set of functions for interacting with databases When possible, it's probably preferable to use a _DbConnection.DbConnect_ object """ from __future__ import print_function from rdkit import RDConfig from rdkit.Dbase.DbResultSet import DbResultSet,RandomAccessDbResultSet def _take(fromL,what): return map(lambda x,y=fromL:y[x],what) from rdkit.Dbase import DbModule import sys from rdkit.Dbase import DbInfo from rdkit.six.moves import xrange #@UnresolvedImport #pylint: disable=F0401 from rdkit.six import string_types def GetColumns(dBase,table,fieldString,user='sysdba',password='masterkey', join='',cn=None): """ gets a set of data from a table **Arguments** - dBase: database name - table: table name - fieldString: a string with the names of the fields to be extracted, this should be a comma delimited list - user and password: - join: a join clause (omit the verb 'join') **Returns** - a list of the data """ if not cn: cn = DbModule.connect(dBase,user,password) c = cn.cursor() cmd = 'select %s from %s'%(fieldString,table) if join: if join.strip().find('join') != 0: join = 'join %s'%(join) cmd +=' ' + join c.execute(cmd) return c.fetchall() def GetData(dBase,table,fieldString='*',whereString='',user='sysdba',password='masterkey', removeDups=-1,join='',forceList=0,transform=None,randomAccess=1,extras=None,cn=None): """ a more flexible method to get a set of data from a table **Arguments** - fields: a string with the names of the fields to be extracted, this should be a comma delimited list - where: the SQL where clause to be used with the DB query - removeDups indicates the column which should be used to screen out duplicates. Only the first appearance of a duplicate will be left in the dataset. **Returns** - a list of the data **Notes** - EFF: this isn't particularly efficient """ if not cn: cn = DbModule.connect(dBase,user,password) c = cn.cursor() cmd = 'select %s from %s'%(fieldString,table) if join: if join.strip().find('join') != 0: join = 'join %s'%(join) cmd += ' ' + join if whereString: if whereString.strip().find('where')!=0: whereString = 'where %s'%(whereString) cmd += ' ' + whereString if forceList: try: if not extras: c.execute(cmd) else: c.execute(cmd,extras) except Exception: sys.stderr.write('the command "%s" generated errors:\n'%(cmd)) import traceback traceback.print_exc() return None if transform is not None: raise ValueError('forceList and transform arguments are not compatible') if not randomAccess: raise ValueError('when forceList is set, randomAccess must also be used') data = c.fetchall() if removeDups>0: seen = [] for entry in data[:]: if entry[removeDups] in seen: data.remove(entry) else: seen.append(entry[removeDups]) else: if randomAccess: klass = RandomAccessDbResultSet else: klass = DbResultSet data = klass(c,cn,cmd,removeDups=removeDups,transform=transform,extras=extras) return data def DatabaseToText(dBase,table,fields='*',join='',where='', user='sysdba',password='masterkey',delim=',',cn=None): """ Pulls the contents of a database and makes a deliminted text file from them **Arguments** - dBase: the name of the DB file to be used - table: the name of the table to query - fields: the fields to select with the SQL query - join: the join clause of the SQL query (e.g. 'join foo on foo.bar=base.bar') - where: the where clause of the SQL query (e.g. 'where foo = 2' or 'where bar > 17.6') - user: the username for DB access - password: the password to be used for DB access **Returns** - the CSV data (as text) """ if len(where) and where.strip().find('where')==-1: where = 'where %s'%(where) if len(join) and join.strip().find('join') == -1: join = 'join %s'%(join) sqlCommand = 'select %s from %s %s %s'%(fields,table,join,where) if not cn: cn = DbModule.connect(dBase,user,password) c = cn.cursor() c.execute(sqlCommand) headers = [] colsToTake = [] # the description field of the cursor carries around info about the columns # of the table for i in range(len(c.description)): item = c.description[i] if item[1] not in DbInfo.sqlBinTypes: colsToTake.append(i) headers.append(item[0]) lines = [] lines.append(delim.join(headers)) # grab the data results = c.fetchall() for res in results: d = _take(res,colsToTake) lines.append(delim.join(map(str,d))) return '\n'.join(lines) def TypeFinder(data,nRows,nCols,nullMarker=None): """ finds the types of the columns in _data_ if nullMarker is not None, elements of the data table which are equal to nullMarker will not count towards setting the type of their columns. """ priorities={float:3,int:2,str:1,-1:-1} res = [None]*nCols for col in xrange(nCols): typeHere = [-1,1] for row in xrange(nRows): d = data[row][col] if d is not None: locType = type(d) if locType != float and locType != int: locType = str try: d = str(d) except UnicodeError as msg: print('cannot convert text from row %d col %d to a string'%(row+2,col)) print('\t>%s'%(repr(d))) raise UnicodeError(msg) else: typeHere[1] = max(typeHere[1],len(str(d))) if isinstance(d, string_types): if nullMarker is None or d != nullMarker: l = max(len(d),typeHere[1]) typeHere = [str,l] else: try: fD = float(int(d)) except OverflowError: locType = float else: if fD == d: locType = int if not isinstance(typeHere[0], string_types) and \ priorities[locType] > priorities[typeHere[0]]: typeHere[0] = locType res[col] = typeHere return res def _AdjustColHeadings(colHeadings,maxColLabelLen): """ *For Internal Use* removes illegal characters from column headings and truncates those which are too long. """ for i in xrange(len(colHeadings)): # replace unallowed characters and strip extra white space colHeadings[i] = colHeadings[i].strip() colHeadings[i] = colHeadings[i].replace(' ','_') colHeadings[i] = colHeadings[i].replace('-','_') colHeadings[i] = colHeadings[i].replace('.','_') if len(colHeadings[i]) > maxColLabelLen: # interbase (at least) has a limit on the maximum length of a column name newHead = colHeadings[i].replace('_','') newHead = newHead[:maxColLabelLen] print('\tHeading %s too long, changed to %s'%(colHeadings[i],newHead)) colHeadings[i] = newHead return colHeadings def GetTypeStrings(colHeadings,colTypes,keyCol=None): """ returns a list of SQL type strings """ typeStrs=[] for i in xrange(len(colTypes)): typ = colTypes[i] if typ[0] == float: typeStrs.append('%s double precision'%colHeadings[i]) elif typ[0] == int: typeStrs.append('%s integer'%colHeadings[i]) else: typeStrs.append('%s varchar(%d)'%(colHeadings[i],typ[1])) if colHeadings[i] == keyCol: typeStrs[-1] = '%s not null primary key'%(typeStrs[-1]) return typeStrs def _insertBlock(conn,sqlStr,block,silent=False): try: conn.cursor().executemany(sqlStr,block) except Exception: res = 0 conn.commit() for row in block: try: conn.cursor().execute(sqlStr,tuple(row)) res += 1 except Exception: if not silent: import traceback traceback.print_exc() print('insert failed:',sqlStr) print('\t',repr(row)) else: conn.commit() else: res = len(block) return res def _AddDataToDb(dBase,table,user,password,colDefs,colTypes,data, nullMarker=None,blockSize=100,cn=None): """ *For Internal Use* (drops and) creates a table and then inserts the values """ if not cn: cn = DbModule.connect(dBase,user,password) c = cn.cursor() try: c.execute('drop table %s'%(table)) except Exception: print('cannot drop table %s'%(table)) try: sqlStr = 'create table %s (%s)'%(table,colDefs) c.execute(sqlStr) except Exception: print('create table failed: ', sqlStr) print('here is the exception:') import traceback traceback.print_exc() return cn.commit() c = None block = [] entryTxt = [DbModule.placeHolder]*len(data[0]) dStr = ','.join(entryTxt) sqlStr = 'insert into %s values (%s)'%(table,dStr) nDone = 0 for row in data: entries = [None]*len(row) for col in xrange(len(row)): if row[col] is not None and \ (nullMarker is None or row[col] != nullMarker): if colTypes[col][0] == float: entries[col] = float(row[col]) elif colTypes[col][0] == int: entries[col] = int(row[col]) else: entries[col] = str(row[col]) else: entries[col] = None block.append(tuple(entries)) if len(block)>=blockSize: nDone += _insertBlock(cn,sqlStr,block) if not hasattr(cn,'autocommit') or not cn.autocommit: cn.commit() block = [] if len(block): nDone += _insertBlock(cn,sqlStr,block) if not hasattr(cn,'autocommit') or not cn.autocommit: cn.commit() def TextFileToDatabase(dBase,table,inF,delim=',', user='sysdba',password='masterkey', maxColLabelLen=31,keyCol=None,nullMarker=None): """loads the contents of the text file into a database. **Arguments** - dBase: the name of the DB to use - table: the name of the table to create/overwrite - inF: the file like object from which the data should be pulled (must support readline()) - delim: the delimiter used to separate fields - user: the user name to use in connecting to the DB - password: the password to use in connecting to the DB - maxColLabelLen: the maximum length a column label should be allowed to have (truncation otherwise) - keyCol: the column to be used as an index for the db **Notes** - if _table_ already exists, it is destroyed before we write the new data - we assume that the first row of the file contains the column names """ table.replace('-','_') table.replace(' ','_') colHeadings = inF.readline().split(delim) _AdjustColHeadings(colHeadings,maxColLabelLen) nCols = len(colHeadings) data = [] inL = inF.readline() while inL: inL = inL.replace('\r','') inL = inL.replace('\n','') splitL = inL.split(delim) if len(splitL)!=nCols: print('>>>',repr(inL)) assert len(splitL)==nCols,'unequal length' tmpVect = [] for entry in splitL: try: val = int(entry) except ValueError: try: val = float(entry) except ValueError: val = entry tmpVect.append(val) data.append(tmpVect) inL = inF.readline() nRows = len(data) # determine the types of each column colTypes = TypeFinder(data,nRows,nCols,nullMarker=nullMarker) typeStrs = GetTypeStrings(colHeadings,colTypes,keyCol=keyCol) colDefs=','.join(typeStrs) _AddDataToDb(dBase,table,user,password,colDefs,colTypes,data, nullMarker=nullMarker) def DatabaseToDatabase(fromDb,fromTbl,toDb,toTbl, fields='*',join='',where='', user='sysdba',password='masterkey',keyCol=None,nullMarker='None'): """ FIX: at the moment this is a hack """ from io import StringIO sio = StringIO() sio.write(DatabaseToText(fromDb,fromTbl,fields=fields,join=join,where=where, user=user,password=password)) sio.seek(-1) TextFileToDatabase(toDb,toTbl,sio,user=user,password=password,keyCol=keyCol, nullMarker=nullMarker) if __name__=='__main__': from io import StringIO sio = StringIO() sio.write('foo,bar,baz\n') sio.write('1,2,3\n') sio.write('1.1,4,5\n') sio.write('4,foo,6\n') sio.seek(0) from rdkit import RDConfig import os dirLoc = os.path.join(RDConfig.RDCodeDir,'Dbase','TEST.GDB') TextFileToDatabase(dirLoc,'fromtext',sio)
{ "repo_name": "adalke/rdkit", "path": "rdkit/Dbase/DbUtils.py", "copies": "1", "size": "12953", "license": "bsd-3-clause", "hash": -3051368705880302000, "line_mean": 27.657079646, "line_max": 97, "alpha_frac": 0.621091639, "autogenerated": false, "ratio": 3.534242837653479, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9500078256352631, "avg_score": 0.031051244060169476, "num_lines": 452 }
""" a set of functions for interacting with databases When possible, it's probably preferable to use a _DbConnection.DbConnect_ object """ from __future__ import print_function import sys from rdkit.Dbase import DbInfo from rdkit.Dbase import DbModule from rdkit.Dbase.DbResultSet import DbResultSet, RandomAccessDbResultSet from rdkit.six import string_types, StringIO from rdkit.six.moves import xrange def _take(fromL, what): """ Given a list fromL, returns an iterator of the elements specified using their indices in the list what """ return map(lambda x, y=fromL: y[x], what) def GetColumns(dBase, table, fieldString, user='sysdba', password='masterkey', join='', cn=None): """ gets a set of data from a table **Arguments** - dBase: database name - table: table name - fieldString: a string with the names of the fields to be extracted, this should be a comma delimited list - user and password: - join: a join clause (omit the verb 'join') **Returns** - a list of the data """ if not cn: cn = DbModule.connect(dBase, user, password) c = cn.cursor() cmd = 'select %s from %s' % (fieldString, table) if join: if join.strip().find('join') != 0: join = 'join %s' % (join) cmd += ' ' + join c.execute(cmd) return c.fetchall() def GetData(dBase, table, fieldString='*', whereString='', user='sysdba', password='masterkey', removeDups=-1, join='', forceList=0, transform=None, randomAccess=1, extras=None, cn=None): """ a more flexible method to get a set of data from a table **Arguments** - fields: a string with the names of the fields to be extracted, this should be a comma delimited list - where: the SQL where clause to be used with the DB query - removeDups indicates the column which should be used to screen out duplicates. Only the first appearance of a duplicate will be left in the dataset. **Returns** - a list of the data **Notes** - EFF: this isn't particularly efficient """ if forceList and (transform is not None): raise ValueError('forceList and transform arguments are not compatible') if forceList and (not randomAccess): raise ValueError('when forceList is set, randomAccess must also be used') if removeDups > -1: forceList = True if not cn: cn = DbModule.connect(dBase, user, password) c = cn.cursor() cmd = 'select %s from %s' % (fieldString, table) if join: if join.strip().find('join') != 0: join = 'join %s' % (join) cmd += ' ' + join if whereString: if whereString.strip().find('where') != 0: whereString = 'where %s' % (whereString) cmd += ' ' + whereString if forceList: try: if not extras: c.execute(cmd) else: c.execute(cmd, extras) except Exception: sys.stderr.write('the command "%s" generated errors:\n' % (cmd)) import traceback traceback.print_exc() return None if transform is not None: raise ValueError('forceList and transform arguments are not compatible') if not randomAccess: raise ValueError('when forceList is set, randomAccess must also be used') data = c.fetchall() if removeDups >= 0: seen = set() for entry in data[:]: if entry[removeDups] in seen: data.remove(entry) else: seen.add(entry[removeDups]) else: if randomAccess: klass = RandomAccessDbResultSet else: klass = DbResultSet data = klass(c, cn, cmd, removeDups=removeDups, transform=transform, extras=extras) return data def DatabaseToText(dBase, table, fields='*', join='', where='', user='sysdba', password='masterkey', delim=',', cn=None): """ Pulls the contents of a database and makes a deliminted text file from them **Arguments** - dBase: the name of the DB file to be used - table: the name of the table to query - fields: the fields to select with the SQL query - join: the join clause of the SQL query (e.g. 'join foo on foo.bar=base.bar') - where: the where clause of the SQL query (e.g. 'where foo = 2' or 'where bar > 17.6') - user: the username for DB access - password: the password to be used for DB access **Returns** - the CSV data (as text) """ if len(where) and where.strip().find('where') == -1: where = 'where %s' % (where) if len(join) and join.strip().find('join') == -1: join = 'join %s' % (join) sqlCommand = 'select %s from %s %s %s' % (fields, table, join, where) if not cn: cn = DbModule.connect(dBase, user, password) c = cn.cursor() c.execute(sqlCommand) headers = [] colsToTake = [] # the description field of the cursor carries around info about the columns # of the table for i in range(len(c.description)): item = c.description[i] if item[1] not in DbInfo.sqlBinTypes: colsToTake.append(i) headers.append(item[0]) lines = [] lines.append(delim.join(headers)) # grab the data results = c.fetchall() for res in results: d = _take(res, colsToTake) lines.append(delim.join(map(str, d))) return '\n'.join(lines) def TypeFinder(data, nRows, nCols, nullMarker=None): """ finds the types of the columns in _data_ if nullMarker is not None, elements of the data table which are equal to nullMarker will not count towards setting the type of their columns. """ priorities = {float: 3, int: 2, str: 1, -1: -1} res = [None] * nCols for col in xrange(nCols): typeHere = [-1, 1] for row in xrange(nRows): d = data[row][col] if d is None: continue locType = type(d) if locType != float and locType != int: locType = str try: d = str(d) except UnicodeError as msg: print('cannot convert text from row %d col %d to a string' % (row + 2, col)) print('\t>%s' % (repr(d))) raise UnicodeError(msg) else: typeHere[1] = max(typeHere[1], len(str(d))) if isinstance(d, string_types): if nullMarker is None or d != nullMarker: l = max(len(d), typeHere[1]) typeHere = [str, l] else: try: fD = float(int(d)) except OverflowError: locType = float else: if fD == d: locType = int if not isinstance(typeHere[0], string_types) and \ priorities[locType] > priorities[typeHere[0]]: typeHere[0] = locType res[col] = typeHere return res def _AdjustColHeadings(colHeadings, maxColLabelLen): """ *For Internal Use* removes illegal characters from column headings and truncates those which are too long. """ for i in xrange(len(colHeadings)): # replace unallowed characters and strip extra white space colHeadings[i] = colHeadings[i].strip() colHeadings[i] = colHeadings[i].replace(' ', '_') colHeadings[i] = colHeadings[i].replace('-', '_') colHeadings[i] = colHeadings[i].replace('.', '_') if len(colHeadings[i]) > maxColLabelLen: # interbase (at least) has a limit on the maximum length of a column name newHead = colHeadings[i].replace('_', '') newHead = newHead[:maxColLabelLen] print('\tHeading %s too long, changed to %s' % (colHeadings[i], newHead)) colHeadings[i] = newHead return colHeadings def GetTypeStrings(colHeadings, colTypes, keyCol=None): """ returns a list of SQL type strings """ typeStrs = [] for i in xrange(len(colTypes)): typ = colTypes[i] if typ[0] == float: typeStrs.append('%s double precision' % colHeadings[i]) elif typ[0] == int: typeStrs.append('%s integer' % colHeadings[i]) else: typeStrs.append('%s varchar(%d)' % (colHeadings[i], typ[1])) if colHeadings[i] == keyCol: typeStrs[-1] = '%s not null primary key' % (typeStrs[-1]) return typeStrs def _insertBlock(conn, sqlStr, block, silent=False): try: conn.cursor().executemany(sqlStr, block) except Exception: res = 0 conn.commit() for row in block: try: conn.cursor().execute(sqlStr, tuple(row)) res += 1 except Exception: if not silent: import traceback traceback.print_exc() print('insert failed:', sqlStr) print('\t', repr(row)) else: conn.commit() else: res = len(block) return res def _AddDataToDb(dBase, table, user, password, colDefs, colTypes, data, nullMarker=None, blockSize=100, cn=None): """ *For Internal Use* (drops and) creates a table and then inserts the values """ if not cn: cn = DbModule.connect(dBase, user, password) c = cn.cursor() try: c.execute('drop table %s' % (table)) except Exception: print('cannot drop table %s' % (table)) try: sqlStr = 'create table %s (%s)' % (table, colDefs) c.execute(sqlStr) except Exception: print('create table failed: ', sqlStr) print('here is the exception:') import traceback traceback.print_exc() return cn.commit() c = None block = [] entryTxt = [DbModule.placeHolder] * len(data[0]) dStr = ','.join(entryTxt) sqlStr = 'insert into %s values (%s)' % (table, dStr) nDone = 0 for row in data: entries = [None] * len(row) for col in xrange(len(row)): if row[col] is not None and \ (nullMarker is None or row[col] != nullMarker): if colTypes[col][0] == float: entries[col] = float(row[col]) elif colTypes[col][0] == int: entries[col] = int(row[col]) else: entries[col] = str(row[col]) else: entries[col] = None block.append(tuple(entries)) if len(block) >= blockSize: nDone += _insertBlock(cn, sqlStr, block) if not hasattr(cn, 'autocommit') or not cn.autocommit: cn.commit() block = [] if len(block): nDone += _insertBlock(cn, sqlStr, block) if not hasattr(cn, 'autocommit') or not cn.autocommit: cn.commit() def TextFileToDatabase(dBase, table, inF, delim=',', user='sysdba', password='masterkey', maxColLabelLen=31, keyCol=None, nullMarker=None): """loads the contents of the text file into a database. **Arguments** - dBase: the name of the DB to use - table: the name of the table to create/overwrite - inF: the file like object from which the data should be pulled (must support readline()) - delim: the delimiter used to separate fields - user: the user name to use in connecting to the DB - password: the password to use in connecting to the DB - maxColLabelLen: the maximum length a column label should be allowed to have (truncation otherwise) - keyCol: the column to be used as an index for the db **Notes** - if _table_ already exists, it is destroyed before we write the new data - we assume that the first row of the file contains the column names """ table.replace('-', '_') table.replace(' ', '_') colHeadings = inF.readline().split(delim) _AdjustColHeadings(colHeadings, maxColLabelLen) nCols = len(colHeadings) data = [] inL = inF.readline() while inL: inL = inL.replace('\r', '') inL = inL.replace('\n', '') splitL = inL.split(delim) if len(splitL) != nCols: print('>>>', repr(inL)) assert len(splitL) == nCols, 'unequal length' tmpVect = [] for entry in splitL: try: val = int(entry) except ValueError: try: val = float(entry) except ValueError: val = entry tmpVect.append(val) data.append(tmpVect) inL = inF.readline() nRows = len(data) # determine the types of each column colTypes = TypeFinder(data, nRows, nCols, nullMarker=nullMarker) typeStrs = GetTypeStrings(colHeadings, colTypes, keyCol=keyCol) colDefs = ','.join(typeStrs) _AddDataToDb(dBase, table, user, password, colDefs, colTypes, data, nullMarker=nullMarker) def DatabaseToDatabase(fromDb, fromTbl, toDb, toTbl, fields='*', join='', where='', user='sysdba', password='masterkey', keyCol=None, nullMarker='None'): """ FIX: at the moment this is a hack """ sio = StringIO() sio.write( DatabaseToText(fromDb, fromTbl, fields=fields, join=join, where=where, user=user, password=password)) sio.seek(0) TextFileToDatabase(toDb, toTbl, sio, user=user, password=password, keyCol=keyCol, nullMarker=nullMarker) if __name__ == '__main__': # pragma: nocover sio = StringIO() sio.write('foo,bar,baz\n') sio.write('1,2,3\n') sio.write('1.1,4,5\n') sio.write('4,foo,6\n') sio.seek(0) from rdkit import RDConfig import os dirLoc = os.path.join(RDConfig.RDCodeDir, 'Dbase', 'TEST.GDB') TextFileToDatabase(dirLoc, 'fromtext', sio)
{ "repo_name": "rvianello/rdkit", "path": "rdkit/Dbase/DbUtils.py", "copies": "4", "size": "13335", "license": "bsd-3-clause", "hash": 5275735814821164000, "line_mean": 27.5546038544, "line_max": 100, "alpha_frac": 0.6197975253, "autogenerated": false, "ratio": 3.532450331125828, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.01689771615124007, "num_lines": 467 }
""" a set of functions for interacting with databases When possible, it's probably preferable to use a _DbConnection.DbConnect_ object """ from rdkit import RDConfig from rdkit.Dbase.DbResultSet import DbResultSet,RandomAccessDbResultSet def _take(fromL,what): return map(lambda x,y=fromL:y[x],what) from rdkit.Dbase import DbModule import sys,types,string from rdkit.Dbase import DbInfo def GetColumns(dBase,table,fieldString,user='sysdba',password='masterkey', join='',cn=None): """ gets a set of data from a table **Arguments** - dBase: database name - table: table name - fieldString: a string with the names of the fields to be extracted, this should be a comma delimited list - user and password: - join: a join clause (omit the verb 'join') **Returns** - a list of the data """ if not cn: cn = DbModule.connect(dBase,user,password) c = cn.cursor() cmd = 'select %s from %s'%(fieldString,table) if join: if join.strip().find('join') != 0: join = 'join %s'%(join) cmd +=' ' + join c.execute(cmd) return c.fetchall() def GetData(dBase,table,fieldString='*',whereString='',user='sysdba',password='masterkey', removeDups=-1,join='',forceList=0,transform=None,randomAccess=1,extras=None,cn=None): """ a more flexible method to get a set of data from a table **Arguments** - fields: a string with the names of the fields to be extracted, this should be a comma delimited list - where: the SQL where clause to be used with the DB query - removeDups indicates the column which should be used to screen out duplicates. Only the first appearance of a duplicate will be left in the dataset. **Returns** - a list of the data **Notes** - EFF: this isn't particularly efficient """ if not cn: cn = DbModule.connect(dBase,user,password) c = cn.cursor() cmd = 'select %s from %s'%(fieldString,table) if join: if join.strip().find('join') != 0: join = 'join %s'%(join) cmd += ' ' + join if whereString: if whereString.strip().find('where')!=0: whereString = 'where %s'%(whereString) cmd += ' ' + whereString if forceList: try: if not extras: c.execute(cmd) else: c.execute(cmd,extras) except: sys.stderr.write('the command "%s" generated errors:\n'%(cmd)) import traceback traceback.print_exc() return None if transform is not None: raise ValueError,'forceList and transform arguments are not compatible' if not randomAccess: raise ValueError,'when forceList is set, randomAccess must also be used' data = c.fetchall() if removeDups>0: seen = [] for entry in data[:]: if entry[removeDups] in seen: data.remove(entry) else: seen.append(entry[removeDups]) else: if randomAccess: klass = RandomAccessDbResultSet else: klass = DbResultSet data = klass(c,cn,cmd,removeDups=removeDups,transform=transform,extras=extras) return data def DatabaseToText(dBase,table,fields='*',join='',where='', user='sysdba',password='masterkey',delim=',',cn=None): """ Pulls the contents of a database and makes a deliminted text file from them **Arguments** - dBase: the name of the DB file to be used - table: the name of the table to query - fields: the fields to select with the SQL query - join: the join clause of the SQL query (e.g. 'join foo on foo.bar=base.bar') - where: the where clause of the SQL query (e.g. 'where foo = 2' or 'where bar > 17.6') - user: the username for DB access - password: the password to be used for DB access **Returns** - the CSV data (as text) """ if len(where) and where.strip().find('where')==-1: where = 'where %s'%(where) if len(join) and join.strip().find('join') == -1: join = 'join %s'%(join) sqlCommand = 'select %s from %s %s %s'%(fields,table,join,where) if not cn: cn = DbModule.connect(dBase,user,password) c = cn.cursor() c.execute(sqlCommand) headers = [] colsToTake = [] # the description field of the cursor carries around info about the columns # of the table for i in range(len(c.description)): item = c.description[i] if item[1] not in DbInfo.sqlBinTypes: colsToTake.append(i) headers.append(item[0]) lines = [] lines.append(delim.join(headers)) # grab the data results = c.fetchall() for res in results: d = _take(res,colsToTake) lines.append(delim.join(map(str,d))) return '\n'.join(lines) def TypeFinder(data,nRows,nCols,nullMarker=None): """ finds the types of the columns in _data_ if nullMarker is not None, elements of the data table which are equal to nullMarker will not count towards setting the type of their columns. """ priorities={types.FloatType:3,types.IntType:2,types.StringType:1,-1:-1} res = [None]*nCols for col in xrange(nCols): typeHere = [-1,1] for row in xrange(nRows): d = data[row][col] if d is not None: locType = type(d) if locType != types.FloatType and locType != types.IntType: locType = types.StringType try: d = str(d) except UnicodeError,msg: print 'cannot convert text from row %d col %d to a string'%(row+2,col) print '\t>%s'%(repr(d)) raise UnicodeError,msg else: typeHere[1] = max(typeHere[1],len(str(d))) if locType == types.StringType: if nullMarker is None or d != nullMarker: l = max(len(d),typeHere[1]) typeHere = [types.StringType,l] else: try: fD = float(int(d)) except OverflowError: locType = types.FloatType else: if fD == d: locType = types.IntType if typeHere[0]!=types.StringType and \ priorities[locType] > priorities[typeHere[0]]: typeHere[0] = locType res[col] = typeHere return res def _AdjustColHeadings(colHeadings,maxColLabelLen): """ *For Internal Use* removes illegal characters from column headings and truncates those which are too long. """ for i in xrange(len(colHeadings)): # replace unallowed characters and strip extra white space colHeadings[i] = string.strip(colHeadings[i]) colHeadings[i] = string.replace(colHeadings[i],' ','_') colHeadings[i] = string.replace(colHeadings[i],'-','_') colHeadings[i] = string.replace(colHeadings[i],'.','_') if len(colHeadings[i]) > maxColLabelLen: # interbase (at least) has a limit on the maximum length of a column name newHead = string.replace(colHeadings[i],'_','') newHead = newHead[:maxColLabelLen] print '\tHeading %s too long, changed to %s'%(colHeadings[i],newHead) colHeadings[i] = newHead return colHeadings def GetTypeStrings(colHeadings,colTypes,keyCol=None): """ returns a list of SQL type strings """ typeStrs=[] for i in xrange(len(colTypes)): type = colTypes[i] if type[0] == types.FloatType: typeStrs.append('%s double precision'%colHeadings[i]) elif type[0] == types.IntType: typeStrs.append('%s integer'%colHeadings[i]) else: typeStrs.append('%s varchar(%d)'%(colHeadings[i],type[1])) if colHeadings[i] == keyCol: typeStrs[-1] = '%s not null primary key'%(typeStrs[-1]) return typeStrs def _insertBlock(conn,sqlStr,block,silent=False): try: conn.cursor().executemany(sqlStr,block) except: res = 0 conn.commit() for row in block: try: conn.cursor().execute(sqlStr,tuple(row)) res += 1 except: if not silent: import traceback traceback.print_exc() print 'insert failed:',sqlStr print '\t',repr(row) else: conn.commit() else: res = len(block) return res def _AddDataToDb(dBase,table,user,password,colDefs,colTypes,data, nullMarker=None,blockSize=100,cn=None): """ *For Internal Use* (drops and) creates a table and then inserts the values """ if not cn: cn = DbModule.connect(dBase,user,password) c = cn.cursor() try: c.execute('drop table %s'%(table)) except: print 'cannot drop table %s'%(table) try: sqlStr = 'create table %s (%s)'%(table,colDefs) c.execute(sqlStr) except: print 'create table failed: ', sqlStr print 'here is the exception:' import traceback traceback.print_exc() return cn.commit() c = None block = [] entryTxt = [DbModule.placeHolder]*len(data[0]) dStr = ','.join(entryTxt) sqlStr = 'insert into %s values (%s)'%(table,dStr) nDone = 0 for row in data: entries = [None]*len(row) for col in xrange(len(row)): if row[col] is not None and \ (nullMarker is None or row[col] != nullMarker): if colTypes[col][0] == types.FloatType: entries[col] = float(row[col]) elif colTypes[col][0] == types.IntType: entries[col] = int(row[col]) else: entries[col] = str(row[col]) else: entries[col] = None block.append(tuple(entries)) if len(block)>=blockSize: nDone += _insertBlock(cn,sqlStr,block) if not hasattr(cn,'autocommit') or not cn.autocommit: cn.commit() block = [] if len(block): nDone += _insertBlock(cn,sqlStr,block) if not hasattr(cn,'autocommit') or not cn.autocommit: cn.commit() def TextFileToDatabase(dBase,table,inF,delim=',', user='sysdba',password='masterkey', maxColLabelLen=31,keyCol=None,nullMarker=None): """loads the contents of the text file into a database. **Arguments** - dBase: the name of the DB to use - table: the name of the table to create/overwrite - inF: the file like object from which the data should be pulled (must support readline()) - delim: the delimiter used to separate fields - user: the user name to use in connecting to the DB - password: the password to use in connecting to the DB - maxColLabelLen: the maximum length a column label should be allowed to have (truncation otherwise) - keyCol: the column to be used as an index for the db **Notes** - if _table_ already exists, it is destroyed before we write the new data - we assume that the first row of the file contains the column names """ table.replace('-','_') table.replace(' ','_') colHeadings = inF.readline().split(delim) _AdjustColHeadings(colHeadings,maxColLabelLen) nCols = len(colHeadings) data = [] inL = inF.readline() while inL: inL = inL.replace('\r','') inL = inL.replace('\n','') splitL = inL.split(delim) if len(splitL)!=nCols: print '>>>',repr(inL) assert len(splitL)==nCols,'unequal length' tmpVect = [] for entry in splitL: try: val = int(entry) except: try: val = float(entry) except: val = entry tmpVect.append(val) data.append(tmpVect) inL = inF.readline() nRows = len(data) # determine the types of each column colTypes = TypeFinder(data,nRows,nCols,nullMarker=nullMarker) typeStrs = GetTypeStrings(colHeadings,colTypes,keyCol=keyCol) colDefs=','.join(typeStrs) _AddDataToDb(dBase,table,user,password,colDefs,colTypes,data, nullMarker=nullMarker) def DatabaseToDatabase(fromDb,fromTbl,toDb,toTbl, fields='*',join='',where='', user='sysdba',password='masterkey',keyCol=None,nullMarker='None'): """ FIX: at the moment this is a hack """ import cStringIO io = cStringIO.StringIO() io.write(DatabaseToText(fromDb,fromTbl,fields=fields,join=join,where=where, user=user,password=password)) io.seek(-1) TextFileToDatabase(toDb,toTbl,io,user=user,password=password,keyCol=keyCol, nullMarker=nullMarker) if __name__=='__main__': import cStringIO io = cStringIO.StringIO() io.write('foo,bar,baz\n') io.write('1,2,3\n') io.write('1.1,4,5\n') io.write('4,foo,6\n') io.seek(0) from rdkit import RDConfig import os dirLoc = os.path.join(RDConfig.RDCodeDir,'Dbase','TEST.GDB') TextFileToDatabase(dirLoc,'fromtext',io)
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Dbase/DbUtils.py", "copies": "2", "size": "12888", "license": "bsd-3-clause", "hash": 7180114529920904000, "line_mean": 27.7037861915, "line_max": 97, "alpha_frac": 0.6219739292, "autogenerated": false, "ratio": 3.523236741388737, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9977195277459262, "avg_score": 0.03360307862589492, "num_lines": 449 }
""" defines class _DbConnect_, for abstracting connections to databases """ from __future__ import print_function from rdkit import RDConfig import sys,types class DbError(RuntimeError): pass from rdkit.Dbase import DbUtils,DbInfo,DbModule class DbConnect(object): """ This class is intended to abstract away many of the details of interacting with databases. It includes some GUI functionality """ def __init__(self,dbName='',tableName='',user='sysdba',password='masterkey'): """ Constructor **Arguments** (all optional) - dbName: the name of the DB file to be used - tableName: the name of the table to be used - user: the username for DB access - password: the password to be used for DB access """ self.dbName = dbName self.tableName = tableName self.user = user self.password = password self.cn = None self.cursor = None def UpdateTableNames(self,dlg): """ Modifies a connect dialog to reflect new table names **Arguments** - dlg: the dialog to be updated """ self.user = self.userEntry.GetValue() self.password = self.passwdEntry.GetValue() self.dbName = self.dbBrowseButton.GetValue() for i in xrange(self.dbTableChoice.Number()): self.dbTableChoice.Delete(0) names = self.GetTableNames() for name in names: self.dbTableChoice.Append(name) dlg.sizer.Fit(dlg) dlg.sizer.SetSizeHints(dlg) dlg.Refresh() def GetTableNames(self,includeViews=0): """ gets a list of tables available in a database **Arguments** - includeViews: if this is non-null, the views in the db will also be returned **Returns** a list of table names **Notes** - this uses _DbInfo.GetTableNames_ """ return DbInfo.GetTableNames(self.dbName,self.user,self.password, includeViews=includeViews,cn=self.cn) def GetColumnNames(self,table='',join='',what='*',where='',**kwargs): """ gets a list of columns available in the current table **Returns** a list of column names **Notes** - this uses _DbInfo.GetColumnNames_ """ if not table: table = self.tableName return DbInfo.GetColumnNames(self.dbName,table, self.user,self.password, join=join,what=what,cn=self.cn) def GetColumnNamesAndTypes(self,table='',join='',what='*',where='',**kwargs): """ gets a list of columns available in the current table along with their types **Returns** a list of 2-tuples containing: 1) column name 2) column type **Notes** - this uses _DbInfo.GetColumnNamesAndTypes_ """ if not table: table = self.tableName return DbInfo.GetColumnNamesAndTypes(self.dbName,table, self.user,self.password, join=join,what=what,cn=self.cn) def GetColumns(self,fields,table='',join='',**kwargs): """ gets a set of data from a table **Arguments** - fields: a string with the names of the fields to be extracted, this should be a comma delimited list **Returns** a list of the data **Notes** - this uses _DbUtils.GetColumns_ """ if not table: table = self.tableName return DbUtils.GetColumns(self.dbName,table,fields, self.user,self.password, join=join) def GetData(self,table=None,fields='*',where='',removeDups=-1,join='', transform=None,randomAccess=1,**kwargs): """ a more flexible method to get a set of data from a table **Arguments** - table: (optional) the table to use - fields: a string with the names of the fields to be extracted, this should be a comma delimited list - where: the SQL where clause to be used with the DB query - removeDups: indicates which column should be used to recognize duplicates in the data. -1 for no duplicate removal. **Returns** a list of the data **Notes** - this uses _DbUtils.GetData_ """ if table is None: table = self.tableName kwargs['forceList'] = kwargs.get('forceList',0) return DbUtils.GetData(self.dbName,table,fieldString=fields,whereString=where, user=self.user,password=self.password,removeDups=removeDups, join=join,cn=self.cn, transform=transform,randomAccess=randomAccess,**kwargs) def GetDataCount(self,table=None,where='',join='',**kwargs): """ returns a count of the number of results a query will return **Arguments** - table: (optional) the table to use - where: the SQL where clause to be used with the DB query - join: the SQL join clause to be used with the DB query **Returns** an int **Notes** - this uses _DbUtils.GetData_ """ if table is None: table = self.tableName return DbUtils.GetData(self.dbName,table,fieldString='count(*)', whereString=where,cn=self.cn, user=self.user,password=self.password,join=join,forceList=0)[0][0] def GetCursor(self): """ returns a cursor for direct manipulation of the DB only one cursor is available """ if self.cursor is not None: return self.cursor self.cn = DbModule.connect(self.dbName,self.user,self.password) self.cursor = self.cn.cursor() return self.cursor def KillCursor(self): """ closes the cursor """ self.cursor = None if self.cn is not None: self.cn.close() self.cn = None def AddTable(self,tableName,colString): """ adds a table to the database **Arguments** - tableName: the name of the table to add - colString: a string containing column defintions **Notes** - if a table named _tableName_ already exists, it will be dropped - the sqlQuery for addition is: "create table %(tableName) (%(colString))" """ c = self.GetCursor() try: c.execute('drop table %s cascade'%tableName) except Exception: try: c.execute('drop table %s'%tableName) except Exception: pass self.Commit() addStr = 'create table %s (%s)'%(tableName,colString) try: c.execute(addStr) except Exception: import traceback print('command failed:',addStr) traceback.print_exc() else: self.Commit() def InsertData(self,tableName,vals): """ inserts data into a table **Arguments** - tableName: the name of the table to manipulate - vals: a sequence with the values to be inserted """ c = self.GetCursor() if type(vals) != tuple: vals = tuple(vals) insTxt = '('+','.join([DbModule.placeHolder]*len(vals))+')' #insTxt = '(%s'%('%s,'*len(vals)) #insTxt = insTxt[0:-1]+')' cmd = "insert into %s values %s"%(tableName,insTxt) try: c.execute(cmd,vals) except Exception: import traceback print('insert failed:') print(cmd) print('the error was:') traceback.print_exc() raise DbError("Insert Failed") def InsertColumnData(self,tableName,columnName,value,where): """ inserts data into a particular column of the table **Arguments** - tableName: the name of the table to manipulate - columnName: name of the column to update - value: the value to insert - where: a query yielding the row where the data should be inserted """ c = self.GetCursor() cmd = "update %s set %s=%s where %s"%(tableName,columnName, DbModule.placeHolder,where) c.execute(cmd,(value,)) def AddColumn(self,tableName,colName,colType): """ adds a column to a table **Arguments** - tableName: the name of the table to manipulate - colName: name of the column to insert - colType: the type of the column to add """ c = self.GetCursor() try: c.execute("alter table %s add %s %s"%(tableName,colName,colType)) except Exception: print('AddColumn failed') def Commit(self): """ commits the current transaction """ self.cn.commit()
{ "repo_name": "adalke/rdkit", "path": "rdkit/Dbase/DbConnection.py", "copies": "1", "size": "8911", "license": "bsd-3-clause", "hash": 2042391088651010600, "line_mean": 24.7543352601, "line_max": 93, "alpha_frac": 0.5986982381, "autogenerated": false, "ratio": 4.091368227731864, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.02008557751108056, "num_lines": 346 }
""" defines class _DbConnect_, for abstracting connections to databases """ from __future__ import print_function from rdkit import RDConfig import sys, types class DbError(RuntimeError): pass from rdkit.Dbase import DbUtils, DbInfo, DbModule class DbConnect(object): """ This class is intended to abstract away many of the details of interacting with databases. It includes some GUI functionality """ def __init__(self, dbName='', tableName='', user='sysdba', password='masterkey'): """ Constructor **Arguments** (all optional) - dbName: the name of the DB file to be used - tableName: the name of the table to be used - user: the username for DB access - password: the password to be used for DB access """ self.dbName = dbName self.tableName = tableName self.user = user self.password = password self.cn = None self.cursor = None def UpdateTableNames(self, dlg): """ Modifies a connect dialog to reflect new table names **Arguments** - dlg: the dialog to be updated """ self.user = self.userEntry.GetValue() self.password = self.passwdEntry.GetValue() self.dbName = self.dbBrowseButton.GetValue() for i in xrange(self.dbTableChoice.Number()): self.dbTableChoice.Delete(0) names = self.GetTableNames() for name in names: self.dbTableChoice.Append(name) dlg.sizer.Fit(dlg) dlg.sizer.SetSizeHints(dlg) dlg.Refresh() def GetTableNames(self, includeViews=0): """ gets a list of tables available in a database **Arguments** - includeViews: if this is non-null, the views in the db will also be returned **Returns** a list of table names **Notes** - this uses _DbInfo.GetTableNames_ """ return DbInfo.GetTableNames(self.dbName, self.user, self.password, includeViews=includeViews, cn=self.cn) def GetColumnNames(self, table='', join='', what='*', where='', **kwargs): """ gets a list of columns available in the current table **Returns** a list of column names **Notes** - this uses _DbInfo.GetColumnNames_ """ if not table: table = self.tableName return DbInfo.GetColumnNames(self.dbName, table, self.user, self.password, join=join, what=what, cn=self.cn) def GetColumnNamesAndTypes(self, table='', join='', what='*', where='', **kwargs): """ gets a list of columns available in the current table along with their types **Returns** a list of 2-tuples containing: 1) column name 2) column type **Notes** - this uses _DbInfo.GetColumnNamesAndTypes_ """ if not table: table = self.tableName return DbInfo.GetColumnNamesAndTypes(self.dbName, table, self.user, self.password, join=join, what=what, cn=self.cn) def GetColumns(self, fields, table='', join='', **kwargs): """ gets a set of data from a table **Arguments** - fields: a string with the names of the fields to be extracted, this should be a comma delimited list **Returns** a list of the data **Notes** - this uses _DbUtils.GetColumns_ """ if not table: table = self.tableName return DbUtils.GetColumns(self.dbName, table, fields, self.user, self.password, join=join) def GetData(self, table=None, fields='*', where='', removeDups=-1, join='', transform=None, randomAccess=1, **kwargs): """ a more flexible method to get a set of data from a table **Arguments** - table: (optional) the table to use - fields: a string with the names of the fields to be extracted, this should be a comma delimited list - where: the SQL where clause to be used with the DB query - removeDups: indicates which column should be used to recognize duplicates in the data. -1 for no duplicate removal. **Returns** a list of the data **Notes** - this uses _DbUtils.GetData_ """ if table is None: table = self.tableName kwargs['forceList'] = kwargs.get('forceList', 0) return DbUtils.GetData(self.dbName, table, fieldString=fields, whereString=where, user=self.user, password=self.password, removeDups=removeDups, join=join, cn=self.cn, transform=transform, randomAccess=randomAccess, **kwargs) def GetDataCount(self, table=None, where='', join='', **kwargs): """ returns a count of the number of results a query will return **Arguments** - table: (optional) the table to use - where: the SQL where clause to be used with the DB query - join: the SQL join clause to be used with the DB query **Returns** an int **Notes** - this uses _DbUtils.GetData_ """ if table is None: table = self.tableName return DbUtils.GetData(self.dbName, table, fieldString='count(*)', whereString=where, cn=self.cn, user=self.user, password=self.password, join=join, forceList=0)[0][0] def GetCursor(self): """ returns a cursor for direct manipulation of the DB only one cursor is available """ if self.cursor is not None: return self.cursor self.cn = DbModule.connect(self.dbName, self.user, self.password) self.cursor = self.cn.cursor() return self.cursor def KillCursor(self): """ closes the cursor """ self.cursor = None if self.cn is not None: self.cn.close() self.cn = None def AddTable(self, tableName, colString): """ adds a table to the database **Arguments** - tableName: the name of the table to add - colString: a string containing column defintions **Notes** - if a table named _tableName_ already exists, it will be dropped - the sqlQuery for addition is: "create table %(tableName) (%(colString))" """ c = self.GetCursor() try: c.execute('drop table %s cascade' % tableName) except Exception: try: c.execute('drop table %s' % tableName) except Exception: pass self.Commit() addStr = 'create table %s (%s)' % (tableName, colString) try: c.execute(addStr) except Exception: import traceback print('command failed:', addStr) traceback.print_exc() else: self.Commit() def InsertData(self, tableName, vals): """ inserts data into a table **Arguments** - tableName: the name of the table to manipulate - vals: a sequence with the values to be inserted """ c = self.GetCursor() if type(vals) != tuple: vals = tuple(vals) insTxt = '(' + ','.join([DbModule.placeHolder] * len(vals)) + ')' #insTxt = '(%s'%('%s,'*len(vals)) #insTxt = insTxt[0:-1]+')' cmd = "insert into %s values %s" % (tableName, insTxt) try: c.execute(cmd, vals) except Exception: import traceback print('insert failed:') print(cmd) print('the error was:') traceback.print_exc() raise DbError("Insert Failed") def InsertColumnData(self, tableName, columnName, value, where): """ inserts data into a particular column of the table **Arguments** - tableName: the name of the table to manipulate - columnName: name of the column to update - value: the value to insert - where: a query yielding the row where the data should be inserted """ c = self.GetCursor() cmd = "update %s set %s=%s where %s" % (tableName, columnName, DbModule.placeHolder, where) c.execute(cmd, (value, )) def AddColumn(self, tableName, colName, colType): """ adds a column to a table **Arguments** - tableName: the name of the table to manipulate - colName: name of the column to insert - colType: the type of the column to add """ c = self.GetCursor() try: c.execute("alter table %s add %s %s" % (tableName, colName, colType)) except Exception: print('AddColumn failed') def Commit(self): """ commits the current transaction """ self.cn.commit()
{ "repo_name": "jandom/rdkit", "path": "rdkit/Dbase/DbConnection.py", "copies": "1", "size": "8759", "license": "bsd-3-clause", "hash": 7791630265357377000, "line_mean": 24.1695402299, "line_max": 100, "alpha_frac": 0.6090877954, "autogenerated": false, "ratio": 4.016047684548372, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.009702387468239128, "num_lines": 348 }
""" defines class _DbConnect_, for abstracting connections to databases """ from rdkit import RDConfig import sys,types import exceptions class DbError(RuntimeError): pass from rdkit.Dbase import DbUtils,DbInfo import DbModule class DbConnect(object): """ This class is intended to abstract away many of the details of interacting with databases. It includes some GUI functionality """ def __init__(self,dbName='',tableName='',user='sysdba',password='masterkey'): """ Constructor **Arguments** (all optional) - dbName: the name of the DB file to be used - tableName: the name of the table to be used - user: the username for DB access - password: the password to be used for DB access """ self.dbName = dbName self.tableName = tableName self.user = user self.password = password self.cn = None self.cursor = None def UpdateTableNames(self,dlg): """ Modifies a connect dialog to reflect new table names **Arguments** - dlg: the dialog to be updated """ self.user = self.userEntry.GetValue() self.password = self.passwdEntry.GetValue() self.dbName = self.dbBrowseButton.GetValue() for i in xrange(self.dbTableChoice.Number()): self.dbTableChoice.Delete(0) names = self.GetTableNames() for name in names: self.dbTableChoice.Append(name) dlg.sizer.Fit(dlg) dlg.sizer.SetSizeHints(dlg) dlg.Refresh() def GetTableNames(self,includeViews=0): """ gets a list of tables available in a database **Arguments** - includeViews: if this is non-null, the views in the db will also be returned **Returns** a list of table names **Notes** - this uses _DbInfo.GetTableNames_ """ return DbInfo.GetTableNames(self.dbName,self.user,self.password, includeViews=includeViews,cn=self.cn) def GetColumnNames(self,table='',join='',what='*',where='',**kwargs): """ gets a list of columns available in the current table **Returns** a list of column names **Notes** - this uses _DbInfo.GetColumnNames_ """ if not table: table = self.tableName return DbInfo.GetColumnNames(self.dbName,table, self.user,self.password, join=join,what=what,cn=self.cn) def GetColumnNamesAndTypes(self,table='',join='',what='*',where='',**kwargs): """ gets a list of columns available in the current table along with their types **Returns** a list of 2-tuples containing: 1) column name 2) column type **Notes** - this uses _DbInfo.GetColumnNamesAndTypes_ """ if not table: table = self.tableName return DbInfo.GetColumnNamesAndTypes(self.dbName,table, self.user,self.password, join=join,what=what,cn=self.cn) def GetColumns(self,fields,table='',join='',**kwargs): """ gets a set of data from a table **Arguments** - fields: a string with the names of the fields to be extracted, this should be a comma delimited list **Returns** a list of the data **Notes** - this uses _DbUtils.GetColumns_ """ if not table: table = self.tableName return DbUtils.GetColumns(self.dbName,table,fields, self.user,self.password, join=join) def GetData(self,table=None,fields='*',where='',removeDups=-1,join='', transform=None,randomAccess=1,**kwargs): """ a more flexible method to get a set of data from a table **Arguments** - table: (optional) the table to use - fields: a string with the names of the fields to be extracted, this should be a comma delimited list - where: the SQL where clause to be used with the DB query - removeDups: indicates which column should be used to recognize duplicates in the data. -1 for no duplicate removal. **Returns** a list of the data **Notes** - this uses _DbUtils.GetData_ """ if table is None: table = self.tableName kwargs['forceList'] = kwargs.get('forceList',0) return DbUtils.GetData(self.dbName,table,fieldString=fields,whereString=where, user=self.user,password=self.password,removeDups=removeDups, join=join,cn=self.cn, transform=transform,randomAccess=randomAccess,**kwargs) def GetDataCount(self,table=None,where='',join='',**kwargs): """ returns a count of the number of results a query will return **Arguments** - table: (optional) the table to use - where: the SQL where clause to be used with the DB query - join: the SQL join clause to be used with the DB query **Returns** an int **Notes** - this uses _DbUtils.GetData_ """ if table is None: table = self.tableName return DbUtils.GetData(self.dbName,table,fieldString='count(*)', whereString=where,cn=self.cn, user=self.user,password=self.password,join=join,forceList=0)[0][0] def GetCursor(self): """ returns a cursor for direct manipulation of the DB only one cursor is available """ if self.cursor is not None: return self.cursor self.cn = DbModule.connect(self.dbName,self.user,self.password) self.cursor = self.cn.cursor() return self.cursor def KillCursor(self): """ closes the cursor """ self.cursor = None self.cn = None def AddTable(self,tableName,colString): """ adds a table to the database **Arguments** - tableName: the name of the table to add - colString: a string containing column defintions **Notes** - if a table named _tableName_ already exists, it will be dropped - the sqlQuery for addition is: "create table %(tableName) (%(colString))" """ c = self.GetCursor() try: c.execute('drop table %s cascade'%tableName) except: try: c.execute('drop table %s'%tableName) except: pass self.Commit() addStr = 'create table %s (%s)'%(tableName,colString) try: c.execute(addStr) except: import traceback print 'command failed:',addStr traceback.print_exc() else: self.Commit() def InsertData(self,tableName,vals): """ inserts data into a table **Arguments** - tableName: the name of the table to manipulate - vals: a sequence with the values to be inserted """ c = self.GetCursor() if type(vals) != types.TupleType: vals = tuple(vals) insTxt = '('+','.join([DbModule.placeHolder]*len(vals))+')' #insTxt = '(%s'%('%s,'*len(vals)) #insTxt = insTxt[0:-1]+')' cmd = "insert into %s values %s"%(tableName,insTxt) try: c.execute(cmd,vals) except: import traceback print 'insert failed:' print cmd print 'the error was:' traceback.print_exc() raise DbError,"Insert Failed" def InsertColumnData(self,tableName,columnName,value,where): """ inserts data into a particular column of the table **Arguments** - tableName: the name of the table to manipulate - columnName: name of the column to update - value: the value to insert - where: a query yielding the row where the data should be inserted """ c = self.GetCursor() cmd = "update %s set %s=%s where %s"%(tableName,columnName, DbModule.placeHolder,where) c.execute(cmd,(value,)) def AddColumn(self,tableName,colName,colType): """ adds a column to a table **Arguments** - tableName: the name of the table to manipulate - colName: name of the column to insert - colType: the type of the column to add """ c = self.GetCursor() try: c.execute("alter table %s add %s %s"%(tableName,colName,colType)) except: print 'AddColumn failed' def Commit(self): """ commits the current transaction """ self.cn.commit()
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Dbase/DbConnection.py", "copies": "2", "size": "8808", "license": "bsd-3-clause", "hash": -7911510795011859000, "line_mean": 24.4566473988, "line_max": 93, "alpha_frac": 0.5976385104, "autogenerated": false, "ratio": 4.0910357640501624, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5688674274450163, "avg_score": null, "num_lines": null }
""" code for dealing with Bayesian composite models For a model to be useable here, it should support the following API: - _ClassifyExample(example)_, returns a classification Other compatibility notes: 1) To use _Composite.Grow_ there must be some kind of builder functionality which returns a 2-tuple containing (model,percent accuracy). 2) The models should be pickleable 3) It would be very happy if the models support the __cmp__ method so that membership tests used to make sure models are unique work. """ from __future__ import print_function import numpy from rdkit.ML.Composite import Composite class BayesComposite(Composite.Composite): """a composite model using Bayesian statistics in the Decision Proxy **Notes** - typical usage: 1) grow the composite with AddModel until happy with it 2) call AverageErrors to calculate the average error values 3) call SortModels to put things in order by either error or count 4) call Train to update the Bayesian stats. """ def Train(self, data, verbose=0): # FIX: this is wrong because it doesn't take the counts of each model into account nModels = len(self) nResults = self.nPossibleVals[-1] self.resultProbs = numpy.zeros(nResults, numpy.float) self.condProbs = [None] * nModels for i in range(nModels): self.condProbs[i] = numpy.zeros((nResults, nResults), numpy.float) # FIX: this is a quick hack which may slow things down a lot for example in data: act = self.QuantizeActivity(example)[-1] self.resultProbs[int(act)] += 1 for example in data: if self._mapOrder is not None: example = self._RemapInput(example) if self.GetActivityQuantBounds(): example = self.QuantizeActivity(example) if self.quantBounds is not None and 1 in self.quantizationRequirements: quantExample = self.QuantizeExample(example, self.quantBounds) else: quantExample = [] trueRes = int(example[-1]) votes = self.CollectVotes(example, quantExample) for i in range(nModels): self.condProbs[i][votes[i], trueRes] += 1 # self.condProbs /= self.resultProbs for i in range(nModels): for j in range(nResults): self.condProbs[i][j] /= sum(self.condProbs[i][j]) # self.condProbs[i] /= self.resultProbs self.resultProbs /= sum(self.resultProbs) if verbose: print('**** Bayesian Results') print('Result probabilities') print('\t', self.resultProbs) print('Model by model breakdown of conditional probs') for mat in self.condProbs: for row in mat: print('\t', row) print() def ClassifyExample(self, example, threshold=0, verbose=0, appendExample=0): """ classifies the given example using the entire composite **Arguments** - example: the data to be classified - threshold: if this is a number greater than zero, then a classification will only be returned if the confidence is above _threshold_. Anything lower is returned as -1. **Returns** a (result,confidence) tuple """ if self._mapOrder is not None: example = self._RemapInput(example) if self.GetActivityQuantBounds(): example = self.QuantizeActivity(example) if self.quantBounds is not None and 1 in self.quantizationRequirements: quantExample = self.QuantizeExample(example, self.quantBounds) else: quantExample = [] self.modelVotes = self.CollectVotes(example, quantExample, appendExample=appendExample) nPossibleRes = self.nPossibleVals[-1] votes = [0.] * nPossibleRes for i in range(len(self)): predict = self.modelVotes[i] for j in range(nPossibleRes): votes[j] += self.condProbs[i][predict, j] # totVotes = sum(votes) res = numpy.argmax(votes) conf = votes[res] / len(self) if verbose: print(votes, conf, example[-1]) if conf > threshold: return res, conf else: return -1, conf def __init__(self): Composite.Composite.__init__(self) self.resultProbs = None self.condProbs = None def CompositeToBayesComposite(obj): """ converts a Composite to a BayesComposite if _obj_ is already a BayesComposite or if it is not a _Composite.Composite_ , nothing will be done. """ if obj.__class__ == BayesComposite: return elif obj.__class__ == Composite.Composite: obj.__class__ = BayesComposite obj.resultProbs = None obj.condProbs = None def BayesCompositeToComposite(obj): """ converts a BayesComposite to a Composite.Composite """ if obj.__class__ == Composite.Composite: return elif obj.__class__ == BayesComposite: obj.__class__ = Composite.Composite obj.resultProbs = None obj.condProbs = None
{ "repo_name": "rvianello/rdkit", "path": "rdkit/ML/Composite/BayesComposite.py", "copies": "4", "size": "4958", "license": "bsd-3-clause", "hash": 8460042876339096000, "line_mean": 27.8255813953, "line_max": 91, "alpha_frac": 0.669826543, "autogenerated": false, "ratio": 3.7674772036474162, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.006254461974826658, "num_lines": 172 }
""" code for dealing with composite models For a model to be useable here, it should support the following API: - _ClassifyExample(example)_, returns a classification Other compatibility notes: 1) To use _Composite.Grow_ there must be some kind of builder functionality which returns a 2-tuple containing (model,percent accuracy). 2) The models should be pickleable 3) It would be very happy if the models support the __cmp__ method so that membership tests used to make sure models are unique work. """ from __future__ import print_function import math import numpy from rdkit.six.moves import cPickle from rdkit.ML.Data import DataUtils class Composite(object): """a composite model **Notes** - adding a model which is already present just results in its count field being incremented and the errors being averaged. - typical usage: 1) grow the composite with AddModel until happy with it 2) call AverageErrors to calculate the average error values 3) call SortModels to put things in order by either error or count - Composites can support individual models requiring either quantized or nonquantized data. This is done by keeping a set of quantization bounds (_QuantBounds_) in the composite and quantizing data passed in when required. Quantization bounds can be set and interrogated using the _Get/SetQuantBounds()_ methods. When models are added to the composite, it can be indicated whether or not they require quantization. - Composites are also capable of extracting relevant variables from longer lists. This is accessible using _SetDescriptorNames()_ to register the descriptors about which the composite cares and _SetInputOrder()_ to tell the composite what the ordering of input vectors will be. **Note** there is a limitation on this: each model needs to take the same set of descriptors as inputs. This could be changed. """ def __init__(self): self.modelList=[] self.errList=[] self.countList=[] self.modelVotes=[] self.quantBounds = None self.nPossibleVals = None self.quantizationRequirements=[] self._descNames = [] self._mapOrder = None self.activityQuant=[] def SetModelFilterData(self, modelFilterFrac=0.0, modelFilterVal=0.0) : self._modelFilterFrac = modelFilterFrac self._modelFilterVal = modelFilterVal def SetDescriptorNames(self,names): """ registers the names of the descriptors this composite uses **Arguments** - names: a list of descriptor names (strings). **NOTE** the _names_ list is not copied, so if you modify it later, the composite itself will also be modified. """ self._descNames = names def GetDescriptorNames(self): """ returns the names of the descriptors this composite uses """ return self._descNames def SetQuantBounds(self,qBounds,nPossible=None): """ sets the quantization bounds that the composite will use **Arguments** - qBounds: a list of quantization bounds, each quantbound is a list of boundaries - nPossible: a list of integers indicating how many possible values each descriptor can take on. **NOTE** - if the two lists are of different lengths, this will assert out - neither list is copied, so if you modify it later, the composite itself will also be modified. """ if nPossible is not None: assert len(qBounds)==len(nPossible),'qBounds/nPossible mismatch' self.quantBounds = qBounds self.nPossibleVals = nPossible def GetQuantBounds(self): """ returns the quantization bounds **Returns** a 2-tuple consisting of: 1) the list of quantization bounds 2) the nPossibleVals list """ return self.quantBounds,self.nPossibleVals def GetActivityQuantBounds(self): if not hasattr(self,'activityQuant'): self.activityQuant=[] return self.activityQuant def SetActivityQuantBounds(self,bounds): self.activityQuant=bounds def QuantizeActivity(self,example,activityQuant=None,actCol=-1): if activityQuant is None: activityQuant=self.activityQuant if activityQuant: example = example[:] act = example[actCol] for box in range(len(activityQuant)): if act < activityQuant[box]: act = box break else: act = box + 1 example[actCol] = act return example def QuantizeExample(self,example,quantBounds=None): """ quantizes an example **Arguments** - example: a data point (list, tuple or numpy array) - quantBounds: a list of quantization bounds, each quantbound is a list of boundaries. If this argument is not provided, the composite will use its own quantBounds **Returns** the quantized example as a list **Notes** - If _example_ is different in length from _quantBounds_, this will assert out. - This is primarily intended for internal use """ if quantBounds is None: quantBounds = self.quantBounds assert len(example)==len(quantBounds),'example/quantBounds mismatch' quantExample = [None]*len(example) for i in range(len(quantBounds)): bounds = quantBounds[i] p = example[i] if len(bounds): for box in range(len(bounds)): if p < bounds[box]: p = box break else: p = box + 1 else: if i != 0: p = int(p) quantExample[i] = p return quantExample def MakeHistogram(self): """ creates a histogram of error/count pairs **Returns** the histogram as a series of (error, count) 2-tuples """ nExamples = len(self.modelList) histo = [] i = 1 lastErr = self.errList[0] countHere = self.countList[0] eps = 0.001 while i < nExamples: if self.errList[i]-lastErr > eps: histo.append((lastErr,countHere)) lastErr = self.errList[i] countHere = self.countList[i] else: countHere = countHere + self.countList[i] i = i + 1 return histo def CollectVotes(self,example,quantExample,appendExample=0, onlyModels=None): """ collects votes across every member of the composite for the given example **Arguments** - example: the example to be voted upon - quantExample: the quantized form of the example - appendExample: toggles saving the example on the models - onlyModels: if provided, this should be a sequence of model indices. Only the specified models will be used in the prediction. **Returns** a list with a vote from each member """ if not onlyModels: onlyModels = range(len(self)) nModels = len(onlyModels) votes = [-1]*len(self) for i in onlyModels: if self.quantizationRequirements[i]: votes[i] = int(round(self.modelList[i].ClassifyExample(quantExample, appendExamples=appendExample))) else: votes[i] = int(round(self.modelList[i].ClassifyExample(example, appendExamples=appendExample))) return votes def ClassifyExample(self,example,threshold=0,appendExample=0, onlyModels=None): """ classifies the given example using the entire composite **Arguments** - example: the data to be classified - threshold: if this is a number greater than zero, then a classification will only be returned if the confidence is above _threshold_. Anything lower is returned as -1. - appendExample: toggles saving the example on the models - onlyModels: if provided, this should be a sequence of model indices. Only the specified models will be used in the prediction. **Returns** a (result,confidence) tuple **FIX:** statistics sucks... I'm not seeing an obvious way to get the confidence intervals. For that matter, I'm not seeing an unobvious way. For now, this is just treated as a voting problem with the confidence measure being the percent of models which voted for the winning result. """ if self._mapOrder is not None: example = self._RemapInput(example) if self.GetActivityQuantBounds(): example = self.QuantizeActivity(example) if self.quantBounds is not None and 1 in self.quantizationRequirements: quantExample = self.QuantizeExample(example,self.quantBounds) else: quantExample = [] if not onlyModels: onlyModels = range(len(self)) self.modelVotes = self.CollectVotes(example,quantExample,appendExample=appendExample, onlyModels=onlyModels) votes = [0]*self.nPossibleVals[-1] for i in onlyModels: res = self.modelVotes[i] votes[res] = votes[res] + self.countList[i] totVotes = sum(votes) res = numpy.argmax(votes) conf = float(votes[res])/float(totVotes) if conf > threshold: return res,conf else: return -1,conf def GetVoteDetails(self): """ returns the votes from the last classification This will be _None_ if nothing has yet be classified """ return self.modelVotes def _RemapInput(self,inputVect): """ remaps the input so that it matches the expected internal ordering **Arguments** - inputVect: the input to be reordered **Returns** - a list with the reordered (and possible shorter) data **Note** - you must call _SetDescriptorNames()_ and _SetInputOrder()_ for this to work - this is primarily intended for internal use """ order = self._mapOrder if order is None: return inputVect remappedInput = [None]*len(order) for i in range(len(order)-1): remappedInput[i] = inputVect[order[i]] if order[-1] == -1: remappedInput[-1] = 0 else: remappedInput[-1] = inputVect[order[-1]] return remappedInput def GetInputOrder(self): """ returns the input order (used in remapping inputs) """ return self._mapOrder def SetInputOrder(self,colNames): """ sets the input order **Arguments** - colNames: a list of the names of the data columns that will be passed in **Note** - you must call _SetDescriptorNames()_ first for this to work - if the local descriptor names do not appear in _colNames_, this will raise an _IndexError_ exception. """ if type(colNames)!=list: colNames = list(colNames) descs = [x.upper() for x in self.GetDescriptorNames()] self._mapOrder = [None]*len(descs) colNames = [x.upper() for x in colNames] # FIX: I believe that we're safe assuming that field 0 # is always the label, and therefore safe to ignore errors, # but this may not be the case try: self._mapOrder[0] = colNames.index(descs[0]) except ValueError: self._mapOrder[0] = 0 for i in range(1,len(descs)-1): try: self._mapOrder[i] = colNames.index(descs[i]) except ValueError: raise ValueError('cannot find descriptor name: %s in set %s'%(repr(descs[i]),repr(colNames))) try: self._mapOrder[-1] = colNames.index(descs[-1]) except ValueError: # ok, there's no obvious match for the final column (activity) # We'll take the last one: #self._mapOrder[-1] = len(descs)-1 self._mapOrder[-1] = -1 def Grow(self,examples,attrs,nPossibleVals,buildDriver,pruner=None, nTries=10,pruneIt=0, needsQuantization=1,progressCallback=None, **buildArgs): """ Grows the composite **Arguments** - examples: a list of examples to be used in training - attrs: a list of the variables to be used in training - nPossibleVals: this is used to provide a list of the number of possible values for each variable. It is used if the local quantBounds have not been set (for example for when you are working with data which is already quantized). - buildDriver: the function to call to build the new models - pruner: a function used to "prune" (reduce the complexity of) the resulting model. - nTries: the number of new models to add - pruneIt: toggles whether or not pruning is done - needsQuantization: used to indicate whether or not this type of model requires quantized data - **buildArgs: all other keyword args are passed to _buildDriver_ **Note** - new models are *added* to the existing ones """ silent = buildArgs.get('silent',0) buildArgs['silent']=1 buildArgs['calcTotalError']=1 if self._mapOrder is not None: examples = map(self._RemapInput,examples) if self.GetActivityQuantBounds(): for i in range(len(examples)): examples[i] = self.QuantizeActivity(examples[i]) nPossibleVals[-1]=len(self.GetActivityQuantBounds())+1 if self.nPossibleVals is None: self.nPossibleVals = nPossibleVals[:] if needsQuantization: trainExamples = [None]*len(examples) nPossibleVals = self.nPossibleVals for i in range(len(examples)): trainExamples[i] = self.QuantizeExample(examples[i],self.quantBounds) else: trainExamples = examples for i in range(nTries): trainSet = None if (hasattr(self, '_modelFilterFrac')) and (self._modelFilterFrac != 0) : trainIdx, temp = DataUtils.FilterData(trainExamples, self._modelFilterVal, self._modelFilterFrac,-1, indicesOnly=1) trainSet = [trainExamples[x] for x in trainIdx] else: trainSet = trainExamples #print("Training model %i with %i out of %i examples"%(i, len(trainSet), len(trainExamples))) model,frac = buildDriver(*(trainSet,attrs,nPossibleVals), **buildArgs) if pruneIt: model,frac2 = pruner(model,model.GetTrainingExamples(), model.GetTestExamples(), minimizeTestErrorOnly=0) frac = frac2 if hasattr(self, '_modelFilterFrac') and self._modelFilterFrac!=0 and \ hasattr(model,'_trainIndices'): # correct the model's training indices: trainIndices = [trainIdx[x] for x in model._trainIndices] model._trainIndices = trainIndices self.AddModel(model,frac,needsQuantization) if not silent and (nTries < 10 or i % (nTries/10) == 0): print('Cycle: % 4d'%(i)) if progressCallback is not None: progressCallback(i) def ClearModelExamples(self): for i in range(len(self)): m = self.GetModel(i) try: m.ClearExamples() except AttributeError: pass def Pickle(self,fileName='foo.pkl',saveExamples=0): """ Writes this composite off to a file so that it can be easily loaded later **Arguments** - fileName: the name of the file to be written - saveExamples: if this is zero, the individual models will have their stored examples cleared. """ if not saveExamples: self.ClearModelExamples() pFile = open(fileName,'wb+') cPickle.dump(self,pFile,1) pFile.close() def AddModel(self,model,error,needsQuantization=1): """ Adds a model to the composite **Arguments** - model: the model to be added - error: the model's error - needsQuantization: a toggle to indicate whether or not this model requires quantized inputs **NOTE** - this can be used as an alternative to _Grow()_ if you already have some models constructed - the errList is run as an accumulator, you probably want to call _AverageErrors_ after finishing the forest """ if model in self.modelList: try: idx = self.modelList.index(model) except ValueError: # FIX: we should never get here, but sometimes we do anyway self.modelList.append(model) self.errList.append(error) self.countList.append(1) self.quantizationRequirements.append(needsQuantization) else: self.errList[idx] = self.errList[idx]+error self.countList[idx] = self.countList[idx] + 1 else: self.modelList.append(model) self.errList.append(error) self.countList.append(1) self.quantizationRequirements.append(needsQuantization) def AverageErrors(self): """ convert local summed error to average error """ self.errList = list(map(lambda x,y:x/y,self.errList,self.countList)) def SortModels(self,sortOnError=1): """ sorts the list of models **Arguments** sortOnError: toggles sorting on the models' errors rather than their counts """ if sortOnError: order = numpy.argsort(self.errList) else: order = numpy.argsort(self.countList) # these elaborate contortions are required because, at the time this # code was written, Numeric arrays didn't unpickle so well... #print(order,sortOnError,self.errList,self.countList) self.modelList = [self.modelList[x] for x in order] self.countList = [self.countList[x] for x in order] self.errList = [self.errList[x] for x in order] def GetModel(self,i): """ returns a particular model """ return self.modelList[i] def SetModel(self,i,val): """ replaces a particular model **Note** This is included for the sake of completeness, but you need to be *very* careful when you use it. """ self.modelList[i] = val def GetCount(self,i): """ returns the count of the _i_th model """ return self.countList[i] def SetCount(self,i,val): """ sets the count of the _i_th model """ self.countList[i] = val def GetError(self,i): """ returns the error of the _i_th model """ return self.errList[i] def SetError(self,i,val): """ sets the error of the _i_th model """ self.errList[i] = val def GetDataTuple(self,i): """ returns all relevant data about a particular model **Arguments** i: an integer indicating which model should be returned **Returns** a 3-tuple consisting of: 1) the model 2) its count 3) its error """ return (self.modelList[i],self.countList[i],self.errList[i]) def SetDataTuple(self,i,tup): """ sets all relevant data for a particular tree in the forest **Arguments** - i: an integer indicating which model should be returned - tup: a 3-tuple consisting of: 1) the model 2) its count 3) its error **Note** This is included for the sake of completeness, but you need to be *very* careful when you use it. """ self.modelList[i],self.countList[i],self.errList[i] = tup def GetAllData(self): """ Returns everything we know **Returns** a 3-tuple consisting of: 1) our list of models 2) our list of model counts 3) our list of model errors """ return (self.modelList,self.countList,self.errList) def __len__(self): """ allows len(composite) to work """ return len(self.modelList) def __getitem__(self,which): """ allows composite[i] to work, returns the data tuple """ return self.GetDataTuple(which) def __str__(self): """ returns a string representation of the composite """ outStr= 'Composite\n' for i in range(len(self.modelList)): outStr = outStr + \ ' Model % 4d: % 5d occurances %%% 5.2f average error\n'%(i,self.countList[i], 100.*self.errList[i]) return outStr if __name__ == '__main__': if 0: from rdkit.ML.DecTree import DecTree c = Composite() n = DecTree.DecTreeNode(None,'foo') c.AddModel(n,0.5) c.AddModel(n,0.5) c.AverageErrors() c.SortModels() print(c) qB = [[],[.5,1,1.5]] exs = [['foo',0],['foo',.4],['foo',.6],['foo',1.1],['foo',2.0]] print('quantBounds:',qB) for ex in exs: q = c.QuantizeExample(ex,qB) print(ex,q) else: pass
{ "repo_name": "adalke/rdkit", "path": "rdkit/ML/Composite/Composite.py", "copies": "1", "size": "20885", "license": "bsd-3-clause", "hash": 8936556680130296000, "line_mean": 27.8466850829, "line_max": 101, "alpha_frac": 0.6275796026, "autogenerated": false, "ratio": 3.9894937917860553, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.01913961238200819, "num_lines": 724 }
""" command line utility for building composite models #DOC **Usage** BuildComposite [optional args] filename Unless indicated otherwise (via command line arguments), _filename_ is a QDAT file. **Command Line Arguments** - -o *filename*: name of the output file for the pickled composite - -n *num*: number of separate models to add to the composite - -p *tablename*: store persistence data in the database in table *tablename* - -N *note*: attach some arbitrary text to the persistence data - -b *filename*: name of the text file to hold examples from the holdout set which are misclassified - -s: split the data into training and hold-out sets before building the composite - -f *frac*: the fraction of data to use in the training set when the data is split - -r: randomize the activities (for testing purposes). This ignores the initial distribution of activity values and produces each possible activity value with equal likliehood. - -S: shuffle the activities (for testing purposes) This produces a permutation of the input activity values. - -l: locks the random number generator to give consistent sets of training and hold-out data. This is primarily intended for testing purposes. - -B: use a so-called Bayesian composite model. - -d *database name*: instead of reading the data from a QDAT file, pull it from a database. In this case, the _filename_ argument provides the name of the database table containing the data set. - -D: show a detailed breakdown of the composite model performance across the training and, when appropriate, hold-out sets. - -P *pickle file name*: write out the pickled data set to the file - -F *filter frac*: filters the data before training to change the distribution of activity values in the training set. *filter frac* is the fraction of the training set that should have the target value. **See note below on data filtering.** - -v *filter value*: filters the data before training to change the distribution of activity values in the training set. *filter value* is the target value to use in filtering. **See note below on data filtering.** - --modelFiltFrac *model filter frac*: Similar to filter frac above, in this case the data is filtered for each model in the composite rather than a single overall filter for a composite. *model filter frac* is the fraction of the training set for each model that should have the target value (*model filter value*). - --modelFiltVal *model filter value*: target value to use for filtering data before training each model in the composite. - -t *threshold value*: use high-confidence predictions for the final analysis of the hold-out data. - -Q *list string*: the values of quantization bounds for the activity value. See the _-q_ argument for the format of *list string*. - --nRuns *count*: build *count* composite models - --prune: prune any models built - -h: print a usage message and exit. - -V: print the version number and exit *-*-*-*-*-*-*-*- Tree-Related Options -*-*-*-*-*-*-*-* - -g: be less greedy when training the models. - -G *number*: force trees to be rooted at descriptor *number*. - -L *limit*: provide an (integer) limit on individual model complexity - -q *list string*: Add QuantTrees to the composite and use the list specified in *list string* as the number of target quantization bounds for each descriptor. Don't forget to include 0's at the beginning and end of *list string* for the name and value fields. For example, if there are 4 descriptors and you want 2 quant bounds apiece, you would use _-q "[0,2,2,2,2,0]"_. Two special cases: 1) If you would like to ignore a descriptor in the model building, use '-1' for its number of quant bounds. 2) If you have integer valued data that should not be quantized further, enter 0 for that descriptor. - --recycle: allow descriptors to be used more than once in a tree - --randomDescriptors=val: toggles growing random forests with val randomly-selected descriptors available at each node. *-*-*-*-*-*-*-*- KNN-Related Options -*-*-*-*-*-*-*-* - --doKnn: use K-Nearest Neighbors models - --knnK=*value*: the value of K to use in the KNN models - --knnTanimoto: use the Tanimoto metric in KNN models - --knnEuclid: use a Euclidean metric in KNN models *-*-*-*-*-*-*- Naive Bayes Classifier Options -*-*-*-*-*-*-*-* - --doNaiveBayes : use Naive Bayes classifiers - --mEstimateVal : the value to be used in the m-estimate formula If this is greater than 0.0, we use it to compute the conditional probabilities by the m-estimate *-*-*-*-*-*-*-*- SVM-Related Options -*-*-*-*-*-*-*-* **** NOTE: THESE ARE DISABLED **** # # - --doSVM: use Support-vector machines # # - --svmKernel=*kernel*: choose the type of kernel to be used for # # the SVMs. Options are: # # The default is: # # - --svmType=*type*: choose the type of support-vector machine # # to be used. Options are: # # The default is: # # - --svmGamma=*gamma*: provide the gamma value for the SVMs. If this # # is not provided, a grid search will be carried out to determine an # # optimal *gamma* value for each SVM. # # - --svmCost=*cost*: provide the cost value for the SVMs. If this is # # not provided, a grid search will be carried out to determine an # # optimal *cost* value for each SVM. # # - --svmWeights=*weights*: provide the weight values for the # # activities. If provided this should be a sequence of (label, # # weight) 2-tuples *nActs* long. If not provided, a weight of 1 # # will be used for each activity. # # - --svmEps=*epsilon*: provide the epsilon value used to determine # # when the SVM has converged. Defaults to 0.001 # # - --svmDegree=*degree*: provide the degree of the kernel (when # # sensible) Defaults to 3 # # - --svmCoeff=*coeff*: provide the coefficient for the kernel (when # # sensible) Defaults to 0 # # - --svmNu=*nu*: provide the nu value for the kernel (when sensible) # # Defaults to 0.5 # # - --svmDataType=*float*: if the data is contains only 1 and 0 s, specify by # # using binary. Defaults to float # # - --svmCache=*cache*: provide the size of the memory cache (in MB) # # to be used while building the SVM. Defaults to 40 **Notes** - *Data filtering*: When there is a large disparity between the numbers of points with various activity levels present in the training set it is sometimes desirable to train on a more homogeneous data set. This can be accomplished using filtering. The filtering process works by selecting a particular target fraction and target value. For example, in a case where 95% of the original training set has activity 0 and ony 5% activity 1, we could filter (by randomly removing points with activity 0) so that 30% of the data set used to build the composite has activity 1. """ from __future__ import print_function import sys import time import numpy from rdkit import DataStructs from rdkit.Dbase import DbModule from rdkit.ML import CompositeRun from rdkit.ML import ScreenComposite from rdkit.ML.Composite import Composite, BayesComposite from rdkit.ML.Data import DataUtils, SplitData from rdkit.utils import listutils from rdkit.six.moves import cPickle # # from ML.SVM import SVMClassificationModel as SVM _runDetails = CompositeRun.CompositeRun() __VERSION_STRING = "3.2.3" _verbose = 1 def message(msg): """ emits messages to _sys.stdout_ override this in modules which import this one to redirect output **Arguments** - msg: the string to be displayed """ if _verbose: sys.stdout.write('%s\n' % (msg)) def testall(composite, examples, badExamples=[]): """ screens a number of examples past a composite **Arguments** - composite: a composite model - examples: a list of examples (with results) to be screened - badExamples: a list to which misclassified examples are appended **Returns** a list of 2-tuples containing: 1) a vote 2) a confidence these are the votes and confidence levels for **misclassified** examples """ wrong = [] for example in examples: if composite.GetActivityQuantBounds(): answer = composite.QuantizeActivity(example)[-1] else: answer = example[-1] res, conf = composite.ClassifyExample(example) if res != answer: wrong.append((res, conf)) badExamples.append(example) return wrong def GetCommandLine(details): """ #DOC """ args = ['BuildComposite'] args.append('-n %d' % (details.nModels)) if details.filterFrac != 0.0: args.append('-F %.3f -v %d' % (details.filterFrac, details.filterVal)) if details.modelFilterFrac != 0.0: args.append('--modelFiltFrac=%.3f --modelFiltVal=%d' % (details.modelFilterFrac, details.modelFilterVal)) if details.splitRun: args.append('-s -f %.3f' % (details.splitFrac)) if details.shuffleActivities: args.append('-S') if details.randomActivities: args.append('-r') if details.threshold > 0.0: args.append('-t %.3f' % (details.threshold)) if details.activityBounds: args.append('-Q "%s"' % (details.activityBoundsVals)) if details.dbName: args.append('-d %s' % (details.dbName)) if details.detailedRes: args.append('-D') if hasattr(details, 'noScreen') and details.noScreen: args.append('--noScreen') if details.persistTblName and details.dbName: args.append('-p %s' % (details.persistTblName)) if details.note: args.append('-N %s' % (details.note)) if details.useTrees: if details.limitDepth > 0: args.append('-L %d' % (details.limitDepth)) if details.lessGreedy: args.append('-g') if details.qBounds: shortBounds = listutils.CompactListRepr(details.qBounds) if details.qBounds: args.append('-q "%s"' % (shortBounds)) else: if details.qBounds: args.append('-q "%s"' % (details.qBoundCount)) if details.pruneIt: args.append('--prune') if details.startAt: args.append('-G %d' % details.startAt) if details.recycleVars: args.append('--recycle') if details.randomDescriptors: args.append('--randomDescriptors=%d' % details.randomDescriptors) if details.useSigTrees: args.append('--doSigTree') if details.limitDepth > 0: args.append('-L %d' % (details.limitDepth)) if details.randomDescriptors: args.append('--randomDescriptors=%d' % details.randomDescriptors) if details.useKNN: args.append('--doKnn --knnK %d' % (details.knnNeighs)) if details.knnDistFunc == 'Tanimoto': args.append('--knnTanimoto') else: args.append('--knnEuclid') if details.useNaiveBayes: args.append('--doNaiveBayes') if details.mEstimateVal >= 0.0: args.append('--mEstimateVal=%.3f' % details.mEstimateVal) # # if details.useSVM: # # args.append('--doSVM') # # if details.svmKernel: # # for k in SVM.kernels.keys(): # # if SVM.kernels[k]==details.svmKernel: # # args.append('--svmKernel=%s'%k) # # break # # if details.svmType: # # for k in SVM.machineTypes.keys(): # # if SVM.machineTypes[k]==details.svmType: # # args.append('--svmType=%s'%k) # # break # # if details.svmGamma: # # args.append('--svmGamma=%f'%details.svmGamma) # # if details.svmCost: # # args.append('--svmCost=%f'%details.svmCost) # # if details.svmWeights: # # args.append("--svmWeights='%s'"%str(details.svmWeights)) # # if details.svmDegree: # # args.append('--svmDegree=%d'%details.svmDegree) # # if details.svmCoeff: # # args.append('--svmCoeff=%d'%details.svmCoeff) # # if details.svmEps: # # args.append('--svmEps=%f'%details.svmEps) # # if details.svmNu: # # args.append('--svmNu=%f'%details.svmNu) # # if details.svmCache: # # args.append('--svmCache=%d'%details.svmCache) # # if detail.svmDataType: # # args.append('--svmDataType=%s'%details.svmDataType) # # if not details.svmShrink: # # args.append('--svmShrink') if details.replacementSelection: args.append('--replacementSelection') # this should always be last: if details.tableName: args.append(details.tableName) return ' '.join(args) def RunOnData(details, data, progressCallback=None, saveIt=1, setDescNames=0): if details.lockRandom: seed = details.randomSeed else: import random seed = (random.randint(0, 1e6), random.randint(0, 1e6)) DataUtils.InitRandomNumbers(seed) testExamples = [] if details.shuffleActivities == 1: DataUtils.RandomizeActivities(data, shuffle=1, runDetails=details) elif details.randomActivities == 1: DataUtils.RandomizeActivities(data, shuffle=0, runDetails=details) namedExamples = data.GetNamedData() if details.splitRun == 1: trainIdx, testIdx = SplitData.SplitIndices( len(namedExamples), details.splitFrac, silent=not _verbose) trainExamples = [namedExamples[x] for x in trainIdx] testExamples = [namedExamples[x] for x in testIdx] else: testExamples = [] testIdx = [] trainIdx = list(range(len(namedExamples))) trainExamples = namedExamples if details.filterFrac != 0.0: # if we're doing quantization on the fly, we need to handle that here: if hasattr(details, 'activityBounds') and details.activityBounds: tExamples = [] bounds = details.activityBounds for pt in trainExamples: pt = pt[:] act = pt[-1] placed = 0 bound = 0 while not placed and bound < len(bounds): if act < bounds[bound]: pt[-1] = bound placed = 1 else: bound += 1 if not placed: pt[-1] = bound tExamples.append(pt) else: bounds = None tExamples = trainExamples trainIdx, temp = DataUtils.FilterData(tExamples, details.filterVal, details.filterFrac, -1, indicesOnly=1) tmp = [trainExamples[x] for x in trainIdx] testExamples += [trainExamples[x] for x in temp] trainExamples = tmp counts = DataUtils.CountResults(trainExamples, bounds=bounds) ks = counts.keys() ks.sort() message('Result Counts in training set:') for k in ks: message(str((k, counts[k]))) counts = DataUtils.CountResults(testExamples, bounds=bounds) ks = counts.keys() ks.sort() message('Result Counts in test set:') for k in ks: message(str((k, counts[k]))) nExamples = len(trainExamples) message('Training with %d examples' % (nExamples)) nVars = data.GetNVars() attrs = list(range(1, nVars + 1)) nPossibleVals = data.GetNPossibleVals() for i in range(1, len(nPossibleVals)): if nPossibleVals[i - 1] == -1: attrs.remove(i) if details.pickleDataFileName != '': pickleDataFile = open(details.pickleDataFileName, 'wb+') cPickle.dump(trainExamples, pickleDataFile) cPickle.dump(testExamples, pickleDataFile) pickleDataFile.close() if details.bayesModel: composite = BayesComposite.BayesComposite() else: composite = Composite.Composite() composite._randomSeed = seed composite._splitFrac = details.splitFrac composite._shuffleActivities = details.shuffleActivities composite._randomizeActivities = details.randomActivities if hasattr(details, 'filterFrac'): composite._filterFrac = details.filterFrac if hasattr(details, 'filterVal'): composite._filterVal = details.filterVal composite.SetModelFilterData(details.modelFilterFrac, details.modelFilterVal) composite.SetActivityQuantBounds(details.activityBounds) nPossibleVals = data.GetNPossibleVals() if details.activityBounds: nPossibleVals[-1] = len(details.activityBounds) + 1 if setDescNames: composite.SetInputOrder(data.GetVarNames()) composite.SetDescriptorNames(details._descNames) else: composite.SetDescriptorNames(data.GetVarNames()) composite.SetActivityQuantBounds(details.activityBounds) if details.nModels == 1: details.internalHoldoutFrac = 0.0 if details.useTrees: from rdkit.ML.DecTree import CrossValidate, PruneTree if details.qBounds != []: from rdkit.ML.DecTree import BuildQuantTree builder = BuildQuantTree.QuantTreeBoot else: from rdkit.ML.DecTree import ID3 builder = ID3.ID3Boot driver = CrossValidate.CrossValidationDriver pruner = PruneTree.PruneTree composite.SetQuantBounds(details.qBounds) nPossibleVals = data.GetNPossibleVals() if details.activityBounds: nPossibleVals[-1] = len(details.activityBounds) + 1 composite.Grow( trainExamples, attrs, nPossibleVals=[0] + nPossibleVals, buildDriver=driver, pruner=pruner, nTries=details.nModels, pruneIt=details.pruneIt, lessGreedy=details.lessGreedy, needsQuantization=0, treeBuilder=builder, nQuantBounds=details.qBounds, startAt=details.startAt, maxDepth=details.limitDepth, progressCallback=progressCallback, holdOutFrac=details.internalHoldoutFrac, replacementSelection=details.replacementSelection, recycleVars=details.recycleVars, randomDescriptors=details.randomDescriptors, silent=not _verbose) elif details.useSigTrees: from rdkit.ML.DecTree import CrossValidate from rdkit.ML.DecTree import BuildSigTree builder = BuildSigTree.SigTreeBuilder driver = CrossValidate.CrossValidationDriver nPossibleVals = data.GetNPossibleVals() if details.activityBounds: nPossibleVals[-1] = len(details.activityBounds) + 1 if hasattr(details, 'sigTreeBiasList'): biasList = details.sigTreeBiasList else: biasList = None if hasattr(details, 'useCMIM'): useCMIM = details.useCMIM else: useCMIM = 0 if hasattr(details, 'allowCollections'): allowCollections = details.allowCollections else: allowCollections = False composite.Grow( trainExamples, attrs, nPossibleVals=[0] + nPossibleVals, buildDriver=driver, nTries=details.nModels, needsQuantization=0, treeBuilder=builder, maxDepth=details.limitDepth, progressCallback=progressCallback, holdOutFrac=details.internalHoldoutFrac, replacementSelection=details.replacementSelection, recycleVars=details.recycleVars, randomDescriptors=details.randomDescriptors, biasList=biasList, useCMIM=useCMIM, allowCollection=allowCollections, silent=not _verbose) elif details.useKNN: from rdkit.ML.KNN import CrossValidate from rdkit.ML.KNN import DistFunctions driver = CrossValidate.CrossValidationDriver dfunc = '' if (details.knnDistFunc == "Euclidean"): dfunc = DistFunctions.EuclideanDist elif (details.knnDistFunc == "Tanimoto"): dfunc = DistFunctions.TanimotoDist else: assert 0, "Bad KNN distance metric value" composite.Grow(trainExamples, attrs, nPossibleVals=[0] + nPossibleVals, buildDriver=driver, nTries=details.nModels, needsQuantization=0, numNeigh=details.knnNeighs, holdOutFrac=details.internalHoldoutFrac, distFunc=dfunc) elif details.useNaiveBayes or details.useSigBayes: from rdkit.ML.NaiveBayes import CrossValidate driver = CrossValidate.CrossValidationDriver if not (hasattr(details, 'useSigBayes') and details.useSigBayes): composite.Grow(trainExamples, attrs, nPossibleVals=[0] + nPossibleVals, buildDriver=driver, nTries=details.nModels, needsQuantization=0, nQuantBounds=details.qBounds, holdOutFrac=details.internalHoldoutFrac, replacementSelection=details.replacementSelection, mEstimateVal=details.mEstimateVal, silent=not _verbose) else: if hasattr(details, 'useCMIM'): useCMIM = details.useCMIM else: useCMIM = 0 composite.Grow(trainExamples, attrs, nPossibleVals=[0] + nPossibleVals, buildDriver=driver, nTries=details.nModels, needsQuantization=0, nQuantBounds=details.qBounds, mEstimateVal=details.mEstimateVal, useSigs=True, useCMIM=useCMIM, holdOutFrac=details.internalHoldoutFrac, replacementSelection=details.replacementSelection, silent=not _verbose) # # elif details.useSVM: # # from rdkit.ML.SVM import CrossValidate # # driver = CrossValidate.CrossValidationDriver # # composite.Grow(trainExamples, attrs, nPossibleVals=[0]+nPossibleVals, # # buildDriver=driver, nTries=details.nModels, # # needsQuantization=0, # # cost=details.svmCost,gamma=details.svmGamma, # # weights=details.svmWeights,degree=details.svmDegree, # # type=details.svmType,kernelType=details.svmKernel, # # coef0=details.svmCoeff,eps=details.svmEps,nu=details.svmNu, # # cache_size=details.svmCache,shrinking=details.svmShrink, # # dataType=details.svmDataType, # # holdOutFrac=details.internalHoldoutFrac, # # replacementSelection=details.replacementSelection, # # silent=not _verbose) else: from rdkit.ML.Neural import CrossValidate driver = CrossValidate.CrossValidationDriver composite.Grow(trainExamples, attrs, [0] + nPossibleVals, nTries=details.nModels, buildDriver=driver, needsQuantization=0) composite.AverageErrors() composite.SortModels() modelList, counts, avgErrs = composite.GetAllData() counts = numpy.array(counts) avgErrs = numpy.array(avgErrs) composite._varNames = data.GetVarNames() for i in range(len(modelList)): modelList[i].NameModel(composite._varNames) # do final statistics weightedErrs = counts * avgErrs averageErr = sum(weightedErrs) / sum(counts) devs = (avgErrs - averageErr) devs = devs * counts devs = numpy.sqrt(devs * devs) avgDev = sum(devs) / sum(counts) message('# Overall Average Error: %%% 5.2f, Average Deviation: %%% 6.2f' % (100. * averageErr, 100. * avgDev)) if details.bayesModel: composite.Train(trainExamples, verbose=0) # blow out the saved examples and then save the composite: composite.ClearModelExamples() if saveIt: composite.Pickle(details.outName) details.model = DbModule.binaryHolder(cPickle.dumps(composite)) badExamples = [] if not details.detailedRes and (not hasattr(details, 'noScreen') or not details.noScreen): if details.splitRun: message('Testing all hold-out examples') wrong = testall(composite, testExamples, badExamples) message('%d examples (%% %5.2f) were misclassified' % (len(wrong), 100. * float(len(wrong)) / float(len(testExamples)))) _runDetails.holdout_error = float(len(wrong)) / len(testExamples) else: message('Testing all examples') wrong = testall(composite, namedExamples, badExamples) message('%d examples (%% %5.2f) were misclassified' % (len(wrong), 100. * float(len(wrong)) / float(len(namedExamples)))) _runDetails.overall_error = float(len(wrong)) / len(namedExamples) if details.detailedRes: message('\nEntire data set:') resTup = ScreenComposite.ShowVoteResults( range(data.GetNPts()), data, composite, nPossibleVals[-1], details.threshold) nGood, nBad, nSkip, avgGood, avgBad, avgSkip, voteTab = resTup nPts = len(namedExamples) nClass = nGood + nBad _runDetails.overall_error = float(nBad) / nClass _runDetails.overall_correct_conf = avgGood _runDetails.overall_incorrect_conf = avgBad _runDetails.overall_result_matrix = repr(voteTab) nRej = nClass - nPts if nRej > 0: _runDetails.overall_fraction_dropped = float(nRej) / nPts if details.splitRun: message('\nHold-out data:') resTup = ScreenComposite.ShowVoteResults( range(len(testExamples)), testExamples, composite, nPossibleVals[-1], details.threshold) nGood, nBad, nSkip, avgGood, avgBad, avgSkip, voteTab = resTup nPts = len(testExamples) nClass = nGood + nBad _runDetails.holdout_error = float(nBad) / nClass _runDetails.holdout_correct_conf = avgGood _runDetails.holdout_incorrect_conf = avgBad _runDetails.holdout_result_matrix = repr(voteTab) nRej = nClass - nPts if nRej > 0: _runDetails.holdout_fraction_dropped = float(nRej) / nPts if details.persistTblName and details.dbName: message('Updating results table %s:%s' % (details.dbName, details.persistTblName)) details.Store(db=details.dbName, table=details.persistTblName) if details.badName != '': badFile = open(details.badName, 'w+') for i in range(len(badExamples)): ex = badExamples[i] vote = wrong[i] outStr = '%s\t%s\n' % (ex, vote) badFile.write(outStr) badFile.close() composite.ClearModelExamples() return composite def RunIt(details, progressCallback=None, saveIt=1, setDescNames=0): """ does the actual work of building a composite model **Arguments** - details: a _CompositeRun.CompositeRun_ object containing details (options, parameters, etc.) about the run - progressCallback: (optional) a function which is called with a single argument (the number of models built so far) after each model is built. - saveIt: (optional) if this is nonzero, the resulting model will be pickled and dumped to the filename specified in _details.outName_ - setDescNames: (optional) if nonzero, the composite's _SetInputOrder()_ method will be called using the results of the data set's _GetVarNames()_ method; it is assumed that the details object has a _descNames attribute which is passed to the composites _SetDescriptorNames()_ method. Otherwise (the default), _SetDescriptorNames()_ gets the results of _GetVarNames()_. **Returns** the composite model constructed """ details.rundate = time.asctime() fName = details.tableName.strip() if details.outName == '': details.outName = fName + '.pkl' if not details.dbName: if details.qBounds != []: data = DataUtils.TextFileToData(fName) else: data = DataUtils.BuildQuantDataSet(fName) elif details.useSigTrees or details.useSigBayes: details.tableName = fName data = details.GetDataSet(pickleCol=0, pickleClass=DataStructs.ExplicitBitVect) elif details.qBounds != [] or not details.useTrees: details.tableName = fName data = details.GetDataSet() else: data = DataUtils.DBToQuantData(details.dbName, # Function no longer defined fName, quantName=details.qTableName, user=details.dbUser, password=details.dbPassword) composite = RunOnData(details, data, progressCallback=progressCallback, saveIt=saveIt, setDescNames=setDescNames) return composite def ShowVersion(includeArgs=0): """ prints the version number """ print('This is BuildComposite.py version %s' % (__VERSION_STRING)) if includeArgs: print('command line was:') print(' '.join(sys.argv)) def Usage(): """ provides a list of arguments for when this is used from the command line """ print(__doc__) sys.exit(-1) def SetDefaults(runDetails=None): """ initializes a details object with default values **Arguments** - details: (optional) a _CompositeRun.CompositeRun_ object. If this is not provided, the global _runDetails will be used. **Returns** the initialized _CompositeRun_ object. """ if runDetails is None: runDetails = _runDetails return CompositeRun.SetDefaults(runDetails) def ParseArgs(runDetails): """ parses command line arguments and updates _runDetails_ **Arguments** - runDetails: a _CompositeRun.CompositeRun_ object. """ import getopt args, extra = getopt.getopt( sys.argv[1:], 'P:o:n:p:b:sf:F:v:hlgd:rSTt:BQ:q:DVG:N:L:', ['nRuns=', 'prune', 'profile', 'seed=', 'noScreen', 'modelFiltFrac=', 'modelFiltVal=', 'recycle', 'randomDescriptors=', 'doKnn', 'knnK=', 'knnTanimoto', 'knnEuclid', 'doSigTree', 'allowCollections', 'doNaiveBayes', 'mEstimateVal=', 'doSigBayes', # # 'doSVM','svmKernel=','svmType=','svmGamma=', # # 'svmCost=','svmWeights=','svmDegree=', # # 'svmCoeff=','svmEps=','svmNu=','svmCache=', # # 'svmShrink','svmDataType=', 'replacementSelection', ]) runDetails.profileIt = 0 for arg, val in args: if arg == '-n': runDetails.nModels = int(val) elif arg == '-N': runDetails.note = val elif arg == '-o': runDetails.outName = val elif arg == '-Q': qBounds = eval(val) assert type(qBounds) in [type([]), type( ())], 'bad argument type for -Q, specify a list as a string' runDetails.activityBounds = qBounds runDetails.activityBoundsVals = val elif arg == '-p': runDetails.persistTblName = val elif arg == '-P': runDetails.pickleDataFileName = val elif arg == '-r': runDetails.randomActivities = 1 elif arg == '-S': runDetails.shuffleActivities = 1 elif arg == '-b': runDetails.badName = val elif arg == '-B': runDetails.bayesModels = 1 elif arg == '-s': runDetails.splitRun = 1 elif arg == '-f': runDetails.splitFrac = float(val) elif arg == '-F': runDetails.filterFrac = float(val) elif arg == '-v': runDetails.filterVal = float(val) elif arg == '-l': runDetails.lockRandom = 1 elif arg == '-g': runDetails.lessGreedy = 1 elif arg == '-G': runDetails.startAt = int(val) elif arg == '-d': runDetails.dbName = val elif arg == '-T': runDetails.useTrees = 0 elif arg == '-t': runDetails.threshold = float(val) elif arg == '-D': runDetails.detailedRes = 1 elif arg == '-L': runDetails.limitDepth = int(val) elif arg == '-q': qBounds = eval(val) assert type(qBounds) in [type([]), type( ())], 'bad argument type for -q, specify a list as a string' runDetails.qBoundCount = val runDetails.qBounds = qBounds elif arg == '-V': ShowVersion() sys.exit(0) elif arg == '--nRuns': runDetails.nRuns = int(val) elif arg == '--modelFiltFrac': runDetails.modelFilterFrac = float(val) elif arg == '--modelFiltVal': runDetails.modelFilterVal = float(val) elif arg == '--prune': runDetails.pruneIt = 1 elif arg == '--profile': runDetails.profileIt = 1 elif arg == '--recycle': runDetails.recycleVars = 1 elif arg == '--randomDescriptors': runDetails.randomDescriptors = int(val) elif arg == '--doKnn': runDetails.useKNN = 1 runDetails.useTrees = 0 # # runDetails.useSVM=0 runDetails.useNaiveBayes = 0 elif arg == '--knnK': runDetails.knnNeighs = int(val) elif arg == '--knnTanimoto': runDetails.knnDistFunc = "Tanimoto" elif arg == '--knnEuclid': runDetails.knnDistFunc = "Euclidean" elif arg == '--doSigTree': # # runDetails.useSVM=0 runDetails.useKNN = 0 runDetails.useTrees = 0 runDetails.useNaiveBayes = 0 runDetails.useSigTrees = 1 elif arg == '--allowCollections': runDetails.allowCollections = True elif arg == '--doNaiveBayes': runDetails.useNaiveBayes = 1 # # runDetails.useSVM=0 runDetails.useKNN = 0 runDetails.useTrees = 0 runDetails.useSigBayes = 0 elif arg == '--doSigBayes': runDetails.useSigBayes = 1 runDetails.useNaiveBayes = 0 # # runDetails.useSVM=0 runDetails.useKNN = 0 runDetails.useTrees = 0 elif arg == '--mEstimateVal': runDetails.mEstimateVal = float(val) # # elif arg == '--doSVM': # # runDetails.useSVM=1 # # runDetails.useKNN=0 # # runDetails.useTrees=0 # # runDetails.useNaiveBayes=0 # # elif arg == '--svmKernel': # # if val not in SVM.kernels.keys(): # # message('kernel %s not in list of available kernels:\n%s\n'%(val,SVM.kernels.keys())) # # sys.exit(-1) # # else: # # runDetails.svmKernel=SVM.kernels[val] # # elif arg == '--svmType': # # if val not in SVM.machineTypes.keys(): # # message('type %s not in list of available machines:\n%s\n'%(val, # # SVM.machineTypes.keys())) # # sys.exit(-1) # # else: # # runDetails.svmType=SVM.machineTypes[val] # # elif arg == '--svmGamma': # # runDetails.svmGamma = float(val) # # elif arg == '--svmCost': # # runDetails.svmCost = float(val) # # elif arg == '--svmWeights': # # # FIX: this is dangerous # # runDetails.svmWeights = eval(val) # # elif arg == '--svmDegree': # # runDetails.svmDegree = int(val) # # elif arg == '--svmCoeff': # # runDetails.svmCoeff = float(val) # # elif arg == '--svmEps': # # runDetails.svmEps = float(val) # # elif arg == '--svmNu': # # runDetails.svmNu = float(val) # # elif arg == '--svmCache': # # runDetails.svmCache = int(val) # # elif arg == '--svmShrink': # # runDetails.svmShrink = 0 # # elif arg == '--svmDataType': # # runDetails.svmDataType=val elif arg == '--seed': # FIX: dangerous runDetails.randomSeed = eval(val) elif arg == '--noScreen': runDetails.noScreen = 1 elif arg == '--replacementSelection': runDetails.replacementSelection = 1 elif arg == '-h': Usage() else: Usage() runDetails.tableName = extra[0] if __name__ == '__main__': if len(sys.argv) < 2: Usage() _runDetails.cmd = ' '.join(sys.argv) SetDefaults(_runDetails) ParseArgs(_runDetails) ShowVersion(includeArgs=1) if _runDetails.nRuns > 1: for i in range(_runDetails.nRuns): sys.stderr.write( '---------------------------------\n\tDoing %d of %d\n---------------------------------\n' % (i + 1, _runDetails.nRuns)) RunIt(_runDetails) else: if _runDetails.profileIt: try: import hotshot import hotshot.stats prof = hotshot.Profile('prof.dat') prof.runcall(RunIt, _runDetails) stats = hotshot.stats.load('prof.dat') stats.strip_dirs() stats.sort_stats('time', 'calls') stats.print_stats(30) except ImportError: print('Profiling requires the hotshot module') else: RunIt(_runDetails)
{ "repo_name": "rvianello/rdkit", "path": "rdkit/ML/BuildComposite.py", "copies": "4", "size": "35920", "license": "bsd-3-clause", "hash": -5752471011890846000, "line_mean": 33.9416342412, "line_max": 100, "alpha_frac": 0.6465200445, "autogenerated": false, "ratio": 3.645590175581041, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6292110220081041, "avg_score": null, "num_lines": null }
""" command line utility for screening composite models **Usage** _ScreenComposite [optional args] modelfile(s) datafile_ Unless indicated otherwise (via command line arguments), _modelfile_ is a file containing a pickled composite model and _filename_ is a QDAT file. **Command Line Arguments** - -t *threshold value(s)*: use high-confidence predictions for the final analysis of the hold-out data. The threshold value can be either a single float or a list/tuple of floats. All thresholds should be between 0.0 and 1.0 - -D: do a detailed screen. - -d *database name*: instead of reading the data from a QDAT file, pull it from a database. In this case, the _datafile_ argument provides the name of the database table containing the data set. - -N *note*: use all models from the database which have this note. The modelfile argument should contain the name of the table with the models. - -H: screen only the hold out set (works only if a version of BuildComposite more recent than 1.2.2 was used). - -T: screen only the training set (works only if a version of BuildComposite more recent than 1.2.2 was used). - -E: do a detailed Error analysis. This shows each misclassified point and the number of times it was missed across all screened composites. If the --enrich argument is also provided, only compounds that have true activity value equal to the enrichment value will be used. - --enrich *enrichVal*: target "active" value to be used in calculating enrichments. - -A: show All predictions. - -S: shuffle activity values before screening - -R: randomize activity values before screening - -F *filter frac*: filters the data before training to change the distribution of activity values in the training set. *filter frac* is the fraction of the training set that should have the target value. **See note in BuildComposite help about data filtering** - -v *filter value*: filters the data before training to change the distribution of activity values in the training set. *filter value* is the target value to use in filtering. **See note in BuildComposite help about data filtering** - -V: be verbose when screening multiple models - -h: show this message and exit - --OOB: Do out an "out-of-bag" generalization error estimate. This only makes sense when applied to the original data set. - --pickleCol *colId*: index of the column containing a pickled value (used primarily for cases where fingerprints are used as descriptors) *** Options for making Prediction (Hanneke) Plots *** - --predPlot=<fileName>: triggers the generation of a Hanneke plot and sets the name of the .txt file which will hold the output data. A Gnuplot control file, <fileName>.gnu, will also be generated. - --predActTable=<name> (optional): name of the database table containing activity values. If this is not provided, activities will be read from the same table containing the screening data - --predActCol=<name> (optional): name of the activity column. If not provided, the name of the last column in the activity table will be used. - --predLogScale (optional): If provided, the x axis of the prediction plot (the activity axis) will be plotted using a log scale - --predShow: launch a gnuplot instance and display the prediction plot (the plot will still be written to disk). *** The following options are likely obsolete *** - -P: read pickled data. The datafile argument should contain a pickled data set. *relevant only to qdat files* - -q: data are not quantized (the composite should take care of quantization itself if it requires quantized data). *relevant only to qdat files* """ from rdkit import RDConfig from rdkit import DataStructs import sys,cPickle,types,copy import numpy try: from PIL import Image,ImageDraw except ImportError: hasPil=0 else: hasPil=1 from rdkit.ML.Data import DataUtils,SplitData from rdkit.ML import CompositeRun from rdkit.Dbase.DbConnection import DbConnect from rdkit.Dbase import DbModule _details = CompositeRun.CompositeRun() __VERSION_STRING="3.3.0" def message(msg,noRet=0): """ emits messages to _sys.stdout_ override this in modules which import this one to redirect output **Arguments** - msg: the string to be displayed """ if noRet: sys.stdout.write('%s '%(msg)) else: sys.stdout.write('%s\n'%(msg)) def error(msg): """ emits messages to _sys.stderr_ override this in modules which import this one to redirect output **Arguments** - msg: the string to be displayed """ sys.stderr.write('ERROR: %s\n'%(msg)) def CalcEnrichment(mat,tgt=1): if tgt<0 or tgt>=mat.shape[0]: return 0 nPts = float(sum(sum(mat))) nTgtPred = float(sum(mat[:,tgt])) if nTgtPred: pctCorrect = mat[tgt,tgt]/nTgtPred nTgtReal = float(sum(mat[tgt,:])) pctOverall = nTgtReal/nPts else: return 0.0 return pctCorrect/pctOverall def CollectResults(indices,dataSet,composite,callback=None,appendExamples=0, errorEstimate=0): """ screens a set of examples through a composite and returns the results #DOC **Arguments** - examples: the examples to be screened (a sequence of sequences) it's assumed that the last element in each example is it's "value" - composite: the composite model to be used - callback: (optional) if provided, this should be a function taking a single argument that is called after each example is screened with the number of examples screened so far as the argument. - appendExamples: (optional) this value is passed on to the composite's _ClassifyExample()_ method. - errorEstimate: (optional) calculate the "out of bag" error estimate for the composite using Breiman's definition. This only makes sense when screening the original data set! [L. Breiman "Out-of-bag Estimation", UC Berkeley Dept of Statistics Technical Report (1996)] **Returns** a list of 3-tuples _nExamples_ long: 1) answer: the value from the example 2) pred: the composite model's prediction 3) conf: the confidence of the composite """ #for i in range(len(composite)): # print ' ',i,'TRAIN:',composite[i][0]._trainIndices for j in range(len(composite)): tmp = composite.GetModel(j) if hasattr(tmp,'_trainIndices') and type(tmp._trainIndices)!=types.DictType: tis = {} if hasattr(tmp,'_trainIndices'): for v in tmp._trainIndices: tis[v]=1 tmp._trainIndices=tis nPts = len(indices) res = [None]*nPts for i in range(nPts): idx = indices[i] example = dataSet[idx] if errorEstimate: use = [] for j in range(len(composite)): mdl = composite.GetModel(j) if not mdl._trainIndices.get(idx,0): use.append(j) else: use = None #print 'IDX:',idx,'use:',use pred,conf = composite.ClassifyExample(example,appendExample=appendExamples, onlyModels=use) if composite.GetActivityQuantBounds(): answer = composite.QuantizeActivity(example)[-1] else: answer = example[-1] res[i] = answer,pred,conf if callback: callback(i) return res def DetailedScreen(indices,data,composite,threshold=0,screenResults=None, goodVotes=None,badVotes=None,noVotes=None,callback=None, appendExamples=0,errorEstimate=0): """ screens a set of examples cross a composite and breaks the predictions into *correct*,*incorrect* and *unclassified* sets. #DOC **Arguments** - examples: the examples to be screened (a sequence of sequences) it's assumed that the last element in each example is its "value" - composite: the composite model to be used - threshold: (optional) the threshold to be used to decide whether or not a given prediction should be kept - screenResults: (optional) the results of screening the results (a sequence of 3-tuples in the format returned by _CollectResults()_). If this is provided, the examples will not be screened again. - goodVotes,badVotes,noVotes: (optional) if provided these should be lists (or anything supporting an _append()_ method) which will be used to pass the screening results back. - callback: (optional) if provided, this should be a function taking a single argument that is called after each example is screened with the number of examples screened so far as the argument. - appendExamples: (optional) this value is passed on to the composite's _ClassifyExample()_ method. - errorEstimate: (optional) calculate the "out of bag" error estimate for the composite using Breiman's definition. This only makes sense when screening the original data set! [L. Breiman "Out-of-bag Estimation", UC Berkeley Dept of Statistics Technical Report (1996)] **Notes** - since this function doesn't return anything, if one or more of the arguments _goodVotes_, _badVotes_, and _noVotes_ is not provided, there's not much reason to call it """ if screenResults is None: screenResults = CollectResults(indices,data,composite,callback=callback, appendExamples=appendExamples, errorEstimate=errorEstimate) if goodVotes is None: goodVotes = [] if badVotes is None: badVotes = [] if noVotes is None: noVotes = [] for i in range(len(screenResults)): answer,pred,conf = screenResults[i] if conf > threshold: if pred != answer: badVotes.append((answer,pred,conf,i)) else: goodVotes.append((answer,pred,conf,i)) else: noVotes.append((answer,pred,conf,i)) def ShowVoteResults(indices,data,composite,nResultCodes,threshold,verbose=1, screenResults=None,callback=None,appendExamples=0, goodVotes=None,badVotes=None,noVotes=None, errorEstimate=0): """ screens the results and shows a detailed workup The work of doing the screening and processing the results is handled by _DetailedScreen()_ #DOC **Arguments** - examples: the examples to be screened (a sequence of sequences) it's assumed that the last element in each example is its "value" - composite: the composite model to be used - nResultCodes: the number of possible results the composite can return - threshold: the threshold to be used to decide whether or not a given prediction should be kept - screenResults: (optional) the results of screening the results (a sequence of 3-tuples in the format returned by _CollectResults()_). If this is provided, the examples will not be screened again. - callback: (optional) if provided, this should be a function taking a single argument that is called after each example is screened with the number of examples screened so far as the argument. - appendExamples: (optional) this value is passed on to the composite's _ClassifyExample()_ method. - goodVotes,badVotes,noVotes: (optional) if provided these should be lists (or anything supporting an _append()_ method) which will be used to pass the screening results back. - errorEstimate: (optional) calculate the "out of bag" error estimate for the composite using Breiman's definition. This only makes sense when screening the original data set! [L. Breiman "Out-of-bag Estimation", UC Berkeley Dept of Statistics Technical Report (1996)] **Returns** a 7-tuple: 1) the number of good (correct) predictions 2) the number of bad (incorrect) predictions 3) the number of predictions skipped due to the _threshold_ 4) the average confidence in the good predictions 5) the average confidence in the bad predictions 6) the average confidence in the skipped predictions 7) the results table """ nExamples = len(indices) if goodVotes is None: goodVotes = [] if badVotes is None: badVotes = [] if noVotes is None: noVotes = [] DetailedScreen(indices,data,composite,threshold,screenResults=screenResults, goodVotes=goodVotes,badVotes=badVotes,noVotes=noVotes,callback=callback, appendExamples=appendExamples,errorEstimate=errorEstimate) nBad = len(badVotes) nGood = len(goodVotes) nClassified = nGood + nBad if verbose: print '\n\t*** Vote Results ***' print 'misclassified: %d/%d (%%%4.2f)\t%d/%d (%%%4.2f)'%(nBad,nExamples, 100.*float(nBad)/nExamples, nBad,nClassified, 100.*float(nBad)/nClassified) nSkip = len(noVotes) if nSkip > 0: if verbose: print 'skipped: %d/%d (%%% 4.2f)'%(nSkip,nExamples,100.*float(nSkip)/nExamples) noConf = numpy.array([x[2] for x in noVotes]) avgSkip = sum(noConf)/float(nSkip) else: avgSkip = 0. if nBad > 0: badConf = numpy.array([x[2] for x in badVotes]) avgBad = sum(badConf)/float(nBad) else: avgBad = 0. if nGood > 0: goodRes = [x[1] for x in goodVotes] goodConf = numpy.array([x[2] for x in goodVotes]) avgGood = sum(goodConf)/float(nGood) else: goodRes = [] goodConf = [] avgGood = 0. if verbose: print print 'average correct confidence: % 6.4f'%avgGood print 'average incorrect confidence: % 6.4f'%avgBad voteTab = numpy.zeros((nResultCodes,nResultCodes),numpy.int) for res in goodRes: voteTab[res,res] += 1 for ans,res,conf,idx in badVotes: voteTab[ans,res] += 1 if verbose: print print '\tResults Table:' vTab=voteTab.transpose() colCounts = numpy.sum(vTab,0) rowCounts = numpy.sum(vTab,1) message('') for i in range(nResultCodes): if rowCounts[i]==0: rowCounts[i]=1 row = vTab[i] message(' ',noRet=1) for j in range(nResultCodes): entry = row[j] message(' % 6d'%entry,noRet=1) message(' | % 4.2f'%(100.*vTab[i,i]/rowCounts[i])) message(' ',noRet=1) for i in range(nResultCodes): message('-------',noRet=1) message('') message(' ',noRet=1) for i in range(nResultCodes): if colCounts[i]==0: colCounts[i]=1 message(' % 6.2f'%(100.*vTab[i,i]/colCounts[i]),noRet=1) message('') return nGood,nBad,nSkip,avgGood,avgBad,avgSkip,voteTab def ScreenIt(composite,indices,data,partialVote=0,voteTol=0.0,verbose=1,screenResults=None, goodVotes=None,badVotes=None,noVotes=None): """ screens a set of data using a composite model and prints out statistics about the screen. #DOC The work of doing the screening and processing the results is handled by _DetailedScreen()_ **Arguments** - composite: the composite model to be used - data: the examples to be screened (a sequence of sequences) it's assumed that the last element in each example is its "value" - partialVote: (optional) toggles use of the threshold value in the screnning. - voteTol: (optional) the threshold to be used to decide whether or not a given prediction should be kept - verbose: (optional) sets degree of verbosity of the screening - screenResults: (optional) the results of screening the results (a sequence of 3-tuples in the format returned by _CollectResults()_). If this is provided, the examples will not be screened again. - goodVotes,badVotes,noVotes: (optional) if provided these should be lists (or anything supporting an _append()_ method) which will be used to pass the screening results back. **Returns** a 7-tuple: 1) the number of good (correct) predictions 2) the number of bad (incorrect) predictions 3) the number of predictions skipped due to the _threshold_ 4) the average confidence in the good predictions 5) the average confidence in the bad predictions 6) the average confidence in the skipped predictions 7) None """ if goodVotes is None: goodVotes = [] if badVotes is None: badVotes = [] if noVotes is None: noVotes = [] if not partialVote: voteTol = 0.0 DetailedScreen(indices,data,composite,voteTol,screenResults=screenResults, goodVotes=goodVotes,badVotes=badVotes,noVotes=noVotes) nGood = len(goodVotes) goodAccum = 0. for res,pred,conf,idx in goodVotes: goodAccum += conf misCount = len(badVotes) badAccum = 0. for res,pred,conf,idx in badVotes: badAccum += conf nSkipped = len(noVotes) goodSkipped = 0 badSkipped = 0 skipAccum = 0. for ans,pred,conf,idx in noVotes: skipAccum += conf if ans != pred: badSkipped += 1 else: goodSkipped += 1 nData = nGood + misCount + nSkipped if verbose: print 'Total N Points:',nData if partialVote: nCounted = nData-nSkipped if verbose: print 'Misclassifications: %d (%%%4.2f)'%(misCount,100.*float(misCount)/nCounted) print 'N Skipped: %d (%%%4.2f)'%(nSkipped,100.*float(nSkipped)/nData) print '\tGood Votes Skipped: %d (%%%4.2f)'%(goodSkipped,100.*float(goodSkipped)/nSkipped) print '\tBad Votes Skipped: %d (%%%4.2f)'%(badSkipped,100.*float(badSkipped)/nSkipped) else: if verbose: print 'Misclassifications: %d (%%%4.2f)'%(misCount,100.*float(misCount)/nData) print 'Average Correct Vote Confidence: % 6.4f'%(goodAccum/(nData-misCount)) print 'Average InCorrect Vote Confidence: % 6.4f'%(badAccum/misCount) avgGood=0 avgBad=0 avgSkip=0 if nGood: avgGood = goodAccum/nGood if misCount: avgBad = badAccum/misCount if nSkipped: avgSkip = skipAccum/nSkipped return nGood,misCount,nSkipped,avgGood,avgBad,avgSkip,None def _processVoteList(votes,data): """ *Internal Use Only* converts a list of 4 tuples: (answer,prediction,confidence,idx) into an alternate list: (answer,prediction,confidence,data point) **Arguments** - votes: a list of 4 tuples: (answer, prediction, confidence, index) - data: a _DataUtils.MLData.MLDataSet_ **Note**: alterations are done in place in the _votes_ list """ for i in range(len(votes)): ans,pred,conf,idx = votes[i] votes[i] = (ans,pred,conf,data[idx]) def PrepareDataFromDetails(model,details,data,verbose=0): if (hasattr(details,'doHoldout') and details.doHoldout) or \ (hasattr(details,'doTraining') and details.doTraining): try: splitF = model._splitFrac except AttributeError: pass else: if verbose: message('s',noRet=1) if hasattr(details,'errorEstimate') and details.errorEstimate and \ hasattr(details,'doHoldout') and details.doHoldout: message('*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*') message('****** WARNING: OOB screening should not be combined with doHoldout option.') message('*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*') trainIdx,testIdx = SplitData.SplitIndices(data.GetNPts(),splitF,silent=1) if hasattr(details,'filterFrac') and details.filterFrac != 0.0: if verbose: message('f',noRet=1) trainFilt,temp = DataUtils.FilterData(data,details.filterVal, details.filterFrac,-1, indicesToUse=trainIdx, indicesOnly=1) testIdx += temp trainIdx = trainFilt elif hasattr(details,'errorEstimate') and details.errorEstimate: # the OOB screening works by checking to see if a given index # is in the if hasattr(details,'filterFrac') and details.filterFrac != 0.0: if verbose: message('f',noRet=1) testIdx,trainIdx = DataUtils.FilterData(data,details.filterVal, details.filterFrac,-1, indicesToUse=range(data.GetNPts()), indicesOnly=1) testIdx.extend(trainIdx) else: testIdx = range(data.GetNPts()) trainIdx = [] else: testIdx = range(data.GetNPts()) trainIdx = [] if hasattr(details,'doTraining') and details.doTraining: testIdx,trainIdx = trainIdx,testIdx return trainIdx,testIdx def ScreenFromDetails(models,details,callback=None,setup=None,appendExamples=0, goodVotes=None,badVotes=None,noVotes=None,data=None, enrichments=None): """ Screens a set of data using a a _CompositeRun.CompositeRun_ instance to provide parameters # DOC The actual data to be used are extracted from the database and table specified in _details_ Aside from dataset construction, _ShowVoteResults()_ does most of the heavy lifting here. **Arguments** - model: a composite model - details: a _CompositeRun.CompositeRun_ object containing details (options, parameters, etc.) about the run - callback: (optional) if provided, this should be a function taking a single argument that is called after each example is screened with the number of examples screened so far as the argument. - setup: (optional) a function taking a single argument which is called at the start of screening with the number of points to be screened as the argument. - appendExamples: (optional) this value is passed on to the composite's _ClassifyExample()_ method. - goodVotes,badVotes,noVotes: (optional) if provided these should be lists (or anything supporting an _append()_ method) which will be used to pass the screening results back. **Returns** a 7-tuple: 1) the number of good (correct) predictions 2) the number of bad (incorrect) predictions 3) the number of predictions skipped due to the _threshold_ 4) the average confidence in the good predictions 5) the average confidence in the bad predictions 6) the average confidence in the skipped predictions 7) the results table """ if data is None: if hasattr(details,'pickleCol'): data = details.GetDataSet(pickleCol=details.pickleCol, pickleClass=DataStructs.ExplicitBitVect) else: data = details.GetDataSet() if details.threshold>0.0: partialVote = 1 else: partialVote = 0 if type(models) not in [types.ListType,types.TupleType]: models = (models,) nModels = len(models) if setup is not None: setup(nModels*data.GetNPts()) nGood = numpy.zeros(nModels,numpy.float) nBad = numpy.zeros(nModels,numpy.float) nSkip = numpy.zeros(nModels,numpy.float) confGood = numpy.zeros(nModels,numpy.float) confBad = numpy.zeros(nModels,numpy.float) confSkip = numpy.zeros(nModels,numpy.float) voteTab = None if goodVotes is None: goodVotes = [] if badVotes is None: badVotes = [] if noVotes is None: noVotes = [] if enrichments is None: enrichments = [0.0]*nModels badVoteDict = {} noVoteDict = {} for i in range(nModels): if nModels>1: goodVotes = [] badVotes=[] noVotes=[] model = models[i] try: seed = model._randomSeed except AttributeError: pass else: DataUtils.InitRandomNumbers(seed) if (hasattr(details,'shuffleActivities') and details.shuffleActivities) or \ (hasattr(details,'randomActivities') and details.randomActivities ): if hasattr(details,'shuffleActivities') and details.shuffleActivities: shuffle = True else: shuffle = False randomize=True DataUtils.RandomizeActivities(data,shuffle=shuffle, runDetails=details) else: randomize=False shuffle=False if hasattr(model,'_shuffleActivities') and \ model._shuffleActivities and \ not shuffle: message('*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*') message('****** WARNING: Shuffled model being screened with unshuffled data.') message('*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*') if hasattr(model,'_randomizeActivities') and \ model._randomizeActivities and \ not randomize: message('*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*') message('****** WARNING: Random model being screened with non-random data.') message('*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*') trainIdx,testIdx = PrepareDataFromDetails(model,details,data) nPossible = model.GetQuantBounds()[1] if callback: cb = lambda x,y=callback,z=i*data.GetNPts():y(x+z) else: cb = None if not hasattr(details,'errorEstimate') or not details.errorEstimate: errorEstimate = 0 else: errorEstimate = 1 g,b,s,aG,aB,aS,vT = ShowVoteResults(testIdx,data,model,nPossible[-1], details.threshold,verbose=0, callback=cb,appendExamples=appendExamples, goodVotes=goodVotes,badVotes=badVotes, noVotes=noVotes, errorEstimate=errorEstimate) if voteTab is None: voteTab = numpy.zeros(vT.shape,numpy.float) if hasattr(details,'errorAnalysis') and details.errorAnalysis: for a,p,c,idx in badVotes: label = testIdx[idx] if hasattr(details,'enrichTgt') and details.enrichTgt >=0: if a==details.enrichTgt: badVoteDict[label] = badVoteDict.get(label,0)+1 else: badVoteDict[label] = badVoteDict.get(label,0)+1 for a,p,c,idx in noVotes: label = testIdx[idx] if hasattr(details,'enrichTgt') and details.enrichTgt >=0: if a==details.enrichTgt: noVoteDict[label] = noVoteDict.get(label,0)+1 else: noVoteDict[label] = noVoteDict.get(label,0)+1 voteTab += vT nGood[i] = g nBad[i] = b nSkip[i] = s confGood[i] = aG confBad[i] = aB confSkip[i] = aS if hasattr(details,'enrichTgt') and details.enrichTgt >=0: enrichments[i] = CalcEnrichment(vT,tgt=details.enrichTgt) if nModels == 1: return g,b,s,aG,aB,aS,vT else: voteTab /= nModels avgNBad = sum(nBad)/nModels devNBad = numpy.sqrt(sum((nBad-avgNBad)**2)/(nModels-1)) bestIdx = numpy.argsort(nBad)[0] avgNGood = sum(nGood)/nModels devNGood = numpy.sqrt(sum((nGood-avgNGood)**2)/(nModels-1)) avgNSkip = sum(nSkip)/nModels devNSkip = numpy.sqrt(sum((nSkip-avgNSkip)**2)/(nModels-1)) avgConfBad = sum(confBad)/nModels devConfBad = numpy.sqrt(sum((confBad-avgConfBad)**2)/(nModels-1)) avgConfGood = sum(confGood)/nModels devConfGood = numpy.sqrt(sum((confGood-avgConfGood)**2)/(nModels-1)) avgConfSkip = sum(confSkip)/nModels devConfSkip = numpy.sqrt(sum((confSkip-avgConfSkip)**2)/(nModels-1)) return (avgNGood,devNGood),(avgNBad,devNBad),(avgNSkip,devNSkip),\ (avgConfGood,devConfGood),(avgConfBad,devConfBad),(avgConfSkip,devConfSkip),\ voteTab def GetScreenImage(nGood,nBad,nRej,size=None): if not hasPil: return None try: nTot = float(nGood)+float(nBad)+float(nRej) except TypeError: nGood = nGood[0] nBad = nBad[0] nRej = nRej[0] nTot = float(nGood)+float(nBad)+float(nRej) if not nTot: return None goodColor = (100,100,255) badColor = (255,100,100) rejColor = (255,255,100) pctGood = float(nGood) / nTot pctBad = float(nBad) / nTot pctRej = float(nRej) / nTot if size is None: size = (100,100) img = Image.new('RGB',size,(255,255,255)) draw = ImageDraw.Draw(img) box = (0,0,size[0]-1,size[1]-1) startP = -90 endP = int(startP + pctGood*360) draw.pieslice(box,startP,endP,fill=goodColor) startP = endP endP = int(startP + pctBad*360) draw.pieslice(box,startP,endP,fill=badColor) startP = endP endP = int(startP + pctRej*360) draw.pieslice(box,startP,endP,fill=rejColor) return img def ScreenToHtml(nGood,nBad,nRej,avgGood,avgBad,avgSkip,voteTable,imgDir='.', fullPage=1,skipImg=0,includeDefs=1): """ returns the text of a web page showing the screening details #DOC **Arguments** - nGood: number of correct predictions - nBad: number of incorrect predictions - nRej: number of rejected predictions - avgGood: average correct confidence - avgBad: average incorrect confidence - avgSkip: average rejected confidence - voteTable: vote table - imgDir: (optional) the directory to be used to hold the vote image (if constructed) **Returns** a string containing HTML """ if type(nGood) == types.TupleType: multModels=1 else: multModels=0 if fullPage: outTxt = ["""<html><body>"""] outTxt.append('<center><h2>VOTE DETAILS</h2></center>') else: outTxt = [] outTxt.append('<font>') # Get the image if not skipImg: img = GetScreenImage(nGood,nBad,nRej) if img: if imgDir: imgFileName = '/'.join((imgDir,'votes.png')) else: imgFileName = 'votes.png' img.save(imgFileName) outTxt.append('<center><img src="%s"></center>'%(imgFileName)) nPoss = len(voteTable) pureCounts = numpy.sum(voteTable,1) accCounts = numpy.sum(voteTable,0) pureVect = numpy.zeros(nPoss,numpy.float) accVect = numpy.zeros(nPoss,numpy.float) for i in range(nPoss): if pureCounts[i]: pureVect[i] = float(voteTable[i,i])/pureCounts[i] if accCounts[i]: accVect[i] = float(voteTable[i,i])/accCounts[i] outTxt.append('<center><table border=1>') outTxt.append('<tr><td></td>') for i in xrange(nPoss): outTxt.append('<th>%d</th>'%i) outTxt.append('<th>% Accurate</th>') outTxt.append('</tr>') #outTxt.append('<th rowspan=%d>Predicted</th></tr>'%(nPoss+1)) for i in xrange(nPoss): outTxt.append('<tr><th>%d</th>'%(i)) for j in xrange(nPoss): if i == j: if not multModels: outTxt.append('<td bgcolor="#A0A0FF">%d</td>'%(voteTable[j,i])) else: outTxt.append('<td bgcolor="#A0A0FF">%.2f</td>'%(voteTable[j,i])) else: if not multModels: outTxt.append('<td>%d</td>'%(voteTable[j,i])) else: outTxt.append('<td>%.2f</td>'%(voteTable[j,i])) outTxt.append('<td>%4.2f</td</tr>'%(100.0*accVect[i])) if i == 0: outTxt.append('<th rowspan=%d>Predicted</th></tr>'%(nPoss)) else: outTxt.append('</tr>') outTxt.append('<tr><th>% Pure</th>') for i in range(nPoss): outTxt.append('<td>%4.2f</td>'%(100.0*pureVect[i])) outTxt.append('</tr>') outTxt.append('<tr><td></td><th colspan=%d>Original</th>'%(nPoss)) outTxt.append('</table></center>') if not multModels: nTotal = nBad+nGood+nRej nClass = nBad+nGood if nClass: pctErr = 100.*float(nBad)/nClass else: pctErr = 0.0 outTxt.append('<p>%d of %d examples were misclassified (%%%4.2f)'%(nBad,nGood+nBad,pctErr)) if nRej > 0: pctErr = 100.*float(nBad)/(nGood+nBad+nRej) outTxt.append('<p> %d of %d overall: (%%%4.2f)'%(nBad,nTotal,pctErr)) pctRej = 100.*float(nRej)/nTotal outTxt.append('<p>%d of %d examples were rejected (%%%4.2f)'%(nRej,nTotal,pctRej)) if nGood != 0: outTxt.append('<p>The correctly classified examples had an average confidence of %6.4f'%avgGood) if nBad != 0: outTxt.append('<p>The incorrectly classified examples had an average confidence of %6.4f'%avgBad) if nRej != 0: outTxt.append('<p>The rejected examples had an average confidence of %6.4f'%avgSkip) else: nTotal = nBad[0]+nGood[0]+nRej[0] nClass = nBad[0]+nGood[0] devClass = nBad[1]+nGood[1] if nClass: pctErr = 100.*float(nBad[0])/nClass devPctErr = 100.*float(nBad[1])/nClass else: pctErr = 0.0 devPctErr = 0.0 outTxt.append('<p>%.2f(%.2f) of %.2f(%.2f) examples were misclassified (%%%4.2f(%4.2f))'%\ (nBad[0],nBad[1],nClass,devClass,pctErr,devPctErr)) if nRej > 0: pctErr = 100.*float(nBad[0])/nTotal devPctErr = 100.*float(nBad[1])/nTotal outTxt.append('<p> %.2f(%.2f) of %d overall: (%%%4.2f(%4.2f))'%\ (nBad[0],nBad[1],nTotal,pctErr,devPctErr)) pctRej = 100.*float(nRej[0])/nTotal devPctRej = 100.*float(nRej[1])/nTotal outTxt.append('<p>%.2f(%.2f) of %d examples were rejected (%%%4.2f(%4.2f))'%\ (nRej[0],nRej[1],nTotal,pctRej,devPctRej)) if nGood != 0: outTxt.append('<p>The correctly classified examples had an average confidence of %6.4f(%.4f)'%avgGood) if nBad != 0: outTxt.append('<p>The incorrectly classified examples had an average confidence of %6.4f(%.4f)'%avgBad) if nRej != 0: outTxt.append('<p>The rejected examples had an average confidence of %6.4f(%.4f)'%avgSkip) outTxt.append('</font>') if includeDefs: txt = """ <p><b>Definitions:</b> <ul> <li> <i>% Pure:</i> The percentage of, for example, known positives predicted to be positive. <li> <i>% Accurate:</i> The percentage of, for example, predicted positives that actually are positive. </ul> """ outTxt.append(txt) if fullPage: outTxt.append("""</body></html>""") return '\n'.join(outTxt) def MakePredPlot(details,indices,data,goodVotes,badVotes,nRes,idCol=0,verbose=0): """ **Arguments** - details: a CompositeRun.RunDetails object - indices: a sequence of integer indices into _data_ - data: the data set in question. We assume that the ids for the data points are in the _idCol_ column - goodVotes/badVotes: predictions where the model was correct/incorrect. These are sequences of 4-tuples: (answer,prediction,confidence,index into _indices_) """ if not hasattr(details,'predPlot') or not details.predPlot: return if verbose: message('\n-> Constructing Prediction (Hanneke) Plot') outF = open(details.predPlot,'w+') gnuF = open('%s.gnu'%details.predPlot,'w+') # first get the ids of the data points we screened: ptIds = [data[x][idCol] for x in indices] # get a connection to the database we'll use to grab the continuous # activity values: origConn = DbConnect(details.dbName,details.tableName, user=details.dbUser,password=details.dbPassword) colNames = origConn.GetColumnNames() idName = colNames[idCol] if not hasattr(details,'predActTable') or \ not details.predActTable or \ details.predActTable==details.tableName: actConn = origConn else: actConn = DbConnect(details.dbName,details.predActTable, user=details.dbUser,password=details.dbPassword) if verbose: message('\t-> Pulling Activity Data') pts = [] if type(ptIds[0]) not in [type(''),type(u'')]: ptIds = [str(x) for x in ptIds] whereL = [DbModule.placeHolder]*len(ptIds) if hasattr(details,'predActCol') and details.predActCol: actColName=details.predActCol else: actColName = actConn.GetColumnNames()[-1] whereTxt = "%s in (%s)"%(idName,','.join(whereL)) rawD = actConn.GetData(fields='%s,%s'%(idName,actColName), where=whereTxt,extras=ptIds) # order the data returned: if verbose: message('\t-> Creating Plot') acts = [None]*len(ptIds) for entry in rawD: id,act = entry idx = ptIds.index(id) acts[idx] = act outF.write('#ID Pred Conf %s\n'%(actColName)) for ans,pred,conf,idx in goodVotes: act = acts[idx] if act!='None': act= float(act) else: act=0 outF.write('%s %d %.4f %f\n'%(ptIds[idx],pred,conf,act)) for ans,pred,conf,idx in badVotes: act = acts[idx] if act!='None': act= float(act) else: act=0 outF.write('%s %d %.4f %f\n'%(ptIds[idx],pred,conf,act)) outF.close() if not hasattr(details,'predLogScale') or not details.predLogScale: actLabel = actColName else: actLabel= 'log(%s)'%(actColName) actLabel = actLabel.replace('_',' ') gnuHdr="""# Generated by ScreenComposite.py version: %s set size square 0.7 set yrange [:1] set data styl points set ylab 'confidence' set xlab '%s' set grid set nokey set term postscript enh color solid "Helvetica" 16 set term X """%(__VERSION_STRING,actLabel) gnuF.write(gnuHdr) plots = [] for i in range(nRes): if not hasattr(details,'predLogScale') or not details.predLogScale: plots.append("'%s' us 4:($2==%d?$3:0/0)"%(details.predPlot,i)) else: plots.append("'%s' us (log10($4)):($2==%d?$3:0/0)"%(details.predPlot,i)) gnuF.write("plot %s\n"%(','.join(plots))) gnuTail=""" # EOF """ gnuF.write(gnuTail) gnuF.close() if hasattr(details,'predShow') and details.predShow: try: import os from Gnuplot import Gnuplot p = Gnuplot() p('cd "%s"'%(os.getcwd())) p('load "%s.gnu"'%(details.predPlot)) raw_input('press return to continue...\n') except: import traceback traceback.print_exc() def Go(details): pass def SetDefaults(details=None): global _details if details is None: details = _details CompositeRun.SetDefaults(details) details.screenVoteTol = [0.] details.detailedScreen = 0 details.doHoldout=0 details.doTraining=0 details.errorAnalysis=0 details.verbose=0 details.partialVote=0 return details def Usage(): """ prints a list of arguments for when this is used from the command line and then exits """ print __doc__ sys.exit(-1) def ShowVersion(includeArgs=0): """ prints the version number of the program """ print 'This is ScreenComposite.py version %s'%(__VERSION_STRING) if includeArgs: import sys print 'command line was:' print ' '.join(sys.argv) def ParseArgs(details): import getopt try: args,extras = getopt.getopt(sys.argv[1:],'EDd:t:VN:HThSRF:v:AX', ['predPlot=','predActCol=','predActTable=', 'predLogScale','predShow', 'OOB','pickleCol=','enrich=', ]) except: import traceback traceback.print_exc() Usage() fName = '' details.predPlot='' details.predActCol='' details.predActTable='' details.predLogScale='' details.predShow=0 details.errorEstimate=0 details.pickleCol=-1 details.enrichTgt=-1 for arg,val in args: if arg == '-d': details.dbName = val elif arg == '-D': details.detailedScreen = 1 elif arg == '-t': details.partialVote = 1 voteTol = eval(val) if type(voteTol) not in [type([]),type((1,1))]: voteTol = [voteTol] for tol in voteTol: if tol > 1 or tol < 0: error('Voting threshold must be between 0 and 1') sys.exit(-2) details.screenVoteTol=voteTol elif arg == '-N': details.note=val elif arg == '-H': details.doTraining=0 details.doHoldout=1 elif arg == '-T': details.doHoldout=0 details.doTraining=1 elif arg == '-E': details.errorAnalysis=1 details.detailedScreen=1 elif arg == '-A': details.showAll=1 details.detailedScreen=1 elif arg == '-S': details.shuffleActivities=1 elif arg == '-R': details.randomActivities=1 elif arg == '-h': Usage() elif arg == '-F': details.filterFrac=float(val) elif arg == '-v': details.filterVal=float(val) elif arg == '-V': verbose=1 elif arg == '--predPlot': details.detailedScreen=1 details.predPlot=val elif arg == '--predActCol': details.predActCol=val elif arg == '--predActTable': details.predActTable=val elif arg == '--predLogScale': details.predLogScale=1 elif arg == '--predShow': details.predShow=1 elif arg == '--predShow': details.predShow=1 elif arg == '--OOB': details.errorEstimate=1 elif arg == '--pickleCol': details.pickleCol=int(val)-1 elif arg == '--enrich': details.enrichTgt=int(val) else: Usage() if len(extras) < 1: Usage() return extras if __name__ == '__main__': details = SetDefaults() extras = ParseArgs(details) ShowVersion(includeArgs=1) models = [] if details.note and details.dbName: tblName = extras[0] message('-> Retrieving models from database') conn = DbConnect(details.dbName,tblName) blobs = conn.GetData(fields='model',where="where note='%s'"%(details.note)) for blob in blobs: blob = blob[0] try: models.append(cPickle.loads(str(blob))) except: import traceback traceback.print_exc() message('Model load failed') else: message('-> Loading model') modelFile=open(extras[0],'rb') models.append(cPickle.load(modelFile)) if not len(models): error('No composite models found') sys.exit(-1) else: message('-> Working with %d models.'%len(models)) extras = extras[1:] for fName in extras: if details.dbName != '': details.tableName = fName data = details.GetDataSet(pickleCol=details.pickleCol, pickleClass=DataStructs.ExplicitBitVect) else: data = DataUtils.BuildDataSet(fName) descNames = data.GetVarNames() nModels = len(models) screenResults = [None]*nModels dataSets = [None]*nModels message('-> Constructing and screening data sets') testIdx = range(data.GetNPts()) trainIdx = testIdx for modelIdx in range(nModels): #tmpD = copy.deepcopy(data) tmpD = data model = models[modelIdx] message('.',noRet=1) try: seed = model._randomSeed except AttributeError: pass else: DataUtils.InitRandomNumbers(seed) if details.shuffleActivities or details.randomActivities: shuffle = details.shuffleActivities randomize = 1 DataUtils.RandomizeActivities(tmpD,shuffle=details.shuffleActivities, runDetails=details) else: randomize = False shuffle = False if hasattr(model,'_shuffleActivities') and \ model._shuffleActivities and \ not shuffle: message('*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*') message('****** WARNING: Shuffled model being screened with unshuffled data.') message('*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*') if hasattr(model,'_randomizeActivities') and \ model._randomizeActivities and \ not randomize: message('*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*') message('****** WARNING: Random model being screened with non-random data.') message('*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*!*') trainIdx,testIdx = PrepareDataFromDetails(model,details,tmpD,verbose=1) screenResults[modelIdx] = CollectResults(testIdx,tmpD,model, errorEstimate=details.errorEstimate) dataSets[modelIdx] = testIdx for tol in details.screenVoteTol: if len(details.screenVoteTol)>1: message('\n-----*****-----*****-----*****-----*****-----*****-----*****-----\n') message('Tolerance: %f'%tol) nGood = numpy.zeros(nModels,numpy.float) nBad = numpy.zeros(nModels,numpy.float) nSkip = numpy.zeros(nModels,numpy.float) confGood = numpy.zeros(nModels,numpy.float) confBad = numpy.zeros(nModels,numpy.float) confSkip = numpy.zeros(nModels,numpy.float) if details.enrichTgt >= 0: enrichments = numpy.zeros(nModels,numpy.float) goodVoteDict = {} badVoteDict = {} noVoteDict = {} voteTab = None for modelIdx in range(nModels): model = models[modelIdx] model.SetInputOrder(descNames) testIdx = dataSets[modelIdx] screenRes = screenResults[modelIdx] if not details.detailedScreen: g,b,s,aG,aB,aS,vT = ScreenIt(model,testIdx,tmpD,details.partialVote,tol, verbose=details.verbose,screenResults=screenRes) else: if model.GetActivityQuantBounds(): nRes = len(model.GetActivityQuantBounds())+1 else: nRes = model.GetQuantBounds()[1][-1] badVotes = [] noVotes = [] if (hasattr(details,'showAll') and details.showAll) or \ (hasattr(details,'predPlot') and details.predPlot): goodVotes = [] else: goodVotes = None g,b,s,aG,aB,aS,vT = ShowVoteResults(testIdx,tmpD,model,nRes,tol, verbose=details.verbose, screenResults=screenRes, badVotes=badVotes,noVotes=noVotes, goodVotes=goodVotes, errorEstimate=details.errorEstimate) if voteTab is None: voteTab = numpy.zeros(vT.shape,numpy.float) if details.errorAnalysis: for a,p,c,idx in badVotes: label = testIdx[idx] if hasattr(details,'enrichTgt') and details.enrichTgt >=0: if a==details.enrichTgt: badVoteDict[label] = badVoteDict.get(label,0)+1 else: badVoteDict[label] = badVoteDict.get(label,0)+1 for a,p,c,idx in noVotes: label = testIdx[idx] if hasattr(details,'enrichTgt') and details.enrichTgt >=0: if a==details.enrichTgt: noVoteDict[label] = noVoteDict.get(label,0)+1 else: noVoteDict[label] = noVoteDict.get(label,0)+1 if hasattr(details,'showAll') and details.showAll: for a,p,c,idx in goodVotes: label = testIdx[idx] if details.enrichTgt >=0: if a==details.enrichTgt: goodVoteDict[label] = goodVoteDict.get(label,0)+1 else: goodVoteDict[label] = goodVoteDict.get(label,0)+1 if details.enrichTgt>-1: enrichments[modelIdx] = CalcEnrichment(vT,tgt=details.enrichTgt) voteTab += vT if details.detailedScreen and hasattr(details,'predPlot') and details.predPlot: MakePredPlot(details,testIdx,tmpD,goodVotes,badVotes,nRes,verbose=1) if hasattr(details,'showAll') and details.showAll: print '-v-v-v-v-v-v-v- All Votes -v-v-v-v-v-v-v-' print 'id, prediction, confidence, flag(-1=skipped,0=wrong,1=correct)' for ans,pred,conf,idx in goodVotes: pt = tmpD[testIdx[idx]] assert model.GetActivityQuantBounds() or pt[-1]==ans,\ 'bad point?: %s != %s'%(str(pt[-1]),str(ans)) print '%s, %d, %.4f, 1'%(str(pt[0]),pred,conf) for ans,pred,conf,idx in badVotes: pt = tmpD[testIdx[idx]] assert model.GetActivityQuantBounds() or pt[-1]==ans,\ 'bad point?: %s != %s'%(str(pt[-1]),str(ans)) print '%s, %d, %.4f, 0'%(str(pt[0]),pred,conf) for ans,pred,conf,idx in noVotes: pt = tmpD[testIdx[idx]] assert model.GetActivityQuantBounds() or pt[-1]==ans,\ 'bad point?: %s != %s'%(str(pt[-1]),str(ans)) print '%s, %d, %.4f, -1'%(str(pt[0]),pred,conf) print '-^-^-^-^-^-^-^- -^-^-^-^-^-^-^-' nGood[modelIdx] = g nBad[modelIdx] = b nSkip[modelIdx] = s confGood[modelIdx] = aG confBad[modelIdx] = aB confSkip[modelIdx] = aS print if nModels > 1: print '-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*' print 'AVERAGES:' avgNBad = sum(nBad)/nModels devNBad = numpy.sqrt(sum((nBad-avgNBad)**2)/(nModels-1)) bestIdx = numpy.argsort(nBad)[0] avgNGood = sum(nGood)/nModels devNGood = numpy.sqrt(sum((nGood-avgNGood)**2)/(nModels-1)) avgNSkip = sum(nSkip)/nModels devNSkip = numpy.sqrt(sum((nSkip-avgNSkip)**2)/(nModels-1)) avgConfBad = sum(confBad)/nModels devConfBad = numpy.sqrt(sum((confBad-avgConfBad)**2)/(nModels-1)) avgConfGood = sum(confGood)/nModels devConfGood = numpy.sqrt(sum((confGood-avgConfGood)**2)/(nModels-1)) avgConfSkip = sum(confSkip)/nModels devConfSkip = numpy.sqrt(sum((confSkip-avgConfSkip)**2)/(nModels-1)) nClassified = avgNGood + avgNBad nExamples = nClassified + avgNSkip print 'Misclassifications: \t%%%5.2f(%%%5.2f) %4.1f(%4.1f) / %d'%(100*avgNBad/nExamples, 100*devNBad/nExamples, avgNBad,devNBad, nExamples) if avgNSkip>0: print '\tthreshold: \t%%%5.2f(%%%5.2f) %4.1f(%4.1f) / %d'%(100*avgNBad/nClassified, 100*devNBad/nClassified, avgNBad,devNBad, nClassified) print print 'Number Skipped: %%%4.2f(%%%4.2f) %4.2f(%4.2f)'%(100*avgNSkip/nExamples, 100*devNSkip/nExamples, avgNSkip,devNSkip) print print 'Confidences:' print '\tCorrect: \t%4.2f(%4.2f)'%(100*avgConfGood,100*devConfGood) print '\tIncorrect: \t%4.2f(%4.2f)'%(100*avgConfBad,100*devConfBad) if avgNSkip>0: print '\tSkipped: \t%4.2f(%4.2f)'%(100*avgConfSkip,100*devConfSkip) if details.detailedScreen: message('Results Table:') voteTab = numpy.transpose(voteTab)/nModels nResultCodes = len(voteTab) colCounts = numpy.sum(voteTab,0) rowCounts = numpy.sum(voteTab,1) print for i in range(nResultCodes): if rowCounts[i]==0: rowCounts[i]=1 row = voteTab[i] message(' ',noRet=1) for j in range(nResultCodes): entry = row[j] message(' % 6.2f'%entry,noRet=1) message(' | % 4.2f'%(100.*voteTab[i,i]/rowCounts[i])) message(' ',noRet=1) for i in range(nResultCodes): message('-------',noRet=1) message('') message(' ',noRet=1) for i in range(nResultCodes): if colCounts[i]==0: colCounts[i]=1 message(' % 6.2f'%(100.*voteTab[i,i]/colCounts[i]),noRet=1) message('') if details.enrichTgt >-1: mean = sum(enrichments)/nModels enrichments -= mean dev = numpy.sqrt(sum(enrichments*enrichments))/(nModels-1) message(' Enrichment of value %d: %.4f (%.4f)'%(details.enrichTgt,mean,dev)) else: bestIdx=0 print '------------------------------------------------' print 'Best Model: ',bestIdx+1 bestBad = nBad[bestIdx] bestGood = nGood[bestIdx] bestSkip = nSkip[bestIdx] nClassified = bestGood + bestBad nExamples = nClassified + bestSkip print 'Misclassifications: \t%%%5.2f %d / %d'%(100*bestBad/nExamples, bestBad,nExamples) if bestSkip>0: print '\tthreshold: \t%%%5.2f %d / %d'%(100*bestBad/nClassified, bestBad,nClassified) print print 'Number Skipped: %%%4.2f %d'%(100*bestSkip/nExamples, bestSkip) print print 'Confidences:' print '\tCorrect: \t%4.2f'%(100*confGood[bestIdx]) print '\tIncorrect: \t%4.2f'%(100*confBad[bestIdx]) if bestSkip>0: print '\tSkipped: \t%4.2f'%(100*confSkip[bestIdx]) if nModels == 1 and details.detailedScreen: message('') message('Results Table:') voteTab = numpy.transpose(vT) nResultCodes = len(vT) colCounts = numpy.sum(voteTab,0) rowCounts = numpy.sum(voteTab,1) message('') for i in range(nResultCodes): if rowCounts[i]==0: rowCounts[i]=1 row = voteTab[i] message(' ',noRet=1) for j in range(nResultCodes): entry = row[j] message(' % 6.2f'%entry,noRet=1) message(' | % 4.2f'%(100.*voteTab[i,i]/rowCounts[i])) message(' ',noRet=1) for i in range(nResultCodes): message('-------',noRet=1) message('') message(' ',noRet=1) for i in range(nResultCodes): if colCounts[i]==0: colCounts[i]=1 message(' % 6.2f'%(100.*voteTab[i,i]/colCounts[i]),noRet=1) message('') if details.errorAnalysis: message('\n*-*-*-*-*-*-*-*- ERROR ANALYSIS -*-*-*-*-*-*-*-*\n') ks = badVoteDict.keys() if len(ks): message(' ---> Bad Vote Counts') ks = noVoteDict.keys() if len(ks): message(' ---> Skipped Compound Counts') for k in ks: pt = data[k] message('%s,%d'%(str(pt[0]),noVoteDict[k])) if hasattr(details,'showAll') and details.showAll: ks = goodVoteDict.keys() if len(ks): message(' ---> Good Vote Counts') for k in ks: pt = data[k] message('%s,%d'%(str(pt[0]),goodVoteDict[k]))
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/ML/ScreenComposite.py", "copies": "2", "size": "54939", "license": "bsd-3-clause", "hash": -7196283739450902000, "line_mean": 32.7255985267, "line_max": 109, "alpha_frac": 0.6049800688, "autogenerated": false, "ratio": 3.481117729058421, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5086097797858421, "avg_score": null, "num_lines": null }
""" Configuration for the RDKit Python code """ import os, sys if 'RDBASE' in os.environ: RDBaseDir = os.environ['RDBASE'] RDCodeDir = os.path.join(RDBaseDir, 'rdkit') RDDataDir = os.path.join(RDBaseDir, 'Data') RDDocsDir = os.path.join(RDBaseDir, 'Docs') RDDemoDir = os.path.join(RDBaseDir, 'Demo') RDBinDir = os.path.join(RDBaseDir, 'bin') RDProjDir = os.path.join(RDBaseDir, 'Projects') RDContribDir = os.path.join(RDBaseDir, 'Contrib') elif 'CONDA_DEFAULT_ENV' in os.environ: # we are running in a conda environ. RDCodeDir = os.path.dirname(__file__) splitdir = RDCodeDir.split(os.path.sep) condaDir = splitdir[:-4] if condaDir[0] == '': condaDir[0] = os.path.sep condaDir += ['share', 'RDKit'] _share = os.path.join(*condaDir) RDDataDir = os.path.join(_share, 'Data') RDDocsDir = os.path.join(_share, 'Docs') RDProjDir = os.path.join(_share, 'Projects') RDContribDir = os.path.join(_share, 'Contrib') else: from rdkit.RDPaths import * rpcTestPort = 8423 pythonTestCommand = "python" defaultDBUser = 'sysdba' defaultDBPassword = 'masterkey' class ObsoleteCodeError(Exception): pass class UnimplementedCodeError(Exception): pass # --------------------- # the following block contains stuff used by the # testing infrastructure if sys.platform == 'win32': pythonExe = sys.executable else: pythonExe = "python" # --------------------- # the following block contains stuff controlling database access: usePgSQL = False useSqlLite = False if not os.environ.get('RD_USESQLLITE', ''): try: from pyPgSQL import PgSQL usePgSQL = True except ImportError: usePgSQL = False if not usePgSQL: try: # python2.5 has this: import sqlite3 useSqlLite = True except ImportError: try: # earlier versions of python: from pysqlite2 import dbapi2 useSqlLite = True except ImportError: pass if usePgSQL: RDTestDatabase = '::RDTests' RDDataDatabase = '::RDData' elif useSqlLite: RDTestDatabase = os.path.join(RDDataDir, "RDTests.sqlt") RDDataDatabase = os.path.join(RDDataDir, "RDData.sqlt") else: RDTestDatabase = None RDDataDatabase = None # --------------------- # the following block contains stuff controlling the program used for # 3D molecular visualization: molViewer = os.environ.get('RD_MOLVIEWER', 'PYMOL').upper()
{ "repo_name": "rvianello/rdkit", "path": "rdkit/RDConfig.py", "copies": "2", "size": "2627", "license": "bsd-3-clause", "hash": 311176032434034560, "line_mean": 25.5353535354, "line_max": 69, "alpha_frac": 0.6844309098, "autogenerated": false, "ratio": 3.051103368176539, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47355342779765386, "avg_score": null, "num_lines": null }
""" Defines the class _QuantTreeNode_, used to represent decision trees with automatic quantization bounds _QuantTreeNode_ is derived from _DecTree.DecTreeNode_ """ from rdkit.ML.DecTree import DecTree,Tree from rdkit.six import cmp class QuantTreeNode(DecTree.DecTreeNode): """ """ def __init__(self,*args,**kwargs): DecTree.DecTreeNode.__init__(self,*args,**kwargs) self.qBounds = [] self.nBounds = 0 def ClassifyExample(self,example,appendExamples=0): """ Recursively classify an example by running it through the tree **Arguments** - example: the example to be classified - appendExamples: if this is nonzero then this node (and all children) will store the example **Returns** the classification of _example_ **NOTE:** In the interest of speed, I don't use accessor functions here. So if you subclass DecTreeNode for your own trees, you'll have to either include ClassifyExample or avoid changing the names of the instance variables this needs. """ if appendExamples: self.examples.append(example) if self.terminalNode: return self.label else: val = example[self.label] if not hasattr(self,'nBounds'): self.nBounds = len(self.qBounds) if self.nBounds: for i,bound in enumerate(self.qBounds): if val < bound: val = i break else: val = i+1 else: val = int(val) return self.children[val].ClassifyExample(example,appendExamples=appendExamples) def SetQuantBounds(self,qBounds): self.qBounds = qBounds[:] self.nBounds = len(self.qBounds) def GetQuantBounds(self): return self.qBounds def __cmp__(self,other): return (self<other)*-1 or (other<self)*1 def __lt__(self,other): if str(type(self)) < str(type(other)): return True if self.qBounds<other.qBounds: return True if Tree.TreeNode.__lt__(self,other): return True return False def __eq__(self,other): return not self<other and not other<self def __str__(self): """ returns a string representation of the tree **Note** this works recursively """ here = '%s%s %s\n'%(' '*self.level,self.name,str(self.qBounds)) for child in self.children: here = here + str(child) return here
{ "repo_name": "AlexanderSavelyev/rdkit", "path": "rdkit/ML/DecTree/QuantTree.py", "copies": "4", "size": "2502", "license": "bsd-3-clause", "hash": -4669066850408949000, "line_mean": 26.8, "line_max": 86, "alpha_frac": 0.6366906475, "autogenerated": false, "ratio": 3.8551617873651773, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.032767582522450066, "num_lines": 90 }
""" Calculation of Lipinski parameters for molecules """ #from Chem import rdchem from rdkit import Chem from rdkit.Chem import rdMolDescriptors #----------------------------------- # on import build the SMARTS patterns so we only have to do it once #----------------------------------- # The Daylight SMARTS expressions for # recognizing H-bond donors and acceptors in the Lipinski scheme. # HDonor '[!#6;!H0;-0]' # HAcceptor '[$([!#6;+0]);!$([F,Cl,Br,I]); # !$([o,s,nX3]);!$([Nv5,Pv5,Sv4,Sv6])]' # Heteroatom '[B,N,O,P,S,F,Cl,Br,I]' # 2 definitions adapted from those in the Gobbi Paper # NOTE: if you want traditional Lipinski numbers, you # should use NOCounts (below) instead of HAcceptor # HDonorSmarts = Chem.MolFromSmarts('[$([N;!H0;v3]),$([N;!H0;+1;v4]),$([O,S;H1;+0]),$([n;H1;+0])]') # changes log for HAcceptorSmarts: # v2, 1-Nov-2008, GL : fix amide-N exclusion; remove Fs from definition HAcceptorSmarts = Chem.MolFromSmarts('[$([O,S;H1;v2]-[!$(*=[O,N,P,S])]),\ $([O,S;H0;v2]),$([O,S;-]),\ $([N;v3;!$(N-*=!@[O,N,P,S])]),\ $([nH0,o,s;+0])\ ]') HeteroatomSmarts = Chem.MolFromSmarts('[!#6;!#1]') # NOTE: the Rotatable bond smarts here doesn't treat deuteriums (which are left in the graph # and therefore contribute to the degree of a carbon) the same as hydrogens (which are removed # from the graph). So the bond in [2H]C([2H])([2H])C([2H])([2H])[2H] *is* considered # rotatable. RotatableBondSmarts = Chem.MolFromSmarts('[!$(*#*)&!D1]-&!@[!$(*#*)&!D1]') NHOHSmarts = Chem.MolFromSmarts('[#8H1,#7H1,#7H2,#7H3]') NOCountSmarts = Chem.MolFromSmarts('[#7,#8]') # this little trick saves duplicated code def _NumMatches(mol, smarts): return len(mol.GetSubstructMatches(smarts, uniquify=1)) NumHDonors = lambda x: rdMolDescriptors.CalcNumHBD(x) NumHDonors.__doc__ = "Number of Hydrogen Bond Donors" NumHDonors.version = "1.0.0" _HDonors = lambda x, y=HDonorSmarts: x.GetSubstructMatches(y, uniquify=1) NumHAcceptors = lambda x: rdMolDescriptors.CalcNumHBA(x) NumHAcceptors.__doc__ = "Number of Hydrogen Bond Acceptors" NumHAcceptors.version = "2.0.0" _HAcceptors = lambda x, y=HAcceptorSmarts: x.GetSubstructMatches(y, uniquify=1) NumHeteroatoms = lambda x: rdMolDescriptors.CalcNumHeteroatoms(x) NumHeteroatoms.__doc__ = "Number of Heteroatoms" NumHeteroatoms.version = "1.0.0" _Heteroatoms = lambda x, y=HeteroatomSmarts: x.GetSubstructMatches(y, uniquify=1) NumRotatableBonds = lambda x: rdMolDescriptors.CalcNumRotatableBonds(x) NumRotatableBonds.__doc__ = "Number of Rotatable Bonds" NumRotatableBonds.version = "1.0.0" _RotatableBonds = lambda x, y=RotatableBondSmarts: x.GetSubstructMatches(y, uniquify=1) NOCount = lambda x: rdMolDescriptors.CalcNumLipinskiHBA(x) NOCount.__doc__ = "Number of Nitrogens and Oxygens" NOCount.version = "1.0.0" NHOHCount = lambda x: rdMolDescriptors.CalcNumLipinskiHBD(x) NHOHCount.__doc__ = "Number of NHs or OHs" NHOHCount.version = "2.0.0" RingCount = lambda x: rdMolDescriptors.CalcNumRings(x) RingCount.version = "1.0.0" def HeavyAtomCount(mol): " Number of heavy atoms a molecule." return mol.GetNumHeavyAtoms() HeavyAtomCount.version = "1.0.1" _bulkConvert = ("CalcFractionCSP3", "CalcNumAromaticRings", "CalcNumSaturatedRings", "CalcNumAromaticHeterocycles", "CalcNumAromaticCarbocycles", "CalcNumSaturatedHeterocycles", "CalcNumSaturatedCarbocycles", "CalcNumAliphaticRings", "CalcNumAliphaticHeterocycles", "CalcNumAliphaticCarbocycles") for txt in _bulkConvert: _cfn = getattr(rdMolDescriptors, txt) _fn = lambda x, y=_cfn: y(x) try: _fn.version = getattr(rdMolDescriptors, "_" + txt + "_version") except AttributeError: pass _fn.__doc__ = _cfn.__doc__ nm = txt.replace("Calc", "") locals()[nm] = _fn
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/Lipinski.py", "copies": "1", "size": "4086", "license": "bsd-3-clause", "hash": 307675783458763200, "line_mean": 38.2884615385, "line_max": 97, "alpha_frac": 0.6857562408, "autogenerated": false, "ratio": 2.6008911521324, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8748218090702599, "avg_score": 0.007685860445960206, "num_lines": 104 }
"""Cluster tree visualization using Sping """ try: from rdkit.sping import pid piddle = pid except ImportError: from rdkit.piddle import piddle import ClusterUtils import numpy class VisOpts(object): """ stores visualization options for cluster viewing **Instance variables** - x/yOffset: amount by which the drawing is offset from the edges of the canvas - lineColor: default color for drawing the cluster tree - lineWidth: the width of the lines used to draw the tree """ xOffset = 20 yOffset = 20 lineColor = piddle.Color(0,0,0) hideColor = piddle.Color(.8,.8,.8) terminalColors = [piddle.Color(1,0,0),piddle.Color(0,0,1),piddle.Color(1,1,0), piddle.Color(0,.5,.5),piddle.Color(0,.8,0),piddle.Color(.5,.5,.5), piddle.Color(.8,.3,.3),piddle.Color(.3,.3,.8),piddle.Color(.8,.8,.3), piddle.Color(.3,.8,.8)] lineWidth = 2 hideWidth = 1.1 nodeRad=15 nodeColor = piddle.Color(1.,.4,.4) highlightColor = piddle.Color(1.,1.,.4) highlightRad = 10 def _scaleMetric(val,power=2,min=1e-4): val = float(val) nval = pow(val,power) if nval < min: return 0.0 else: return numpy.log(nval/min) class ClusterRenderer(object): def __init__(self,canvas,size, ptColors=[],lineWidth=None, showIndices=0, showNodes=1, stopAtCentroids=0, logScale=0, tooClose=-1): self.canvas = canvas self.size = size self.ptColors = ptColors self.lineWidth = lineWidth self.showIndices = showIndices self.showNodes = showNodes self.stopAtCentroids = stopAtCentroids self.logScale = logScale self.tooClose = tooClose def _AssignPointLocations(self,cluster,terminalOffset=4): self.pts = cluster.GetPoints() self.nPts = len(self.pts) self.xSpace = float(self.size[0]-2*VisOpts.xOffset)/float(self.nPts-1) ySize = self.size[1] for i in xrange(self.nPts): pt = self.pts[i] if self.logScale > 0: v = _scaleMetric(pt.GetMetric(), self.logScale) else: v = float(pt.GetMetric()) pt._drawPos = (VisOpts.xOffset+i*self.xSpace, ySize-(v*self.ySpace+VisOpts.yOffset)+terminalOffset) def _AssignClusterLocations(self,cluster): # first get the search order (top down) toDo = [cluster] examine = cluster.GetChildren()[:] while len(examine): node = examine.pop(0) children = node.GetChildren() if len(children): toDo.append(node) for child in children: if not child.IsTerminal(): examine.append(child) # and reverse it (to run from bottom up) toDo.reverse() for node in toDo: if self.logScale > 0: v = _scaleMetric(node.GetMetric(), self.logScale) else: v = float(node.GetMetric()) # average our children's x positions childLocs = [x._drawPos[0] for x in node.GetChildren()] if len(childLocs): xp = sum(childLocs)/float(len(childLocs)) yp = self.size[1] - (v*self.ySpace+VisOpts.yOffset) node._drawPos = (xp,yp) def _DrawToLimit(self,cluster): """ we assume that _drawPos settings have been done already """ if self.lineWidth is None: lineWidth = VisOpts.lineWidth else: lineWidth = self.lineWidth examine = [cluster] while len(examine): node = examine.pop(0) xp,yp = node._drawPos children = node.GetChildren() if abs(children[1]._drawPos[0]-children[0]._drawPos[0])>self.tooClose: # draw the horizontal line connecting things drawColor = VisOpts.lineColor self.canvas.drawLine(children[0]._drawPos[0],yp, children[-1]._drawPos[0],yp, drawColor,lineWidth) # and draw the lines down to the children for child in children: if self.ptColors and child.GetData() is not None: drawColor = self.ptColors[child.GetData()] else: drawColor = VisOpts.lineColor cxp,cyp = child._drawPos self.canvas.drawLine(cxp,yp,cxp,cyp,drawColor,lineWidth) if not child.IsTerminal(): examine.append(child) else: if self.showIndices and not self.stopAtCentroids: try: txt = str(child.GetName()) except Exception: txt = str(child.GetIndex()) self.canvas.drawString(txt, cxp-self.canvas.stringWidth(txt)/2, cyp) else: # draw a "hidden" line to the bottom self.canvas.drawLine(xp,yp,xp,self.size[1]-VisOpts.yOffset, VisOpts.hideColor,lineWidth) def DrawTree(self,cluster,minHeight=2.0): if self.logScale > 0: v = _scaleMetric(cluster.GetMetric(), self.logScale) else: v = float(cluster.GetMetric()) if v <= 0: v = minHeight self.ySpace = float(self.size[1]-2*VisOpts.yOffset)/v self._AssignPointLocations(cluster) self._AssignClusterLocations(cluster) if not self.stopAtCentroids: self._DrawToLimit(cluster) else: raise NotImplementedError('stopAtCentroids drawing not yet implemented') def DrawClusterTree(cluster,canvas,size, ptColors=[],lineWidth=None, showIndices=0, showNodes=1, stopAtCentroids=0, logScale=0, tooClose=-1): """ handles the work of drawing a cluster tree on a Sping canvas **Arguments** - cluster: the cluster tree to be drawn - canvas: the Sping canvas on which to draw - size: the size of _canvas_ - ptColors: if this is specified, the _colors_ will be used to color the terminal nodes of the cluster tree. (color == _pid.Color_) - lineWidth: if specified, it will be used for the widths of the lines used to draw the tree **Notes** - _Canvas_ is neither _save_d nor _flush_ed at the end of this - if _ptColors_ is the wrong length for the number of possible terminal node types, this will throw an IndexError - terminal node types are determined using their _GetData()_ methods """ renderer = ClusterRenderer(canvas,size,ptColors,lineWidth,showIndices,showNodes,stopAtCentroids, logScale,tooClose) renderer.DrawTree(cluster) def _DrawClusterTree(cluster,canvas,size, ptColors=[],lineWidth=None, showIndices=0, showNodes=1, stopAtCentroids=0, logScale=0, tooClose=-1): """ handles the work of drawing a cluster tree on a Sping canvas **Arguments** - cluster: the cluster tree to be drawn - canvas: the Sping canvas on which to draw - size: the size of _canvas_ - ptColors: if this is specified, the _colors_ will be used to color the terminal nodes of the cluster tree. (color == _pid.Color_) - lineWidth: if specified, it will be used for the widths of the lines used to draw the tree **Notes** - _Canvas_ is neither _save_d nor _flush_ed at the end of this - if _ptColors_ is the wrong length for the number of possible terminal node types, this will throw an IndexError - terminal node types are determined using their _GetData()_ methods """ if lineWidth is None: lineWidth = VisOpts.lineWidth pts = cluster.GetPoints() nPts = len(pts) if nPts <= 1: return xSpace = float(size[0]-2*VisOpts.xOffset)/float(nPts-1) if logScale > 0: v = _scaleMetric(cluster.GetMetric(), logScale) else: v = float(cluster.GetMetric()) ySpace = float(size[1]-2*VisOpts.yOffset)/v for i in xrange(nPts): pt = pts[i] if logScale > 0: v = _scaleMetric(pt.GetMetric(), logScale) else: v = float(pt.GetMetric()) pt._drawPos = (VisOpts.xOffset+i*xSpace, size[1]-(v*ySpace+VisOpts.yOffset)) if not stopAtCentroids or not hasattr(pt,'_isCentroid'): allNodes.remove(pt) if not stopAtCentroids: allNodes=ClusterUtils.GetNodeList(cluster) else: allNodes=ClusterUtils.GetNodesDownToCentroids(cluster) while len(allNodes): node = allNodes.pop(0) children = node.GetChildren() if len(children): if logScale > 0: v = _scaleMetric(node.GetMetric(), logScale) else: v = float(node.GetMetric()) yp = size[1]-(v*ySpace+VisOpts.yOffset) childLocs = [x._drawPos[0] for x in children] xp = sum(childLocs)/float(len(childLocs)) node._drawPos = (xp,yp) if not stopAtCentroids or node._aboveCentroid > 0: for child in children: if ptColors != [] and child.GetData() is not None: drawColor = ptColors[child.GetData()] else: drawColor = VisOpts.lineColor if showNodes and hasattr(child,'_isCentroid'): canvas.drawLine(child._drawPos[0],child._drawPos[1]-VisOpts.nodeRad/2, child._drawPos[0],node._drawPos[1], drawColor,lineWidth) else: canvas.drawLine(child._drawPos[0],child._drawPos[1], child._drawPos[0],node._drawPos[1], drawColor,lineWidth) canvas.drawLine(children[0]._drawPos[0],node._drawPos[1], children[-1]._drawPos[0],node._drawPos[1], VisOpts.lineColor,lineWidth) else: for child in children: drawColor = VisOpts.hideColor canvas.drawLine(child._drawPos[0],child._drawPos[1], child._drawPos[0],node._drawPos[1], drawColor,VisOpts.hideWidth) canvas.drawLine(children[0]._drawPos[0],node._drawPos[1], children[-1]._drawPos[0],node._drawPos[1], VisOpts.hideColor,VisOpts.hideWidth) if showIndices and (not stopAtCentroids or node._aboveCentroid >= 0): txt = str(node.GetIndex()) if hasattr(node,'_isCentroid'): txtColor = piddle.Color(1,.2,.2) else: txtColor = piddle.Color(0,0,0) canvas.drawString(txt, node._drawPos[0]-canvas.stringWidth(txt)/2, node._drawPos[1]+canvas.fontHeight()/4, color=txtColor) if showNodes and hasattr(node,'_isCentroid'): rad = VisOpts.nodeRad canvas.drawEllipse(node._drawPos[0]-rad/2,node._drawPos[1]-rad/2, node._drawPos[0]+rad/2,node._drawPos[1]+rad/2, piddle.transparent, fillColor=VisOpts.nodeColor) txt = str(node._clustID) canvas.drawString(txt, node._drawPos[0]-canvas.stringWidth(txt)/2, node._drawPos[1]+canvas.fontHeight()/4, color=piddle.Color(0,0,0)) if showIndices and not stopAtCentroids: for pt in pts: txt = str(pt.GetIndex()) canvas.drawString(str(pt.GetIndex()), pt._drawPos[0]-canvas.stringWidth(txt)/2, pt._drawPos[1]) def ClusterToPDF(cluster,fileName,size=(300,300),ptColors=[],lineWidth=None, showIndices=0,stopAtCentroids=0,logScale=0): """ handles the work of drawing a cluster tree to an PDF file **Arguments** - cluster: the cluster tree to be drawn - fileName: the name of the file to be created - size: the size of output canvas - ptColors: if this is specified, the _colors_ will be used to color the terminal nodes of the cluster tree. (color == _pid.Color_) - lineWidth: if specified, it will be used for the widths of the lines used to draw the tree **Notes** - if _ptColors_ is the wrong length for the number of possible terminal node types, this will throw an IndexError - terminal node types are determined using their _GetData()_ methods """ try: from rdkit.sping.PDF import pidPDF except ImportError: from rdkit.piddle import piddlePDF pidPDF = piddlePDF canvas = pidPDF.PDFCanvas(size,fileName) if lineWidth is None: lineWidth = VisOpts.lineWidth DrawClusterTree(cluster,canvas,size,ptColors=ptColors,lineWidth=lineWidth, showIndices=showIndices,stopAtCentroids=stopAtCentroids, logScale=logScale) if fileName: canvas.save() return canvas def ClusterToSVG(cluster,fileName,size=(300,300),ptColors=[],lineWidth=None, showIndices=0,stopAtCentroids=0,logScale=0): """ handles the work of drawing a cluster tree to an SVG file **Arguments** - cluster: the cluster tree to be drawn - fileName: the name of the file to be created - size: the size of output canvas - ptColors: if this is specified, the _colors_ will be used to color the terminal nodes of the cluster tree. (color == _pid.Color_) - lineWidth: if specified, it will be used for the widths of the lines used to draw the tree **Notes** - if _ptColors_ is the wrong length for the number of possible terminal node types, this will throw an IndexError - terminal node types are determined using their _GetData()_ methods """ try: from rdkit.sping.SVG import pidSVG except ImportError: from rdkit.piddle.piddleSVG import piddleSVG pidSVG = piddleSVG canvas = pidSVG.SVGCanvas(size,fileName) if lineWidth is None: lineWidth = VisOpts.lineWidth DrawClusterTree(cluster,canvas,size,ptColors=ptColors,lineWidth=lineWidth, showIndices=showIndices,stopAtCentroids=stopAtCentroids, logScale=logScale) if fileName: canvas.save() return canvas def ClusterToImg(cluster,fileName,size=(300,300),ptColors=[],lineWidth=None, showIndices=0,stopAtCentroids=0,logScale=0): """ handles the work of drawing a cluster tree to an image file **Arguments** - cluster: the cluster tree to be drawn - fileName: the name of the file to be created - size: the size of output canvas - ptColors: if this is specified, the _colors_ will be used to color the terminal nodes of the cluster tree. (color == _pid.Color_) - lineWidth: if specified, it will be used for the widths of the lines used to draw the tree **Notes** - The extension on _fileName_ determines the type of image file created. All formats supported by PIL can be used. - if _ptColors_ is the wrong length for the number of possible terminal node types, this will throw an IndexError - terminal node types are determined using their _GetData()_ methods """ try: from rdkit.sping.PIL import pidPIL except ImportError: from rdkit.piddle import piddlePIL pidPIL = piddlePIL canvas = pidPIL.PILCanvas(size,fileName) if lineWidth is None: lineWidth = VisOpts.lineWidth DrawClusterTree(cluster,canvas,size,ptColors=ptColors,lineWidth=lineWidth, showIndices=showIndices,stopAtCentroids=stopAtCentroids, logScale=logScale) if fileName: canvas.save() return canvas
{ "repo_name": "adalke/rdkit", "path": "rdkit/ML/Cluster/ClusterVis.py", "copies": "1", "size": "15882", "license": "bsd-3-clause", "hash": 5021258960670961000, "line_mean": 32.5063291139, "line_max": 98, "alpha_frac": 0.6120765647, "autogenerated": false, "ratio": 3.743106292717417, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9750328263548533, "avg_score": 0.020970918773776902, "num_lines": 474 }
"""Cluster tree visualization using Sping """ try: from rdkit.sping import pid piddle = pid except ImportError: from rdkit.piddle import piddle import ClusterUtils import numpy class VisOpts(object): """ stores visualization options for cluster viewing **Instance variables** - x/yOffset: amount by which the drawing is offset from the edges of the canvas - lineColor: default color for drawing the cluster tree - lineWidth: the width of the lines used to draw the tree """ xOffset = 20 yOffset = 20 lineColor = piddle.Color(0, 0, 0) hideColor = piddle.Color(.8, .8, .8) terminalColors = [piddle.Color(1, 0, 0), piddle.Color(0, 0, 1), piddle.Color(1, 1, 0), piddle.Color(0, .5, .5), piddle.Color(0, .8, 0), piddle.Color(.5, .5, .5), piddle.Color(.8, .3, .3), piddle.Color(.3, .3, .8), piddle.Color(.8, .8, .3), piddle.Color(.3, .8, .8)] lineWidth = 2 hideWidth = 1.1 nodeRad = 15 nodeColor = piddle.Color(1., .4, .4) highlightColor = piddle.Color(1., 1., .4) highlightRad = 10 def _scaleMetric(val, power=2, min=1e-4): val = float(val) nval = pow(val, power) if nval < min: return 0.0 else: return numpy.log(nval / min) class ClusterRenderer(object): def __init__(self, canvas, size, ptColors=[], lineWidth=None, showIndices=0, showNodes=1, stopAtCentroids=0, logScale=0, tooClose=-1): self.canvas = canvas self.size = size self.ptColors = ptColors self.lineWidth = lineWidth self.showIndices = showIndices self.showNodes = showNodes self.stopAtCentroids = stopAtCentroids self.logScale = logScale self.tooClose = tooClose def _AssignPointLocations(self, cluster, terminalOffset=4): self.pts = cluster.GetPoints() self.nPts = len(self.pts) self.xSpace = float(self.size[0] - 2 * VisOpts.xOffset) / float(self.nPts - 1) ySize = self.size[1] for i in xrange(self.nPts): pt = self.pts[i] if self.logScale > 0: v = _scaleMetric(pt.GetMetric(), self.logScale) else: v = float(pt.GetMetric()) pt._drawPos = (VisOpts.xOffset + i * self.xSpace, ySize - (v * self.ySpace + VisOpts.yOffset) + terminalOffset) def _AssignClusterLocations(self, cluster): # first get the search order (top down) toDo = [cluster] examine = cluster.GetChildren()[:] while len(examine): node = examine.pop(0) children = node.GetChildren() if len(children): toDo.append(node) for child in children: if not child.IsTerminal(): examine.append(child) # and reverse it (to run from bottom up) toDo.reverse() for node in toDo: if self.logScale > 0: v = _scaleMetric(node.GetMetric(), self.logScale) else: v = float(node.GetMetric()) # average our children's x positions childLocs = [x._drawPos[0] for x in node.GetChildren()] if len(childLocs): xp = sum(childLocs) / float(len(childLocs)) yp = self.size[1] - (v * self.ySpace + VisOpts.yOffset) node._drawPos = (xp, yp) def _DrawToLimit(self, cluster): """ we assume that _drawPos settings have been done already """ if self.lineWidth is None: lineWidth = VisOpts.lineWidth else: lineWidth = self.lineWidth examine = [cluster] while len(examine): node = examine.pop(0) xp, yp = node._drawPos children = node.GetChildren() if abs(children[1]._drawPos[0] - children[0]._drawPos[0]) > self.tooClose: # draw the horizontal line connecting things drawColor = VisOpts.lineColor self.canvas.drawLine(children[0]._drawPos[0], yp, children[-1]._drawPos[0], yp, drawColor, lineWidth) # and draw the lines down to the children for child in children: if self.ptColors and child.GetData() is not None: drawColor = self.ptColors[child.GetData()] else: drawColor = VisOpts.lineColor cxp, cyp = child._drawPos self.canvas.drawLine(cxp, yp, cxp, cyp, drawColor, lineWidth) if not child.IsTerminal(): examine.append(child) else: if self.showIndices and not self.stopAtCentroids: try: txt = str(child.GetName()) except Exception: txt = str(child.GetIndex()) self.canvas.drawString(txt, cxp - self.canvas.stringWidth(txt) / 2, cyp) else: # draw a "hidden" line to the bottom self.canvas.drawLine(xp, yp, xp, self.size[1] - VisOpts.yOffset, VisOpts.hideColor, lineWidth) def DrawTree(self, cluster, minHeight=2.0): if self.logScale > 0: v = _scaleMetric(cluster.GetMetric(), self.logScale) else: v = float(cluster.GetMetric()) if v <= 0: v = minHeight self.ySpace = float(self.size[1] - 2 * VisOpts.yOffset) / v self._AssignPointLocations(cluster) self._AssignClusterLocations(cluster) if not self.stopAtCentroids: self._DrawToLimit(cluster) else: raise NotImplementedError('stopAtCentroids drawing not yet implemented') def DrawClusterTree(cluster, canvas, size, ptColors=[], lineWidth=None, showIndices=0, showNodes=1, stopAtCentroids=0, logScale=0, tooClose=-1): """ handles the work of drawing a cluster tree on a Sping canvas **Arguments** - cluster: the cluster tree to be drawn - canvas: the Sping canvas on which to draw - size: the size of _canvas_ - ptColors: if this is specified, the _colors_ will be used to color the terminal nodes of the cluster tree. (color == _pid.Color_) - lineWidth: if specified, it will be used for the widths of the lines used to draw the tree **Notes** - _Canvas_ is neither _save_d nor _flush_ed at the end of this - if _ptColors_ is the wrong length for the number of possible terminal node types, this will throw an IndexError - terminal node types are determined using their _GetData()_ methods """ renderer = ClusterRenderer(canvas, size, ptColors, lineWidth, showIndices, showNodes, stopAtCentroids, logScale, tooClose) renderer.DrawTree(cluster) def _DrawClusterTree(cluster, canvas, size, ptColors=[], lineWidth=None, showIndices=0, showNodes=1, stopAtCentroids=0, logScale=0, tooClose=-1): """ handles the work of drawing a cluster tree on a Sping canvas **Arguments** - cluster: the cluster tree to be drawn - canvas: the Sping canvas on which to draw - size: the size of _canvas_ - ptColors: if this is specified, the _colors_ will be used to color the terminal nodes of the cluster tree. (color == _pid.Color_) - lineWidth: if specified, it will be used for the widths of the lines used to draw the tree **Notes** - _Canvas_ is neither _save_d nor _flush_ed at the end of this - if _ptColors_ is the wrong length for the number of possible terminal node types, this will throw an IndexError - terminal node types are determined using their _GetData()_ methods """ if lineWidth is None: lineWidth = VisOpts.lineWidth pts = cluster.GetPoints() nPts = len(pts) if nPts <= 1: return xSpace = float(size[0] - 2 * VisOpts.xOffset) / float(nPts - 1) if logScale > 0: v = _scaleMetric(cluster.GetMetric(), logScale) else: v = float(cluster.GetMetric()) ySpace = float(size[1] - 2 * VisOpts.yOffset) / v for i in xrange(nPts): pt = pts[i] if logScale > 0: v = _scaleMetric(pt.GetMetric(), logScale) else: v = float(pt.GetMetric()) pt._drawPos = (VisOpts.xOffset + i * xSpace, size[1] - (v * ySpace + VisOpts.yOffset)) if not stopAtCentroids or not hasattr(pt, '_isCentroid'): allNodes.remove(pt) if not stopAtCentroids: allNodes = ClusterUtils.GetNodeList(cluster) else: allNodes = ClusterUtils.GetNodesDownToCentroids(cluster) while len(allNodes): node = allNodes.pop(0) children = node.GetChildren() if len(children): if logScale > 0: v = _scaleMetric(node.GetMetric(), logScale) else: v = float(node.GetMetric()) yp = size[1] - (v * ySpace + VisOpts.yOffset) childLocs = [x._drawPos[0] for x in children] xp = sum(childLocs) / float(len(childLocs)) node._drawPos = (xp, yp) if not stopAtCentroids or node._aboveCentroid > 0: for child in children: if ptColors != [] and child.GetData() is not None: drawColor = ptColors[child.GetData()] else: drawColor = VisOpts.lineColor if showNodes and hasattr(child, '_isCentroid'): canvas.drawLine(child._drawPos[0], child._drawPos[1] - VisOpts.nodeRad / 2, child._drawPos[0], node._drawPos[1], drawColor, lineWidth) else: canvas.drawLine(child._drawPos[0], child._drawPos[1], child._drawPos[0], node._drawPos[1], drawColor, lineWidth) canvas.drawLine(children[0]._drawPos[0], node._drawPos[1], children[-1]._drawPos[0], node._drawPos[1], VisOpts.lineColor, lineWidth) else: for child in children: drawColor = VisOpts.hideColor canvas.drawLine(child._drawPos[0], child._drawPos[1], child._drawPos[0], node._drawPos[1], drawColor, VisOpts.hideWidth) canvas.drawLine(children[0]._drawPos[0], node._drawPos[1], children[-1]._drawPos[0], node._drawPos[1], VisOpts.hideColor, VisOpts.hideWidth) if showIndices and (not stopAtCentroids or node._aboveCentroid >= 0): txt = str(node.GetIndex()) if hasattr(node, '_isCentroid'): txtColor = piddle.Color(1, .2, .2) else: txtColor = piddle.Color(0, 0, 0) canvas.drawString(txt, node._drawPos[0] - canvas.stringWidth(txt) / 2, node._drawPos[1] + canvas.fontHeight() / 4, color=txtColor) if showNodes and hasattr(node, '_isCentroid'): rad = VisOpts.nodeRad canvas.drawEllipse(node._drawPos[0] - rad / 2, node._drawPos[1] - rad / 2, node._drawPos[0] + rad / 2, node._drawPos[1] + rad / 2, piddle.transparent, fillColor=VisOpts.nodeColor) txt = str(node._clustID) canvas.drawString(txt, node._drawPos[0] - canvas.stringWidth(txt) / 2, node._drawPos[1] + canvas.fontHeight() / 4, color=piddle.Color(0, 0, 0)) if showIndices and not stopAtCentroids: for pt in pts: txt = str(pt.GetIndex()) canvas.drawString( str(pt.GetIndex()), pt._drawPos[0] - canvas.stringWidth(txt) / 2, pt._drawPos[1]) def ClusterToPDF(cluster, fileName, size=(300, 300), ptColors=[], lineWidth=None, showIndices=0, stopAtCentroids=0, logScale=0): """ handles the work of drawing a cluster tree to an PDF file **Arguments** - cluster: the cluster tree to be drawn - fileName: the name of the file to be created - size: the size of output canvas - ptColors: if this is specified, the _colors_ will be used to color the terminal nodes of the cluster tree. (color == _pid.Color_) - lineWidth: if specified, it will be used for the widths of the lines used to draw the tree **Notes** - if _ptColors_ is the wrong length for the number of possible terminal node types, this will throw an IndexError - terminal node types are determined using their _GetData()_ methods """ try: from rdkit.sping.PDF import pidPDF except ImportError: from rdkit.piddle import piddlePDF pidPDF = piddlePDF canvas = pidPDF.PDFCanvas(size, fileName) if lineWidth is None: lineWidth = VisOpts.lineWidth DrawClusterTree(cluster, canvas, size, ptColors=ptColors, lineWidth=lineWidth, showIndices=showIndices, stopAtCentroids=stopAtCentroids, logScale=logScale) if fileName: canvas.save() return canvas def ClusterToSVG(cluster, fileName, size=(300, 300), ptColors=[], lineWidth=None, showIndices=0, stopAtCentroids=0, logScale=0): """ handles the work of drawing a cluster tree to an SVG file **Arguments** - cluster: the cluster tree to be drawn - fileName: the name of the file to be created - size: the size of output canvas - ptColors: if this is specified, the _colors_ will be used to color the terminal nodes of the cluster tree. (color == _pid.Color_) - lineWidth: if specified, it will be used for the widths of the lines used to draw the tree **Notes** - if _ptColors_ is the wrong length for the number of possible terminal node types, this will throw an IndexError - terminal node types are determined using their _GetData()_ methods """ try: from rdkit.sping.SVG import pidSVG except ImportError: from rdkit.piddle.piddleSVG import piddleSVG pidSVG = piddleSVG canvas = pidSVG.SVGCanvas(size, fileName) if lineWidth is None: lineWidth = VisOpts.lineWidth DrawClusterTree(cluster, canvas, size, ptColors=ptColors, lineWidth=lineWidth, showIndices=showIndices, stopAtCentroids=stopAtCentroids, logScale=logScale) if fileName: canvas.save() return canvas def ClusterToImg(cluster, fileName, size=(300, 300), ptColors=[], lineWidth=None, showIndices=0, stopAtCentroids=0, logScale=0): """ handles the work of drawing a cluster tree to an image file **Arguments** - cluster: the cluster tree to be drawn - fileName: the name of the file to be created - size: the size of output canvas - ptColors: if this is specified, the _colors_ will be used to color the terminal nodes of the cluster tree. (color == _pid.Color_) - lineWidth: if specified, it will be used for the widths of the lines used to draw the tree **Notes** - The extension on _fileName_ determines the type of image file created. All formats supported by PIL can be used. - if _ptColors_ is the wrong length for the number of possible terminal node types, this will throw an IndexError - terminal node types are determined using their _GetData()_ methods """ try: from rdkit.sping.PIL import pidPIL except ImportError: from rdkit.piddle import piddlePIL pidPIL = piddlePIL canvas = pidPIL.PILCanvas(size, fileName) if lineWidth is None: lineWidth = VisOpts.lineWidth DrawClusterTree(cluster, canvas, size, ptColors=ptColors, lineWidth=lineWidth, showIndices=showIndices, stopAtCentroids=stopAtCentroids, logScale=logScale) if fileName: canvas.save() return canvas
{ "repo_name": "jandom/rdkit", "path": "rdkit/ML/Cluster/ClusterVis.py", "copies": "1", "size": "15392", "license": "bsd-3-clause", "hash": 2184193016502254300, "line_mean": 33.2044444444, "line_max": 100, "alpha_frac": 0.6315618503, "autogenerated": false, "ratio": 3.610602861834389, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4742164712134389, "avg_score": null, "num_lines": null }
"""Cluster tree visualization using Sping """ try: from rdkit.sping import pid piddle = pid except ImportError: from rdkit.piddle import piddle import numpy from . import ClusterUtils class VisOpts(object): """ stores visualization options for cluster viewing **Instance variables** - x/yOffset: amount by which the drawing is offset from the edges of the canvas - lineColor: default color for drawing the cluster tree - lineWidth: the width of the lines used to draw the tree """ xOffset = 20 yOffset = 20 lineColor = piddle.Color(0, 0, 0) hideColor = piddle.Color(.8, .8, .8) terminalColors = [piddle.Color(1, 0, 0), piddle.Color(0, 0, 1), piddle.Color(1, 1, 0), piddle.Color(0, .5, .5), piddle.Color(0, .8, 0), piddle.Color(.5, .5, .5), piddle.Color(.8, .3, .3), piddle.Color(.3, .3, .8), piddle.Color(.8, .8, .3), piddle.Color(.3, .8, .8)] lineWidth = 2 hideWidth = 1.1 nodeRad = 15 nodeColor = piddle.Color(1., .4, .4) highlightColor = piddle.Color(1., 1., .4) highlightRad = 10 def _scaleMetric(val, power=2, min=1e-4): val = float(val) nval = pow(val, power) if nval < min: return 0.0 else: return numpy.log(nval / min) class ClusterRenderer(object): def __init__(self, canvas, size, ptColors=[], lineWidth=None, showIndices=0, showNodes=1, stopAtCentroids=0, logScale=0, tooClose=-1): self.canvas = canvas self.size = size self.ptColors = ptColors self.lineWidth = lineWidth self.showIndices = showIndices self.showNodes = showNodes self.stopAtCentroids = stopAtCentroids self.logScale = logScale self.tooClose = tooClose def _AssignPointLocations(self, cluster, terminalOffset=4): self.pts = cluster.GetPoints() self.nPts = len(self.pts) self.xSpace = float(self.size[0] - 2 * VisOpts.xOffset) / float(self.nPts - 1) ySize = self.size[1] for i in range(self.nPts): pt = self.pts[i] if self.logScale > 0: v = _scaleMetric(pt.GetMetric(), self.logScale) else: v = float(pt.GetMetric()) pt._drawPos = (VisOpts.xOffset + i * self.xSpace, ySize - (v * self.ySpace + VisOpts.yOffset) + terminalOffset) def _AssignClusterLocations(self, cluster): # first get the search order (top down) toDo = [cluster] examine = cluster.GetChildren()[:] while len(examine): node = examine.pop(0) children = node.GetChildren() if len(children): toDo.append(node) for child in children: if not child.IsTerminal(): examine.append(child) # and reverse it (to run from bottom up) toDo.reverse() for node in toDo: if self.logScale > 0: v = _scaleMetric(node.GetMetric(), self.logScale) else: v = float(node.GetMetric()) # average our children's x positions childLocs = [x._drawPos[0] for x in node.GetChildren()] if len(childLocs): xp = sum(childLocs) / float(len(childLocs)) yp = self.size[1] - (v * self.ySpace + VisOpts.yOffset) node._drawPos = (xp, yp) def _DrawToLimit(self, cluster): """ we assume that _drawPos settings have been done already """ if self.lineWidth is None: lineWidth = VisOpts.lineWidth else: lineWidth = self.lineWidth examine = [cluster] while len(examine): node = examine.pop(0) xp, yp = node._drawPos children = node.GetChildren() if abs(children[1]._drawPos[0] - children[0]._drawPos[0]) > self.tooClose: # draw the horizontal line connecting things drawColor = VisOpts.lineColor self.canvas.drawLine(children[0]._drawPos[0], yp, children[-1]._drawPos[0], yp, drawColor, lineWidth) # and draw the lines down to the children for child in children: if self.ptColors and child.GetData() is not None: drawColor = self.ptColors[child.GetData()] else: drawColor = VisOpts.lineColor cxp, cyp = child._drawPos self.canvas.drawLine(cxp, yp, cxp, cyp, drawColor, lineWidth) if not child.IsTerminal(): examine.append(child) else: if self.showIndices and not self.stopAtCentroids: try: txt = str(child.GetName()) except Exception: txt = str(child.GetIndex()) self.canvas.drawString(txt, cxp - self.canvas.stringWidth(txt) / 2, cyp) else: # draw a "hidden" line to the bottom self.canvas.drawLine(xp, yp, xp, self.size[1] - VisOpts.yOffset, VisOpts.hideColor, lineWidth) def DrawTree(self, cluster, minHeight=2.0): if self.logScale > 0: v = _scaleMetric(cluster.GetMetric(), self.logScale) else: v = float(cluster.GetMetric()) if v <= 0: v = minHeight self.ySpace = float(self.size[1] - 2 * VisOpts.yOffset) / v self._AssignPointLocations(cluster) self._AssignClusterLocations(cluster) if not self.stopAtCentroids: self._DrawToLimit(cluster) else: raise NotImplementedError('stopAtCentroids drawing not yet implemented') def DrawClusterTree(cluster, canvas, size, ptColors=[], lineWidth=None, showIndices=0, showNodes=1, stopAtCentroids=0, logScale=0, tooClose=-1): """ handles the work of drawing a cluster tree on a Sping canvas **Arguments** - cluster: the cluster tree to be drawn - canvas: the Sping canvas on which to draw - size: the size of _canvas_ - ptColors: if this is specified, the _colors_ will be used to color the terminal nodes of the cluster tree. (color == _pid.Color_) - lineWidth: if specified, it will be used for the widths of the lines used to draw the tree **Notes** - _Canvas_ is neither _save_d nor _flush_ed at the end of this - if _ptColors_ is the wrong length for the number of possible terminal node types, this will throw an IndexError - terminal node types are determined using their _GetData()_ methods """ renderer = ClusterRenderer(canvas, size, ptColors, lineWidth, showIndices, showNodes, stopAtCentroids, logScale, tooClose) renderer.DrawTree(cluster) def _DrawClusterTree(cluster, canvas, size, ptColors=[], lineWidth=None, showIndices=0, showNodes=1, stopAtCentroids=0, logScale=0, tooClose=-1): """ handles the work of drawing a cluster tree on a Sping canvas **Arguments** - cluster: the cluster tree to be drawn - canvas: the Sping canvas on which to draw - size: the size of _canvas_ - ptColors: if this is specified, the _colors_ will be used to color the terminal nodes of the cluster tree. (color == _pid.Color_) - lineWidth: if specified, it will be used for the widths of the lines used to draw the tree **Notes** - _Canvas_ is neither _save_d nor _flush_ed at the end of this - if _ptColors_ is the wrong length for the number of possible terminal node types, this will throw an IndexError - terminal node types are determined using their _GetData()_ methods """ if lineWidth is None: lineWidth = VisOpts.lineWidth pts = cluster.GetPoints() nPts = len(pts) if nPts <= 1: return xSpace = float(size[0] - 2 * VisOpts.xOffset) / float(nPts - 1) if logScale > 0: v = _scaleMetric(cluster.GetMetric(), logScale) else: v = float(cluster.GetMetric()) ySpace = float(size[1] - 2 * VisOpts.yOffset) / v for i in range(nPts): pt = pts[i] if logScale > 0: v = _scaleMetric(pt.GetMetric(), logScale) else: v = float(pt.GetMetric()) pt._drawPos = (VisOpts.xOffset + i * xSpace, size[1] - (v * ySpace + VisOpts.yOffset)) # if not stopAtCentroids or not hasattr(pt, '_isCentroid'): # allNodes.remove(pt) # allNodes not defined if not stopAtCentroids: allNodes = ClusterUtils.GetNodeList(cluster) else: allNodes = ClusterUtils.GetNodesDownToCentroids(cluster) while len(allNodes): node = allNodes.pop(0) children = node.GetChildren() if len(children): if logScale > 0: v = _scaleMetric(node.GetMetric(), logScale) else: v = float(node.GetMetric()) yp = size[1] - (v * ySpace + VisOpts.yOffset) childLocs = [x._drawPos[0] for x in children] xp = sum(childLocs) / float(len(childLocs)) node._drawPos = (xp, yp) if not stopAtCentroids or node._aboveCentroid > 0: for child in children: if ptColors != [] and child.GetData() is not None: drawColor = ptColors[child.GetData()] else: drawColor = VisOpts.lineColor if showNodes and hasattr(child, '_isCentroid'): canvas.drawLine(child._drawPos[0], child._drawPos[1] - VisOpts.nodeRad / 2, child._drawPos[0], node._drawPos[1], drawColor, lineWidth) else: canvas.drawLine(child._drawPos[0], child._drawPos[1], child._drawPos[0], node._drawPos[1], drawColor, lineWidth) canvas.drawLine(children[0]._drawPos[0], node._drawPos[1], children[-1]._drawPos[0], node._drawPos[1], VisOpts.lineColor, lineWidth) else: for child in children: drawColor = VisOpts.hideColor canvas.drawLine(child._drawPos[0], child._drawPos[1], child._drawPos[0], node._drawPos[1], drawColor, VisOpts.hideWidth) canvas.drawLine(children[0]._drawPos[0], node._drawPos[1], children[-1]._drawPos[0], node._drawPos[1], VisOpts.hideColor, VisOpts.hideWidth) if showIndices and (not stopAtCentroids or node._aboveCentroid >= 0): txt = str(node.GetIndex()) if hasattr(node, '_isCentroid'): txtColor = piddle.Color(1, .2, .2) else: txtColor = piddle.Color(0, 0, 0) canvas.drawString(txt, node._drawPos[0] - canvas.stringWidth(txt) / 2, node._drawPos[1] + canvas.fontHeight() / 4, color=txtColor) if showNodes and hasattr(node, '_isCentroid'): rad = VisOpts.nodeRad canvas.drawEllipse(node._drawPos[0] - rad / 2, node._drawPos[1] - rad / 2, node._drawPos[0] + rad / 2, node._drawPos[1] + rad / 2, piddle.transparent, fillColor=VisOpts.nodeColor) txt = str(node._clustID) canvas.drawString(txt, node._drawPos[0] - canvas.stringWidth(txt) / 2, node._drawPos[1] + canvas.fontHeight() / 4, color=piddle.Color(0, 0, 0)) if showIndices and not stopAtCentroids: for pt in pts: txt = str(pt.GetIndex()) canvas.drawString( str(pt.GetIndex()), pt._drawPos[0] - canvas.stringWidth(txt) / 2, pt._drawPos[1]) def ClusterToPDF(cluster, fileName, size=(300, 300), ptColors=[], lineWidth=None, showIndices=0, stopAtCentroids=0, logScale=0): """ handles the work of drawing a cluster tree to an PDF file **Arguments** - cluster: the cluster tree to be drawn - fileName: the name of the file to be created - size: the size of output canvas - ptColors: if this is specified, the _colors_ will be used to color the terminal nodes of the cluster tree. (color == _pid.Color_) - lineWidth: if specified, it will be used for the widths of the lines used to draw the tree **Notes** - if _ptColors_ is the wrong length for the number of possible terminal node types, this will throw an IndexError - terminal node types are determined using their _GetData()_ methods """ try: from rdkit.sping.PDF import pidPDF except ImportError: from rdkit.piddle import piddlePDF pidPDF = piddlePDF canvas = pidPDF.PDFCanvas(size, fileName) if lineWidth is None: lineWidth = VisOpts.lineWidth DrawClusterTree(cluster, canvas, size, ptColors=ptColors, lineWidth=lineWidth, showIndices=showIndices, stopAtCentroids=stopAtCentroids, logScale=logScale) if fileName: canvas.save() return canvas def ClusterToSVG(cluster, fileName, size=(300, 300), ptColors=[], lineWidth=None, showIndices=0, stopAtCentroids=0, logScale=0): """ handles the work of drawing a cluster tree to an SVG file **Arguments** - cluster: the cluster tree to be drawn - fileName: the name of the file to be created - size: the size of output canvas - ptColors: if this is specified, the _colors_ will be used to color the terminal nodes of the cluster tree. (color == _pid.Color_) - lineWidth: if specified, it will be used for the widths of the lines used to draw the tree **Notes** - if _ptColors_ is the wrong length for the number of possible terminal node types, this will throw an IndexError - terminal node types are determined using their _GetData()_ methods """ try: from rdkit.sping.SVG import pidSVG except ImportError: from rdkit.piddle.piddleSVG import piddleSVG pidSVG = piddleSVG canvas = pidSVG.SVGCanvas(size, fileName) if lineWidth is None: lineWidth = VisOpts.lineWidth DrawClusterTree(cluster, canvas, size, ptColors=ptColors, lineWidth=lineWidth, showIndices=showIndices, stopAtCentroids=stopAtCentroids, logScale=logScale) if fileName: canvas.save() return canvas def ClusterToImg(cluster, fileName, size=(300, 300), ptColors=[], lineWidth=None, showIndices=0, stopAtCentroids=0, logScale=0): """ handles the work of drawing a cluster tree to an image file **Arguments** - cluster: the cluster tree to be drawn - fileName: the name of the file to be created - size: the size of output canvas - ptColors: if this is specified, the _colors_ will be used to color the terminal nodes of the cluster tree. (color == _pid.Color_) - lineWidth: if specified, it will be used for the widths of the lines used to draw the tree **Notes** - The extension on _fileName_ determines the type of image file created. All formats supported by PIL can be used. - if _ptColors_ is the wrong length for the number of possible terminal node types, this will throw an IndexError - terminal node types are determined using their _GetData()_ methods """ try: from rdkit.sping.PIL import pidPIL except ImportError: from rdkit.piddle import piddlePIL pidPIL = piddlePIL canvas = pidPIL.PILCanvas(size, fileName) if lineWidth is None: lineWidth = VisOpts.lineWidth DrawClusterTree(cluster, canvas, size, ptColors=ptColors, lineWidth=lineWidth, showIndices=showIndices, stopAtCentroids=stopAtCentroids, logScale=logScale) if fileName: canvas.save() return canvas
{ "repo_name": "rvianello/rdkit", "path": "rdkit/ML/Cluster/ClusterVis.py", "copies": "11", "size": "15377", "license": "bsd-3-clause", "hash": 6919427527792495000, "line_mean": 33.1711111111, "line_max": 100, "alpha_frac": 0.6334785719, "autogenerated": false, "ratio": 3.602858481724461, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9736337053624462, "avg_score": null, "num_lines": null }
""" demo code for the Logger class """ from sping.SVG import pidSVG from sping.PIL import pidPIL from sping import pid import Logger # create a logged canvas and draw on it sz = (300,300) c1 = Logger.Logger(pidSVG.SVGCanvas,sz,'foo.svg',loggerFlushCommand='clear') c1.drawPolygon([(100,100),(100,200),(200,200),(200,100)],fillColor=pid.Color(0,0,1)) c1.drawLines([(100,100,200,200),(100,200,200,100)],color=pid.Color(0,1,0),width=2) # because the log has been instantiated with clear() as the loggerFlushCommand, # this will blow out the log as well as the contents of the canvas. c1.clear() # draw some more stuff c1.drawPolygon([(100,100),(100,200),(200,200),(200,100)],fillColor=pid.Color(1,0,0)) c1.drawLines([(100,100,200,200),(100,200,200,100)],color=pid.Color(0,0,0),width=2) # and write the resulting file. c1.save() # save the log by pickling it. import cPickle cPickle.dump(c1._LoggerGetLog(),open('foo.pkl','wb+')) # create a new canvas c2 = pidPIL.PILCanvas(sz,'foo.png') # read the pickled log back in t = cPickle.load(open('foo.pkl','rb')) # and play the log on the new canvas Logger.replay(t,c2) # there should now be a file 'foo.png' with the image
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Logger/SpingDemo.py", "copies": "2", "size": "1481", "license": "bsd-3-clause", "hash": -2497341435541921300, "line_mean": 29.8541666667, "line_max": 84, "alpha_frac": 0.7076299797, "autogenerated": false, "ratio": 2.8813229571984436, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45889529368984433, "avg_score": null, "num_lines": null }
""" Functionality for SATIS typing atoms """ from __future__ import print_function from rdkit import Chem from rdkit.six.moves import xrange _debug = 0 # # These are SMARTS patterns for the special cases used in # SATIS typing. # aldehydePatt = Chem.MolFromSmarts('[CD2]=[OD1]') ketonePatt = Chem.MolFromSmarts('[CD3]=[OD1]') amidePatt = Chem.MolFromSmarts('[CD3](=[OD1])-[#7]') esterPatt = Chem.MolFromSmarts('C(=[OD1])-O-[#6]') carboxylatePatt = Chem.MolFromSmarts('C(=[OD1])-[OX1]') carboxylPatt = Chem.MolFromSmarts('C(=[OD1])-[OX2]') specialCases = ((carboxylatePatt, 97), (esterPatt, 96), (carboxylPatt, 98), (amidePatt, 95), (ketonePatt, 94), (aldehydePatt, 93)) def SATISTypes(mol, neighborsToInclude=4): """ returns SATIS codes for all atoms in a molecule The SATIS definition used is from: J. Chem. Inf. Comput. Sci. _39_ 751-757 (1999) each SATIS code is a string consisting of _neighborsToInclude_ + 1 2 digit numbers **Arguments** - mol: a molecule - neighborsToInclude (optional): the number of neighbors to include in the SATIS codes **Returns** a list of strings nAtoms long """ global specialCases nAtoms = mol.GetNumAtoms() atomicNums = [0] * nAtoms atoms = mol.GetAtoms() for i in xrange(nAtoms): atomicNums[i] = atoms[i].GetAtomicNum() nSpecialCases = len(specialCases) specialCaseMatches = [None] * nSpecialCases for i, (patt, idx) in enumerate(specialCases): if mol.HasSubstructMatch(patt): specialCaseMatches[i] = mol.GetSubstructMatches(patt) else: specialCaseMatches[i] = () codes = [None] * nAtoms for i in range(nAtoms): code = [99] * (neighborsToInclude + 1) atom = atoms[i] atomIdx = atom.GetIdx() code[0] = min(atom.GetAtomicNum(), 99) bonds = atom.GetBonds() nBonds = len(bonds) otherIndices = [-1] * nBonds if _debug: print(code[0], end='') for j in range(nBonds): otherIndices[j] = bonds[j].GetOtherAtom(atom).GetIdx() if _debug: print(otherIndices[j], end='') if _debug: print() otherNums = [atomicNums[x] for x in otherIndices] + \ [1]*atom.GetTotalNumHs() otherNums.sort() nOthers = len(otherNums) if nOthers > neighborsToInclude: otherNums.reverse() otherNums = otherNums[:neighborsToInclude] otherNums.reverse() for j in range(neighborsToInclude): code[j + 1] = min(otherNums[j], 99) else: for j in range(nOthers): code[j + 1] = min(otherNums[j], 99) if nOthers < neighborsToInclude and code[0] in [6, 8]: found = 0 for j in range(nSpecialCases): for matchTuple in specialCaseMatches[j]: if atomIdx in matchTuple: code[-1] = specialCases[j][1] found = 1 break if found: break codes[i] = ''.join(['%02d' % (x) for x in code]) return codes if __name__ == '__main__': smis = ['CC(=O)NC', 'CP(F)(Cl)(Br)(O)', 'O=CC(=O)C', 'C(=O)OCC(=O)O', 'C(=O)[O-]'] for smi in smis: print(smi) m = Chem.MolFromSmiles(smi) codes = SATISTypes(m) print(codes)
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/SATIS.py", "copies": "1", "size": "3490", "license": "bsd-3-clause", "hash": 3222429987020087300, "line_mean": 27.1451612903, "line_max": 92, "alpha_frac": 0.6223495702, "autogenerated": false, "ratio": 2.9352396972245582, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9013495408875418, "avg_score": 0.008818771709827889, "num_lines": 124 }
# Demo code for the Logger class import Logger class Foo: """ a simple class """ def __init__(self,aVal): self.a = aVal def method1(self,a,b,c='foo'): print 'method1',a,b,c return 'method1' def method2(self): print 'method2' return 'method2' def demo1(): l = Logger.Logger(Foo,7) l.method1(1,2) l.method1(1,2,c='grm') l.method2() l.method1(7,6,'pizza') l.b = 3 l.method2() print l._LoggerGetLog() f = Foo(6) r = Logger.replay(l._LoggerGetLog(),f) print 'playback results:',r # f is now in more or less the same state as l... the only differences # will arise because of different arguments passed to the underlying # classes __init__ method print f.b def demo2(): # create a Logger which will flush itself: l = Logger.Logger(Foo,7,loggerFlushCommand='method2') l.method1(23,42) l.method1(1,2,'foo') print l._LoggerGetLog() # this will blow out the log l.method2() print l._LoggerGetLog() if __name__ == '__main__': demo1() demo2()
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Logger/demo.py", "copies": "2", "size": "1336", "license": "bsd-3-clause", "hash": 4828567404388620000, "line_mean": 21.6440677966, "line_max": 73, "alpha_frac": 0.6407185629, "autogenerated": false, "ratio": 2.982142857142857, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.46228614200428575, "avg_score": null, "num_lines": null }
""" periodic table data, **obsolete** now that the C++ code exposes an interface to the internal PT stuff, this data is mostly obsolete """ import re blankExpr = re.compile(r'\ *\t*\ *') # Num Symb RCov RBO RVdW Max Bnd Mass nval periodicData=\ """ 0 X 0.0 0.0 0.0 0 0.000 0 1 H 0.230 0.330 1.200 1 1.008 1 2 He 0.930 0.700 1.400 0 4.003 2 3 Li 0.680 1.230 1.820 1 6.941 1 4 Be 0.350 0.900 1.700 2 9.012 2 5 B 0.830 0.820 2.080 3 10.812 3 6 C 0.680 0.770 1.950 4 12.011 4 7 N 0.680 0.700 1.850 4 14.007 5 8 O 0.680 0.660 1.700 2 15.999 6 9 F 0.640 0.611 1.730 1 18.998 7 10 Ne 1.120 0.700 1.540 0 20.180 8 11 Na 0.970 1.540 2.270 1 22.990 1 12 Mg 1.100 1.360 1.730 2 24.305 2 13 Al 1.350 1.180 2.050 6 26.982 3 14 Si 1.200 0.937 2.100 6 28.086 4 15 P 0.750 0.890 2.080 5 30.974 5 16 S 1.020 1.040 2.000 6 32.067 6 17 Cl 0.990 0.997 1.970 1 35.453 7 18 Ar 1.570 1.740 1.880 0 39.948 8 19 K 1.330 2.030 2.750 1 39.098 1 20 Ca 0.990 1.740 1.973 2 40.078 2 21 Sc 1.440 1.440 1.700 6 44.956 3 22 Ti 1.470 1.320 1.700 6 47.867 4 23 V 1.330 1.220 1.700 6 50.942 5 24 Cr 1.350 1.180 1.700 6 51.996 6 25 Mn 1.350 1.170 1.700 8 54.938 7 26 Fe 1.340 1.170 1.700 6 55.845 8 27 Co 1.330 1.160 1.700 6 58.933 9 28 Ni 1.500 1.150 1.630 6 58.693 10 29 Cu 1.520 1.170 1.400 6 63.546 11 30 Zn 1.450 1.250 1.390 6 65.39 2 31 Ga 1.220 1.260 1.870 3 69.723 3 32 Ge 1.170 1.188 1.700 4 72.61 4 33 As 1.210 1.200 1.850 3 74.922 5 34 Se 1.220 1.170 1.900 2 78.96 6 35 Br 1.210 1.167 2.100 1 79.904 7 36 Kr 1.910 1.910 2.020 0 83.80 8 37 Rb 1.470 2.160 1.700 1 85.468 1 38 Sr 1.120 1.910 1.700 2 87.62 2 39 Y 1.780 1.620 1.700 6 88.906 3 40 Zr 1.560 1.450 1.700 6 91.224 4 41 Nb 1.480 1.340 1.700 6 92.906 5 42 Mo 1.470 1.300 1.700 6 95.94 6 43 Tc 1.350 1.270 1.700 6 98.0 7 44 Ru 1.400 1.250 1.700 6 101.07 8 45 Rh 1.450 1.250 1.700 6 102.906 9 46 Pd 1.500 1.280 1.630 6 106.42 10 47 Ag 1.590 1.340 1.720 6 107.868 11 48 Cd 1.690 1.480 1.580 6 112.412 2 49 In 1.630 1.440 1.930 3 114.818 3 50 Sn 1.460 1.385 2.170 4 118.711 4 51 Sb 1.460 1.400 2.200 3 121.760 5 52 Te 1.470 1.378 2.060 2 127.60 6 53 I 1.400 1.387 2.150 1 126.904 7 54 Xe 1.980 1.980 2.160 0 131.29 8 55 Cs 1.670 2.350 1.700 1 132.905 1 56 Ba 1.340 1.980 1.700 2 137.328 2 57 La 1.870 1.690 1.700 12 138.906 3 58 Ce 1.830 1.830 1.700 6 140.116 4 59 Pr 1.820 1.820 1.700 6 140.908 3 60 Nd 1.810 1.810 1.700 6 144.24 4 61 Pm 1.800 1.800 1.700 6 145.0 5 62 Sm 1.800 1.800 1.700 6 150.36 6 63 Eu 1.990 1.990 1.700 6 151.964 7 64 Gd 1.790 1.790 1.700 6 157.25 8 65 Tb 1.760 1.760 1.700 6 158.925 9 66 Dy 1.750 1.750 1.700 6 162.50 10 67 Ho 1.740 1.740 1.700 6 164.930 11 68 Er 1.730 1.730 1.700 6 167.26 12 69 Tm 1.720 1.720 1.700 6 168.934 13 70 Yb 1.940 1.940 1.700 6 173.04 14 71 Lu 1.720 1.720 1.700 6 174.967 15 72 Hf 1.570 1.440 1.700 6 178.49 4 73 Ta 1.430 1.340 1.700 6 180.948 5 74 W 1.370 1.300 1.700 6 183.84 6 75 Re 1.350 1.280 1.700 6 186.207 7 76 Os 1.370 1.260 1.700 6 190.23 8 77 Ir 1.320 1.270 1.700 6 192.217 9 78 Pt 1.500 1.300 1.720 6 195.078 10 79 Au 1.500 1.340 1.660 6 196.967 11 80 Hg 1.700 1.490 1.550 6 200.59 2 81 Tl 1.550 1.480 1.960 3 204.383 3 82 Pb 1.540 1.480 2.020 4 207.2 4 83 Bi 1.540 1.450 1.700 3 208.980 5 84 Po 1.680 1.460 1.700 2 209.0 6 85 At 1.700 1.450 1.700 1 210.0 7 86 Rn 2.400 2.400 1.700 0 222.0 8 87 Fr 2.000 2.000 1.700 1 223.0 1 88 Ra 1.900 1.900 1.700 2 226.0 2 89 Ac 1.880 1.880 1.700 6 227.0 3 90 Th 1.790 1.790 1.700 6 232.038 4 91 Pa 1.610 1.610 1.700 6 231.036 3 92 U 1.580 1.580 1.860 6 238.029 4 93 Np 1.550 1.550 1.700 6 237.0 5 94 Pu 1.530 1.530 1.700 6 244.0 6 95 Am 1.510 1.070 1.700 6 243.0 7 96 Cm 1.500 0.000 1.700 6 247.0 8 97 Bk 1.500 0.000 1.700 6 247.0 9 98 Cf 1.500 0.000 1.700 6 251.0 10 99 Es 1.500 0.000 1.700 6 252.0 11 100 Fm 1.500 0.000 1.700 6 257.0 12 101 Md 1.500 0.000 1.700 6 258.0 13 102 No 1.500 0.000 1.700 6 259.0 14 103 Lr 1.500 0.000 1.700 6 262.0 15 """ nameTable = {} numTable = {} for line in periodicData.split('\n'): splitLine = blankExpr.split(line) if len(splitLine)>1: nameTable[splitLine[1]] = (int(splitLine[0]),float(splitLine[6]),int(splitLine[7]),\ int(splitLine[5]),float(splitLine[2]),float(splitLine[3]), float(splitLine[4])) numTable[int(splitLine[0])] = (splitLine[1],float(splitLine[6]),int(splitLine[7]),\ int(splitLine[5]),float(splitLine[2]),float(splitLine[3]), float(splitLine[4])) # a list of metals (transition metals, semi-metals, lanthanides and actinides) metalRanges = ["13","21-32","39-51","57-84","89-103"] metalNumList = [] for entry in metalRanges: t = entry.split('-') start = int(t[0]) if len(t)>1: end = int(t[1]) else: end = start if start > end: start,end = end,start metalNumList += range(start,end+1) metalNames = map(lambda x:numTable[x][0],metalNumList) # these are from table 4 of Rev. Comp. Chem. vol 2, 367-422, (1991) # the order is [alpha(SP),alpha(SP2),alpha(SP3)] # where values are not known, None has been inserted hallKierAlphas = { 'H':[0.0,0.0,0.0], # removes explicit H's from consideration in the shape 'C':[-0.22,-0.13,0.0], 'N':[-0.29,-0.20,-0.04], 'O':[None,-0.20,-0.04], 'F':[None,None,-0.07], 'P':[None,0.30,0.43], 'S':[None,0.22,0.35], 'Cl':[None,None,0.29], 'Br':[None,None,0.48], 'I':[None,None,0.73]}
{ "repo_name": "AlexanderSavelyev/rdkit", "path": "rdkit/Chem/PeriodicTable.py", "copies": "5", "size": "5882", "license": "bsd-3-clause", "hash": 5651774482652656000, "line_mean": 33.8047337278, "line_max": 93, "alpha_frac": 0.6181570894, "autogenerated": false, "ratio": 1.7433313574392413, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4861488446839241, "avg_score": null, "num_lines": null }
""" periodic table data, **obsolete** now that the C++ code exposes an interface to the internal PT stuff, this data is mostly obsolete """ # Num Symb RCov RBO RVdW Max Bnd Mass nval periodicData = """ 0 X 0.0 0.0 0.0 0 0.000 0 1 H 0.230 0.330 1.200 1 1.008 1 2 He 0.930 0.700 1.400 0 4.003 2 3 Li 0.680 1.230 1.820 1 6.941 1 4 Be 0.350 0.900 1.700 2 9.012 2 5 B 0.830 0.820 2.080 3 10.812 3 6 C 0.680 0.770 1.950 4 12.011 4 7 N 0.680 0.700 1.850 4 14.007 5 8 O 0.680 0.660 1.700 2 15.999 6 9 F 0.640 0.611 1.730 1 18.998 7 10 Ne 1.120 0.700 1.540 0 20.180 8 11 Na 0.970 1.540 2.270 1 22.990 1 12 Mg 1.100 1.360 1.730 2 24.305 2 13 Al 1.350 1.180 2.050 6 26.982 3 14 Si 1.200 0.937 2.100 6 28.086 4 15 P 0.750 0.890 2.080 5 30.974 5 16 S 1.020 1.040 2.000 6 32.067 6 17 Cl 0.990 0.997 1.970 1 35.453 7 18 Ar 1.570 1.740 1.880 0 39.948 8 19 K 1.330 2.030 2.750 1 39.098 1 20 Ca 0.990 1.740 1.973 2 40.078 2 21 Sc 1.440 1.440 1.700 6 44.956 3 22 Ti 1.470 1.320 1.700 6 47.867 4 23 V 1.330 1.220 1.700 6 50.942 5 24 Cr 1.350 1.180 1.700 6 51.996 6 25 Mn 1.350 1.170 1.700 8 54.938 7 26 Fe 1.340 1.170 1.700 6 55.845 8 27 Co 1.330 1.160 1.700 6 58.933 9 28 Ni 1.500 1.150 1.630 6 58.693 10 29 Cu 1.520 1.170 1.400 6 63.546 11 30 Zn 1.450 1.250 1.390 6 65.39 2 31 Ga 1.220 1.260 1.870 3 69.723 3 32 Ge 1.170 1.188 1.700 4 72.61 4 33 As 1.210 1.200 1.850 3 74.922 5 34 Se 1.220 1.170 1.900 2 78.96 6 35 Br 1.210 1.167 2.100 1 79.904 7 36 Kr 1.910 1.910 2.020 0 83.80 8 37 Rb 1.470 2.160 1.700 1 85.468 1 38 Sr 1.120 1.910 1.700 2 87.62 2 39 Y 1.780 1.620 1.700 6 88.906 3 40 Zr 1.560 1.450 1.700 6 91.224 4 41 Nb 1.480 1.340 1.700 6 92.906 5 42 Mo 1.470 1.300 1.700 6 95.94 6 43 Tc 1.350 1.270 1.700 6 98.0 7 44 Ru 1.400 1.250 1.700 6 101.07 8 45 Rh 1.450 1.250 1.700 6 102.906 9 46 Pd 1.500 1.280 1.630 6 106.42 10 47 Ag 1.590 1.340 1.720 6 107.868 11 48 Cd 1.690 1.480 1.580 6 112.412 2 49 In 1.630 1.440 1.930 3 114.818 3 50 Sn 1.460 1.385 2.170 4 118.711 4 51 Sb 1.460 1.400 2.200 3 121.760 5 52 Te 1.470 1.378 2.060 2 127.60 6 53 I 1.400 1.387 2.150 1 126.904 7 54 Xe 1.980 1.980 2.160 0 131.29 8 55 Cs 1.670 2.350 1.700 1 132.905 1 56 Ba 1.340 1.980 1.700 2 137.328 2 57 La 1.870 1.690 1.700 12 138.906 3 58 Ce 1.830 1.830 1.700 6 140.116 4 59 Pr 1.820 1.820 1.700 6 140.908 3 60 Nd 1.810 1.810 1.700 6 144.24 4 61 Pm 1.800 1.800 1.700 6 145.0 5 62 Sm 1.800 1.800 1.700 6 150.36 6 63 Eu 1.990 1.990 1.700 6 151.964 7 64 Gd 1.790 1.790 1.700 6 157.25 8 65 Tb 1.760 1.760 1.700 6 158.925 9 66 Dy 1.750 1.750 1.700 6 162.50 10 67 Ho 1.740 1.740 1.700 6 164.930 11 68 Er 1.730 1.730 1.700 6 167.26 12 69 Tm 1.720 1.720 1.700 6 168.934 13 70 Yb 1.940 1.940 1.700 6 173.04 14 71 Lu 1.720 1.720 1.700 6 174.967 15 72 Hf 1.570 1.440 1.700 6 178.49 4 73 Ta 1.430 1.340 1.700 6 180.948 5 74 W 1.370 1.300 1.700 6 183.84 6 75 Re 1.350 1.280 1.700 6 186.207 7 76 Os 1.370 1.260 1.700 6 190.23 8 77 Ir 1.320 1.270 1.700 6 192.217 9 78 Pt 1.500 1.300 1.720 6 195.078 10 79 Au 1.500 1.340 1.660 6 196.967 11 80 Hg 1.700 1.490 1.550 6 200.59 2 81 Tl 1.550 1.480 1.960 3 204.383 3 82 Pb 1.540 1.480 2.020 4 207.2 4 83 Bi 1.540 1.450 1.700 3 208.980 5 84 Po 1.680 1.460 1.700 2 209.0 6 85 At 1.700 1.450 1.700 1 210.0 7 86 Rn 2.400 2.400 1.700 0 222.0 8 87 Fr 2.000 2.000 1.700 1 223.0 1 88 Ra 1.900 1.900 1.700 2 226.0 2 89 Ac 1.880 1.880 1.700 6 227.0 3 90 Th 1.790 1.790 1.700 6 232.038 4 91 Pa 1.610 1.610 1.700 6 231.036 3 92 U 1.580 1.580 1.860 6 238.029 4 93 Np 1.550 1.550 1.700 6 237.0 5 94 Pu 1.530 1.530 1.700 6 244.0 6 95 Am 1.510 1.070 1.700 6 243.0 7 96 Cm 1.500 0.000 1.700 6 247.0 8 97 Bk 1.500 0.000 1.700 6 247.0 9 98 Cf 1.500 0.000 1.700 6 251.0 10 99 Es 1.500 0.000 1.700 6 252.0 11 100 Fm 1.500 0.000 1.700 6 257.0 12 101 Md 1.500 0.000 1.700 6 258.0 13 102 No 1.500 0.000 1.700 6 259.0 14 103 Lr 1.500 0.000 1.700 6 262.0 15 """ nameTable = {} numTable = {} for line in periodicData.split('\n'): splitLine = line.split() if len(splitLine) > 1: nameTable[splitLine[1]] = (int(splitLine[0]), float(splitLine[6]), int(splitLine[7]), int(splitLine[5]), float(splitLine[2]), float(splitLine[3]), float(splitLine[4])) numTable[int(splitLine[0])] = (splitLine[1], float(splitLine[6]), int(splitLine[7]), int(splitLine[5]), float(splitLine[2]), float(splitLine[3]), float(splitLine[4])) # a list of metals (transition metals, semi-metals, lanthanides and actinides) metalRanges = ["13", "21-32", "39-51", "57-84", "89-103"] metalNumList = [] for entry in metalRanges: t = entry.split('-') start = int(t[0]) if len(t) > 1: end = int(t[1]) else: end = start if start > end: start, end = end, start metalNumList += range(start, end + 1) metalNames = [numTable[x][0] for x in metalNumList] # these are from table 4 of Rev. Comp. Chem. vol 2, 367-422, (1991) # the order is [alpha(SP),alpha(SP2),alpha(SP3)] # where values are not known, None has been inserted hallKierAlphas = { 'H': [0.0, 0.0, 0.0], # removes explicit H's from consideration in the shape 'C': [-0.22, -0.13, 0.0], 'N': [-0.29, -0.20, -0.04], 'O': [None, -0.20, -0.04], 'F': [None, None, -0.07], 'P': [None, 0.30, 0.43], 'S': [None, 0.22, 0.35], 'Cl': [None, None, 0.29], 'Br': [None, None, 0.48], 'I': [None, None, 0.73] }
{ "repo_name": "rvianello/rdkit", "path": "rdkit/Chem/PeriodicTable.py", "copies": "4", "size": "5775", "license": "bsd-3-clause", "hash": -8604614121041290000, "line_mean": 33.7891566265, "line_max": 95, "alpha_frac": 0.6225108225, "autogenerated": false, "ratio": 1.757455873402313, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4379966695902313, "avg_score": null, "num_lines": null }
""" This has all be re-implemented in the C++ code """ from __future__ import print_function import math class BitVect: def __init__(self,nBits): self.nBits = nBits self.bits = [0]*nBits def NumOnBits(self): return len(self.GetOnBits()) def GetOnBits(self,sort=1,reverse=0): l = [idx for idx in xrange(self.nBits) if self.bits[idx] == 1] if reverse: l.reverse() return l def TanimotoSimilarity(self,other): if not isinstance(other,BitVect): raise TypeError("Tanimoto similarities can only be calculated between two BitVects") if len(self)!=len(other): raise ValueError("BitVects must be the same length") bc = len(self & other) b1 = self.NumOnBits() b2 = other.NumOnBits() return float(bc) / float(b1 + b2 - bc) TanimotoSimilarity = TanimotoSimilarity def EuclideanDistance(self,other): if not isinstance(other,BitVect): raise TypeError("Tanimoto similarities can only be calculated between two BitVects") bt = len(self) bi = len(self ^ (~ other)) return math.sqrt(bt-bi)/bt def __getitem__(self,which): if which >= self.nBits or which < 0: raise ValueError('bad index') return self.bits[which] def __setitem__(self,which,val): if which >= self.nBits or which < 0: raise ValueError('bad index') if val not in [0,1]: raise ValueError('val must be 0 or 1') self.bits[which] = val def __len__(self): return self.nBits def __and__(self,other): if not isinstance(other,BitVect): raise TypeError("BitVects can only be &'ed with other BitVects") if len(self) != len(other): raise ValueError("BitVects must be of the same length") l1 = self.GetOnBits() l2 = other.GetOnBits() r = [bit for bit in l1 if bit in l2] return r def __or__(self,other): if not isinstance(other,BitVect): raise TypeError("BitVects can only be |'ed with other BitVects") if len(self) != len(other): raise ValueError("BitVects must be of the same length") l1 = self.GetOnBits() l2 = other.GetOnBits() r = l1 + [bit for bit in l2 if bit not in l1] r.sort() return r def __xor__(self,other): if not isinstance(other,BitVect): raise TypeError("BitVects can only be ^'ed with other BitVects") if len(self) != len(other): raise ValueError("BitVects must be of the same length") l1 = self.GetOnBits() l2 = other.GetOnBits() r = [bit for bit in l1 if bit not in l2] + [bit for bit in l2 if bit not in l1] r.sort() return r def __invert__(self): res = BitVect(len(self)) for i in xrange(len(self)): res[i] = not self[i] return res class SparseBitVect(BitVect): def __init__(self,nBits): self.nBits = nBits self.bits = [] def NumOnBits(self): return len(self.bits) def GetOnBits(self,sort=1,reverse=0): l = self.bits[:] if sort: l.sort() if reverse: l.reverse() return l def __getitem__(self,which): if which >= self.nBits or which < 0: raise ValueError('bad index') if which in self.bits: return 1 else: return 0 def __setitem__(self,which,val): if which >= self.nBits or which < 0: raise ValueError('bad index') if val == 0: if which in self.bits: self.bits.remove(which) else: self.bits.append(which) def __len__(self): return self.nBits if __name__ == '__main__': b1 = BitVect(10) b2 = SparseBitVect(10) b1[0] = 1 b2[0] = 1 b1[3] = 1 b2[4] = 1 b2[5] = 1 b2[5] = 0 print('b1:',b1.GetOnBits()) print('b2:',b2.GetOnBits()) print('&:', b1 & b2) print('|:', b1 | b2) print('^:', b1 ^ b2) print('b1.Tanimoto(b2):',b1.TanimotoSimilarity(b2)) print('b1.Tanimoto(b1):',b1.TanimotoSimilarity(b1)) print('b2.Tanimoto(b2):',b2.TanimotoSimilarity(b2)) print('b2.Tanimoto(b1):',b2.TanimotoSimilarity(b1))
{ "repo_name": "strets123/rdkit", "path": "rdkit/DataStructs/BitVect.py", "copies": "3", "size": "4250", "license": "bsd-3-clause", "hash": 2949613029355050500, "line_mean": 25.7295597484, "line_max": 90, "alpha_frac": 0.6192941176, "autogenerated": false, "ratio": 3.0553558590941767, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5174649976694177, "avg_score": null, "num_lines": null }
""" This has all be re-implemented in the C++ code """ import math class BitVect: def __init__(self,nBits): self.nBits = nBits self.bits = [0]*nBits def NumOnBits(self): return len(self.GetOnBits()) def GetOnBits(self,sort=1,reverse=0): l = [idx for idx in xrange(self.nBits) if self.bits[idx] == 1] if reverse: l.reverse() return l def TanimotoSimilarity(self,other): if not isinstance(other,BitVect): raise TypeError,"Tanimoto similarities can only be calculated between two BitVects" if len(self)!=len(other): raise ValueError,"BitVects must be the same length" bc = len(self & other) b1 = self.NumOnBits() b2 = other.NumOnBits() return float(bc) / float(b1 + b2 - bc) TanimotoSimilarity = TanimotoSimilarity def EuclideanDistance(self,other): if not isinstance(other,BitVect): raise TypeError,"Tanimoto similarities can only be calculated between two BitVects" bt = len(self) bi = len(self ^ (~ other)) return math.sqrt(bt-bi)/bt def __getitem__(self,which): if which >= self.nBits or which < 0: raise ValueError,'bad index' return self.bits[which] def __setitem__(self,which,val): if which >= self.nBits or which < 0: raise ValueError,'bad index' if val not in [0,1]: raise ValueError,'val must be 0 or 1' self.bits[which] = val def __len__(self): return self.nBits def __and__(self,other): if not isinstance(other,BitVect): raise TypeError,"BitVects can only be &'ed with other BitVects" if len(self) != len(other): raise ValueError,"BitVects must be of the same length" l1 = self.GetOnBits() l2 = other.GetOnBits() r = [bit for bit in l1 if bit in l2] return r def __or__(self,other): if not isinstance(other,BitVect): raise TypeError,"BitVects can only be |'ed with other BitVects" if len(self) != len(other): raise ValueError,"BitVects must be of the same length" l1 = self.GetOnBits() l2 = other.GetOnBits() r = l1 + [bit for bit in l2 if bit not in l1] r.sort() return r def __xor__(self,other): if not isinstance(other,BitVect): raise TypeError,"BitVects can only be ^'ed with other BitVects" if len(self) != len(other): raise ValueError,"BitVects must be of the same length" l1 = self.GetOnBits() l2 = other.GetOnBits() r = [bit for bit in l1 if bit not in l2] + [bit for bit in l2 if bit not in l1] r.sort() return r def __invert__(self): res = BitVect(len(self)) for i in xrange(len(self)): res[i] = not self[i] return res class SparseBitVect(BitVect): def __init__(self,nBits): self.nBits = nBits self.bits = [] def NumOnBits(self): return len(self.bits) def GetOnBits(self,sort=1,reverse=0): l = self.bits[:] if sort: l.sort() if reverse: l.reverse() return l def __getitem__(self,which): if which >= self.nBits or which < 0: raise ValueError,'bad index' if which in self.bits: return 1 else: return 0 def __setitem__(self,which,val): if which >= self.nBits or which < 0: raise ValueError,'bad index' if val == 0: if which in self.bits: self.bits.remove(which) else: self.bits.append(which) def __len__(self): return self.nBits if __name__ == '__main__': b1 = BitVect(10) b2 = SparseBitVect(10) b1[0] = 1 b2[0] = 1 b1[3] = 1 b2[4] = 1 b2[5] = 1 b2[5] = 0 print 'b1:',b1.GetOnBits() print 'b2:',b2.GetOnBits() print '&:', b1 & b2 print '|:', b1 | b2 print '^:', b1 ^ b2 print 'b1.Tanimoto(b2):',b1.TanimotoSimilarity(b2) print 'b1.Tanimoto(b1):',b1.TanimotoSimilarity(b1) print 'b2.Tanimoto(b2):',b2.TanimotoSimilarity(b2) print 'b2.Tanimoto(b1):',b2.TanimotoSimilarity(b1)
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/DataStructs/BitVect.py", "copies": "2", "size": "4189", "license": "bsd-3-clause", "hash": 1921393998897308700, "line_mean": 25.5126582278, "line_max": 89, "alpha_frac": 0.6213893531, "autogenerated": false, "ratio": 3.037708484408992, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9458577055542323, "avg_score": 0.04010415639333373, "num_lines": 158 }
""" unit testing code for the C++ BitVects """ from __future__ import print_function import unittest,os,sys from rdkit.six.moves import cPickle from rdkit.DataStructs import cDataStructs klass = cDataStructs.SparseBitVect def feq(n1,n2,tol=1e-4): return abs(n1-n2)<=tol def ieq(n1,n2): return abs(n1-n2)==0 class VectTests(object): def testSparseIdx(self): """ test indexing into SparseBitVects """ v = self.klass(10) v[0] = 1 v[2] = 1 v[9] = 1 with self.assertRaisesRegexp(IndexError, ""): v[10] = 1 assert v[0] == 1, 'bad bit' assert v[1] == 0, 'bad bit' assert v[2] == 1, 'bad bit' assert v[9] == 1, 'bad bit' assert v[-1] == 1, 'bad bit' assert v[-2] == 0, 'bad bit' with self.assertRaisesRegexp(IndexError, ""): foo = v[10] def testSparseBitGet(self): """ test operations to get sparse bits """ v = self.klass(10) v[0] = 1 v[2] = 1 v[6] = 1 assert len(v)==10,'len(SparseBitVect) failed' assert v.GetNumOnBits()==3,'NumOnBits failed' assert tuple(v.GetOnBits())==(0,2,6), 'GetOnBits failed' def testSparseBitOps(self): """ test bit operations on SparseBitVects """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 assert tuple((v1&v2).GetOnBits()) == (0,6),'binary & failed' assert tuple((v1&v2).GetOnBits()) == (0,6),'binary & failed' assert tuple((v1|v2).GetOnBits()) == (0,2,3,6),'binary | failed' assert tuple((v1^v2).GetOnBits()) == (2,3),'binary ^ failed' def testTanimotoSim(self): """ test Tanimoto Similarity measure """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 v3 = self.klass(10) v3[1] = 1 v3[4] = 1 v3[8] = 1 assert feq(cDataStructs.TanimotoSimilarity(v1,v1),1.0),'bad v1,v1 TanimotoSimilarity' assert feq(cDataStructs.TanimotoSimilarity(v2,v2),1.0),'bad v2,v2 TanimotoSimilarity' assert feq(cDataStructs.TanimotoSimilarity(v1,v2),0.5),'bad v1,v2 TanimotoSimilarity' assert feq(cDataStructs.TanimotoSimilarity(v2,v1),0.5),'bad v2,v1 TanimotoSimilarity' assert feq(cDataStructs.TanimotoSimilarity(v1,v3),0.0),'bad v1,v3 TanimotoSimilarity' assert feq(cDataStructs.TanimotoSimilarity(v2,v3),0.0),'bad v2,v3 TanimotoSimilarity' def testOnBitSim(self): """ test On Bit Similarity measure """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 v3 = self.klass(10) v3[1] = 1 v3[4] = 1 v3[8] = 1 assert feq(cDataStructs.OnBitSimilarity(v1,v1),1.0),'bad v1,v1 OnBitSimilarity' assert feq(cDataStructs.OnBitSimilarity(v2,v2),1.0),'bad v2,v2 OnBitSimilarity' assert feq(cDataStructs.OnBitSimilarity(v1,v2),0.5),'bad v1,v2 OnBitSimilarity' assert feq(cDataStructs.OnBitSimilarity(v2,v1),0.5),'bad v2,v1 OnBitSimilarity' assert feq(cDataStructs.OnBitSimilarity(v1,v3),0.0),'bad v1,v3 OnBitSimilarity' assert feq(cDataStructs.OnBitSimilarity(v2,v3),0.0),'bad v2,v3 OnBitSimilarity' def testNumBitsInCommon(self): """ test calculation of Number of Bits in Common """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 v3 = self.klass(10) v3[1] = 1 v3[4] = 1 v3[8] = 1 assert ieq(cDataStructs.NumBitsInCommon(v1,v1),10),'bad v1,v1 NumBitsInCommon' assert ieq(cDataStructs.NumBitsInCommon(v2,v2),10),'bad v2,v2 NumBitsInCommon' assert ieq(cDataStructs.NumBitsInCommon(v1,v2),8),'bad v1,v2 NumBitsInCommon' assert ieq(cDataStructs.NumBitsInCommon(v2,v1),8),'bad v2,v1 NumBitsInCommon' assert ieq(cDataStructs.NumBitsInCommon(v1,v3),4),'bad v1,v3 NumBitsInCommon' assert ieq(cDataStructs.NumBitsInCommon(v2,v3),4),'bad v2,v3 NumBitsInCommon' def testAllBitSim(self): """ test All Bit Similarity measure """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 v3 = self.klass(10) v3[1] = 1 v3[4] = 1 v3[8] = 1 assert feq(cDataStructs.AllBitSimilarity(v1,v1),1.0),'bad v1,v1 AllBitSimilarity' assert feq(cDataStructs.AllBitSimilarity(v2,v2),1.0),'bad v2,v2 AllBitSimilarity' assert feq(cDataStructs.AllBitSimilarity(v1,v2),0.8),'bad v1,v2 AllBitSimilarity' assert feq(cDataStructs.AllBitSimilarity(v2,v1),0.8),'bad v2,v1 AllBitSimilarity' assert feq(cDataStructs.AllBitSimilarity(v1,v3),0.4),'bad v1,v3 AllBitSimilarity' assert feq(cDataStructs.AllBitSimilarity(v2,v3),0.4),'bad v2,v3 AllBitSimilarity' def testStringOps(self): """ test serialization operations """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 s = v1.ToBinary() v2 = self.klass(s) assert tuple(v2.GetOnBits())==tuple(v1.GetOnBits()),'To/From string failed' def testOnBitsInCommon(self): """ test OnBitsInCommon """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 v3 = cDataStructs.OnBitsInCommon(v1,v2) assert tuple(v3)==(0,6),'bad on bits in common' def testOffBitsInCommon(self): """ test OffBitsInCommon """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 v3 = cDataStructs.OffBitsInCommon(v1,v2) assert tuple(v3)==(1,4,5,7,8,9),'bad off bits in common' def testOnBitProjSimilarity(self): """ test OnBitProjSimilarity """ v1 = self.klass(10) v1[1] = 1 v1[2] = 1 v1[3] = 1 v2 = self.klass(10) v2[2] = 1 v2[3] = 1 res = cDataStructs.OnBitProjSimilarity(v1,v2) assert feq(res[0],0.666667),'bad 1st OnBitsProjSimilarity' assert feq(res[1],1.0),'bad 2nd OnBitsProjSimilarity' res = cDataStructs.OnBitProjSimilarity(v2,v1) assert feq(res[1],0.666667),'bad 1st OnBitsProjSimilarity' assert feq(res[0],1.0),'bad 2nd OnBitsProjSimilarity' def testOffBitProjSimilarity(self): """ test OffBitProjSimilarity """ v1 = self.klass(10) v1[1] = 1 v1[2] = 1 v1[3] = 1 v2 = self.klass(10) v2[2] = 1 v2[3] = 1 res = cDataStructs.OffBitProjSimilarity(v1,v2) assert feq(res[0],1.0),'bad 1st OffBitsProjSimilarity' assert feq(res[1],0.875),'bad 2nd OffBitsProjSimilarity' res = cDataStructs.OffBitProjSimilarity(v2,v1) assert feq(res[1],1.0),'bad 1st OffBitsProjSimilarity' assert feq(res[0],0.875),'bad 2nd OffBitsProjSimilarity' def testPkl(self): """ test pickling """ v1 = self.klass(10) v1[1] = 1 v1[2] = 1 v1[3] = 1 pklName = 'foo.pkl' outF = open(pklName,'wb+') cPickle.dump(v1,outF) outF.close() inF = open(pklName,'rb') v2 = cPickle.load(inF) inF.close() os.unlink(pklName) assert tuple(v1.GetOnBits())==tuple(v2.GetOnBits()),'pkl failed' def testFingerprints(self): " test the parsing of daylight fingerprints " #actual daylight output: rawD=""" 0,Cc1n[nH]c(=O)nc1N,.b+HHa.EgU6+ibEIr89.CpX0g8FZiXH+R0+Ps.mr6tg.2 1,Cc1n[nH]c(=O)[nH]c1=O,.b7HEa..ccc+gWEIr89.8lV8gOF3aXFFR.+Ps.mZ6lg.2 2,Cc1nnc(NN)nc1O,.H+nHq2EcY09y5EIr9e.8p50h0NgiWGNx4+Hm+Gbslw.2 3,Cc1nnc(N)nc1C,.1.HHa..cUI6i5E2rO8.Op10d0NoiWGVx.+Hm.Gb6lo.2 """ dists="""0,0,1.000000 0,1,0.788991 0,2,0.677165 0,3,0.686957 1,1,1.000000 1,2,0.578125 1,3,0.591304 2,2,1.000000 2,3,0.732759 3,3,1.000000 """ fps = [] for line in rawD.split('\n'): if line: sbv = self.klass(256) id,smi,fp=line.split(',') cDataStructs.InitFromDaylightString(sbv,fp) fps.append(sbv) ds = dists.split('\n') whichd=0 for i in range(len(fps)): for j in range(i,len(fps)): idx1,idx2,tgt = ds[whichd].split(',') whichd += 1 tgt = float(tgt) dist = cDataStructs.TanimotoSimilarity(fps[i],fps[j]) assert feq(tgt,dist),'tanimoto between fps %d and %d failed'%(int(idx1),int(idx2)) def testFold(self): """ test folding fingerprints """ v1 = self.klass(16) v1[1] = 1 v1[12] = 1 v1[9] = 1 v2 = cDataStructs.FoldFingerprint(v1) # check fold with no args assert v1.GetNumBits()/2==v2.GetNumBits(),'bad num bits post folding' v2 = cDataStructs.FoldFingerprint(v1,2) # check fold with arg assert v1.GetNumBits()/2==v2.GetNumBits(),'bad num bits post folding' v2 = cDataStructs.FoldFingerprint(v1,4) assert v1.GetNumBits()/4==v2.GetNumBits(),'bad num bits post folding' def testOtherSims(self): """ test other similarity measures """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 assert feq(cDataStructs.CosineSimilarity(v1,v2),.6667) assert feq(cDataStructs.KulczynskiSimilarity(v1,v2),.6667) assert feq(cDataStructs.DiceSimilarity(v1,v2),.6667) assert feq(cDataStructs.SokalSimilarity(v1,v2),.3333) assert feq(cDataStructs.McConnaugheySimilarity(v1,v2),.3333) assert feq(cDataStructs.AsymmetricSimilarity(v1,v2),.6667) assert feq(cDataStructs.BraunBlanquetSimilarity(v1,v2),.6667) assert feq(cDataStructs.RusselSimilarity(v1,v2),.2000) assert feq(cDataStructs.RogotGoldbergSimilarity(v1,v2),.7619) def testQuickSims(self): """ the asymmetric similarity stuff (bv,pkl) """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 pkl = v2.ToBinary() v2 = pkl assert feq(cDataStructs.CosineSimilarity(v1,v2),.6667) assert feq(cDataStructs.KulczynskiSimilarity(v1,v2),.6667) assert feq(cDataStructs.DiceSimilarity(v1,v2),.6667) assert feq(cDataStructs.SokalSimilarity(v1,v2),.3333) assert feq(cDataStructs.McConnaugheySimilarity(v1,v2),.3333) assert feq(cDataStructs.AsymmetricSimilarity(v1,v2),.6667) assert feq(cDataStructs.BraunBlanquetSimilarity(v1,v2),.6667) assert feq(cDataStructs.RusselSimilarity(v1,v2),.2000) assert feq(cDataStructs.RogotGoldbergSimilarity(v1,v2),.7619) class SparseBitVectTests(VectTests, unittest.TestCase): klass = cDataStructs.SparseBitVect class ExplicitTestCase(VectTests, unittest.TestCase): klass = cDataStructs.ExplicitBitVect if __name__ == '__main__': unittest.main()
{ "repo_name": "adalke/rdkit", "path": "rdkit/DataStructs/UnitTestcBitVect.py", "copies": "1", "size": "10854", "license": "bsd-3-clause", "hash": -5713702337100957000, "line_mean": 29.3184357542, "line_max": 90, "alpha_frac": 0.6360788649, "autogenerated": false, "ratio": 2.471874288317012, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8513253465059296, "avg_score": 0.018939937631543082, "num_lines": 358 }
""" unit testing code for the C++ BitVects """ from __future__ import print_function import os import unittest from rdkit.DataStructs import cDataStructs from rdkit.six.moves import cPickle # @UnresolvedImport klass = cDataStructs.SparseBitVect def feq(n1, n2, tol=1e-4): return abs(n1 - n2) <= tol def ieq(n1, n2): return abs(n1 - n2) == 0 class VectTests(object): def testSparseIdx(self): """ test indexing into SparseBitVects """ v = self.klass(10) v[0] = 1 v[2] = 1 v[9] = 1 with self.assertRaisesRegexp(IndexError, ""): v[10] = 1 assert v[0] == 1, 'bad bit' assert v[1] == 0, 'bad bit' assert v[2] == 1, 'bad bit' assert v[9] == 1, 'bad bit' assert v[-1] == 1, 'bad bit' assert v[-2] == 0, 'bad bit' with self.assertRaisesRegexp(IndexError, ""): _ = v[10] def testSparseBitGet(self): """ test operations to get sparse bits """ v = self.klass(10) v[0] = 1 v[2] = 1 v[6] = 1 assert len(v) == 10, 'len(SparseBitVect) failed' assert v.GetNumOnBits() == 3, 'NumOnBits failed' assert tuple(v.GetOnBits()) == (0, 2, 6), 'GetOnBits failed' def testSparseBitOps(self): """ test bit operations on SparseBitVects """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 assert tuple((v1 & v2).GetOnBits()) == (0, 6), 'binary & failed' assert tuple((v1 & v2).GetOnBits()) == (0, 6), 'binary & failed' assert tuple((v1 | v2).GetOnBits()) == (0, 2, 3, 6), 'binary | failed' assert tuple((v1 ^ v2).GetOnBits()) == (2, 3), 'binary ^ failed' def testTanimotoSim(self): """ test Tanimoto Similarity measure """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 v3 = self.klass(10) v3[1] = 1 v3[4] = 1 v3[8] = 1 assert feq(cDataStructs.TanimotoSimilarity(v1, v1), 1.0), 'bad v1,v1 TanimotoSimilarity' assert feq(cDataStructs.TanimotoSimilarity(v2, v2), 1.0), 'bad v2,v2 TanimotoSimilarity' assert feq(cDataStructs.TanimotoSimilarity(v1, v2), 0.5), 'bad v1,v2 TanimotoSimilarity' assert feq(cDataStructs.TanimotoSimilarity(v2, v1), 0.5), 'bad v2,v1 TanimotoSimilarity' assert feq(cDataStructs.TanimotoSimilarity(v1, v3), 0.0), 'bad v1,v3 TanimotoSimilarity' assert feq(cDataStructs.TanimotoSimilarity(v2, v3), 0.0), 'bad v2,v3 TanimotoSimilarity' def testOnBitSim(self): """ test On Bit Similarity measure """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 v3 = self.klass(10) v3[1] = 1 v3[4] = 1 v3[8] = 1 assert feq(cDataStructs.OnBitSimilarity(v1, v1), 1.0), 'bad v1,v1 OnBitSimilarity' assert feq(cDataStructs.OnBitSimilarity(v2, v2), 1.0), 'bad v2,v2 OnBitSimilarity' assert feq(cDataStructs.OnBitSimilarity(v1, v2), 0.5), 'bad v1,v2 OnBitSimilarity' assert feq(cDataStructs.OnBitSimilarity(v2, v1), 0.5), 'bad v2,v1 OnBitSimilarity' assert feq(cDataStructs.OnBitSimilarity(v1, v3), 0.0), 'bad v1,v3 OnBitSimilarity' assert feq(cDataStructs.OnBitSimilarity(v2, v3), 0.0), 'bad v2,v3 OnBitSimilarity' def testNumBitsInCommon(self): """ test calculation of Number of Bits in Common """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 v3 = self.klass(10) v3[1] = 1 v3[4] = 1 v3[8] = 1 assert ieq(cDataStructs.NumBitsInCommon(v1, v1), 10), 'bad v1,v1 NumBitsInCommon' assert ieq(cDataStructs.NumBitsInCommon(v2, v2), 10), 'bad v2,v2 NumBitsInCommon' assert ieq(cDataStructs.NumBitsInCommon(v1, v2), 8), 'bad v1,v2 NumBitsInCommon' assert ieq(cDataStructs.NumBitsInCommon(v2, v1), 8), 'bad v2,v1 NumBitsInCommon' assert ieq(cDataStructs.NumBitsInCommon(v1, v3), 4), 'bad v1,v3 NumBitsInCommon' assert ieq(cDataStructs.NumBitsInCommon(v2, v3), 4), 'bad v2,v3 NumBitsInCommon' def testAllBitSim(self): """ test All Bit Similarity measure """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 v3 = self.klass(10) v3[1] = 1 v3[4] = 1 v3[8] = 1 assert feq(cDataStructs.AllBitSimilarity(v1, v1), 1.0), 'bad v1,v1 AllBitSimilarity' assert feq(cDataStructs.AllBitSimilarity(v2, v2), 1.0), 'bad v2,v2 AllBitSimilarity' assert feq(cDataStructs.AllBitSimilarity(v1, v2), 0.8), 'bad v1,v2 AllBitSimilarity' assert feq(cDataStructs.AllBitSimilarity(v2, v1), 0.8), 'bad v2,v1 AllBitSimilarity' assert feq(cDataStructs.AllBitSimilarity(v1, v3), 0.4), 'bad v1,v3 AllBitSimilarity' assert feq(cDataStructs.AllBitSimilarity(v2, v3), 0.4), 'bad v2,v3 AllBitSimilarity' def testStringOps(self): """ test serialization operations """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 s = v1.ToBinary() v2 = self.klass(s) assert tuple(v2.GetOnBits()) == tuple(v1.GetOnBits()), 'To/From string failed' def testOnBitsInCommon(self): """ test OnBitsInCommon """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 v3 = cDataStructs.OnBitsInCommon(v1, v2) assert tuple(v3) == (0, 6), 'bad on bits in common' def testOffBitsInCommon(self): """ test OffBitsInCommon """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 v3 = cDataStructs.OffBitsInCommon(v1, v2) assert tuple(v3) == (1, 4, 5, 7, 8, 9), 'bad off bits in common' def testOnBitProjSimilarity(self): """ test OnBitProjSimilarity """ v1 = self.klass(10) v1[1] = 1 v1[2] = 1 v1[3] = 1 v2 = self.klass(10) v2[2] = 1 v2[3] = 1 res = cDataStructs.OnBitProjSimilarity(v1, v2) assert feq(res[0], 0.666667), 'bad 1st OnBitsProjSimilarity' assert feq(res[1], 1.0), 'bad 2nd OnBitsProjSimilarity' res = cDataStructs.OnBitProjSimilarity(v2, v1) assert feq(res[1], 0.666667), 'bad 1st OnBitsProjSimilarity' assert feq(res[0], 1.0), 'bad 2nd OnBitsProjSimilarity' def testOffBitProjSimilarity(self): """ test OffBitProjSimilarity """ v1 = self.klass(10) v1[1] = 1 v1[2] = 1 v1[3] = 1 v2 = self.klass(10) v2[2] = 1 v2[3] = 1 res = cDataStructs.OffBitProjSimilarity(v1, v2) assert feq(res[0], 1.0), 'bad 1st OffBitsProjSimilarity' assert feq(res[1], 0.875), 'bad 2nd OffBitsProjSimilarity' res = cDataStructs.OffBitProjSimilarity(v2, v1) assert feq(res[1], 1.0), 'bad 1st OffBitsProjSimilarity' assert feq(res[0], 0.875), 'bad 2nd OffBitsProjSimilarity' def testPkl(self): # Test pickling v1 = self.klass(10) v1[1] = 1 v1[2] = 1 v1[3] = 1 pklName = 'foo.pkl' outF = open(pklName, 'wb+') cPickle.dump(v1, outF) outF.close() inF = open(pklName, 'rb') v2 = cPickle.load(inF) inF.close() os.unlink(pklName) assert tuple(v1.GetOnBits()) == tuple(v2.GetOnBits()), 'pkl failed' def testFingerprints(self): # Test parsing Daylight fingerprints # actual daylight output: rawD = """ 0,Cc1n[nH]c(=O)nc1N,.b+HHa.EgU6+ibEIr89.CpX0g8FZiXH+R0+Ps.mr6tg.2 1,Cc1n[nH]c(=O)[nH]c1=O,.b7HEa..ccc+gWEIr89.8lV8gOF3aXFFR.+Ps.mZ6lg.2 2,Cc1nnc(NN)nc1O,.H+nHq2EcY09y5EIr9e.8p50h0NgiWGNx4+Hm+Gbslw.2 3,Cc1nnc(N)nc1C,.1.HHa..cUI6i5E2rO8.Op10d0NoiWGVx.+Hm.Gb6lo.2 """ dists = """0,0,1.000000 0,1,0.788991 0,2,0.677165 0,3,0.686957 1,1,1.000000 1,2,0.578125 1,3,0.591304 2,2,1.000000 2,3,0.732759 3,3,1.000000 """ fps = [] for line in rawD.split('\n'): if line: sbv = self.klass(256) _, _, fp = line.split(',') cDataStructs.InitFromDaylightString(sbv, fp) fps.append(sbv) ds = dists.split('\n') whichd = 0 for i in range(len(fps)): for j in range(i, len(fps)): idx1, idx2, tgt = ds[whichd].split(',') whichd += 1 tgt = float(tgt) dist = cDataStructs.TanimotoSimilarity(fps[i], fps[j]) assert feq(tgt, dist), 'tanimoto between fps %d and %d failed' % (int(idx1), int(idx2)) def testFold(self): """ test folding fingerprints """ v1 = self.klass(16) v1[1] = 1 v1[12] = 1 v1[9] = 1 v2 = cDataStructs.FoldFingerprint(v1) # check fold with no args assert v1.GetNumBits() / 2 == v2.GetNumBits(), 'bad num bits post folding' v2 = cDataStructs.FoldFingerprint(v1, 2) # check fold with arg assert v1.GetNumBits() / 2 == v2.GetNumBits(), 'bad num bits post folding' v2 = cDataStructs.FoldFingerprint(v1, 4) assert v1.GetNumBits() / 4 == v2.GetNumBits(), 'bad num bits post folding' def testOtherSims(self): """ test other similarity measures """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 assert feq(cDataStructs.CosineSimilarity(v1, v2), .6667) assert feq(cDataStructs.KulczynskiSimilarity(v1, v2), .6667) assert feq(cDataStructs.DiceSimilarity(v1, v2), .6667) assert feq(cDataStructs.SokalSimilarity(v1, v2), .3333) assert feq(cDataStructs.McConnaugheySimilarity(v1, v2), .3333) assert feq(cDataStructs.AsymmetricSimilarity(v1, v2), .6667) assert feq(cDataStructs.BraunBlanquetSimilarity(v1, v2), .6667) assert feq(cDataStructs.RusselSimilarity(v1, v2), .2000) assert feq(cDataStructs.RogotGoldbergSimilarity(v1, v2), .7619) def testQuickSims(self): """ the asymmetric similarity stuff (bv,pkl) """ v1 = self.klass(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = self.klass(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 pkl = v2.ToBinary() v2 = pkl assert feq(cDataStructs.CosineSimilarity(v1, v2), .6667) assert feq(cDataStructs.KulczynskiSimilarity(v1, v2), .6667) assert feq(cDataStructs.DiceSimilarity(v1, v2), .6667) assert feq(cDataStructs.SokalSimilarity(v1, v2), .3333) assert feq(cDataStructs.McConnaugheySimilarity(v1, v2), .3333) assert feq(cDataStructs.AsymmetricSimilarity(v1, v2), .6667) assert feq(cDataStructs.BraunBlanquetSimilarity(v1, v2), .6667) assert feq(cDataStructs.RusselSimilarity(v1, v2), .2000) assert feq(cDataStructs.RogotGoldbergSimilarity(v1, v2), .7619) class SparseBitVectTests(VectTests, unittest.TestCase): klass = cDataStructs.SparseBitVect class ExplicitTestCase(VectTests, unittest.TestCase): klass = cDataStructs.ExplicitBitVect if __name__ == '__main__': # pragma: nocover unittest.main()
{ "repo_name": "jandom/rdkit", "path": "rdkit/DataStructs/UnitTestcBitVect.py", "copies": "1", "size": "11080", "license": "bsd-3-clause", "hash": -2645713607277623000, "line_mean": 29.1086956522, "line_max": 95, "alpha_frac": 0.6248194946, "autogenerated": false, "ratio": 2.487651549169286, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8594943050221752, "avg_score": 0.003505598709506999, "num_lines": 368 }
""" unit testing code for the python BitVects """ import unittest from rdkit.six.moves import cPickle from rdkit.DataStructs import BitVect def feq(v1,v2,tol=1e-4): return abs(v1-v2)<tol class TestCase(unittest.TestCase): def testVectIdx(self): """ test indexing into BitVects """ v = BitVect.BitVect(10) ok = 1 try: v[0] = 1 v[2] = 1 except: ok = 0 assert ok, 'setting bits failed' try: v[10] = 1 except: ok = 1 else: ok = 0 assert ok, 'setting high bit should have failed' try: v[-1] = 1 except: ok = 1 else: ok = 0 assert ok, 'setting negative bit should have failed' assert v[0] == 1, 'bad bit' assert v[1] == 0, 'bad bit' assert v[2] == 1, 'bad bit' try: foo = v[10] except: ok = 1 else: ok = 0 assert ok, 'getting high bit should have failed' try: foo = v[-1] except: ok = 1 else: ok = 0 assert ok, 'getting negative bit should have failed' def testSparseIdx(self): """ test indexing into SparseBitVects """ v = BitVect.SparseBitVect(10) ok = 1 try: v[0] = 1 v[2] = 1 except: ok = 0 assert ok, 'setting bits failed' try: v[10] = 1 except: ok = 1 else: ok = 0 assert ok, 'setting high bit should have failed' try: v[-1] = 1 except: ok = 1 else: ok = 0 assert ok, 'setting negative bit should have failed' assert v[0] == 1, 'bad bit' assert v[1] == 0, 'bad bit' assert v[2] == 1, 'bad bit' try: foo = v[10] except: ok = 1 else: ok = 0 assert ok, 'getting high bit should have failed' try: foo = v[-1] except: ok = 1 else: ok = 0 assert ok, 'getting negative bit should have failed' def testVectBitGet(self): """ test operations to get bits """ v = BitVect.BitVect(10) v[0] = 1 v[2] = 1 v[6] = 1 assert len(v)==10,'len(BitVect) failed' assert v.NumOnBits()==3,'NumOnBits failed' assert v.GetOnBits()==[0,2,6], 'GetOnBits failed' assert v.GetOnBits(reverse=1)==[6,2,0], 'GetOnBits(reverse) failed' def testSparseBitGet(self): """ test operations to get sparse bits """ v = BitVect.BitVect(10) v[0] = 1 v[2] = 1 v[6] = 1 assert len(v)==10,'len(SparseBitVect) failed' assert v.NumOnBits()==3,'NumOnBits failed' assert v.GetOnBits()==[0,2,6], 'GetOnBits failed' assert v.GetOnBits(reverse=1)==[6,2,0], 'GetOnBits(reverse) failed' def testVectBitOps(self): """ test bit operations on BitVects """ v1 = BitVect.BitVect(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = BitVect.BitVect(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 assert v1&v2 == [0,6],'binary & failed' assert v1|v2 == [0,2,3,6],'binary | failed' assert v1^v2 == [2,3],'binary ^ failed' def testCrossBitOps(self): """ test bit operations between BitVects and SparseBitVects """ v1 = BitVect.SparseBitVect(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = BitVect.BitVect(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 assert v1&v2 == [0,6],'binary & failed' assert v1|v2 == [0,2,3,6],'binary | failed' assert v1^v2 == [2,3],'binary ^ failed' def testSparseBitOps(self): """ test bit operations on SparseBitVects """ v1 = BitVect.SparseBitVect(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = BitVect.SparseBitVect(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 assert v1&v2 == [0,6],'binary & failed' assert v1|v2 == [0,2,3,6],'binary | failed' assert v1^v2 == [2,3],'binary ^ failed' def testVectTanimoto(self): v1 = BitVect.BitVect(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = BitVect.BitVect(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 assert v1.TanimotoSimilarity(v2)==0.5,'TanimotoSimilarity failed' assert v2.TanimotoSimilarity(v1)==0.5,'TanimotoSimilarity failed' assert v1.TanimotoSimilarity(v1)==1.0,'TanimotoSimilarity failed' assert v2.TanimotoSimilarity(v2)==1.0,'TanimotoSimilarity failed' def testSparseTanimoto(self): v1 = BitVect.SparseBitVect(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = BitVect.SparseBitVect(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 assert v1.TanimotoSimilarity(v2)==0.5,'TanimotoSimilarity failed' assert v2.TanimotoSimilarity(v1)==0.5,'TanimotoSimilarity failed' assert v1.TanimotoSimilarity(v1)==1.0,'TanimotoSimilarity failed' assert v2.TanimotoSimilarity(v2)==1.0,'TanimotoSimilarity failed' def testCrossTanimoto(self): v1 = BitVect.SparseBitVect(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = BitVect.BitVect(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 assert v1.TanimotoSimilarity(v2)==0.5,'TanimotoSimilarity failed' assert v2.TanimotoSimilarity(v1)==0.5,'TanimotoSimilarity failed' assert v1.TanimotoSimilarity(v1)==1.0,'TanimotoSimilarity failed' assert v2.TanimotoSimilarity(v2)==1.0,'TanimotoSimilarity failed' def testVectEuclid(self): v1 = BitVect.BitVect(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = BitVect.BitVect(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 assert abs(v1.EuclideanDistance(v2)-.14142)<.0001, 'EuclideanDistance failed' assert abs(v2.EuclideanDistance(v1)-.14142)<.0001, 'EuclideanDistance failed' assert v1.EuclideanDistance(v1)==0.0, 'EuclideanDistance failed' assert v2.EuclideanDistance(v2)==0.0, 'EuclideanDistance failed' def testSparseEuclid(self): v1 = BitVect.SparseBitVect(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = BitVect.SparseBitVect(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 assert abs(v1.EuclideanDistance(v2)-.14142)<.0001, 'EuclideanDistance failed' assert abs(v2.EuclideanDistance(v1)-.14142)<.0001, 'EuclideanDistance failed' assert v1.EuclideanDistance(v1)==0.0, 'EuclideanDistance failed' assert v2.EuclideanDistance(v2)==0.0, 'EuclideanDistance failed' def testCrossEuclid(self): v1 = BitVect.BitVect(10) v1[0] = 1 v1[2] = 1 v1[6] = 1 v2 = BitVect.SparseBitVect(10) v2[0] = 1 v2[3] = 1 v2[6] = 1 assert abs(v1.EuclideanDistance(v2)-.14142)<.0001, 'EuclideanDistance failed' assert abs(v2.EuclideanDistance(v1)-.14142)<.0001, 'EuclideanDistance failed' assert v1.EuclideanDistance(v1)==0.0, 'EuclideanDistance failed' assert v2.EuclideanDistance(v2)==0.0, 'EuclideanDistance failed' def test90BulkDistances(self): """ verify that the base similarity (tanimoto) works using an 18 fp regression panel of pubchem compounds (chosen to have different lengths: 5x2048, 5x1024, 5x512, 3x256) """ from rdkit import DataStructs import os from rdkit import RDConfig fps = cPickle.load(file(os.path.join(RDConfig.RDCodeDir,'DataStructs','test_data', 'pubchem_fps.pkl'),'rb')) dm = cPickle.load(file(os.path.join(RDConfig.RDCodeDir,'DataStructs','test_data', 'pubchem_fps.dm.pkl'),'rb')) dmIdx=0 for i in range(len(fps)): nmi,fpi = fps[i] for j in range(i+1,len(fps)): nmj,fpj = fps[j] sim = DataStructs.FingerprintSimilarity(fpi,fpj) self.failUnless(feq(sim,dm[dmIdx])) dmIdx+=1 def test91BoundDistances(self): """ verify that the bounded similarity (tanimoto) works """ from rdkit import DataStructs import os from rdkit import RDConfig fps = cPickle.load(file(os.path.join(RDConfig.RDCodeDir,'DataStructs','test_data', 'pubchem_fps.pkl'),'rb')) dm = cPickle.load(file(os.path.join(RDConfig.RDCodeDir,'DataStructs','test_data', 'pubchem_fps.dm.pkl'),'rb')) dmIdx=0 for i in range(len(fps)): nmi,fpi = fps[i] for j in range(i+1,len(fps)): nmj,fpj = fps[j] sim = DataStructs.FingerprintSimilarity(fpi,fpj) self.failUnless(feq(sim,dm[dmIdx])) dmIdx+=1 if __name__ == '__main__': unittest.main()
{ "repo_name": "soerendip42/rdkit", "path": "rdkit/DataStructs/UnitTestBitVect.py", "copies": "3", "size": "8576", "license": "bsd-3-clause", "hash": -788062747523414300, "line_mean": 25.9685534591, "line_max": 86, "alpha_frac": 0.5901352612, "autogenerated": false, "ratio": 2.8247694334650855, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9775372216450031, "avg_score": 0.027906495643010863, "num_lines": 318 }
"""basic unit testing code for the molecule boost wrapper """ from rdkit import RDConfig import unittest,cPickle,os from rdkit import Chem class TestCase(unittest.TestCase): def setUp(self): self.bigSmiList = [ "CC1=CC(=O)C=CC1=O", "S(SC1=NC2=CC=CC=C2S1)C3=NC4=C(S3)C=CC=C4", "OC1=C(Cl)C=C(C=C1[N+]([O-])=O)[N+]([O-])=O", "[O-][N+](=O)C1=CNC(=N)S1", "NC1=CC2=C(C=C1)C(=O)C3=C(C=CC=C3)C2=O", "OC(=O)C1=C(C=CC=C1)C2=C3C=CC(=O)C(=C3OC4=C2C=CC(=C4Br)O)Br", "CN(C)C1=C(Cl)C(=O)C2=C(C=CC=C2)C1=O", "CC1=C(C2=C(C=C1)C(=O)C3=CC=CC=C3C2=O)[N+]([O-])=O", "CC(=NO)C(C)=NO", "C1=CC=C(C=C1)P(C2=CC=CC=C2)C3=CC=CC=C3", "CC(C)(C)C1=C(O)C=C(C(=C1)O)C(C)(C)C", "CC1=NN(C(=O)C1)C2=CC=CC=C2", "NC1=CC=NC2=C1C=CC(=C2)Cl", "CCCCCC[CH]1CCCCN1", "O=CC1=C2C=CC=CC2=CC3=C1C=CC=C3", "BrN1C(=O)CCC1=O", "CCCCCCCCCCCCCCCC1=C(N)C=CC(=C1)O", "C(COC1=C(C=CC=C1)C2=CC=CC=C2)OC3=CC=CC=C3C4=CC=CC=C4", "CCCCSCC", "CC(=O)NC1=NC2=C(C=C1)C(=CC=N2)O", "CC1=C2C=CC(=NC2=NC(=C1)O)N", "CCOC(=O)C1=CN=C2N=C(N)C=CC2=C1O", "CC1=CC(=NC=C1)N=CC2=CC=CC=C2", "C[N+](C)(C)CC1=CC=CC=C1", "C[N+](C)(C)C(=O)C1=CC=CC=C1", "ICCC(C1=CC=CC=C1)(C2=CC=CC=C2)C3=CC=CC=C3", "CC1=CC(=C(C[N+](C)(C)C)C(=C1)C)C", "C[C](O)(CC(O)=O)C1=CC=C(C=C1)[N+]([O-])=O", "CC1=CC=C(C=C1)C(=O)C2=CC=C(Cl)C=C2", "ON=CC1=CC=C(O)C=C1", "CC1=CC(=C(N)C(=C1)C)C", "CC1=CC=C(C=C1)C(=O)C2=CC=C(C=C2)[N+]([O-])=O", "CC(O)(C1=CC=CC=C1)C2=CC=CC=C2", "ON=CC1=CC(=CC=C1)[N+]([O-])=O", "OC1=C2C=CC(=CC2=NC=C1[N+]([O-])=O)Cl", "CC1=CC=CC2=NC=C(C)C(=C12)Cl", "CCC(CC)([CH](OC(N)=O)C1=CC=CC=C1)C2=CC=CC=C2", "ON=C(CC1=CC=CC=C1)[CH](C#N)C2=CC=CC=C2", "O[CH](CC1=CC=CC=C1)C2=CC=CC=C2", "COC1=CC=C(CC2=CC=C(OC)C=C2)C=C1", "CN(C)[CH](C1=CC=CC=C1)C2=C(C)C=CC=C2", "COC1=CC(=C(N)C(=C1)[N+]([O-])=O)[N+]([O-])=O", "NN=C(C1=CC=CC=C1)C2=CC=CC=C2", "COC1=CC=C(C=C1)C=NO", "C1=CC=C(C=C1)C(N=C(C2=CC=CC=C2)C3=CC=CC=C3)C4=CC=CC=C4", "C1=CC=C(C=C1)N=C(C2=CC=CC=C2)C3=CC=CC=C3", "CC1=C(C2=CC=CC=C2)C(=C3C=CC=CC3=N1)O", "CCC1=[O+][Cu]2([O+]=C(CC)C1)[O+]=C(CC)CC(=[O+]2)CC", "OC(=O)[CH](CC1=CC=CC=C1)C2=CC=CC=C2", "CCC1=C(N)C=C(C)N=C1", ] def _testPkl10(self): " testing 5k molecule pickles " inLines = open('%s/NCI/first_5K.smi'%(RDConfig.RDDataDir),'r').readlines() smis = [] for line in inLines: smis.append(line.split('\t')[0]) for smi in smis: m = Chem.MolFromSmiles(smi) newM1 = cPickle.loads(cPickle.dumps(m)) newSmi1 = Chem.MolToSmiles(newM1) newM2 = cPickle.loads(cPickle.dumps(newM1)) newSmi2 = Chem.MolToSmiles(newM2) assert newM1.GetNumAtoms()==m.GetNumAtoms(),'num atoms comparison failed' assert newM2.GetNumAtoms()==m.GetNumAtoms(),'num atoms comparison failed' assert len(newSmi1)>0,'empty smi1' assert len(newSmi2)>0,'empty smi2' assert newSmi1==newSmi2,'string compare failed:\n%s\n\t!=\n%s\norig smiles:\n%s'%(newSmi1,newSmi2,smi) def testPkl1(self): " testing single molecule pickle " m = Chem.MolFromSmiles('CCOC') outS = Chem.MolToSmiles(m) m2 = cPickle.loads(cPickle.dumps(m)) outS2 = Chem.MolToSmiles(m2) assert outS==outS2,"bad pickle: %s != %s"%(outS,outS2) def testPkl2(self): """ further pickle tests """ smis = self.bigSmiList for smi in smis: m = Chem.MolFromSmiles(smi) newM1 = cPickle.loads(cPickle.dumps(m)) newM2 = cPickle.loads(cPickle.dumps(newM1)) oldSmi = Chem.MolToSmiles(newM1) newSmi = Chem.MolToSmiles(newM2) assert newM1.GetNumAtoms()==m.GetNumAtoms(),'num atoms comparison failed' assert newM2.GetNumAtoms()==m.GetNumAtoms(),'num atoms comparison failed' assert oldSmi==newSmi,'string compare failed: %s != %s'%(oldSmi,newSmi) def testPkl(self): " testing molecule pickle " import tempfile f,self.fName = tempfile.mkstemp('.pkl') f=None self.m = Chem.MolFromSmiles('CC(=O)CC') outF = open(self.fName,'wb+') cPickle.dump(self.m,outF) outF.close() inF = open(self.fName,'rb') m2 = cPickle.load(inF) inF.close() try: os.unlink(self.fName) except: pass oldSmi = Chem.MolToSmiles(self.m) newSmi = Chem.MolToSmiles(m2) assert oldSmi==newSmi,'string compare failed' def testRings(self): " testing SSSR handling " m = Chem.MolFromSmiles('OC1C(O)C2C1C(O)C2O') for i in range(m.GetNumAtoms()): at = m.GetAtomWithIdx(i) n = at.GetAtomicNum() if n==8: assert not at.IsInRingSize(4),'atom %d improperly in ring'%(i) else: assert at.IsInRingSize(4),'atom %d not in ring of size 4'%(i) if __name__ == '__main__': unittest.main()
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/UnitTestChem.py", "copies": "2", "size": "5153", "license": "bsd-3-clause", "hash": -4525461195508101000, "line_mean": 33.5838926174, "line_max": 108, "alpha_frac": 0.5734523578, "autogenerated": false, "ratio": 2.0097503900156006, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8475935043219458, "avg_score": 0.021453540919228613, "num_lines": 149 }
""" code for dealing with resemblance (metric) matrices Here's how the matrices are stored: '[(0,1),(0,2),(1,2),(0,3),(1,3),(2,3)...] (row,col), col>row' or, alternatively the matrix can be drawn, with indices as: || - || 0 || 1 || 3 || - || - || 2 || 4 || - || - || - || 5 || - || - || - || - the index of a given (row,col) pair is: '(col*(col-1))/2 + row' """ from __future__ import print_function import numpy def EuclideanDistance(inData): """returns the euclidean metricMat between the points in _inData_ **Arguments** - inData: a Numeric array of data points **Returns** a Numeric array with the metric matrix. See the module documentation for the format. """ nObjs = len(inData) res = numpy.zeros((nObjs * (nObjs - 1) / 2), numpy.float) nSoFar = 0 for col in range(1, nObjs): for row in range(col): t = inData[row] - inData[col] res[nSoFar] = sum(t * t) nSoFar += 1 return numpy.sqrt(res) def CalcMetricMatrix(inData, metricFunc): """ generates a metric matrix **Arguments** - inData is assumed to be a list of clusters (or anything with a GetPosition() method) - metricFunc is the function to be used to generate the matrix **Returns** the metric matrix as a Numeric array """ nObjs = len(inData) res = [] inData = map(lambda x: x.GetPosition(), inData) return metricFunc(inData) def FindMinValInList(mat, nObjs, minIdx=None): """ finds the minimum value in a metricMatrix and returns it and its indices **Arguments** - mat: the metric matrix - nObjs: the number of objects to be considered - minIdx: the index of the minimum value (value, row and column still need to be calculated **Returns** a 3-tuple containing: 1) the row 2) the column 3) the minimum value itself **Notes** -this probably ain't the speediest thing on earth """ assert len(mat) == nObjs * (nObjs - 1) / 2, 'bad matrix length in FindMinValInList' if minIdx is None: minIdx = numpy.argmin(mat) nSoFar = 0 col = 0 while nSoFar <= minIdx: col = col + 1 nSoFar += col row = minIdx - nSoFar + col return row, col, mat[minIdx] def ShowMetricMat(metricMat, nObjs): """ displays a metric matrix **Arguments** - metricMat: the matrix to be displayed - nObjs: the number of objects to display """ assert len(metricMat) == nObjs * (nObjs - 1) / 2, 'bad matrix length in FindMinValInList' for row in range(nObjs): for col in range(nObjs): if col <= row: print(' --- ', end='') else: print('%10.6f' % metricMat[(col * (col - 1)) / 2 + row], end='') print() methods = [("Euclidean", EuclideanDistance, "Euclidean Distance"), ] if __name__ == '__main__': m = [.1, .2, .3, .4, .5, .6, .7, .8, .9, 1.0] nObjs = 5 for i in range(10): print(i, FindMinValInList(m, nObjs, i))
{ "repo_name": "jandom/rdkit", "path": "rdkit/ML/Cluster/Resemblance.py", "copies": "1", "size": "3291", "license": "bsd-3-clause", "hash": -3045037407623741000, "line_mean": 22.013986014, "line_max": 91, "alpha_frac": 0.5958675175, "autogenerated": false, "ratio": 3.2681231380337636, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4363990655533764, "avg_score": null, "num_lines": null }
"""unit testing code for the SATIS numbers """ from __future__ import print_function import unittest from rdkit.Chem import * from rdkit.Chem import SATIS from rdkit.six.moves import xrange class TestCase(unittest.TestCase): def setUp(self): print('\n%s: ' % self.shortDescription(), end='') def test1(self): """ first set of test cases """ data = [('CC(=O)NC', ['0601010106', '0606070895', '0806999995', '0701060699', '0601010107']), ('O=CC(=O)C', ['0806999993', '0601060893', '0606060894', '0806999994', '0601010106']), ('C(=O)OCC(=O)O', ['0601080896', '0806999996', '0806069996', '0601010608', '0606080898', '0806999998', '0801069998']), ('C(=O)[O-]', ['0601080897', '0806999997', '0806999997']), ('CP(F)(Cl)(Br)(O)', ['0601010115', '1508091735', '0915999999', '1715999999', '3515999999', '0801159999']), ] for smi, res in data: m = MolFromSmiles(smi) satis = SATIS.SATISTypes(m) assert satis == res, "Bad SATIS for mol %s: %s should have been %s" % (smi, str(satis), str(res)) if __name__ == '__main__': unittest.main()
{ "repo_name": "jandom/rdkit", "path": "rdkit/Chem/UnitTestSATIS.py", "copies": "1", "size": "1538", "license": "bsd-3-clause", "hash": 5093941320331542000, "line_mean": 33.1777777778, "line_max": 100, "alpha_frac": 0.5624187256, "autogenerated": false, "ratio": 3.082164328657315, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4144583054257315, "avg_score": null, "num_lines": null }
""" Automatic search for quantization bounds This uses the expected informational gain to determine where quantization bounds should lie. **Notes**: - bounds are less than, so if the bounds are [1.,2.], [0.9,1.,1.1,2.,2.2] -> [0,1,1,2,2] """ from __future__ import print_function import numpy from rdkit.ML.InfoTheory import entropy from rdkit.six.moves import zip, map, range try: from rdkit.ML.Data import cQuantize except ImportError: hascQuantize = 0 else: hascQuantize = 1 _float_tol = 1e-8 def feq(v1,v2,tol=_float_tol): """ floating point equality with a tolerance factor **Arguments** - v1: a float - v2: a float - tol: the tolerance for comparison **Returns** 0 or 1 """ return abs(v1-v2) < tol def FindVarQuantBound(vals,results,nPossibleRes): """ Uses FindVarMultQuantBounds, only here for historic reasons """ bounds,gain = FindVarMultQuantBounds(vals,1,results,nPossibleRes) return (bounds[0],gain) def _GenVarTable(vals,cuts,starts,results,nPossibleRes): """ Primarily intended for internal use constructs a variable table for the data passed in The table for a given variable records the number of times each possible value of that variable appears for each possible result of the function. **Arguments** - vals: a 1D Numeric array with the values of the variables - cuts: a list with the indices of the quantization bounds (indices are into _starts_ ) - starts: a list of potential starting points for quantization bounds - results: a 1D Numeric array of integer result codes - nPossibleRes: an integer with the number of possible result codes **Returns** the varTable, a 2D Numeric array which is nVarValues x nPossibleRes **Notes** - _vals_ should be sorted! """ nVals = len(cuts)+1 varTable = numpy.zeros((nVals,nPossibleRes),'i') idx = 0 for i in range(nVals-1): cut = cuts[i] while idx < starts[cut]: varTable[i,results[idx]] += 1 idx += 1 while idx < len(vals): varTable[-1,results[idx]] += 1 idx += 1 return varTable def _PyRecurseOnBounds(vals,cuts,which,starts,results,nPossibleRes,varTable=None): """ Primarily intended for internal use Recursively finds the best quantization boundaries **Arguments** - vals: a 1D Numeric array with the values of the variables, this should be sorted - cuts: a list with the indices of the quantization bounds (indices are into _starts_ ) - which: an integer indicating which bound is being adjusted here (and index into _cuts_ ) - starts: a list of potential starting points for quantization bounds - results: a 1D Numeric array of integer result codes - nPossibleRes: an integer with the number of possible result codes **Returns** - a 2-tuple containing: 1) the best information gain found so far 2) a list of the quantization bound indices ( _cuts_ for the best case) **Notes** - this is not even remotely efficient, which is why a C replacement was written """ nBounds = len(cuts) maxGain = -1e6 bestCuts = None highestCutHere = len(starts) - nBounds + which if varTable is None: varTable = _GenVarTable(vals,cuts,starts,results,nPossibleRes) while cuts[which] <= highestCutHere: varTable = _GenVarTable(vals,cuts,starts,results,nPossibleRes) gainHere = entropy.InfoGain(varTable) if gainHere > maxGain: maxGain = gainHere bestCuts = cuts[:] # recurse on the next vars if needed if which < nBounds-1: gainHere,cutsHere=_RecurseOnBounds(vals,cuts[:],which+1,starts,results,nPossibleRes, varTable = varTable) if gainHere > maxGain: maxGain = gainHere bestCuts = cutsHere # update this cut cuts[which] += 1 for i in range(which+1,nBounds): if cuts[i] == cuts[i-1]: cuts[i] += 1 return maxGain,bestCuts def _NewPyRecurseOnBounds(vals,cuts,which,starts,results,nPossibleRes,varTable=None): """ Primarily intended for internal use Recursively finds the best quantization boundaries **Arguments** - vals: a 1D Numeric array with the values of the variables, this should be sorted - cuts: a list with the indices of the quantization bounds (indices are into _starts_ ) - which: an integer indicating which bound is being adjusted here (and index into _cuts_ ) - starts: a list of potential starting points for quantization bounds - results: a 1D Numeric array of integer result codes - nPossibleRes: an integer with the number of possible result codes **Returns** - a 2-tuple containing: 1) the best information gain found so far 2) a list of the quantization bound indices ( _cuts_ for the best case) **Notes** - this is not even remotely efficient, which is why a C replacement was written """ nBounds = len(cuts) maxGain = -1e6 bestCuts = None highestCutHere = len(starts) - nBounds + which if varTable is None: varTable = _GenVarTable(vals,cuts,starts,results,nPossibleRes) while cuts[which] <= highestCutHere: gainHere = entropy.InfoGain(varTable) if gainHere > maxGain: maxGain = gainHere bestCuts = cuts[:] # recurse on the next vars if needed if which < nBounds-1: gainHere,cutsHere=_RecurseOnBounds(vals,cuts[:],which+1,starts,results,nPossibleRes, varTable = None) if gainHere > maxGain: maxGain = gainHere bestCuts = cutsHere # update this cut oldCut = cuts[which] cuts[which] += 1 bot = starts[oldCut] if oldCut+1 < len(starts): top = starts[oldCut+1] else: top = starts[-1] for i in range(bot,top): v = results[i] varTable[which,v] += 1 varTable[which+1,v] -= 1 for i in range(which+1,nBounds): if cuts[i] == cuts[i-1]: cuts[i] += 1 return maxGain,bestCuts # -------------------------------- # # find all possible dividing points # # There are a couple requirements for a dividing point: # 1) the dependent variable (descriptor) must change across it, # 2) the result score must change across it # # So, in the list [(0,0),(1,0),(1,1),(2,1)]: # we should divide before (1,0) and (2,1) # # -------------------------------- def _NewPyFindStartPoints(sortVals,sortResults,nData): startNext = [] tol = 1e-8 blockAct=sortResults[0] lastBlockAct=None lastDiv=None i = 1 while i<nData: # move to the end of this block: while i<nData and sortVals[i]-sortVals[i-1]<=tol: if sortResults[i] != blockAct: # this block is heterogeneous blockAct=-1 i+=1 if lastBlockAct is None: # first time through: lastBlockAct = blockAct lastDiv = i else: if blockAct==-1 or lastBlockAct==-1 or blockAct!=lastBlockAct: startNext.append(lastDiv) lastDiv = i lastBlockAct = blockAct else: lastDiv=i if i<nData: blockAct=sortResults[i] i+=1 # catch the case that the last point also sets a bin: if blockAct != lastBlockAct : startNext.append(lastDiv) return startNext def FindVarMultQuantBounds(vals,nBounds,results,nPossibleRes): """ finds multiple quantization bounds for a single variable **Arguments** - vals: sequence of variable values (assumed to be floats) - nBounds: the number of quantization bounds to find - results: a list of result codes (should be integers) - nPossibleRes: an integer with the number of possible values of the result variable **Returns** - a 2-tuple containing: 1) a list of the quantization bounds (floats) 2) the information gain associated with this quantization """ assert len(vals) == len(results), 'vals/results length mismatch' nData = len(vals) if nData == 0: return [],-1e8 # sort the variable values: svs = list(zip(vals,results)) svs.sort() sortVals,sortResults = zip(*svs) startNext=_FindStartPoints(sortVals,sortResults,nData) if not len(startNext): return [0],0.0 if len(startNext)<nBounds: nBounds = len(startNext)-1 if nBounds == 0: nBounds=1 initCuts = list(range(nBounds)) maxGain,bestCuts = _RecurseOnBounds(sortVals,initCuts,0,startNext, sortResults,nPossibleRes) quantBounds = [] nVs = len(sortVals) for cut in bestCuts: idx = startNext[cut] if idx == nVs: quantBounds.append(sortVals[-1]) elif idx == 0: quantBounds.append(sortVals[idx]) else: quantBounds.append((sortVals[idx]+sortVals[idx-1])/2.) return quantBounds,maxGain #hascQuantize=0 if hascQuantize: _RecurseOnBounds = cQuantize._RecurseOnBounds _FindStartPoints = cQuantize._FindStartPoints else: _RecurseOnBounds = _NewPyRecurseOnBounds _FindStartPoints = _NewPyFindStartPoints if __name__ == '__main__': import sys if 1: d = [(1.,0), (1.1,0), (1.2,0), (1.4,1), (1.4,0), (1.6,1), (2.,1), (2.1,0), (2.1,0), (2.1,0), (2.2,1), (2.3,0)] varValues = list(map(lambda x:x[0],d)) resCodes = list(map(lambda x:x[1],d)) nPossibleRes = 2 res = FindVarMultQuantBounds(varValues,2,resCodes,nPossibleRes) print('RES:',res) target = ([1.3, 2.05],.34707 ) else: d = [(1.,0), (1.1,0), (1.2,0), (1.4,1), (1.4,0), (1.6,1), (2.,1), (2.1,0), (2.1,0), (2.1,0), (2.2,1), (2.3,0)] varValues = list(map(lambda x:x[0],d)) resCodes = list(map(lambda x:x[1],d)) nPossibleRes =2 res = FindVarMultQuantBounds(varValues,1,resCodes,nPossibleRes) print(res) #sys.exit(1) d = [(1.4,1), (1.4,0)] varValues = list(map(lambda x:x[0],d)) resCodes = list(map(lambda x:x[1],d)) nPossibleRes =2 res = FindVarMultQuantBounds(varValues,1,resCodes,nPossibleRes) print(res) d = [(1.4,0), (1.4,0),(1.6,1)] varValues = list(map(lambda x:x[0],d)) resCodes = list(map(lambda x:x[1],d)) nPossibleRes =2 res = FindVarMultQuantBounds(varValues,2,resCodes,nPossibleRes) print(res)
{ "repo_name": "adalke/rdkit", "path": "rdkit/ML/Data/Quantize.py", "copies": "1", "size": "10595", "license": "bsd-3-clause", "hash": 6258270919210217000, "line_mean": 25.2252475248, "line_max": 90, "alpha_frac": 0.628975932, "autogenerated": false, "ratio": 3.403469322197237, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9357002051693295, "avg_score": 0.03508864050078849, "num_lines": 404 }
""" various statistical operations on data """ import numpy import math def StandardizeMatrix(mat): """ This is the standard *subtract off the average and divide by the deviation* standardization function. **Arguments** - mat: a numpy array **Notes** - in addition to being returned, _mat_ is modified in place, so **beware** """ nObjs = len(mat) avgs = sum(mat, 0) / float(nObjs) mat -= avgs devs = math.sqrt(sum(mat * mat, 0) / (float(nObjs - 1))) try: newMat = mat / devs except OverflowError: newMat = numpy.zeros(mat.shape, 'd') for i in range(mat.shape[1]): if devs[i] != 0.0: newMat[:, i] = mat[:, i] / devs[i] return newMat def FormCovarianceMatrix(mat): """ form and return the covariance matrix """ nPts = mat.shape[0] sumVect = sum(mat) sumVect /= float(nPts) for row in mat: row -= sumVect return numpy.dot(numpy.transpose(mat), mat) / (nPts - 1) def FormCorrelationMatrix(mat): """ form and return the covariance matrix """ nVars = len(mat[0]) N = len(mat) res = numpy.zeros((nVars, nVars), 'd') for i in range(nVars): x = mat[:, i] sumX = sum(x) sumX2 = sum(x * x) for j in range(i, nVars): y = mat[:, j] sumY = sum(y) sumY2 = sum(y * y) numerator = N * sum(x * y) - sumX * sumY denom = numpy.sqrt((N * sumX2 - sumX**2) * (N * sumY2 - sumY**2)) if denom != 0.0: res[i, j] = numerator / denom res[j, i] = numerator / denom else: res[i, j] = 0 res[j, i] = 0 return res def PrincipalComponents(mat, reverseOrder=1): """ do a principal components analysis """ covMat = FormCorrelationMatrix(mat) eigenVals, eigenVects = numpy.linalg.eig(covMat) # The the 'real' component, if it exists as its own attribute eigenVals = getattr(eigenVals, "real", eigenVals) eigenVects = getattr(eigenVects, "real", eigenVects) # and now sort: ptOrder = numpy.argsort(eigenVals).tolist() if reverseOrder: ptOrder.reverse() eigenVals = numpy.array([eigenVals[x] for x in ptOrder]) eigenVects = numpy.array([eigenVects[x] for x in ptOrder]) return eigenVals, eigenVects def TransformPoints(tFormMat, pts): """ transforms a set of points using tFormMat **Arguments** - tFormMat: a numpy array - pts: a list of numpy arrays (or a 2D array) **Returns** a list of numpy arrays """ pts = numpy.array(pts) nPts = len(pts) avgP = sum(pts) / nPts pts = pts - avgP res = [None] * nPts for i in range(nPts): res[i] = numpy.dot(tFormMat, pts[i]) return res def MeanAndDev(vect, sampleSD=1): """ returns the mean and standard deviation of a vector """ vect = numpy.array(vect, 'd') n = vect.shape[0] if n <= 0: return 0., 0. mean = sum(vect) / n v = vect - mean if n > 1: if sampleSD: dev = numpy.sqrt(sum(v * v) / (n - 1)) else: dev = numpy.sqrt(sum(v * v) / (n)) else: dev = 0 return mean, dev def R2(orig, residSum): """ returns the R2 value for a set of predictions """ # FIX: this just is not right # # A correct formulation of this (from Excel) for 2 variables is: # r2 = [n*(Sxy) - (Sx)(Sy)]^2 / ([n*(Sx2) - (Sx)^2]*[n*(Sy2) - (Sy)^2]) # # vect = numpy.array(orig) n = vect.shape[0] if n <= 0: return 0., 0. oMean = sum(vect) / n v = vect - oMean oVar = sum(v * v) return 1. - residSum / oVar # One Tail 0.10 0.05 0.025 0.01 0.005 0.001 0.0005 tConfs = {80: 1, 90: 2, 95: 3, 98: 4, 99: 5, 99.8: 6, 99.9: 7} tTable = [ [1, 3.078, 6.314, 12.71, 31.82, 63.66, 318.30, 637], [2, 1.886, 2.920, 4.303, 6.965, 9.925, 22.330, 31.6], [3, 1.638, 2.353, 3.182, 4.541, 5.841, 10.210, 12.92], [4, 1.533, 2.132, 2.776, 3.747, 4.604, 7.173, 8.610], [5, 1.476, 2.015, 2.571, 3.365, 4.032, 5.893, 6.869], [6, 1.440, 1.943, 2.447, 3.143, 3.707, 5.208, 5.959], [7, 1.415, 1.895, 2.365, 2.998, 3.499, 4.785, 5.408], [8, 1.397, 1.860, 2.306, 2.896, 3.355, 4.501, 5.041], [9, 1.383, 1.833, 2.262, 2.821, 3.250, 4.297, 4.781], [10, 1.372, 1.812, 2.228, 2.764, 3.169, 4.144, 4.587], [11, 1.363, 1.796, 2.201, 2.718, 3.106, 4.025, 4.437], [12, 1.356, 1.782, 2.179, 2.681, 3.055, 3.930, 4.318], [13, 1.350, 1.771, 2.160, 2.650, 3.012, 3.852, 4.221], [14, 1.345, 1.761, 2.145, 2.624, 2.977, 3.787, 4.140], [15, 1.341, 1.753, 2.131, 2.602, 2.947, 3.733, 4.073], [16, 1.337, 1.746, 2.120, 2.583, 2.921, 3.686, 4.015], [17, 1.333, 1.740, 2.110, 2.567, 2.898, 3.646, 3.965], [18, 1.330, 1.734, 2.101, 2.552, 2.878, 3.610, 3.922], [19, 1.328, 1.729, 2.093, 2.539, 2.861, 3.579, 3.883], [20, 1.325, 1.725, 2.086, 2.528, 2.845, 3.552, 3.850], [21, 1.323, 1.721, 2.080, 2.518, 2.831, 3.527, 3.819], [22, 1.321, 1.717, 2.074, 2.508, 2.819, 3.505, 3.792], [23, 1.319, 1.714, 2.069, 2.500, 2.807, 3.485, 3.768], [24, 1.318, 1.711, 2.064, 2.492, 2.797, 3.467, 3.745], [25, 1.316, 1.708, 2.060, 2.485, 2.787, 3.450, 3.725], [26, 1.315, 1.706, 2.056, 2.479, 2.779, 3.435, 3.707], [27, 1.314, 1.703, 2.052, 2.473, 2.771, 3.421, 3.690], [28, 1.313, 1.701, 2.048, 2.467, 2.763, 3.408, 3.674], [29, 1.311, 1.699, 2.045, 2.462, 2.756, 3.396, 3.659], [30, 1.310, 1.697, 2.042, 2.457, 2.750, 3.385, 3.646], [32, 1.309, 1.694, 2.037, 2.449, 2.738, 3.365, 3.622], [34, 1.307, 1.691, 2.032, 2.441, 2.728, 3.348, 3.601], [36, 1.306, 1.688, 2.028, 2.434, 2.719, 3.333, 3.582], [38, 1.304, 1.686, 2.024, 2.429, 2.712, 3.319, 3.566], [40, 1.303, 1.684, 2.021, 2.423, 2.704, 3.307, 3.551], [42, 1.302, 1.682, 2.018, 2.418, 2.698, 3.296, 3.538], [44, 1.301, 1.680, 2.015, 2.414, 2.692, 3.286, 3.526], [46, 1.300, 1.679, 2.013, 2.410, 2.687, 3.277, 3.515], [48, 1.299, 1.677, 2.011, 2.407, 2.682, 3.269, 3.505], [50, 1.299, 1.676, 2.009, 2.403, 2.678, 3.261, 3.496], [55, 1.297, 1.673, 2.004, 2.396, 2.668, 3.245, 3.476], [60, 1.296, 1.671, 2.000, 2.390, 2.660, 3.232, 3.460], [65, 1.295, 1.669, 1.997, 2.385, 2.654, 3.220, 3.447], [70, 1.294, 1.667, 1.994, 2.381, 2.648, 3.211, 3.435], [80, 1.292, 1.664, 1.990, 2.374, 2.639, 3.195, 3.416], [100, 1.290, 1.660, 1.984, 2.364, 2.626, 3.174, 3.390], [150, 1.287, 1.655, 1.976, 2.351, 2.609, 3.145, 3.357], [200, 1.286, 1.653, 1.972, 2.345, 2.601, 3.131, 3.340] ] def GetConfidenceInterval(sd, n, level=95): col = tConfs[level] dofs = n - 1 sem = sd / numpy.sqrt(n) idx = 0 while idx < len(tTable) and tTable[idx][0] < dofs: idx += 1 if idx < len(tTable): t = tTable[idx][col] else: t = tTable[-1][col] return t * sem
{ "repo_name": "rvianello/rdkit", "path": "rdkit/ML/Data/Stats.py", "copies": "5", "size": "6719", "license": "bsd-3-clause", "hash": 8351514614420589000, "line_mean": 28.3406113537, "line_max": 79, "alpha_frac": 0.5643696979, "autogenerated": false, "ratio": 2.2737732656514384, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5338142963551439, "avg_score": null, "num_lines": null }
""" Exposes functionality for MOE-like approximate molecular surface area descriptors. The MOE-like VSA descriptors are also calculated here """ from __future__ import print_function from rdkit import Chem from rdkit.Chem.PeriodicTable import numTable from rdkit.Chem import Crippen from rdkit.Chem import rdPartialCharges,rdMolDescriptors import numpy import bisect radCol = 5 bondScaleFacts = [ .1,0,.2,.3] # aromatic,single,double,triple def _LabuteHelper(mol,includeHs=1,force=0): """ *Internal Use Only* helper function for LabuteASA calculation returns an array of atomic contributions to the ASA **Note:** Changes here affect the version numbers of all ASA descriptors """ if not force: try: res = mol._labuteContribs except AttributeError: pass else: if res: return res tpl = rdMolDescriptors._CalcLabuteASAContribs(mol,includeHs) ats,hs=tpl Vi=[hs]+list(ats) mol._labuteContribs=Vi return Vi def _pyLabuteHelper(mol,includeHs=1,force=0): """ *Internal Use Only* helper function for LabuteASA calculation returns an array of atomic contributions to the ASA **Note:** Changes here affect the version numbers of all ASA descriptors """ import math if not force: try: res = mol._labuteContribs except AttributeError: pass else: if res.all(): return res nAts = mol.GetNumAtoms() Vi = numpy.zeros(nAts+1,'d') rads = numpy.zeros(nAts+1,'d') # 0 contains the H information rads[0] = numTable[1][radCol] for i in xrange(nAts): rads[i+1] = numTable[mol.GetAtomWithIdx(i).GetAtomicNum()][radCol] # start with explicit bonds for bond in mol.GetBonds(): idx1 = bond.GetBeginAtomIdx()+1 idx2 = bond.GetEndAtomIdx()+1 Ri = rads[idx1] Rj = rads[idx2] if not bond.GetIsAromatic(): bij = Ri+Rj - bondScaleFacts[bond.GetBondType()] else: bij = Ri+Rj - bondScaleFacts[0] dij = min( max( abs(Ri-Rj), bij), Ri+Rj) Vi[idx1] += Rj*Rj - (Ri-dij)**2 / dij Vi[idx2] += Ri*Ri - (Rj-dij)**2 / dij # add in hydrogens if includeHs: j = 0 Rj = rads[j] for i in xrange(1,nAts+1): Ri = rads[i] bij = Ri+Rj dij = min( max( abs(Ri-Rj), bij), Ri+Rj) Vi[i] += Rj*Rj - (Ri-dij)**2 / dij Vi[j] += Ri*Ri - (Rj-dij)**2 / dij for i in xrange(nAts+1): Ri = rads[i] Vi[i] = 4*math.pi * Ri**2 - math.pi * Ri * Vi[i] mol._labuteContribs=Vi return Vi #def SMR_VSA(mol,bins=[0.11,0.26,0.35,0.39,0.44,0.485,0.56]): # original default bins from assuming Labute values are logs # mrBins=[1.29, 1.82, 2.24, 2.45, 2.75, 3.05, 3.63] mrBins=[1.29, 1.82, 2.24, 2.45, 2.75, 3.05, 3.63,3.8,4.0] def pySMR_VSA_(mol,bins=None,force=1): """ *Internal Use Only* """ if not force: try: res = mol._smrVSA except AttributeError: pass else: if res.all(): return res if bins is None: bins = mrBins Crippen._Init() propContribs = Crippen._GetAtomContribs(mol,force=force) volContribs = _LabuteHelper(mol) ans = numpy.zeros(len(bins)+1,'d') for i in range(len(propContribs)): prop = propContribs[i] vol = volContribs[i+1] if prop is not None: bin = bisect.bisect_right(bins,prop[1]) ans[bin] += vol mol._smrVSA=ans return ans SMR_VSA_ = rdMolDescriptors.SMR_VSA_ # # Original bins (from Labute paper) are: # [-0.4,-0.2,0,0.1,0.15,0.2,0.25,0.3,0.4] # logpBins=[-0.4,-0.2,0,0.1,0.15,0.2,0.25,0.3,0.4,0.5,0.6] def pySlogP_VSA_(mol,bins=None,force=1): """ *Internal Use Only* """ if not force: try: res = mol._slogpVSA except AttributeError: pass else: if res.all(): return res if bins is None: bins = logpBins Crippen._Init() propContribs = Crippen._GetAtomContribs(mol,force=force) volContribs = _LabuteHelper(mol) ans = numpy.zeros(len(bins)+1,'d') for i in range(len(propContribs)): prop = propContribs[i] vol = volContribs[i+1] if prop is not None: bin = bisect.bisect_right(bins,prop[0]) ans[bin] += vol mol._slogpVSA=ans return ans SlogP_VSA_ = rdMolDescriptors.SlogP_VSA_ chgBins=[-.3,-.25,-.20,-.15,-.10,-.05,0,.05,.10,.15,.20,.25,.30] def pyPEOE_VSA_(mol,bins=None,force=1): """ *Internal Use Only* """ if not force: try: res = mol._peoeVSA except AttributeError: pass else: if res.all(): return res if bins is None: bins = chgBins Crippen._Init() #print('\ts:',repr(mol.GetMol())) #print('\t\t:',len(mol.GetAtoms())) rdPartialCharges.ComputeGasteigerCharges(mol) #propContribs = [float(x.GetProp('_GasteigerCharge')) for x in mol.GetAtoms()] propContribs=[] for at in mol.GetAtoms(): p = at.GetProp('_GasteigerCharge') try: v = float(p) except ValueError: v = 0.0 propContribs.append(v) #print '\tp',propContribs volContribs = _LabuteHelper(mol) #print '\tv',volContribs ans = numpy.zeros(len(bins)+1,'d') for i in range(len(propContribs)): prop = propContribs[i] vol = volContribs[i+1] if prop is not None: bin = bisect.bisect_right(bins,prop) ans[bin] += vol mol._peoeVSA=ans return ans PEOE_VSA_=rdMolDescriptors.PEOE_VSA_ #------------------------------------------------- # install the various VSA descriptors in the namespace def _InstallDescriptors(): for i in range(len(mrBins)): fn = lambda x,y=i:SMR_VSA_(x,force=0)[y] if i > 0: fn.__doc__="MOE MR VSA Descriptor %d (% 4.2f <= x < % 4.2f)"%(i+1,mrBins[i-1],mrBins[i]) else: fn.__doc__="MOE MR VSA Descriptor %d (-inf < x < % 4.2f)"%(i+1,mrBins[i]) name="SMR_VSA%d"%(i+1) fn.version="1.0.1" globals()[name]=fn i+=1 fn = lambda x,y=i:SMR_VSA_(x,force=0)[y] fn.__doc__="MOE MR VSA Descriptor %d (% 4.2f <= x < inf)"%(i+1,mrBins[i-1]) fn.version="1.0.1" name="SMR_VSA%d"%(i+1) globals()[name]=fn for i in range(len(logpBins)): fn = lambda x,y=i:SlogP_VSA_(x,force=0)[y] if i > 0: fn.__doc__="MOE logP VSA Descriptor %d (% 4.2f <= x < % 4.2f)"%(i+1,logpBins[i-1], logpBins[i]) else: fn.__doc__="MOE logP VSA Descriptor %d (-inf < x < % 4.2f)"%(i+1,logpBins[i]) name="SlogP_VSA%d"%(i+1) fn.version="1.0.1" globals()[name]=fn i+=1 fn = lambda x,y=i:SlogP_VSA_(x,force=0)[y] fn.__doc__="MOE logP VSA Descriptor %d (% 4.2f <= x < inf)"%(i+1,logpBins[i-1]) fn.version="1.0.1" name="SlogP_VSA%d"%(i+1) globals()[name]=fn for i in range(len(chgBins)): fn = lambda x,y=i:PEOE_VSA_(x,force=0)[y] if i > 0: fn.__doc__="MOE Charge VSA Descriptor %d (% 4.2f <= x < % 4.2f)"%(i+1,chgBins[i-1], chgBins[i]) else: fn.__doc__="MOE Charge VSA Descriptor %d (-inf < x < % 4.2f)"%(i+1,chgBins[i]) name="PEOE_VSA%d"%(i+1) fn.version="1.0.1" globals()[name]=fn i+=1 fn = lambda x,y=i:PEOE_VSA_(x,force=0)[y] fn.version="1.0.1" fn.__doc__="MOE Charge VSA Descriptor %d (% 4.2f <= x < inf)"%(i+1,chgBins[i-1]) name="PEOE_VSA%d"%(i+1) globals()[name]=fn fn = None # Change log for the MOE-type descriptors: # version 1.0.1: optimizations, values unaffected _InstallDescriptors() def pyLabuteASA(mol,includeHs=1): """ calculates Labute's Approximate Surface Area (ASA from MOE) Definition from P. Labute's article in the Journal of the Chemical Computing Group and J. Mol. Graph. Mod. _18_ 464-477 (2000) """ Vi = _LabuteHelper(mol,includeHs=includeHs) return sum(Vi) pyLabuteASA.version="1.0.1" # Change log for LabuteASA: # version 1.0.1: optimizations, values unaffected LabuteASA=lambda *x,**y:rdMolDescriptors.CalcLabuteASA(*x,**y) LabuteASA.version=rdMolDescriptors._CalcLabuteASA_version def _pyTPSAContribs(mol,verbose=False): """ DEPRECATED: this has been reimplmented in C++ calculates atomic contributions to a molecules TPSA Algorithm described in: P. Ertl, B. Rohde, P. Selzer Fast Calculation of Molecular Polar Surface Area as a Sum of Fragment-based Contributions and Its Application to the Prediction of Drug Transport Properties, J.Med.Chem. 43, 3714-3717, 2000 Implementation based on the Daylight contrib program tpsa.c NOTE: The JMC paper describing the TPSA algorithm includes contributions from sulfur and phosphorus, however according to Peter Ertl (personal communication, 2010) the correlation of TPSA with various ADME properties is better if only contributions from oxygen and nitrogen are used. This matches the daylight contrib implementation. """ res = [0]*mol.GetNumAtoms() for i in range(mol.GetNumAtoms()): atom = mol.GetAtomWithIdx(i) atNum = atom.GetAtomicNum() if atNum in [7,8]: #nHs = atom.GetImplicitValence()-atom.GetHvyValence() nHs = atom.GetTotalNumHs() chg = atom.GetFormalCharge() isArom = atom.GetIsAromatic() in3Ring = atom.IsInRingSize(3) bonds = atom.GetBonds() numNeighbors = atom.GetDegree() nSing = 0 nDoub = 0 nTrip = 0 nArom = 0 for bond in bonds: otherAt = bond.GetOtherAtom(atom) if otherAt.GetAtomicNum()!=1: if bond.GetIsAromatic(): nArom += 1 else: ord = bond.GetBondType() if ord == Chem.BondType.SINGLE: nSing += 1 elif ord == Chem.BondType.DOUBLE: nDoub += 1 elif ord == Chem.BondType.TRIPLE: nTrip += 1 else: numNeighbors-=1 nHs += 1 tmp = -1 if atNum == 7: if numNeighbors == 1: if nHs==0 and nTrip==1 and chg==0: tmp = 23.79 elif nHs==1 and nDoub==1 and chg==0: tmp = 23.85 elif nHs==2 and nSing==1 and chg==0: tmp = 26.02 elif nHs==2 and nDoub==1 and chg==1: tmp = 25.59 elif nHs==3 and nSing==1 and chg==1: tmp = 27.64 elif numNeighbors == 2: if nHs==0 and nSing==1 and nDoub==1 and chg==0: tmp = 12.36 elif nHs==0 and nTrip==1 and nDoub==1 and chg==0: tmp = 13.60 elif nHs==1 and nSing==2 and chg==0: if not in3Ring: tmp = 12.03 else: tmp=21.94 elif nHs==0 and nTrip==1 and nSing==1 and chg==1: tmp = 4.36 elif nHs==1 and nDoub==1 and nSing==1 and chg==1: tmp = 13.97 elif nHs==2 and nSing==2 and chg==1: tmp = 16.61 elif nHs==0 and nArom==2 and chg==0: tmp = 12.89 elif nHs==1 and nArom==2 and chg==0: tmp = 15.79 elif nHs==1 and nArom==2 and chg==1: tmp = 14.14 elif numNeighbors == 3: if nHs==0 and nSing==3 and chg==0: if not in3Ring: tmp = 3.24 else: tmp = 3.01 elif nHs==0 and nSing==1 and nDoub==2 and chg==0: tmp = 11.68 elif nHs==0 and nSing==2 and nDoub==1 and chg==1: tmp = 3.01 elif nHs==1 and nSing==3 and chg==1: tmp = 4.44 elif nHs==0 and nArom==3 and chg==0: tmp = 4.41 elif nHs==0 and nSing==1 and nArom==2 and chg==0: tmp = 4.93 elif nHs==0 and nDoub==1 and nArom==2 and chg==0: tmp = 8.39 elif nHs==0 and nArom==3 and chg==1: tmp = 4.10 elif nHs==0 and nSing==1 and nArom==2 and chg==1: tmp = 3.88 elif numNeighbors == 4: if nHs==0 and nSing==4 and chg==1: tmp = 0.00 if tmp < 0.0: tmp = 30.5 - numNeighbors * 8.2 + nHs * 1.5 if tmp < 0.0: tmp = 0.0 elif atNum==8: #print(nHs,nSing,chg) if numNeighbors == 1: if nHs==0 and nDoub==1 and chg==0: tmp = 17.07 elif nHs==1 and nSing==1 and chg==0: tmp = 20.23 elif nHs==0 and nSing==1 and chg==-1: tmp = 23.06 elif numNeighbors == 2: if nHs==0 and nSing==2 and chg==0: if not in3Ring: tmp = 9.23 else: tmp = 12.53 elif nHs==0 and nArom==2 and chg==0: tmp = 13.14 if tmp < 0.0: tmp = 28.5 - numNeighbors * 8.6 + nHs * 1.5 if tmp < 0.0: tmp = 0.0 if verbose: print('\t',atom.GetIdx(),atom.GetSymbol(),atNum,nHs,nSing,nDoub,nTrip,nArom,chg,tmp) res[atom.GetIdx()] = tmp return res def _pyTPSA(mol,verbose=False): """ DEPRECATED: this has been reimplmented in C++ calculates the polar surface area of a molecule based upon fragments Algorithm in: P. Ertl, B. Rohde, P. Selzer Fast Calculation of Molecular Polar Surface Area as a Sum of Fragment-based Contributions and Its Application to the Prediction of Drug Transport Properties, J.Med.Chem. 43, 3714-3717, 2000 Implementation based on the Daylight contrib program tpsa.c """ contribs = _pyTPSAContribs(mol,verbose=verbose) res = 0.0 for contrib in contribs: res += contrib return res _pyTPSA.version="1.0.1" TPSA=lambda *x,**y:rdMolDescriptors.CalcTPSA(*x,**y) TPSA.version=rdMolDescriptors._CalcTPSA_version if __name__ == '__main__': smis = ['C','CC','CCC','CCCC','CO','CCO','COC'] smis = ['C(=O)O','c1ccccc1'] for smi in smis: m = Chem.MolFromSmiles(smi) #print(smi, LabuteASA(m)) print('-----------\n',smi) #print('M:',['% 4.2f'%x for x in SMR_VSA_(m)]) #print('L:',['% 4.2f'%x for x in SlogP_VSA_(m)]) print('P:',['% 4.2f'%x for x in PEOE_VSA_(m)]) print('P:',['% 4.2f'%x for x in PEOE_VSA_(m)]) print()
{ "repo_name": "soerendip42/rdkit", "path": "rdkit/Chem/MolSurf.py", "copies": "4", "size": "13832", "license": "bsd-3-clause", "hash": -963004292698474800, "line_mean": 30.652173913, "line_max": 94, "alpha_frac": 0.5947802198, "autogenerated": false, "ratio": 2.7537328289866614, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.04043878908878671, "num_lines": 437 }
""" Exposes functionality for MOE-like approximate molecular surface area descriptors. The MOE-like VSA descriptors are also calculated here """ from rdkit import Chem from rdkit.Chem.PeriodicTable import numTable from rdkit.Chem import Crippen from rdkit.Chem import rdPartialCharges,rdMolDescriptors import numpy import bisect radCol = 5 bondScaleFacts = [ .1,0,.2,.3] # aromatic,single,double,triple def _LabuteHelper(mol,includeHs=1,force=0): """ *Internal Use Only* helper function for LabuteASA calculation returns an array of atomic contributions to the ASA **Note:** Changes here affect the version numbers of all ASA descriptors """ if not force: try: res = mol._labuteContribs except AttributeError: pass else: if res: return res tpl = rdMolDescriptors._CalcLabuteASAContribs(mol,includeHs) ats,hs=tpl Vi=[hs]+list(ats) mol._labuteContribs=Vi return Vi def _pyLabuteHelper(mol,includeHs=1,force=0): """ *Internal Use Only* helper function for LabuteASA calculation returns an array of atomic contributions to the ASA **Note:** Changes here affect the version numbers of all ASA descriptors """ import math if not force: try: res = mol._labuteContribs except AttributeError: pass else: if res.all(): return res nAts = mol.GetNumAtoms() Vi = numpy.zeros(nAts+1,'d') rads = numpy.zeros(nAts+1,'d') # 0 contains the H information rads[0] = numTable[1][radCol] for i in xrange(nAts): rads[i+1] = numTable[mol.GetAtomWithIdx(i).GetAtomicNum()][radCol] # start with explicit bonds for bond in mol.GetBonds(): idx1 = bond.GetBeginAtomIdx()+1 idx2 = bond.GetEndAtomIdx()+1 Ri = rads[idx1] Rj = rads[idx2] if not bond.GetIsAromatic(): bij = Ri+Rj - bondScaleFacts[bond.GetBondType()] else: bij = Ri+Rj - bondScaleFacts[0] dij = min( max( abs(Ri-Rj), bij), Ri+Rj) Vi[idx1] += Rj*Rj - (Ri-dij)**2 / dij Vi[idx2] += Ri*Ri - (Rj-dij)**2 / dij # add in hydrogens if includeHs: j = 0 Rj = rads[j] for i in xrange(1,nAts+1): Ri = rads[i] bij = Ri+Rj dij = min( max( abs(Ri-Rj), bij), Ri+Rj) Vi[i] += Rj*Rj - (Ri-dij)**2 / dij Vi[j] += Ri*Ri - (Rj-dij)**2 / dij for i in xrange(nAts+1): Ri = rads[i] Vi[i] = 4*math.pi * Ri**2 - math.pi * Ri * Vi[i] mol._labuteContribs=Vi return Vi #def SMR_VSA(mol,bins=[0.11,0.26,0.35,0.39,0.44,0.485,0.56]): # original default bins from assuming Labute values are logs # mrBins=[1.29, 1.82, 2.24, 2.45, 2.75, 3.05, 3.63] mrBins=[1.29, 1.82, 2.24, 2.45, 2.75, 3.05, 3.63,3.8,4.0] def pySMR_VSA_(mol,bins=None,force=1): """ *Internal Use Only* """ if not force: try: res = mol._smrVSA except AttributeError: pass else: if res.all(): return res if bins is None: bins = mrBins Crippen._Init() propContribs = Crippen._GetAtomContribs(mol,force=force) volContribs = _LabuteHelper(mol) ans = numpy.zeros(len(bins)+1,'d') for i in range(len(propContribs)): prop = propContribs[i] vol = volContribs[i+1] if prop is not None: bin = bisect.bisect_right(bins,prop[1]) ans[bin] += vol mol._smrVSA=ans return ans SMR_VSA_ = rdMolDescriptors.SMR_VSA_ # # Original bins (from Labute paper) are: # [-0.4,-0.2,0,0.1,0.15,0.2,0.25,0.3,0.4] # logpBins=[-0.4,-0.2,0,0.1,0.15,0.2,0.25,0.3,0.4,0.5,0.6] def pySlogP_VSA_(mol,bins=None,force=1): """ *Internal Use Only* """ if not force: try: res = mol._slogpVSA except AttributeError: pass else: if res.all(): return res if bins is None: bins = logpBins Crippen._Init() propContribs = Crippen._GetAtomContribs(mol,force=force) volContribs = _LabuteHelper(mol) ans = numpy.zeros(len(bins)+1,'d') for i in range(len(propContribs)): prop = propContribs[i] vol = volContribs[i+1] if prop is not None: bin = bisect.bisect_right(bins,prop[0]) ans[bin] += vol mol._slogpVSA=ans return ans SlogP_VSA_ = rdMolDescriptors.SlogP_VSA_ chgBins=[-.3,-.25,-.20,-.15,-.10,-.05,0,.05,.10,.15,.20,.25,.30] def pyPEOE_VSA_(mol,bins=None,force=1): """ *Internal Use Only* """ if not force: try: res = mol._peoeVSA except AttributeError: pass else: if res.all(): return res if bins is None: bins = chgBins Crippen._Init() #print '\ts:',repr(mol.GetMol()) #print '\t\t:',len(mol.GetAtoms()) rdPartialCharges.ComputeGasteigerCharges(mol) #propContribs = [float(x.GetProp('_GasteigerCharge')) for x in mol.GetAtoms()] propContribs=[] for at in mol.GetAtoms(): p = at.GetProp('_GasteigerCharge') try: v = float(p) except ValueError: v = 0.0 propContribs.append(v) #print '\tp',propContribs volContribs = _LabuteHelper(mol) #print '\tv',volContribs ans = numpy.zeros(len(bins)+1,'d') for i in range(len(propContribs)): prop = propContribs[i] vol = volContribs[i+1] if prop is not None: bin = bisect.bisect_right(bins,prop) ans[bin] += vol mol._peoeVSA=ans return ans PEOE_VSA_=rdMolDescriptors.PEOE_VSA_ #------------------------------------------------- # install the various VSA descriptors in the namespace def _InstallDescriptors(): for i in range(len(mrBins)): fn = lambda x,y=i:SMR_VSA_(x,force=0)[y] if i > 0: fn.__doc__="MOE MR VSA Descriptor %d (% 4.2f <= x < % 4.2f)"%(i+1,mrBins[i-1],mrBins[i]) else: fn.__doc__="MOE MR VSA Descriptor %d (-inf < x < % 4.2f)"%(i+1,mrBins[i]) name="SMR_VSA%d"%(i+1) fn.version="1.0.1" globals()[name]=fn i+=1 fn = lambda x,y=i:SMR_VSA_(x,force=0)[y] fn.__doc__="MOE MR VSA Descriptor %d (% 4.2f <= x < inf)"%(i+1,mrBins[i-1]) fn.version="1.0.1" name="SMR_VSA%d"%(i+1) globals()[name]=fn for i in range(len(logpBins)): fn = lambda x,y=i:SlogP_VSA_(x,force=0)[y] if i > 0: fn.__doc__="MOE logP VSA Descriptor %d (% 4.2f <= x < % 4.2f)"%(i+1,logpBins[i-1], logpBins[i]) else: fn.__doc__="MOE logP VSA Descriptor %d (-inf < x < % 4.2f)"%(i+1,logpBins[i]) name="SlogP_VSA%d"%(i+1) fn.version="1.0.1" globals()[name]=fn i+=1 fn = lambda x,y=i:SlogP_VSA_(x,force=0)[y] fn.__doc__="MOE logP VSA Descriptor %d (% 4.2f <= x < inf)"%(i+1,logpBins[i-1]) fn.version="1.0.1" name="SlogP_VSA%d"%(i+1) globals()[name]=fn for i in range(len(chgBins)): fn = lambda x,y=i:PEOE_VSA_(x,force=0)[y] if i > 0: fn.__doc__="MOE Charge VSA Descriptor %d (% 4.2f <= x < % 4.2f)"%(i+1,chgBins[i-1], chgBins[i]) else: fn.__doc__="MOE Chage VSA Descriptor %d (-inf < x < % 4.2f)"%(i+1,chgBins[i]) name="PEOE_VSA%d"%(i+1) fn.version="1.0.1" globals()[name]=fn i+=1 fn = lambda x,y=i:PEOE_VSA_(x,force=0)[y] fn.version="1.0.1" fn.__doc__="MOE Charge VSA Descriptor %d (% 4.2f <= x < inf)"%(i+1,chgBins[i-1]) name="PEOE_VSA%d"%(i+1) globals()[name]=fn fn = None # Change log for the MOE-type descriptors: # version 1.0.1: optimizations, values unaffected _InstallDescriptors() def pyLabuteASA(mol,includeHs=1): """ calculates Labute's Approximate Surface Area (ASA from MOE) Definition from P. Labute's article in the Journal of the Chemical Computing Group and J. Mol. Graph. Mod. _18_ 464-477 (2000) """ Vi = _LabuteHelper(mol,includeHs=includeHs) return sum(Vi) pyLabuteASA.version="1.0.1" # Change log for LabuteASA: # version 1.0.1: optimizations, values unaffected LabuteASA=lambda *x,**y:rdMolDescriptors.CalcLabuteASA(*x,**y) LabuteASA.version=rdMolDescriptors._CalcLabuteASA_version def _pyTPSAContribs(mol,verbose=False): """ DEPRECATED: this has been reimplmented in C++ calculates atomic contributions to a molecules TPSA Algorithm described in: P. Ertl, B. Rohde, P. Selzer Fast Calculation of Molecular Polar Surface Area as a Sum of Fragment-based Contributions and Its Application to the Prediction of Drug Transport Properties, J.Med.Chem. 43, 3714-3717, 2000 Implementation based on the Daylight contrib program tpsa.c NOTE: The JMC paper describing the TPSA algorithm includes contributions from sulfur and phosphorus, however according to Peter Ertl (personal communication, 2010) the correlation of TPSA with various ADME properties is better if only contributions from oxygen and nitrogen are used. This matches the daylight contrib implementation. """ res = [0]*mol.GetNumAtoms() for i in range(mol.GetNumAtoms()): atom = mol.GetAtomWithIdx(i) atNum = atom.GetAtomicNum() if atNum in [7,8]: #nHs = atom.GetImplicitValence()-atom.GetHvyValence() nHs = atom.GetTotalNumHs() chg = atom.GetFormalCharge() isArom = atom.GetIsAromatic() in3Ring = atom.IsInRingSize(3) bonds = atom.GetBonds() numNeighbors = atom.GetDegree() nSing = 0 nDoub = 0 nTrip = 0 nArom = 0 for bond in bonds: otherAt = bond.GetOtherAtom(atom) if otherAt.GetAtomicNum()!=1: if bond.GetIsAromatic(): nArom += 1 else: ord = bond.GetBondType() if ord == Chem.BondType.SINGLE: nSing += 1 elif ord == Chem.BondType.DOUBLE: nDoub += 1 elif ord == Chem.BondType.TRIPLE: nTrip += 1 else: numNeighbors-=1 nHs += 1 tmp = -1 if atNum == 7: if numNeighbors == 1: if nHs==0 and nTrip==1 and chg==0: tmp = 23.79 elif nHs==1 and nDoub==1 and chg==0: tmp = 23.85 elif nHs==2 and nSing==1 and chg==0: tmp = 26.02 elif nHs==2 and nDoub==1 and chg==1: tmp = 25.59 elif nHs==3 and nSing==1 and chg==1: tmp = 27.64 elif numNeighbors == 2: if nHs==0 and nSing==1 and nDoub==1 and chg==0: tmp = 12.36 elif nHs==0 and nTrip==1 and nDoub==1 and chg==0: tmp = 13.60 elif nHs==1 and nSing==2 and chg==0: if not in3Ring: tmp = 12.03 else: tmp=21.94 elif nHs==0 and nTrip==1 and nSing==1 and chg==1: tmp = 4.36 elif nHs==1 and nDoub==1 and nSing==1 and chg==1: tmp = 13.97 elif nHs==2 and nSing==2 and chg==1: tmp = 16.61 elif nHs==0 and nArom==2 and chg==0: tmp = 12.89 elif nHs==1 and nArom==2 and chg==0: tmp = 15.79 elif nHs==1 and nArom==2 and chg==1: tmp = 14.14 elif numNeighbors == 3: if nHs==0 and nSing==3 and chg==0: if not in3Ring: tmp = 3.24 else: tmp = 3.01 elif nHs==0 and nSing==1 and nDoub==2 and chg==0: tmp = 11.68 elif nHs==0 and nSing==2 and nDoub==1 and chg==1: tmp = 3.01 elif nHs==1 and nSing==3 and chg==1: tmp = 4.44 elif nHs==0 and nArom==3 and chg==0: tmp = 4.41 elif nHs==0 and nSing==1 and nArom==2 and chg==0: tmp = 4.93 elif nHs==0 and nDoub==1 and nArom==2 and chg==0: tmp = 8.39 elif nHs==0 and nArom==3 and chg==1: tmp = 4.10 elif nHs==0 and nSing==1 and nArom==2 and chg==1: tmp = 3.88 elif numNeighbors == 4: if nHs==0 and nSing==4 and chg==1: tmp = 0.00 if tmp < 0.0: tmp = 30.5 - numNeighbors * 8.2 + nHs * 1.5 if tmp < 0.0: tmp = 0.0 elif atNum==8: #print nHs,nSing,chg if numNeighbors == 1: if nHs==0 and nDoub==1 and chg==0: tmp = 17.07 elif nHs==1 and nSing==1 and chg==0: tmp = 20.23 elif nHs==0 and nSing==1 and chg==-1: tmp = 23.06 elif numNeighbors == 2: if nHs==0 and nSing==2 and chg==0: if not in3Ring: tmp = 9.23 else: tmp = 12.53 elif nHs==0 and nArom==2 and chg==0: tmp = 13.14 if tmp < 0.0: tmp = 28.5 - numNeighbors * 8.6 + nHs * 1.5 if tmp < 0.0: tmp = 0.0 if verbose: print '\t',atom.GetIdx(),atom.GetSymbol(),atNum,nHs,nSing,nDoub,nTrip,nArom,chg,tmp res[atom.GetIdx()] = tmp return res def _pyTPSA(mol,verbose=False): """ DEPRECATED: this has been reimplmented in C++ calculates the polar surface area of a molecule based upon fragments Algorithm in: P. Ertl, B. Rohde, P. Selzer Fast Calculation of Molecular Polar Surface Area as a Sum of Fragment-based Contributions and Its Application to the Prediction of Drug Transport Properties, J.Med.Chem. 43, 3714-3717, 2000 Implementation based on the Daylight contrib program tpsa.c """ contribs = _pyTPSAContribs(mol,verbose=verbose) res = 0.0 for contrib in contribs: res += contrib return res _pyTPSA.version="1.0.1" TPSA=lambda *x,**y:rdMolDescriptors.CalcTPSA(*x,**y) TPSA.version=rdMolDescriptors._CalcTPSA_version if __name__ == '__main__': smis = ['C','CC','CCC','CCCC','CO','CCO','COC'] smis = ['C(=O)O','c1ccccc1'] for smi in smis: m = Chem.MolFromSmiles(smi) #print smi, LabuteASA(m); print '-----------\n',smi #print 'M:',['% 4.2f'%x for x in SMR_VSA_(m)] #print 'L:',['% 4.2f'%x for x in SlogP_VSA_(m)] print 'P:',['% 4.2f'%x for x in PEOE_VSA_(m)] print 'P:',['% 4.2f'%x for x in PEOE_VSA_(m)] print
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/Chem/MolSurf.py", "copies": "1", "size": "13782", "license": "bsd-3-clause", "hash": 1202441314341587500, "line_mean": 30.6100917431, "line_max": 94, "alpha_frac": 0.5947612828, "autogenerated": false, "ratio": 2.751996805111821, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8643990945030795, "avg_score": 0.04055342857620506, "num_lines": 436 }
""" Interface to the C++ Murtagh hierarchic clustering code """ from rdkit.ML.Cluster import Clusters from rdkit.ML.Cluster.Clustering import MurtaghCluster,MurtaghDistCluster import numpy # constants to select the clustering algorithm WARDS=1 SLINK=2 CLINK=3 UPGMA=4 MCQUITTY=5 GOWER=6 CENTROID=7 # descriptions of the methods: methods = [ ("Ward's Minimum Variance",WARDS,"Ward's Minimum Variance"), ('Average Linkage',UPGMA,'Group Average Linkage (UPGMA)'), ('Single Linkage',SLINK,'Single Linkage (SLINK)'), ('Complete Linkage',CLINK,'Complete Linkage (CLINK)'), # ("McQuitty",MCQUITTY,"McQuitty's method"), # ("Gower",GOWER,"Gower's median method"), ("Centroid",CENTROID,"Centroid method"), ] def _LookupDist(dists,i,j,n): """ *Internal Use Only* returns the distance between points i and j in the symmetric distance matrix _dists_ """ if i==j: return 0.0 if i > j: i,j=j,i return dists[j*(j-1)/2+i] def _ToClusters(data,nPts,ia,ib,crit,isDistData=0): """ *Internal Use Only* Converts the results of the Murtagh clustering code into a cluster tree, which is returned in a single-entry list """ cs = [None]*nPts for i in range(nPts): cs[i] = Clusters.Cluster(metric=0.0,data=i,index=(i+1)) nClus = len(ia)-1 for i in range(nClus): idx1 = ia[i]-1 idx2 = ib[i]-1 c1 = cs[idx1] c2 = cs[idx2] newClust = Clusters.Cluster(metric=crit[i],children=[c1,c2], index=nPts+i+1) cs[idx1] = newClust return [newClust] def ClusterData(data,nPts,method,isDistData=0): """ clusters the data points passed in and returns the cluster tree **Arguments** - data: a list of lists (or array, or whatever) with the input data (see discussion of _isDistData_ argument for the exception) - nPts: the number of points to be used - method: determines which clustering algorithm should be used. The defined constants for these are: 'WARDS, SLINK, CLINK, UPGMA' - isDistData: set this toggle when the data passed in is a distance matrix. The distance matrix should be stored symmetrically so that _LookupDist (above) can retrieve the results: for i<j: d_ij = dists[j*(j-1)/2 + i] **Returns** - a single entry list with the cluster tree """ data = numpy.array(data) if not isDistData: sz = data.shape[1] ia,ib,crit = MurtaghCluster(data,nPts,sz,method) else: ia,ib,crit = MurtaghDistCluster(data,nPts,method) c = _ToClusters(data,nPts,ia,ib,crit,isDistData=isDistData) return c
{ "repo_name": "strets123/rdkit", "path": "rdkit/ML/Cluster/Murtagh.py", "copies": "6", "size": "2935", "license": "bsd-3-clause", "hash": 6244210261824371000, "line_mean": 25.6818181818, "line_max": 73, "alpha_frac": 0.6626916525, "autogenerated": false, "ratio": 3.1593110871905274, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.04791324432170718, "num_lines": 110 }
""" Interface to the C++ Murtagh hierarchic clustering code """ import numpy from rdkit.ML.Cluster import Clusters from rdkit.ML.Cluster.Clustering import MurtaghCluster, MurtaghDistCluster # constants to select the clustering algorithm WARDS = 1 SLINK = 2 CLINK = 3 UPGMA = 4 MCQUITTY = 5 GOWER = 6 CENTROID = 7 # descriptions of the methods: methods = [ ("Ward's Minimum Variance", WARDS, "Ward's Minimum Variance"), ('Average Linkage', UPGMA, 'Group Average Linkage (UPGMA)'), ('Single Linkage', SLINK, 'Single Linkage (SLINK)'), ('Complete Linkage', CLINK, 'Complete Linkage (CLINK)'), # ("McQuitty",MCQUITTY,"McQuitty's method"), # ("Gower",GOWER,"Gower's median method"), ("Centroid", CENTROID, "Centroid method"), ] def _LookupDist(dists, i, j, n): """ *Internal Use Only* returns the distance between points i and j in the symmetric distance matrix _dists_ """ if i == j: return 0.0 if i > j: i, j = j, i return dists[j * (j - 1) / 2 + i] def _ToClusters(data, nPts, ia, ib, crit, isDistData=0): """ *Internal Use Only* Converts the results of the Murtagh clustering code into a cluster tree, which is returned in a single-entry list """ cs = [None] * nPts for i in range(nPts): cs[i] = Clusters.Cluster(metric=0.0, data=i, index=(i + 1)) nClus = len(ia) - 1 for i in range(nClus): idx1 = ia[i] - 1 idx2 = ib[i] - 1 c1 = cs[idx1] c2 = cs[idx2] newClust = Clusters.Cluster(metric=crit[i], children=[c1, c2], index=nPts + i + 1) cs[idx1] = newClust return [newClust] def ClusterData(data, nPts, method, isDistData=0): """ clusters the data points passed in and returns the cluster tree **Arguments** - data: a list of lists (or array, or whatever) with the input data (see discussion of _isDistData_ argument for the exception) - nPts: the number of points to be used - method: determines which clustering algorithm should be used. The defined constants for these are: 'WARDS, SLINK, CLINK, UPGMA' - isDistData: set this toggle when the data passed in is a distance matrix. The distance matrix should be stored symmetrically so that _LookupDist (above) can retrieve the results: for i<j: d_ij = dists[j*(j-1)/2 + i] **Returns** - a single entry list with the cluster tree """ data = numpy.array(data) if not isDistData: sz = data.shape[1] ia, ib, crit = MurtaghCluster(data, nPts, sz, method) else: ia, ib, crit = MurtaghDistCluster(data, nPts, method) c = _ToClusters(data, nPts, ia, ib, crit, isDistData=isDistData) return c
{ "repo_name": "rvianello/rdkit", "path": "rdkit/ML/Cluster/Murtagh.py", "copies": "4", "size": "2982", "license": "bsd-3-clause", "hash": 6136189354368038000, "line_mean": 26.1090909091, "line_max": 86, "alpha_frac": 0.6522468142, "autogenerated": false, "ratio": 3.12906610703043, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.007552425757389503, "num_lines": 110 }
""" Python functions for manipulating molecular graphs In theory much of the functionality in here should be migrating into the C/C++ codebase. """ import numpy from rdkit import Chem from rdkit import DataStructs from rdkit.six.moves import xrange import types def CharacteristicPolynomial(mol, mat=None): """ calculates the characteristic polynomial for a molecular graph if mat is not passed in, the molecule's Weighted Adjacency Matrix will be used. The approach used is the Le Verrier-Faddeev-Frame method described in _Chemical Graph Theory, 2nd Edition_ by Nenad Trinajstic (CRC Press, 1992), pg 76. """ nAtoms = mol.GetNumAtoms() if mat is None: # FIX: complete this: #A = mol.GetWeightedAdjacencyMatrix() pass else: A = mat I = 1. * numpy.identity(nAtoms) An = A res = numpy.zeros(nAtoms + 1, numpy.float) res[0] = 1.0 for n in xrange(1, nAtoms + 1): res[n] = 1. / n * numpy.trace(An) Bn = An - res[n] * I An = numpy.dot(A, Bn) res[1:] *= -1 return res
{ "repo_name": "rvianello/rdkit", "path": "rdkit/Chem/Graphs.py", "copies": "5", "size": "1343", "license": "bsd-3-clause", "hash": 3169020811040307700, "line_mean": 24.8269230769, "line_max": 75, "alpha_frac": 0.6827997022, "autogenerated": false, "ratio": 3.1900237529691213, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6372823455169121, "avg_score": null, "num_lines": null }
""" contains the Cluster class for representing hierarchical cluster trees """ from __future__ import print_function import numpy from rdkit.six.moves import reduce from rdkit.six import cmp CMPTOL = 1e-6 class Cluster(object): """a class for storing clusters/data **General Remarks** - It is assumed that the bottom of any cluster hierarchy tree is composed of the individual data points which were clustered. - Clusters objects store the following pieces of data, most are accessible via standard Setters/Getters: - Children: *Not Settable*, the list of children. You can add children with the _AddChild()_ and _AddChildren()_ methods. **Note** this can be of arbitrary length, but the current algorithms I have only produce trees with two children per cluster - Metric: the metric for this cluster (i.e. how far apart its children are) - Index: the order in which this cluster was generated - Points: *Not Settable*, the list of original points in this cluster (calculated recursively from the children) - PointsPositions: *Not Settable*, the list of positions of the original points in this cluster (calculated recursively from the children) - Position: the location of the cluster **Note** for a cluster this probably means the location of the average of all the Points which are its children. - Data: a data field. This is used with the original points to store their data value (i.e. the value we're using to classify) - Name: the name of this cluster """ def __init__(self, metric=0.0, children=None, position=None, index=-1, name=None, data=None): """Constructor **Arguments** see the class documentation for the meanings of these arguments *my wrists are tired* """ if children is None: children = [] if position is None: position = [] self.metric = metric self.children = children self._UpdateLength() self.pos = position self.index = index self.name = name self._points = None self._pointsPositions = None self.data = data def SetMetric(self, metric): self.metric = metric def GetMetric(self): return self.metric def SetIndex(self, index): self.index = index def GetIndex(self): return self.index def SetPosition(self, pos): self.pos = pos def GetPosition(self): return self.pos def GetPointsPositions(self): if self._pointsPositions is not None: return self._pointsPositions else: self._GenPoints() return self._pointsPositions def GetPoints(self): if self._points is not None: return self._points else: self._GenPoints() return self._points def FindSubtree(self, index): """ finds and returns the subtree with a particular index """ res = None if index == self.index: res = self else: for child in self.children: res = child.FindSubtree(index) if res: break return res def _GenPoints(self): """ Generates the _Points_ and _PointsPositions_ lists *intended for internal use* """ if len(self) == 1: self._points = [self] self._pointsPositions = [self.GetPosition()] return self._points else: res = [] children = self.GetChildren() # children.sort(lambda x,y:cmp(len(y),len(x))) children.sort(key=lambda x: len(x), reverse=True) for child in children: res += child.GetPoints() self._points = res self._pointsPositions = [x.GetPosition() for x in res] def AddChild(self, child): """Adds a child to our list **Arguments** - child: a Cluster """ self.children.append(child) self._GenPoints() self._UpdateLength() def AddChildren(self, children): """Adds a bunch of children to our list **Arguments** - children: a list of Clusters """ self.children += children self._GenPoints() self._UpdateLength() def RemoveChild(self, child): """Removes a child from our list **Arguments** - child: a Cluster """ self.children.remove(child) self._UpdateLength() def GetChildren(self): #self.children.sort(lambda x,y:cmp(x.GetMetric(),y.GetMetric())) self.children.sort(key=lambda x: x.GetMetric()) return self.children def SetData(self, data): self.data = data def GetData(self): return self.data def SetName(self, name): self.name = name def GetName(self): if self.name is None: return 'Cluster(%d)' % (self.GetIndex()) else: return self.name def Print(self, level=0, showData=0, offset='\t'): if not showData or self.GetData() is None: print('%s%s%s Metric: %f' % (' ' * level, self.GetName(), offset, self.GetMetric())) else: print('%s%s%s Data: %f\t Metric: %f' % (' ' * level, self.GetName(), offset, self.GetData(), self.GetMetric())) for child in self.GetChildren(): child.Print(level=level + 1, showData=showData, offset=offset) def Compare(self, other, ignoreExtras=1): """ not as choosy as self==other """ tv1, tv2 = str(type(self)), str(type(other)) tv = cmp(tv1, tv2) if tv: return tv tv1, tv2 = len(self), len(other) tv = cmp(tv1, tv2) if tv: return tv if not ignoreExtras: m1, m2 = self.GetMetric(), other.GetMetric() if abs(m1 - m2) > CMPTOL: return cmp(m1, m2) if cmp(self.GetName(), other.GetName()): return cmp(self.GetName(), other.GetName()) sP = self.GetPosition() oP = other.GetPosition() try: r = cmp(len(sP), len(oP)) except Exception: pass else: if r: return r try: r = cmp(sP, oP) except Exception: r = sum(sP - oP) if r: return r c1, c2 = self.GetChildren(), other.GetChildren() if cmp(len(c1), len(c2)): return cmp(len(c1), len(c2)) for i in range(len(c1)): t = c1[i].Compare(c2[i], ignoreExtras=ignoreExtras) if t: return t return 0 def _UpdateLength(self): """ updates our length *intended for internal use* """ self._len = reduce(lambda x, y: len(y) + x, self.children, 1) def IsTerminal(self): return self._len <= 1 def __len__(self): """ allows _len(cluster)_ to work """ return self._len def __cmp__(self, other): """ allows _cluster1 == cluster2_ to work """ if cmp(type(self), type(other)): return cmp(type(self), type(other)) m1, m2 = self.GetMetric(), other.GetMetric() if abs(m1 - m2) > CMPTOL: return cmp(m1, m2) if cmp(self.GetName(), other.GetName()): return cmp(self.GetName(), other.GetName()) c1, c2 = self.GetChildren(), other.GetChildren() return cmp(c1, c2) if __name__ == '__main__': from rdkit.ML.Cluster import ClusterUtils root = Cluster(index=1, metric=1000) c1 = Cluster(index=10, metric=100) c1.AddChild(Cluster(index=30, metric=10)) c1.AddChild(Cluster(index=31, metric=10)) c1.AddChild(Cluster(index=32, metric=10)) c2 = Cluster(index=11, metric=100) c2.AddChild(Cluster(index=40, metric=10)) c2.AddChild(Cluster(index=41, metric=10)) root.AddChild(c1) root.AddChild(c2) nodes = ClusterUtils.GetNodeList(root) indices = [x.GetIndex() for x in nodes] print('XXX:', indices)
{ "repo_name": "jandom/rdkit", "path": "rdkit/ML/Cluster/Clusters.py", "copies": "1", "size": "7885", "license": "bsd-3-clause", "hash": -4730743003609806000, "line_mean": 23.8738170347, "line_max": 95, "alpha_frac": 0.6144578313, "autogenerated": false, "ratio": 3.6437153419593344, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9682950593384773, "avg_score": 0.0150445159749123, "num_lines": 317 }
""" contains the Cluster class for representing hierarchical cluster trees """ from __future__ import print_function from rdkit.six import cmp CMPTOL = 1e-6 class Cluster(object): """a class for storing clusters/data **General Remarks** - It is assumed that the bottom of any cluster hierarchy tree is composed of the individual data points which were clustered. - Clusters objects store the following pieces of data, most are accessible via standard Setters/Getters: - Children: *Not Settable*, the list of children. You can add children with the _AddChild()_ and _AddChildren()_ methods. **Note** this can be of arbitrary length, but the current algorithms I have only produce trees with two children per cluster - Metric: the metric for this cluster (i.e. how far apart its children are) - Index: the order in which this cluster was generated - Points: *Not Settable*, the list of original points in this cluster (calculated recursively from the children) - PointsPositions: *Not Settable*, the list of positions of the original points in this cluster (calculated recursively from the children) - Position: the location of the cluster **Note** for a cluster this probably means the location of the average of all the Points which are its children. - Data: a data field. This is used with the original points to store their data value (i.e. the value we're using to classify) - Name: the name of this cluster """ def __init__(self, metric=0.0, children=None, position=None, index=-1, name=None, data=None): """Constructor **Arguments** see the class documentation for the meanings of these arguments *my wrists are tired* """ if children is None: children = [] if position is None: position = [] self.metric = metric self.children = children self._UpdateLength() self.pos = position self.index = index self.name = name self._points = None self._pointsPositions = None self.data = data def SetMetric(self, metric): self.metric = metric def GetMetric(self): return self.metric def SetIndex(self, index): self.index = index def GetIndex(self): return self.index def SetPosition(self, pos): self.pos = pos def GetPosition(self): return self.pos def GetPointsPositions(self): if self._pointsPositions is not None: return self._pointsPositions else: self._GenPoints() return self._pointsPositions def GetPoints(self): if self._points is not None: return self._points else: self._GenPoints() return self._points def FindSubtree(self, index): """ finds and returns the subtree with a particular index """ res = None if index == self.index: res = self else: for child in self.children: res = child.FindSubtree(index) if res: break return res def _GenPoints(self): """ Generates the _Points_ and _PointsPositions_ lists *intended for internal use* """ if len(self) == 1: self._points = [self] self._pointsPositions = [self.GetPosition()] return self._points else: res = [] children = self.GetChildren() children.sort(key=lambda x: len(x), reverse=True) for child in children: res += child.GetPoints() self._points = res self._pointsPositions = [x.GetPosition() for x in res] def AddChild(self, child): """Adds a child to our list **Arguments** - child: a Cluster """ self.children.append(child) self._GenPoints() self._UpdateLength() def AddChildren(self, children): """Adds a bunch of children to our list **Arguments** - children: a list of Clusters """ self.children += children self._GenPoints() self._UpdateLength() def RemoveChild(self, child): """Removes a child from our list **Arguments** - child: a Cluster """ self.children.remove(child) self._UpdateLength() def GetChildren(self): self.children.sort(key=lambda x: x.GetMetric()) return self.children def SetData(self, data): self.data = data def GetData(self): return self.data def SetName(self, name): self.name = name def GetName(self): if self.name is None: return 'Cluster(%d)' % (self.GetIndex()) else: return self.name def Print(self, level=0, showData=0, offset='\t'): if not showData or self.GetData() is None: print('%s%s%s Metric: %f' % (' ' * level, self.GetName(), offset, self.GetMetric())) else: print('%s%s%s Data: %f\t Metric: %f' % (' ' * level, self.GetName(), offset, self.GetData(), self.GetMetric())) for child in self.GetChildren(): child.Print(level=level + 1, showData=showData, offset=offset) def Compare(self, other, ignoreExtras=1): """ not as choosy as self==other """ tv1, tv2 = str(type(self)), str(type(other)) tv = cmp(tv1, tv2) if tv: return tv tv1, tv2 = len(self), len(other) tv = cmp(tv1, tv2) if tv: return tv if not ignoreExtras: m1, m2 = self.GetMetric(), other.GetMetric() if abs(m1 - m2) > CMPTOL: return cmp(m1, m2) if cmp(self.GetName(), other.GetName()): return cmp(self.GetName(), other.GetName()) sP = self.GetPosition() oP = other.GetPosition() try: r = cmp(len(sP), len(oP)) except Exception: pass else: if r: return r try: r = cmp(sP, oP) except Exception: r = sum(sP - oP) if r: return r c1, c2 = self.GetChildren(), other.GetChildren() if cmp(len(c1), len(c2)): return cmp(len(c1), len(c2)) for i in range(len(c1)): t = c1[i].Compare(c2[i], ignoreExtras=ignoreExtras) if t: return t return 0 def _UpdateLength(self): """ updates our length *intended for internal use* """ self._len = sum(len(c) for c in self.children) + 1 def IsTerminal(self): return self._len <= 1 def __len__(self): """ allows _len(cluster)_ to work """ return self._len def __cmp__(self, other): """ allows _cluster1 == cluster2_ to work """ if cmp(type(self), type(other)): return cmp(type(self), type(other)) m1, m2 = self.GetMetric(), other.GetMetric() if abs(m1 - m2) > CMPTOL: return cmp(m1, m2) if cmp(self.GetName(), other.GetName()): return cmp(self.GetName(), other.GetName()) c1, c2 = self.GetChildren(), other.GetChildren() return cmp(c1, c2) if __name__ == '__main__': # pragma: nocover from rdkit.ML.Cluster import ClusterUtils root = Cluster(index=1, metric=1000) c1 = Cluster(index=10, metric=100) c1.AddChild(Cluster(index=30, metric=10)) c1.AddChild(Cluster(index=31, metric=10)) c1.AddChild(Cluster(index=32, metric=10)) c2 = Cluster(index=11, metric=100) c2.AddChild(Cluster(index=40, metric=10)) c2.AddChild(Cluster(index=41, metric=10)) root.AddChild(c1) root.AddChild(c2) nodes = ClusterUtils.GetNodeList(root) indices = [x.GetIndex() for x in nodes] print('XXX:', indices)
{ "repo_name": "rvianello/rdkit", "path": "rdkit/ML/Cluster/Clusters.py", "copies": "4", "size": "7679", "license": "bsd-3-clause", "hash": -1746190875493639700, "line_mean": 23.5335463259, "line_max": 95, "alpha_frac": 0.6164865217, "autogenerated": false, "ratio": 3.6601525262154433, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6276639047915443, "avg_score": null, "num_lines": null }
""" contains the Cluster class for representing hierarchical cluster trees """ import numpy CMPTOL=1e-6 class Cluster(object): """a class for storing clusters/data **General Remarks** - It is assumed that the bottom of any cluster hierarchy tree is composed of the individual data points which were clustered. - Clusters objects store the following pieces of data, most are accessible via standard Setters/Getters: - Children: *Not Settable*, the list of children. You can add children with the _AddChild()_ and _AddChildren()_ methods. **Note** this can be of arbitrary length, but the current algorithms I have only produce trees with two children per cluster - Metric: the metric for this cluster (i.e. how far apart its children are) - Index: the order in which this cluster was generated - Points: *Not Settable*, the list of original points in this cluster (calculated recursively from the children) - PointsPositions: *Not Settable*, the list of positions of the original points in this cluster (calculated recursively from the children) - Position: the location of the cluster **Note** for a cluster this probably means the location of the average of all the Points which are its children. - Data: a data field. This is used with the original points to store their data value (i.e. the value we're using to classify) - Name: the name of this cluster """ def __init__(self,metric=0.0,children=None,position=None,index=-1,name=None,data=None): """Constructor **Arguments** see the class documentation for the meanings of these arguments *my wrists are tired* """ if children is None: children = [] if position is None: position = [] self.metric = metric self.children = children self._UpdateLength() self.pos = position self.index = index self.name = name self._points = None self._pointsPositions = None self.data = data def SetMetric(self,metric): self.metric = metric def GetMetric(self): return self.metric def SetIndex(self,index): self.index = index def GetIndex(self): return self.index def SetPosition(self,pos): self.pos = pos def GetPosition(self): return self.pos def GetPointsPositions(self): if self._pointsPositions is not None: return self._pointsPositions else: self._GenPoints() return self._pointsPositions def GetPoints(self): if self._points is not None: return self._points else: self._GenPoints() return self._points def FindSubtree(self,index): """ finds and returns the subtree with a particular index """ res = None if index == self.index: res = self else: for child in self.children: res = child.FindSubtree(index) if res: break return res def _GenPoints(self): """ Generates the _Points_ and _PointsPositions_ lists *intended for internal use* """ if len(self) == 1: self._points = [self] self._pointsPositions = [self.GetPosition()] return self._points else: res = [] children = self.GetChildren() children.sort(lambda x,y:cmp(len(y),len(x))) for child in children: res += child.GetPoints() self._points=res self._pointsPositions = [x.GetPosition() for x in res] def AddChild(self,child): """Adds a child to our list **Arguments** - child: a Cluster """ self.children.append(child) self._GenPoints() self._UpdateLength() def AddChildren(self,children): """Adds a bunch of children to our list **Arguments** - children: a list of Clusters """ self.children += children self._GenPoints() self._UpdateLength() def RemoveChild(self,child): """Removes a child from our list **Arguments** - child: a Cluster """ self.children.remove(child) self._UpdateLength() def GetChildren(self): self.children.sort(lambda x,y:cmp(x.GetMetric(),y.GetMetric())) return self.children def SetData(self,data): self.data = data def GetData(self): return self.data def SetName(self,name): self.name = name def GetName(self): if self.name is None: return 'Cluster(%d)'%(self.GetIndex()) else: return self.name def Print(self,level=0,showData=0,offset='\t'): if not showData or self.GetData() is None: print '%s%s%s Metric: %f'%(' '*level,self.GetName(),offset,self.GetMetric()) else: print '%s%s%s Data: %f\t Metric: %f'%(' '*level,self.GetName(),offset,self.GetData(),self.GetMetric()) for child in self.GetChildren(): child.Print(level=level+1,showData=showData,offset=offset) def Compare(self,other,ignoreExtras=1): """ not as choosy as self==other """ if cmp(type(self),type(other)): return cmp(type(self),type(other)) if cmp(len(self),len(other)): return cmp(len(self),len(other)) if not ignoreExtras: m1,m2=self.GetMetric(),other.GetMetric() if abs(m1-m2)>CMPTOL: return cmp(m1,m2) if cmp(self.GetName(),other.GetName()): return cmp(self.GetName(),other.GetName()) sP = self.GetPosition() oP = other.GetPosition() try: r = cmp(len(sP),len(oP)) except: pass else: if r: return r try: r = cmp(sP,oP) except: r = sum(sP-oP) if r: return r c1,c2=self.GetChildren(),other.GetChildren() if cmp(len(c1),len(c2)): return cmp(len(c1),len(c2)) for i in range(len(c1)): t = c1[i].Compare(c2[i],ignoreExtras=ignoreExtras) if t: return t return 0 def _UpdateLength(self): """ updates our length *intended for internal use* """ self._len = reduce(lambda x,y: len(y)+x,self.children,1) def IsTerminal(self): return self._len<=1 def __len__(self): """ allows _len(cluster)_ to work """ return self._len def __cmp__(self,other): """ allows _cluster1 == cluster2_ to work """ if cmp(type(self),type(other)): return cmp(type(self),type(other)) m1,m2=self.GetMetric(),other.GetMetric() if abs(m1-m2)>CMPTOL: return cmp(m1,m2) if cmp(self.GetName(),other.GetName()): return cmp(self.GetName(),other.GetName()) c1,c2=self.GetChildren(),other.GetChildren() return cmp(c1,c2) if __name__ == '__main__': from rdkit.ML.Cluster import ClusterUtils root = Cluster(index=1,metric=1000) c1 = Cluster(index=10,metric=100) c1.AddChild(Cluster(index=30,metric=10)) c1.AddChild(Cluster(index=31,metric=10)) c1.AddChild(Cluster(index=32,metric=10)) c2 = Cluster(index=11,metric=100) c2.AddChild(Cluster(index=40,metric=10)) c2.AddChild(Cluster(index=41,metric=10)) root.AddChild(c1) root.AddChild(c2) nodes = ClusterUtils.GetNodeList(root) indices = [x.GetIndex() for x in nodes] print 'XXX:',indices
{ "repo_name": "rdkit/rdkit-orig", "path": "rdkit/ML/Cluster/Clusters.py", "copies": "2", "size": "7573", "license": "bsd-3-clause", "hash": -269112209765461820, "line_mean": 24.3277591973, "line_max": 109, "alpha_frac": 0.6167965139, "autogenerated": false, "ratio": 3.661992263056093, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.03156565016196123, "num_lines": 299 }
"""utility functions for clustering """ def GetNodeList(cluster): """returns an ordered list of all nodes below cluster the ordering is done using the lengths of the child nodes **Arguments** - cluster: the cluster in question **Returns** - a list of the leaves below this cluster """ if len(cluster) == 1: return [cluster] else: children = cluster.GetChildren() children.sort(key=lambda x:len(x), reverse=True) res = [] for child in children: res += GetNodeList(child) res += [cluster] return res def GetNodesDownToCentroids(cluster,above=1): """returns an ordered list of all nodes below cluster """ if hasattr(cluster,'_isCentroid'): cluster._aboveCentroid = 0 above = -1 else: cluster._aboveCentroid = above if len(cluster) == 1: return [cluster] else: res = [] children = cluster.GetChildren() children.sort(lambda x,y:cmp(len(y),len(x))) for child in children: res = res + GetNodesDownToCentroids(child,above) res = res + [cluster] return res def FindClusterCentroidFromDists(cluster,dists): """ find the point in a cluster which has the smallest summed Euclidean distance to all others **Arguments** - cluster: the cluster to work with - dists: the distance matrix to use for the points **Returns** - the index of the centroid point """ children = cluster.GetPoints() pts = [x.GetData() for x in children] best = 1e24 bestIdx = -1 for pt in pts: dAccum = 0.0 # loop over others and add'em up for other in pts: if other != pt: if other > pt: row,col = pt,other else: row,col = other,pt dAccum += dists[col*(col-1)/2+row] if dAccum >= best: # minor efficiency hack break if dAccum < best: best = dAccum bestIdx = pt for i in range(len(pts)): pt = pts[i] if pt != bestIdx: if pt > bestIdx: row,col = bestIdx,pt else: row,col = pt,bestIdx children[i]._distToCenter = dists[col*(col-1)/2+row] else: children[i]._distToCenter = 0.0 children[i]._clustCenter = bestIdx cluster._clustCenter=bestIdx cluster._distToCenter=0.0 return bestIdx def _BreadthFirstSplit(cluster,n): """ *Internal Use Only* """ if len(cluster)<n: raise ValueError('Cannot split cluster of length %d into %d pieces'%(len(cluster),n)) if len(cluster)==n: return cluster.GetPoints() clusters = [cluster] nxtIdx = 0 for i in range(n-1): while nxtIdx<len(clusters) and len(clusters[nxtIdx])==1: nxtIdx+=1 assert nxtIdx<len(clusters) children = clusters[nxtIdx].GetChildren() children.sort(key=lambda x: x.GetMetric(), reverse=True) for child in children: clusters.append(child) del clusters[nxtIdx] return clusters def _HeightFirstSplit(cluster,n): """ *Internal Use Only* """ if len(cluster)<n: raise ValueError('Cannot split cluster of length %d into %d pieces'%(len(cluster),n)) if len(cluster)==n: return cluster.GetPoints() clusters = [cluster] for i in range(n-1): nxtIdx = 0 while nxtIdx<len(clusters) and len(clusters[nxtIdx])==1: nxtIdx+=1 assert nxtIdx<len(clusters) children = clusters[nxtIdx].GetChildren() for child in children: clusters.append(child) del clusters[nxtIdx] clusters.sort(key=lambda x: x.GetMetric(), reverse=True) return clusters def SplitIntoNClusters(cluster,n,breadthFirst=1): """ splits a cluster tree into a set of branches **Arguments** - cluster: the root of the cluster tree - n: the number of clusters to include in the split - breadthFirst: toggles breadth first (vs depth first) cleavage of the cluster tree. **Returns** - a list of sub clusters """ if breadthFirst: return _BreadthFirstSplit(cluster,n) else: return _HeightFirstSplit(cluster,n)
{ "repo_name": "adalke/rdkit", "path": "rdkit/ML/Cluster/ClusterUtils.py", "copies": "4", "size": "4245", "license": "bsd-3-clause", "hash": 1982911366184751400, "line_mean": 23.2571428571, "line_max": 89, "alpha_frac": 0.6445229682, "autogenerated": false, "ratio": 3.5140728476821192, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.033794284058948916, "num_lines": 175 }
"""utility functions for clustering """ def GetNodeList(cluster): """returns an ordered list of all nodes below cluster the ordering is done using the lengths of the child nodes **Arguments** - cluster: the cluster in question **Returns** - a list of the leaves below this cluster """ if len(cluster) == 1: return [cluster] else: children = cluster.GetChildren() children.sort(key=lambda x: len(x), reverse=True) res = [] for child in children: res += GetNodeList(child) res += [cluster] return res def GetNodesDownToCentroids(cluster, above=1): """returns an ordered list of all nodes below cluster """ if hasattr(cluster, '_isCentroid'): cluster._aboveCentroid = 0 above = -1 else: cluster._aboveCentroid = above if len(cluster) == 1: return [cluster] else: res = [] children = cluster.GetChildren() children.sort(key=lambda x: len(x), reverse=True) # children.sort(lambda x, y: cmp(len(y), len(x))) for child in children: res = res + GetNodesDownToCentroids(child, above) res = res + [cluster] return res def FindClusterCentroidFromDists(cluster, dists): """ find the point in a cluster which has the smallest summed Euclidean distance to all others **Arguments** - cluster: the cluster to work with - dists: the distance matrix to use for the points **Returns** - the index of the centroid point """ children = cluster.GetPoints() pts = [x.GetData() for x in children] best = 1e24 bestIdx = -1 for pt in pts: dAccum = 0.0 # loop over others and add'em up for other in pts: if other != pt: if other > pt: row, col = pt, other else: row, col = other, pt dAccum += dists[col * (col - 1) / 2 + row] if dAccum >= best: # minor efficiency hack break if dAccum < best: best = dAccum bestIdx = pt for i in range(len(pts)): pt = pts[i] if pt != bestIdx: if pt > bestIdx: row, col = bestIdx, pt else: row, col = pt, bestIdx children[i]._distToCenter = dists[col * (col - 1) / 2 + row] else: children[i]._distToCenter = 0.0 children[i]._clustCenter = bestIdx cluster._clustCenter = bestIdx cluster._distToCenter = 0.0 return bestIdx def _BreadthFirstSplit(cluster, n): """ *Internal Use Only* """ if len(cluster) < n: raise ValueError('Cannot split cluster of length %d into %d pieces' % (len(cluster), n)) if len(cluster) == n: return cluster.GetPoints() clusters = [cluster] nxtIdx = 0 for _ in range(n - 1): while nxtIdx < len(clusters) and len(clusters[nxtIdx]) == 1: nxtIdx += 1 assert nxtIdx < len(clusters) children = clusters[nxtIdx].GetChildren() children.sort(key=lambda x: x.GetMetric(), reverse=True) for child in children: clusters.append(child) del clusters[nxtIdx] return clusters def _HeightFirstSplit(cluster, n): """ *Internal Use Only* """ if len(cluster) < n: raise ValueError('Cannot split cluster of length %d into %d pieces' % (len(cluster), n)) if len(cluster) == n: return cluster.GetPoints() clusters = [cluster] for _ in range(n - 1): nxtIdx = 0 while nxtIdx < len(clusters) and len(clusters[nxtIdx]) == 1: nxtIdx += 1 assert nxtIdx < len(clusters) children = clusters[nxtIdx].GetChildren() for child in children: clusters.append(child) del clusters[nxtIdx] clusters.sort(key=lambda x: x.GetMetric(), reverse=True) return clusters def SplitIntoNClusters(cluster, n, breadthFirst=True): """ splits a cluster tree into a set of branches **Arguments** - cluster: the root of the cluster tree - n: the number of clusters to include in the split - breadthFirst: toggles breadth first (vs depth first) cleavage of the cluster tree. **Returns** - a list of sub clusters """ if breadthFirst: return _BreadthFirstSplit(cluster, n) else: return _HeightFirstSplit(cluster, n)
{ "repo_name": "rvianello/rdkit", "path": "rdkit/ML/Cluster/ClusterUtils.py", "copies": "11", "size": "4413", "license": "bsd-3-clause", "hash": 976770165609097000, "line_mean": 22.9836956522, "line_max": 92, "alpha_frac": 0.6285973261, "autogenerated": false, "ratio": 3.5531400966183573, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9681737422718357, "avg_score": null, "num_lines": null }