body
stringlengths
26
98.2k
body_hash
int64
-9,222,864,604,528,158,000
9,221,803,474B
docstring
stringlengths
1
16.8k
path
stringlengths
5
230
name
stringlengths
1
96
repository_name
stringlengths
7
89
lang
stringclasses
1 value
body_without_docstring
stringlengths
20
98.2k
def all_characters_without_spaces(self, text): ' count the total of characters without any space char ' return (len(text) - self.number_spaces(text))
-7,804,322,849,488,053,000
count the total of characters without any space char
words.py
all_characters_without_spaces
Layto888/Words-Analysis
python
def all_characters_without_spaces(self, text): ' ' return (len(text) - self.number_spaces(text))
def differents_words_list(self, text): " select only the total of different words,\n it's a set, return the set.\n " return set(self.words_list(text))
89,076,078,975,208,600
select only the total of different words, it's a set, return the set.
words.py
differents_words_list
Layto888/Words-Analysis
python
def differents_words_list(self, text): " select only the total of different words,\n it's a set, return the set.\n " return set(self.words_list(text))
def average_sentence_length(self, text): ' count the average length of sentences\n avg = words / sentences\n ' if (len(self.words_list(text)) == 0): return 0 else: return (len(self.words_list(text)) / len(self.sentence_split(text)))
-7,883,651,800,705,555,000
count the average length of sentences avg = words / sentences
words.py
average_sentence_length
Layto888/Words-Analysis
python
def average_sentence_length(self, text): ' count the average length of sentences\n avg = words / sentences\n ' if (len(self.words_list(text)) == 0): return 0 else: return (len(self.words_list(text)) / len(self.sentence_split(text)))
def max_sentence_length(self, text): ' count and return the maximum length\n of sentences list ' all_senteces = self.sentence_split(text) try: return max(list(map(len, all_senteces))) except Exception as e: print(e) return 0
-224,361,079,335,925,060
count and return the maximum length of sentences list
words.py
max_sentence_length
Layto888/Words-Analysis
python
def max_sentence_length(self, text): ' count and return the maximum length\n of sentences list ' all_senteces = self.sentence_split(text) try: return max(list(map(len, all_senteces))) except Exception as e: print(e) return 0
def min_sentence_length(self, text): ' count and return the minimum length\n of sentences list ' all_senteces = self.sentence_split(text) try: return min(list(map(len, all_senteces))) except Exception as e: print(e) return 0
-2,005,733,370,709,845,200
count and return the minimum length of sentences list
words.py
min_sentence_length
Layto888/Words-Analysis
python
def min_sentence_length(self, text): ' count and return the minimum length\n of sentences list ' all_senteces = self.sentence_split(text) try: return min(list(map(len, all_senteces))) except Exception as e: print(e) return 0
@staticmethod def normalize_text(normal_text): ' remove extra spaces if any in the text\n and put it in lowercase, to normalize the input text.\n ' normalized_text = re.sub(' +', ' ', normal_text) normalized_text = normalized_text.lower() return normalized_text
-7,855,099,181,739,662,000
remove extra spaces if any in the text and put it in lowercase, to normalize the input text.
words.py
normalize_text
Layto888/Words-Analysis
python
@staticmethod def normalize_text(normal_text): ' remove extra spaces if any in the text\n and put it in lowercase, to normalize the input text.\n ' normalized_text = re.sub(' +', ' ', normal_text) normalized_text = normalized_text.lower() return normalized_text
@staticmethod def number_spaces(text): ' count the number of spaces in the text ' return text.count(' ')
-3,373,104,589,458,795,000
count the number of spaces in the text
words.py
number_spaces
Layto888/Words-Analysis
python
@staticmethod def number_spaces(text): ' ' return text.count(' ')
@staticmethod def words_list(text): ' get all words in a list\n return the list of words [a-zA-Z_].\n ' return re.findall('[a-zA-Z]+', text)
-6,780,613,056,861,164,000
get all words in a list return the list of words [a-zA-Z_].
words.py
words_list
Layto888/Words-Analysis
python
@staticmethod def words_list(text): ' get all words in a list\n return the list of words [a-zA-Z_].\n ' return re.findall('[a-zA-Z]+', text)
@staticmethod def sentence_split(text): ' split sentences into list of sentences.\n return len(sentence_split(text)) to get the number of sentences.\n ' sentences = re.split('[.!?]', text) sentences = [sentence.strip() for sentence in sentences if (len(sentence) > 1)] return sentences
796,200,292,554,774,800
split sentences into list of sentences. return len(sentence_split(text)) to get the number of sentences.
words.py
sentence_split
Layto888/Words-Analysis
python
@staticmethod def sentence_split(text): ' split sentences into list of sentences.\n return len(sentence_split(text)) to get the number of sentences.\n ' sentences = re.split('[.!?]', text) sentences = [sentence.strip() for sentence in sentences if (len(sentence) > 1)] return sentences
def __init__(self): 'Init discovery.' self.server_socket = _get_socket() self.log = logging.getLogger(__name__)
2,154,616,157,608,050,700
Init discovery.
roombapy/discovery.py
__init__
Erelen-Laiquendi/roombapy
python
def __init__(self): self.server_socket = _get_socket() self.log = logging.getLogger(__name__)
def main(): '\n Cancels all bitcoin orders.\n ' client = gdax.AuthenticatedClient(API_KEY, API_SECRET, API_PASS) r = client.cancel_all(product='LTC-USD') print(json.dumps(r))
140,713,330,605,226,910
Cancels all bitcoin orders.
cancel.py
main
griswaldbrooks/gdax-tools
python
def main(): '\n \n ' client = gdax.AuthenticatedClient(API_KEY, API_SECRET, API_PASS) r = client.cancel_all(product='LTC-USD') print(json.dumps(r))
def calc_profit_score(rage_score=0, prev_profit_rate=0, current_profit_rate=0): '\n ๋งค๋„ ํ•  ํƒ€์ด๋ฐ์€ ์Šค์ฝ”์–ด๊ฐ€ 5์  ์ด์ƒ์ธ ๊ฒฝ์šฐ๋กœ ํ•œ๋‹ค.\n 1. ์ ˆ๋Œ€ ์ˆ˜์ต๋ฅ ์ด 100% ๋ณด๋‹ค ๋†’์€ ๊ฒฝ์šฐ\n - ์ง์ „ ์ˆ˜์ต๋ฅ  ๋ณด๋‹ค ๋–จ์–ด์กŒ์„ ๋•Œ(+)\n rage_score = rage_score + minus_change_rate * 2\n - ์ง์ „ ์ˆ˜์ต๋ฅ  ๋ณด๋‹ค ์˜ฌ๋ผ๊ฐ”์„ ๋•Œ(-)\n rage_score = rage_score + minus_change_rate / 2\n 2. ์ ˆ๋Œ€ ์ˆ˜์ต๋ฅ ์ด 100% ๋ณด๋‹ค ๋‚ฎ์€ ๊ฒฝ์šฐ๋Š” ๊ทธ๋ƒฅ 97% ๋ฏธ๋งŒ์ผ ๋•Œ ๋งค๋„ ์ฒ˜๋ฆฌ(๋นก์นจ ์Šค์ฝ”์–ด๋Š” ๊ณ„์‚ฐ)\n - ์ง์ „ ์ˆ˜์ต๋ฅ  ๋ณด๋‹ค ๋–จ์–ด์กŒ์„ ๋•Œ(+)\n rage_score = rage_score + minus_change_rate * 2\n - ์ง์ „ ์ˆ˜์ต๋ฅ  ๋ณด๋‹ค ์˜ฌ๋ผ๊ฐ”์„ ๋•Œ(-)\n rage_score = rage_score + minus_change_rate * 1.5\n 3. ๋นก์นจ ์Šค์ฝ”์–ด๊ฐ€ ๋งˆ์ด๋„ˆ์Šค์ธ ๊ฒฝ์šฐ 0์œผ๋กœ ์ฒ˜๋ฆฌ\n ' minus_change_rate = (prev_profit_rate - current_profit_rate) if (current_profit_rate >= 100): if (minus_change_rate >= 0): rage_score = (rage_score + (minus_change_rate * 3)) else: rage_score = (rage_score + (minus_change_rate / 2)) elif (minus_change_rate >= 0): rage_score = (rage_score + (minus_change_rate * 2)) else: rage_score = (rage_score + (minus_change_rate * 2)) slack_message = f'ํ˜„์žฌ ์ ์ˆ˜๋Š” ::: {round(rage_score, 2)} / ๋ณ€๋™ํญ์€ ::: {round((- minus_change_rate), 2)}% / ์ง์ „ ์ˆ˜์ต๋ฅ ์€ ::: {prev_profit_rate}% / ํ˜„์žฌ ์ˆ˜์ต๋ฅ ์€ ::: {current_profit_rate}%' print(slack_message) if (rage_score >= 6.5): pyupbit.send_message(pyupbit.get_slack_channel(), slack_message) elif (rage_score < 0): rage_score = 0 return rage_score
4,407,924,379,584,943,000
๋งค๋„ ํ•  ํƒ€์ด๋ฐ์€ ์Šค์ฝ”์–ด๊ฐ€ 5์  ์ด์ƒ์ธ ๊ฒฝ์šฐ๋กœ ํ•œ๋‹ค. 1. ์ ˆ๋Œ€ ์ˆ˜์ต๋ฅ ์ด 100% ๋ณด๋‹ค ๋†’์€ ๊ฒฝ์šฐ - ์ง์ „ ์ˆ˜์ต๋ฅ  ๋ณด๋‹ค ๋–จ์–ด์กŒ์„ ๋•Œ(+) rage_score = rage_score + minus_change_rate * 2 - ์ง์ „ ์ˆ˜์ต๋ฅ  ๋ณด๋‹ค ์˜ฌ๋ผ๊ฐ”์„ ๋•Œ(-) rage_score = rage_score + minus_change_rate / 2 2. ์ ˆ๋Œ€ ์ˆ˜์ต๋ฅ ์ด 100% ๋ณด๋‹ค ๋‚ฎ์€ ๊ฒฝ์šฐ๋Š” ๊ทธ๋ƒฅ 97% ๋ฏธ๋งŒ์ผ ๋•Œ ๋งค๋„ ์ฒ˜๋ฆฌ(๋นก์นจ ์Šค์ฝ”์–ด๋Š” ๊ณ„์‚ฐ) - ์ง์ „ ์ˆ˜์ต๋ฅ  ๋ณด๋‹ค ๋–จ์–ด์กŒ์„ ๋•Œ(+) rage_score = rage_score + minus_change_rate * 2 - ์ง์ „ ์ˆ˜์ต๋ฅ  ๋ณด๋‹ค ์˜ฌ๋ผ๊ฐ”์„ ๋•Œ(-) rage_score = rage_score + minus_change_rate * 1.5 3. ๋นก์นจ ์Šค์ฝ”์–ด๊ฐ€ ๋งˆ์ด๋„ˆ์Šค์ธ ๊ฒฝ์šฐ 0์œผ๋กœ ์ฒ˜๋ฆฌ
pyupbit/strategy.py
calc_profit_score
snj830526/py_autoinvestment
python
def calc_profit_score(rage_score=0, prev_profit_rate=0, current_profit_rate=0): '\n ๋งค๋„ ํ•  ํƒ€์ด๋ฐ์€ ์Šค์ฝ”์–ด๊ฐ€ 5์  ์ด์ƒ์ธ ๊ฒฝ์šฐ๋กœ ํ•œ๋‹ค.\n 1. ์ ˆ๋Œ€ ์ˆ˜์ต๋ฅ ์ด 100% ๋ณด๋‹ค ๋†’์€ ๊ฒฝ์šฐ\n - ์ง์ „ ์ˆ˜์ต๋ฅ  ๋ณด๋‹ค ๋–จ์–ด์กŒ์„ ๋•Œ(+)\n rage_score = rage_score + minus_change_rate * 2\n - ์ง์ „ ์ˆ˜์ต๋ฅ  ๋ณด๋‹ค ์˜ฌ๋ผ๊ฐ”์„ ๋•Œ(-)\n rage_score = rage_score + minus_change_rate / 2\n 2. ์ ˆ๋Œ€ ์ˆ˜์ต๋ฅ ์ด 100% ๋ณด๋‹ค ๋‚ฎ์€ ๊ฒฝ์šฐ๋Š” ๊ทธ๋ƒฅ 97% ๋ฏธ๋งŒ์ผ ๋•Œ ๋งค๋„ ์ฒ˜๋ฆฌ(๋นก์นจ ์Šค์ฝ”์–ด๋Š” ๊ณ„์‚ฐ)\n - ์ง์ „ ์ˆ˜์ต๋ฅ  ๋ณด๋‹ค ๋–จ์–ด์กŒ์„ ๋•Œ(+)\n rage_score = rage_score + minus_change_rate * 2\n - ์ง์ „ ์ˆ˜์ต๋ฅ  ๋ณด๋‹ค ์˜ฌ๋ผ๊ฐ”์„ ๋•Œ(-)\n rage_score = rage_score + minus_change_rate * 1.5\n 3. ๋นก์นจ ์Šค์ฝ”์–ด๊ฐ€ ๋งˆ์ด๋„ˆ์Šค์ธ ๊ฒฝ์šฐ 0์œผ๋กœ ์ฒ˜๋ฆฌ\n ' minus_change_rate = (prev_profit_rate - current_profit_rate) if (current_profit_rate >= 100): if (minus_change_rate >= 0): rage_score = (rage_score + (minus_change_rate * 3)) else: rage_score = (rage_score + (minus_change_rate / 2)) elif (minus_change_rate >= 0): rage_score = (rage_score + (minus_change_rate * 2)) else: rage_score = (rage_score + (minus_change_rate * 2)) slack_message = f'ํ˜„์žฌ ์ ์ˆ˜๋Š” ::: {round(rage_score, 2)} / ๋ณ€๋™ํญ์€ ::: {round((- minus_change_rate), 2)}% / ์ง์ „ ์ˆ˜์ต๋ฅ ์€ ::: {prev_profit_rate}% / ํ˜„์žฌ ์ˆ˜์ต๋ฅ ์€ ::: {current_profit_rate}%' print(slack_message) if (rage_score >= 6.5): pyupbit.send_message(pyupbit.get_slack_channel(), slack_message) elif (rage_score < 0): rage_score = 0 return rage_score
def prepare_product_state(state: BitString) -> QCircuit: 'Small convenience function\n\n Parameters\n ----------\n state :\n product state encoded into a bitstring\n state: BitString :\n\n\n Returns\n -------\n type\n unitary circuit which prepares the product state\n\n ' result = QCircuit() for (i, v) in enumerate(state.array): if (v == 1): result += gates.X(target=i) return result
5,049,321,781,134,345,000
Small convenience function Parameters ---------- state : product state encoded into a bitstring state: BitString : Returns ------- type unitary circuit which prepares the product state
src/tequila/quantumchemistry/qc_base.py
prepare_product_state
CopperHu/tequila
python
def prepare_product_state(state: BitString) -> QCircuit: 'Small convenience function\n\n Parameters\n ----------\n state :\n product state encoded into a bitstring\n state: BitString :\n\n\n Returns\n -------\n type\n unitary circuit which prepares the product state\n\n ' result = QCircuit() for (i, v) in enumerate(state.array): if (v == 1): result += gates.X(target=i) return result
@property def molecular_data_param(self) -> dict: ':return: Give back all parameters for the MolecularData format from openfermion as dictionary' return {'basis': self.basis_set, 'geometry': self.get_geometry(), 'description': self.description, 'charge': self.charge, 'multiplicity': self.multiplicity, 'filename': self.filename}
-3,557,471,394,562,385,400
:return: Give back all parameters for the MolecularData format from openfermion as dictionary
src/tequila/quantumchemistry/qc_base.py
molecular_data_param
CopperHu/tequila
python
@property def molecular_data_param(self) -> dict: return {'basis': self.basis_set, 'geometry': self.get_geometry(), 'description': self.description, 'charge': self.charge, 'multiplicity': self.multiplicity, 'filename': self.filename}
@staticmethod def format_element_name(string): "OpenFermion uses case sensitive hash tables for chemical elements\n I.e. you need to name Lithium: 'Li' and 'li' or 'LI' will not work\n this convenience function does the naming\n :return: first letter converted to upper rest to lower\n\n Parameters\n ----------\n string :\n\n\n Returns\n -------\n\n " assert (len(string) > 0) assert isinstance(string, str) fstring = (string[0].upper() + string[1:].lower()) return fstring
-2,788,771,041,327,360,000
OpenFermion uses case sensitive hash tables for chemical elements I.e. you need to name Lithium: 'Li' and 'li' or 'LI' will not work this convenience function does the naming :return: first letter converted to upper rest to lower Parameters ---------- string : Returns -------
src/tequila/quantumchemistry/qc_base.py
format_element_name
CopperHu/tequila
python
@staticmethod def format_element_name(string): "OpenFermion uses case sensitive hash tables for chemical elements\n I.e. you need to name Lithium: 'Li' and 'li' or 'LI' will not work\n this convenience function does the naming\n :return: first letter converted to upper rest to lower\n\n Parameters\n ----------\n string :\n\n\n Returns\n -------\n\n " assert (len(string) > 0) assert isinstance(string, str) fstring = (string[0].upper() + string[1:].lower()) return fstring
@staticmethod def convert_to_list(geometry): 'Convert a molecular structure given as a string into a list suitable for openfermion\n\n Parameters\n ----------\n geometry :\n a string specifying a mol. structure. E.g. geometry="h 0.0 0.0 0.0\n h 0.0 0.0 1.0"\n\n Returns\n -------\n type\n A list with the correct format for openfermion E.g return [ [\'h\',[0.0,0.0,0.0], [..]]\n\n ' result = [] lines = [l for l in geometry.split('\n') if l] for line in lines: words = line.split() if (len(words) < 4): words += ([0.0] * (4 - len(words))) try: tmp = (ParametersQC.format_element_name(words[0]), (float(words[1]), float(words[2]), float(words[3]))) result.append(tmp) except ValueError: print('get_geometry list unknown line:\n ', line, '\n proceed with caution!') return result
577,410,896,616,177,700
Convert a molecular structure given as a string into a list suitable for openfermion Parameters ---------- geometry : a string specifying a mol. structure. E.g. geometry="h 0.0 0.0 0.0 h 0.0 0.0 1.0" Returns ------- type A list with the correct format for openfermion E.g return [ ['h',[0.0,0.0,0.0], [..]]
src/tequila/quantumchemistry/qc_base.py
convert_to_list
CopperHu/tequila
python
@staticmethod def convert_to_list(geometry): 'Convert a molecular structure given as a string into a list suitable for openfermion\n\n Parameters\n ----------\n geometry :\n a string specifying a mol. structure. E.g. geometry="h 0.0 0.0 0.0\n h 0.0 0.0 1.0"\n\n Returns\n -------\n type\n A list with the correct format for openfermion E.g return [ [\'h\',[0.0,0.0,0.0], [..]]\n\n ' result = [] lines = [l for l in geometry.split('\n') if l] for line in lines: words = line.split() if (len(words) < 4): words += ([0.0] * (4 - len(words))) try: tmp = (ParametersQC.format_element_name(words[0]), (float(words[1]), float(words[2]), float(words[3]))) result.append(tmp) except ValueError: print('get_geometry list unknown line:\n ', line, '\n proceed with caution!') return result
def get_geometry_string(self) -> str: 'returns the geometry as a string\n :return: geometry string\n\n Parameters\n ----------\n\n Returns\n -------\n\n ' if (self.geometry.split('.')[(- 1)] == 'xyz'): (geomstring, comment) = self.read_xyz_from_file(self.geometry) if (comment is not None): self.description = comment return geomstring else: return self.geometry
-444,497,867,409,335,100
returns the geometry as a string :return: geometry string Parameters ---------- Returns -------
src/tequila/quantumchemistry/qc_base.py
get_geometry_string
CopperHu/tequila
python
def get_geometry_string(self) -> str: 'returns the geometry as a string\n :return: geometry string\n\n Parameters\n ----------\n\n Returns\n -------\n\n ' if (self.geometry.split('.')[(- 1)] == 'xyz'): (geomstring, comment) = self.read_xyz_from_file(self.geometry) if (comment is not None): self.description = comment return geomstring else: return self.geometry
def get_geometry(self): 'Returns the geometry\n If a xyz filename was given the file is read out\n otherwise it is assumed that the geometry was given as string\n which is then reformatted as a list usable as input for openfermion\n :return: geometry as list\n e.g. [(h,(0.0,0.0,0.35)),(h,(0.0,0.0,-0.35))]\n Units: Angstrom!\n\n Parameters\n ----------\n\n Returns\n -------\n\n ' if (self.geometry.split('.')[(- 1)] == 'xyz'): (geomstring, comment) = self.read_xyz_from_file(self.geometry) if (self.description == ''): self.description = comment return self.convert_to_list(geomstring) elif (self.geometry is not None): return self.convert_to_list(self.geometry) else: raise Exception('Parameters.qc.geometry is None')
-1,481,264,362,287,455,700
Returns the geometry If a xyz filename was given the file is read out otherwise it is assumed that the geometry was given as string which is then reformatted as a list usable as input for openfermion :return: geometry as list e.g. [(h,(0.0,0.0,0.35)),(h,(0.0,0.0,-0.35))] Units: Angstrom! Parameters ---------- Returns -------
src/tequila/quantumchemistry/qc_base.py
get_geometry
CopperHu/tequila
python
def get_geometry(self): 'Returns the geometry\n If a xyz filename was given the file is read out\n otherwise it is assumed that the geometry was given as string\n which is then reformatted as a list usable as input for openfermion\n :return: geometry as list\n e.g. [(h,(0.0,0.0,0.35)),(h,(0.0,0.0,-0.35))]\n Units: Angstrom!\n\n Parameters\n ----------\n\n Returns\n -------\n\n ' if (self.geometry.split('.')[(- 1)] == 'xyz'): (geomstring, comment) = self.read_xyz_from_file(self.geometry) if (self.description == ): self.description = comment return self.convert_to_list(geomstring) elif (self.geometry is not None): return self.convert_to_list(self.geometry) else: raise Exception('Parameters.qc.geometry is None')
@staticmethod def read_xyz_from_file(filename): 'Read XYZ filetype for molecular structures\n https://en.wikipedia.org/wiki/XYZ_file_format\n Units: Angstrom!\n\n Parameters\n ----------\n filename :\n return:\n\n Returns\n -------\n\n ' with open(filename, 'r') as file: content = file.readlines() natoms = int(content[0]) comment = str(content[1]).strip('\n') coord = '' for i in range(natoms): coord += content[(2 + i)] return (coord, comment)
6,780,003,109,991,882,000
Read XYZ filetype for molecular structures https://en.wikipedia.org/wiki/XYZ_file_format Units: Angstrom! Parameters ---------- filename : return: Returns -------
src/tequila/quantumchemistry/qc_base.py
read_xyz_from_file
CopperHu/tequila
python
@staticmethod def read_xyz_from_file(filename): 'Read XYZ filetype for molecular structures\n https://en.wikipedia.org/wiki/XYZ_file_format\n Units: Angstrom!\n\n Parameters\n ----------\n filename :\n return:\n\n Returns\n -------\n\n ' with open(filename, 'r') as file: content = file.readlines() natoms = int(content[0]) comment = str(content[1]).strip('\n') coord = for i in range(natoms): coord += content[(2 + i)] return (coord, comment)
def make_parameter_dictionary(self, threshold=1e-08): '\n\n Parameters\n ----------\n threshold :\n (Default value = 1.e-8)\n\n Returns\n -------\n\n ' variables = {} if (self.tIjAb is not None): nvirt = self.tIjAb.shape[2] nocc = self.tIjAb.shape[0] assert ((self.tIjAb.shape[1] == nocc) and (self.tIjAb.shape[3] == nvirt)) for ((I, J, A, B), value) in numpy.ndenumerate(self.tIjAb): if (not numpy.isclose(value, 0.0, atol=threshold)): variables[((nocc + A), I, (nocc + B), J)] = value if (self.tIA is not None): nocc = self.tIA.shape[0] for ((I, A), value) in numpy.ndenumerate(self.tIA): if (not numpy.isclose(value, 0.0, atol=threshold)): variables[((A + nocc), I)] = value return dict(sorted(variables.items(), key=(lambda x: numpy.abs(x[1])), reverse=True))
-6,719,897,537,732,402,000
Parameters ---------- threshold : (Default value = 1.e-8) Returns -------
src/tequila/quantumchemistry/qc_base.py
make_parameter_dictionary
CopperHu/tequila
python
def make_parameter_dictionary(self, threshold=1e-08): '\n\n Parameters\n ----------\n threshold :\n (Default value = 1.e-8)\n\n Returns\n -------\n\n ' variables = {} if (self.tIjAb is not None): nvirt = self.tIjAb.shape[2] nocc = self.tIjAb.shape[0] assert ((self.tIjAb.shape[1] == nocc) and (self.tIjAb.shape[3] == nvirt)) for ((I, J, A, B), value) in numpy.ndenumerate(self.tIjAb): if (not numpy.isclose(value, 0.0, atol=threshold)): variables[((nocc + A), I, (nocc + B), J)] = value if (self.tIA is not None): nocc = self.tIA.shape[0] for ((I, A), value) in numpy.ndenumerate(self.tIA): if (not numpy.isclose(value, 0.0, atol=threshold)): variables[((A + nocc), I)] = value return dict(sorted(variables.items(), key=(lambda x: numpy.abs(x[1])), reverse=True))
@classmethod def from_closed_shell(cls, cs: ClosedShellAmplitudes): '\n Initialize from closed-shell Amplitude structure\n\n Parameters\n ----------\n cs: ClosedShellAmplitudes :\n\n\n Returns\n -------\n\n ' tijab = (cs.tIjAb - numpy.einsum('ijab -> ijba', cs.tIjAb, optimize='greedy')) return cls(tIjAb=cs.tIjAb, tIA=cs.tIA, tiJaB=cs.tIjAb, tia=cs.tIA, tijab=tijab, tIJAB=tijab)
-4,469,272,883,012,262,400
Initialize from closed-shell Amplitude structure Parameters ---------- cs: ClosedShellAmplitudes : Returns -------
src/tequila/quantumchemistry/qc_base.py
from_closed_shell
CopperHu/tequila
python
@classmethod def from_closed_shell(cls, cs: ClosedShellAmplitudes): '\n Initialize from closed-shell Amplitude structure\n\n Parameters\n ----------\n cs: ClosedShellAmplitudes :\n\n\n Returns\n -------\n\n ' tijab = (cs.tIjAb - numpy.einsum('ijab -> ijba', cs.tIjAb, optimize='greedy')) return cls(tIjAb=cs.tIjAb, tIA=cs.tIA, tiJaB=cs.tIjAb, tia=cs.tIA, tijab=tijab, tIJAB=tijab)
def make_parameter_dictionary(self, threshold=1e-08): '\n\n Parameters\n ----------\n threshold :\n (Default value = 1.e-8)\n Neglect amplitudes below the threshold\n\n Returns\n -------\n Dictionary of tequila variables (hash is in the style of (a,i,b,j))\n\n ' variables = {} if (self.tIjAb is not None): nvirt = self.tIjAb.shape[2] nocc = self.tIjAb.shape[0] assert ((self.tIjAb.shape[1] == nocc) and (self.tIjAb.shape[3] == nvirt)) for ((I, j, A, b), value) in numpy.ndenumerate(self.tIjAb): if (not numpy.isclose(value, 0.0, atol=threshold)): variables[((2 * (nocc + A)), (2 * I), ((2 * (nocc + b)) + 1), (j + 1))] = value for ((i, J, a, B), value) in numpy.ndenumerate(self.tiJaB): if (not numpy.isclose(value, 0.0, atol=threshold)): variables[(((2 * (nocc + a)) + 1), ((2 * i) + 1), (2 * (nocc + B)), J)] = value for ((i, j, a, b), value) in numpy.ndenumerate(self.tijab): if (not numpy.isclose(value, 0.0, atol=threshold)): variables[(((2 * (nocc + a)) + 1), ((2 * i) + 1), ((2 * (nocc + b)) + 1), (j + 1))] = value for ((I, J, A, B), value) in numpy.ndenumerate(self.tijab): if (not numpy.isclose(value, 0.0, atol=threshold)): variables[((2 * (nocc + A)), (2 * I), (2 * (nocc + B)), J)] = value if (self.tIA is not None): nocc = self.tIjAb.shape[0] assert (self.tia.shape[0] == nocc) for ((I, A), value) in numpy.ndenumerate(self.tIA): if (not numpy.isclose(value, 0.0, atol=threshold)): variables[((2 * (A + nocc)), (2 * I))] = value for ((i, a), value) in numpy.ndenumerate(self.tIA): if (not numpy.isclose(value, 0.0, atol=threshold)): variables[(((2 * (a + nocc)) + 1), ((2 * i) + 1))] = value return variables
-6,105,695,800,096,477,000
Parameters ---------- threshold : (Default value = 1.e-8) Neglect amplitudes below the threshold Returns ------- Dictionary of tequila variables (hash is in the style of (a,i,b,j))
src/tequila/quantumchemistry/qc_base.py
make_parameter_dictionary
CopperHu/tequila
python
def make_parameter_dictionary(self, threshold=1e-08): '\n\n Parameters\n ----------\n threshold :\n (Default value = 1.e-8)\n Neglect amplitudes below the threshold\n\n Returns\n -------\n Dictionary of tequila variables (hash is in the style of (a,i,b,j))\n\n ' variables = {} if (self.tIjAb is not None): nvirt = self.tIjAb.shape[2] nocc = self.tIjAb.shape[0] assert ((self.tIjAb.shape[1] == nocc) and (self.tIjAb.shape[3] == nvirt)) for ((I, j, A, b), value) in numpy.ndenumerate(self.tIjAb): if (not numpy.isclose(value, 0.0, atol=threshold)): variables[((2 * (nocc + A)), (2 * I), ((2 * (nocc + b)) + 1), (j + 1))] = value for ((i, J, a, B), value) in numpy.ndenumerate(self.tiJaB): if (not numpy.isclose(value, 0.0, atol=threshold)): variables[(((2 * (nocc + a)) + 1), ((2 * i) + 1), (2 * (nocc + B)), J)] = value for ((i, j, a, b), value) in numpy.ndenumerate(self.tijab): if (not numpy.isclose(value, 0.0, atol=threshold)): variables[(((2 * (nocc + a)) + 1), ((2 * i) + 1), ((2 * (nocc + b)) + 1), (j + 1))] = value for ((I, J, A, B), value) in numpy.ndenumerate(self.tijab): if (not numpy.isclose(value, 0.0, atol=threshold)): variables[((2 * (nocc + A)), (2 * I), (2 * (nocc + B)), J)] = value if (self.tIA is not None): nocc = self.tIjAb.shape[0] assert (self.tia.shape[0] == nocc) for ((I, A), value) in numpy.ndenumerate(self.tIA): if (not numpy.isclose(value, 0.0, atol=threshold)): variables[((2 * (A + nocc)), (2 * I))] = value for ((i, a), value) in numpy.ndenumerate(self.tIA): if (not numpy.isclose(value, 0.0, atol=threshold)): variables[(((2 * (a + nocc)) + 1), ((2 * i) + 1))] = value return variables
def __init__(self, elems: numpy.ndarray=None, active_indices: list=None, ordering: str=None, size_full: int=None): '\n Parameters\n ----------\n elems: Tensor data as numpy array\n active_indices: List of active indices in total ordering\n ordering: Ordering scheme for two body tensors\n "dirac" or "phys": <12|g|12>\n .. math::\n g_{pqrs} = \\int d1 d2 p(1)q(2) g(1,2) r(1)s(2)\n "mulliken" or "chem": (11|g|22)\n .. math::\n g_{pqrs} = \\int d1 d2 p(1)r(2) g(1,2) q(1)s(2)\n "openfermion":\n .. math:: [12|g|21]\n g_{gqprs} = \\int d1 d2 p(1)q(2) g(1,2) s(1)r(2)\n\n size_full\n ' self.elems = elems if (active_indices is not None): self.active_indices = active_indices self._passive_indices = None self._full_indices = None self._indices_set: bool = False self.order = len(self.elems.shape) if (size_full is None): self._size_full = self.elems.shape[0] else: self._size_full = size_full if (self.order == 4): self.ordering = self.Ordering(ordering) else: if (ordering is not None): raise Exception('Ordering only implemented for tensors of order 4 / 2-body tensors.') self.ordering = None
-2,529,443,688,893,883,400
Parameters ---------- elems: Tensor data as numpy array active_indices: List of active indices in total ordering ordering: Ordering scheme for two body tensors "dirac" or "phys": <12|g|12> .. math:: g_{pqrs} = \int d1 d2 p(1)q(2) g(1,2) r(1)s(2) "mulliken" or "chem": (11|g|22) .. math:: g_{pqrs} = \int d1 d2 p(1)r(2) g(1,2) q(1)s(2) "openfermion": .. math:: [12|g|21] g_{gqprs} = \int d1 d2 p(1)q(2) g(1,2) s(1)r(2) size_full
src/tequila/quantumchemistry/qc_base.py
__init__
CopperHu/tequila
python
def __init__(self, elems: numpy.ndarray=None, active_indices: list=None, ordering: str=None, size_full: int=None): '\n Parameters\n ----------\n elems: Tensor data as numpy array\n active_indices: List of active indices in total ordering\n ordering: Ordering scheme for two body tensors\n "dirac" or "phys": <12|g|12>\n .. math::\n g_{pqrs} = \\int d1 d2 p(1)q(2) g(1,2) r(1)s(2)\n "mulliken" or "chem": (11|g|22)\n .. math::\n g_{pqrs} = \\int d1 d2 p(1)r(2) g(1,2) q(1)s(2)\n "openfermion":\n .. math:: [12|g|21]\n g_{gqprs} = \\int d1 d2 p(1)q(2) g(1,2) s(1)r(2)\n\n size_full\n ' self.elems = elems if (active_indices is not None): self.active_indices = active_indices self._passive_indices = None self._full_indices = None self._indices_set: bool = False self.order = len(self.elems.shape) if (size_full is None): self._size_full = self.elems.shape[0] else: self._size_full = size_full if (self.order == 4): self.ordering = self.Ordering(ordering) else: if (ordering is not None): raise Exception('Ordering only implemented for tensors of order 4 / 2-body tensors.') self.ordering = None
def sub_lists(self, idx_lists: list=None) -> numpy.ndarray: '\n Get subspace of tensor by a set of index lists\n according to hPQ.sub_lists(idx_lists=[p, q]) = [hPQ for P in p and Q in q]\n\n This essentially is an implementation of a non-contiguous slicing using numpy.take\n\n Parameters\n ----------\n idx_lists :\n List of lists, each defining the desired subspace per axis\n Size needs to match order of tensor, and lists successively correspond to axis=0,1,2,...,N\n\n Returns\n -------\n out :\n Sliced tensor as numpy.ndarray\n ' if (len(idx_lists) != self.order): raise Exception(('Need to pass an index list for each dimension!' + ' Length of idx_lists needs to match order of tensor.')) out = self.elems for ax in range(self.order): if (idx_lists[ax] is not None): out = numpy.take(out, idx_lists[ax], axis=ax) return out
8,856,364,918,677,615,000
Get subspace of tensor by a set of index lists according to hPQ.sub_lists(idx_lists=[p, q]) = [hPQ for P in p and Q in q] This essentially is an implementation of a non-contiguous slicing using numpy.take Parameters ---------- idx_lists : List of lists, each defining the desired subspace per axis Size needs to match order of tensor, and lists successively correspond to axis=0,1,2,...,N Returns ------- out : Sliced tensor as numpy.ndarray
src/tequila/quantumchemistry/qc_base.py
sub_lists
CopperHu/tequila
python
def sub_lists(self, idx_lists: list=None) -> numpy.ndarray: '\n Get subspace of tensor by a set of index lists\n according to hPQ.sub_lists(idx_lists=[p, q]) = [hPQ for P in p and Q in q]\n\n This essentially is an implementation of a non-contiguous slicing using numpy.take\n\n Parameters\n ----------\n idx_lists :\n List of lists, each defining the desired subspace per axis\n Size needs to match order of tensor, and lists successively correspond to axis=0,1,2,...,N\n\n Returns\n -------\n out :\n Sliced tensor as numpy.ndarray\n ' if (len(idx_lists) != self.order): raise Exception(('Need to pass an index list for each dimension!' + ' Length of idx_lists needs to match order of tensor.')) out = self.elems for ax in range(self.order): if (idx_lists[ax] is not None): out = numpy.take(out, idx_lists[ax], axis=ax) return out
def set_index_lists(self): ' Set passive and full index lists based on class inputs ' tmp_size = self._size_full if (self._size_full is None): tmp_size = self.elems.shape[0] self._passive_indices = [i for i in range(tmp_size) if (i not in self.active_indices)] self._full_indices = [i for i in range(tmp_size)]
2,603,122,348,096,272,000
Set passive and full index lists based on class inputs
src/tequila/quantumchemistry/qc_base.py
set_index_lists
CopperHu/tequila
python
def set_index_lists(self): ' ' tmp_size = self._size_full if (self._size_full is None): tmp_size = self.elems.shape[0] self._passive_indices = [i for i in range(tmp_size) if (i not in self.active_indices)] self._full_indices = [i for i in range(tmp_size)]
def sub_str(self, name: str) -> numpy.ndarray: "\n Get subspace of tensor by a string\n Currently is able to resolve an active space, named 'a', full space 'f', and the complement 'p' = 'f' - 'a'.\n Full space in this context may also be smaller than actual tensor dimension.\n\n The specification of active space in this context only allows to pick a set from a list of orbitals, and\n is not able to resolve an active space from irreducible representations.\n\n Example for one-body tensor:\n hPQ.sub_lists(name='ap') = [hPQ for P in active_indices and Q in _passive_indices]\n\n Parameters\n ----------\n name :\n String specifying the desired subspace, elements need to be a (active), f (full), p (full - active)\n\n Returns\n -------\n out :\n Sliced tensor as numpy.ndarray\n " if (not self._indices_set): self.set_index_lists() self._indices_set = True if (name is None): raise Exception('No name specified.') if (len(name) != self.order): raise Exception('Name does not match order of the tensor.') if (self.active_indices is None): raise Exception('Need to set an active space in order to call this function.') idx_lists = [] for char in name: if (char.lower() == 'a'): idx_lists.append(self.active_indices) elif (char.lower() == 'p'): idx_lists.append(self._passive_indices) elif (char.lower() == 'f'): if (self._size_full is None): idx_lists.append(None) else: idx_lists.append(self._full_indices) else: raise Exception('Need to specify a valid letter (a,p,f).') out = self.sub_lists(idx_lists) return out
4,548,037,151,362,943,000
Get subspace of tensor by a string Currently is able to resolve an active space, named 'a', full space 'f', and the complement 'p' = 'f' - 'a'. Full space in this context may also be smaller than actual tensor dimension. The specification of active space in this context only allows to pick a set from a list of orbitals, and is not able to resolve an active space from irreducible representations. Example for one-body tensor: hPQ.sub_lists(name='ap') = [hPQ for P in active_indices and Q in _passive_indices] Parameters ---------- name : String specifying the desired subspace, elements need to be a (active), f (full), p (full - active) Returns ------- out : Sliced tensor as numpy.ndarray
src/tequila/quantumchemistry/qc_base.py
sub_str
CopperHu/tequila
python
def sub_str(self, name: str) -> numpy.ndarray: "\n Get subspace of tensor by a string\n Currently is able to resolve an active space, named 'a', full space 'f', and the complement 'p' = 'f' - 'a'.\n Full space in this context may also be smaller than actual tensor dimension.\n\n The specification of active space in this context only allows to pick a set from a list of orbitals, and\n is not able to resolve an active space from irreducible representations.\n\n Example for one-body tensor:\n hPQ.sub_lists(name='ap') = [hPQ for P in active_indices and Q in _passive_indices]\n\n Parameters\n ----------\n name :\n String specifying the desired subspace, elements need to be a (active), f (full), p (full - active)\n\n Returns\n -------\n out :\n Sliced tensor as numpy.ndarray\n " if (not self._indices_set): self.set_index_lists() self._indices_set = True if (name is None): raise Exception('No name specified.') if (len(name) != self.order): raise Exception('Name does not match order of the tensor.') if (self.active_indices is None): raise Exception('Need to set an active space in order to call this function.') idx_lists = [] for char in name: if (char.lower() == 'a'): idx_lists.append(self.active_indices) elif (char.lower() == 'p'): idx_lists.append(self._passive_indices) elif (char.lower() == 'f'): if (self._size_full is None): idx_lists.append(None) else: idx_lists.append(self._full_indices) else: raise Exception('Need to specify a valid letter (a,p,f).') out = self.sub_lists(idx_lists) return out
def reorder(self, to: str='of'): "\n Function to reorder tensors according to some convention.\n\n Parameters\n ----------\n to :\n Ordering scheme of choice.\n 'openfermion', 'of' (default) :\n openfermion - ordering, corresponds to integrals of the type\n h^pq_rs = int p(1)* q(2)* O(1,2) r(2) s(1) (O(1,2)\n with operators a^pq_rs = a^p a^q a_r a_s (a^p == a^dagger_p)\n currently needed for dependencies on openfermion-library\n 'chem', 'c' :\n quantum chemistry ordering, collect particle terms,\n more convenient for real-space methods\n h^pq_rs = int p(1) q(1) O(1,2) r(2) s(2)\n This is output by psi4\n 'phys', 'p' :\n typical physics ordering, integrals of type\n h^pq_rs = int p(1)* q(2)* O(1,2) r(1) s(2)\n with operators a^pq_rs = a^p a^q a_s a_r\n\n Returns\n -------\n " if (self.order != 4): raise Exception('Reordering currently only implemented for two-body tensors.') to = self.Ordering(to) if (self.ordering == to): return self elif self.ordering.is_chem(): if to.is_of(): self.elems = numpy.einsum('psqr -> pqrs', self.elems, optimize='greedy') elif to.is_phys(): self.elems = numpy.einsum('prqs -> pqrs', self.elems, optimize='greedy') elif self.ordering.is_of(): if to.is_chem(): self.elems = numpy.einsum('pqrs -> psqr', self.elems, optimize='greedy') elif to.is_phys(): self.elems = numpy.einsum('pqrs -> pqsr', self.elems, optimize='greedy') elif self.ordering.is_phys(): if to.is_chem(): self.elems = numpy.einsum('pqrs -> prqs', self.elems, optimize='greedy') elif to.is_of(): self.elems = numpy.einsum('pqsr -> pqrs', self.elems, optimize='greedy') return self
-4,108,216,377,736,539,600
Function to reorder tensors according to some convention. Parameters ---------- to : Ordering scheme of choice. 'openfermion', 'of' (default) : openfermion - ordering, corresponds to integrals of the type h^pq_rs = int p(1)* q(2)* O(1,2) r(2) s(1) (O(1,2) with operators a^pq_rs = a^p a^q a_r a_s (a^p == a^dagger_p) currently needed for dependencies on openfermion-library 'chem', 'c' : quantum chemistry ordering, collect particle terms, more convenient for real-space methods h^pq_rs = int p(1) q(1) O(1,2) r(2) s(2) This is output by psi4 'phys', 'p' : typical physics ordering, integrals of type h^pq_rs = int p(1)* q(2)* O(1,2) r(1) s(2) with operators a^pq_rs = a^p a^q a_s a_r Returns -------
src/tequila/quantumchemistry/qc_base.py
reorder
CopperHu/tequila
python
def reorder(self, to: str='of'): "\n Function to reorder tensors according to some convention.\n\n Parameters\n ----------\n to :\n Ordering scheme of choice.\n 'openfermion', 'of' (default) :\n openfermion - ordering, corresponds to integrals of the type\n h^pq_rs = int p(1)* q(2)* O(1,2) r(2) s(1) (O(1,2)\n with operators a^pq_rs = a^p a^q a_r a_s (a^p == a^dagger_p)\n currently needed for dependencies on openfermion-library\n 'chem', 'c' :\n quantum chemistry ordering, collect particle terms,\n more convenient for real-space methods\n h^pq_rs = int p(1) q(1) O(1,2) r(2) s(2)\n This is output by psi4\n 'phys', 'p' :\n typical physics ordering, integrals of type\n h^pq_rs = int p(1)* q(2)* O(1,2) r(1) s(2)\n with operators a^pq_rs = a^p a^q a_s a_r\n\n Returns\n -------\n " if (self.order != 4): raise Exception('Reordering currently only implemented for two-body tensors.') to = self.Ordering(to) if (self.ordering == to): return self elif self.ordering.is_chem(): if to.is_of(): self.elems = numpy.einsum('psqr -> pqrs', self.elems, optimize='greedy') elif to.is_phys(): self.elems = numpy.einsum('prqs -> pqrs', self.elems, optimize='greedy') elif self.ordering.is_of(): if to.is_chem(): self.elems = numpy.einsum('pqrs -> psqr', self.elems, optimize='greedy') elif to.is_phys(): self.elems = numpy.einsum('pqrs -> pqsr', self.elems, optimize='greedy') elif self.ordering.is_phys(): if to.is_chem(): self.elems = numpy.einsum('pqrs -> prqs', self.elems, optimize='greedy') elif to.is_of(): self.elems = numpy.einsum('pqsr -> pqrs', self.elems, optimize='greedy') return self
def _make_active_space_data(self, active_orbitals, reference=None): '\n Small helper function\n Internal use only\n Parameters\n ----------\n active_orbitals: dictionary :\n list: Give a list of spatial orbital indices\n i.e. occ = [0,1,3] means that spatial orbital 0, 1 and 3 are used\n reference: (Default value=None)\n List of orbitals which form the reference\n Can be given in the same format as active_orbitals\n If given as None then the first N_electron/2 orbitals are taken\n for closed-shell systems.\n\n Returns\n -------\n Dataclass with active indices and reference indices (in spatial notation)\n\n ' if (active_orbitals is None): return None if (reference is None): assert ((self.n_electrons % 2) == 0) reference = sorted([i for i in range((self.n_electrons // 2))]) return ActiveSpaceData(active_orbitals=sorted(active_orbitals), reference_orbitals=sorted(reference))
-1,637,839,840,288,407,000
Small helper function Internal use only Parameters ---------- active_orbitals: dictionary : list: Give a list of spatial orbital indices i.e. occ = [0,1,3] means that spatial orbital 0, 1 and 3 are used reference: (Default value=None) List of orbitals which form the reference Can be given in the same format as active_orbitals If given as None then the first N_electron/2 orbitals are taken for closed-shell systems. Returns ------- Dataclass with active indices and reference indices (in spatial notation)
src/tequila/quantumchemistry/qc_base.py
_make_active_space_data
CopperHu/tequila
python
def _make_active_space_data(self, active_orbitals, reference=None): '\n Small helper function\n Internal use only\n Parameters\n ----------\n active_orbitals: dictionary :\n list: Give a list of spatial orbital indices\n i.e. occ = [0,1,3] means that spatial orbital 0, 1 and 3 are used\n reference: (Default value=None)\n List of orbitals which form the reference\n Can be given in the same format as active_orbitals\n If given as None then the first N_electron/2 orbitals are taken\n for closed-shell systems.\n\n Returns\n -------\n Dataclass with active indices and reference indices (in spatial notation)\n\n ' if (active_orbitals is None): return None if (reference is None): assert ((self.n_electrons % 2) == 0) reference = sorted([i for i in range((self.n_electrons // 2))]) return ActiveSpaceData(active_orbitals=sorted(active_orbitals), reference_orbitals=sorted(reference))
@classmethod def from_openfermion(cls, molecule: openfermion.MolecularData, transformation: typing.Union[(str, typing.Callable)]=None, *args, **kwargs): '\n Initialize direclty from openfermion MolecularData object\n\n Parameters\n ----------\n molecule\n The openfermion molecule\n Returns\n -------\n The Tequila molecule\n ' parameters = ParametersQC(basis_set=molecule.basis, geometry=molecule.geometry, description=molecule.description, multiplicity=molecule.multiplicity, charge=molecule.charge) return cls(*args, parameters=parameters, transformation=transformation, molecule=molecule, **kwargs)
-5,664,757,410,306,859,000
Initialize direclty from openfermion MolecularData object Parameters ---------- molecule The openfermion molecule Returns ------- The Tequila molecule
src/tequila/quantumchemistry/qc_base.py
from_openfermion
CopperHu/tequila
python
@classmethod def from_openfermion(cls, molecule: openfermion.MolecularData, transformation: typing.Union[(str, typing.Callable)]=None, *args, **kwargs): '\n Initialize direclty from openfermion MolecularData object\n\n Parameters\n ----------\n molecule\n The openfermion molecule\n Returns\n -------\n The Tequila molecule\n ' parameters = ParametersQC(basis_set=molecule.basis, geometry=molecule.geometry, description=molecule.description, multiplicity=molecule.multiplicity, charge=molecule.charge) return cls(*args, parameters=parameters, transformation=transformation, molecule=molecule, **kwargs)
def make_excitation_generator(self, indices: typing.Iterable[typing.Tuple[(int, int)]], form: str=None, remove_constant_term: bool=True) -> QubitHamiltonian: "\n Notes\n ----------\n Creates the transformed hermitian generator of UCC type unitaries:\n M(a^\\dagger_{a_0} a_{i_0} a^\\dagger{a_1}a_{i_1} ... - h.c.)\n where the qubit map M depends is self.transformation\n\n Parameters\n ----------\n indices : typing.Iterable[typing.Tuple[int, int]] :\n List of tuples [(a_0, i_0), (a_1, i_1), ... ] - recommended format, in spin-orbital notation (alpha odd numbers, beta even numbers)\n can also be given as one big list: [a_0, i_0, a_1, i_1 ...]\n form : str : (Default value None):\n Manipulate the generator to involution or projector\n set form='involution' or 'projector'\n the default is no manipulation which gives the standard fermionic excitation operator back\n remove_constant_term: bool: (Default value True):\n by default the constant term in the qubit operator is removed since it has no effect on the unitary it generates\n if the unitary is controlled this might not be true!\n Returns\n -------\n type\n 1j*Transformed qubit excitation operator, depends on self.transformation\n " if (type(self.transformation).__name__ == 'BravyiKitaevFast'): raise TequilaException('The Bravyi-Kitaev-Superfast transformation does not support general FermionOperators yet') if (len(indices) == 0): raise TequilaException('make_excitation_operator: no indices given') elif (not isinstance(indices[0], typing.Iterable)): if ((len(indices) % 2) != 0): raise TequilaException('make_excitation_generator: unexpected input format of indices\nuse list of tuples as [(a_0, i_0),(a_1, i_1) ...]\nor list as [a_0, i_0, a_1, i_1, ... ]\nyou gave: {}'.format(indices)) converted = [(indices[(2 * i)], indices[((2 * i) + 1)]) for i in range((len(indices) // 2))] else: converted = indices converted = [(int(pair[0]), int(pair[1])) for pair in converted] ofi = [] dag = [] for pair in converted: assert (len(pair) == 2) ofi += [(int(pair[0]), 1), (int(pair[1]), 0)] dag += [(int(pair[0]), 0), (int(pair[1]), 1)] op = openfermion.FermionOperator(tuple(ofi), 1j) op += openfermion.FermionOperator(tuple(reversed(dag)), (- 1j)) if (isinstance(form, str) and (form.lower() != 'fermionic')): Na = [x for pair in converted for x in [(pair[0], 1), (pair[0], 0)]] Ma = [x for pair in converted for x in [(pair[0], 0), (pair[0], 1)]] Ni = [x for pair in converted for x in [(pair[1], 1), (pair[1], 0)]] Mi = [x for pair in converted for x in [(pair[1], 0), (pair[1], 1)]] if (form.lower() == 'p+'): op *= 0.5 op += openfermion.FermionOperator((Na + Mi), 0.5) op += openfermion.FermionOperator((Ni + Ma), 0.5) elif (form.lower() == 'p-'): op *= 0.5 op += openfermion.FermionOperator((Na + Mi), (- 0.5)) op += openfermion.FermionOperator((Ni + Ma), (- 0.5)) elif (form.lower() == 'g+'): op += openfermion.FermionOperator([], 1.0) op += openfermion.FermionOperator((Na + Mi), (- 1.0)) op += openfermion.FermionOperator((Ni + Ma), (- 1.0)) elif (form.lower() == 'g-'): op += openfermion.FermionOperator([], (- 1.0)) op += openfermion.FermionOperator((Na + Mi), 1.0) op += openfermion.FermionOperator((Ni + Ma), 1.0) elif (form.lower() == 'p0'): op = openfermion.FermionOperator([], 1.0) op += openfermion.FermionOperator((Na + Mi), (- 1.0)) op += openfermion.FermionOperator((Ni + Ma), (- 1.0)) else: raise TequilaException('Unknown generator form {}, supported are G, P+, P-, G+, G- and P0'.format(form)) qop = self.transformation(op) if remove_constant_term: qop.qubit_operator.terms[tuple()] = 0.0 assert qop.is_hermitian() for (k, v) in qop.qubit_operator.terms.items(): qop.qubit_operator.terms[k] = to_float(v) qop = qop.simplify() if (len(qop) == 0): warnings.warn(('Excitation generator is a unit operator.\nNon-standard transformations might not work with general fermionic operators\nindices = ' + str(indices)), category=TequilaWarning) return qop
-7,399,805,011,970,150,000
Notes ---------- Creates the transformed hermitian generator of UCC type unitaries: M(a^\dagger_{a_0} a_{i_0} a^\dagger{a_1}a_{i_1} ... - h.c.) where the qubit map M depends is self.transformation Parameters ---------- indices : typing.Iterable[typing.Tuple[int, int]] : List of tuples [(a_0, i_0), (a_1, i_1), ... ] - recommended format, in spin-orbital notation (alpha odd numbers, beta even numbers) can also be given as one big list: [a_0, i_0, a_1, i_1 ...] form : str : (Default value None): Manipulate the generator to involution or projector set form='involution' or 'projector' the default is no manipulation which gives the standard fermionic excitation operator back remove_constant_term: bool: (Default value True): by default the constant term in the qubit operator is removed since it has no effect on the unitary it generates if the unitary is controlled this might not be true! Returns ------- type 1j*Transformed qubit excitation operator, depends on self.transformation
src/tequila/quantumchemistry/qc_base.py
make_excitation_generator
CopperHu/tequila
python
def make_excitation_generator(self, indices: typing.Iterable[typing.Tuple[(int, int)]], form: str=None, remove_constant_term: bool=True) -> QubitHamiltonian: "\n Notes\n ----------\n Creates the transformed hermitian generator of UCC type unitaries:\n M(a^\\dagger_{a_0} a_{i_0} a^\\dagger{a_1}a_{i_1} ... - h.c.)\n where the qubit map M depends is self.transformation\n\n Parameters\n ----------\n indices : typing.Iterable[typing.Tuple[int, int]] :\n List of tuples [(a_0, i_0), (a_1, i_1), ... ] - recommended format, in spin-orbital notation (alpha odd numbers, beta even numbers)\n can also be given as one big list: [a_0, i_0, a_1, i_1 ...]\n form : str : (Default value None):\n Manipulate the generator to involution or projector\n set form='involution' or 'projector'\n the default is no manipulation which gives the standard fermionic excitation operator back\n remove_constant_term: bool: (Default value True):\n by default the constant term in the qubit operator is removed since it has no effect on the unitary it generates\n if the unitary is controlled this might not be true!\n Returns\n -------\n type\n 1j*Transformed qubit excitation operator, depends on self.transformation\n " if (type(self.transformation).__name__ == 'BravyiKitaevFast'): raise TequilaException('The Bravyi-Kitaev-Superfast transformation does not support general FermionOperators yet') if (len(indices) == 0): raise TequilaException('make_excitation_operator: no indices given') elif (not isinstance(indices[0], typing.Iterable)): if ((len(indices) % 2) != 0): raise TequilaException('make_excitation_generator: unexpected input format of indices\nuse list of tuples as [(a_0, i_0),(a_1, i_1) ...]\nor list as [a_0, i_0, a_1, i_1, ... ]\nyou gave: {}'.format(indices)) converted = [(indices[(2 * i)], indices[((2 * i) + 1)]) for i in range((len(indices) // 2))] else: converted = indices converted = [(int(pair[0]), int(pair[1])) for pair in converted] ofi = [] dag = [] for pair in converted: assert (len(pair) == 2) ofi += [(int(pair[0]), 1), (int(pair[1]), 0)] dag += [(int(pair[0]), 0), (int(pair[1]), 1)] op = openfermion.FermionOperator(tuple(ofi), 1j) op += openfermion.FermionOperator(tuple(reversed(dag)), (- 1j)) if (isinstance(form, str) and (form.lower() != 'fermionic')): Na = [x for pair in converted for x in [(pair[0], 1), (pair[0], 0)]] Ma = [x for pair in converted for x in [(pair[0], 0), (pair[0], 1)]] Ni = [x for pair in converted for x in [(pair[1], 1), (pair[1], 0)]] Mi = [x for pair in converted for x in [(pair[1], 0), (pair[1], 1)]] if (form.lower() == 'p+'): op *= 0.5 op += openfermion.FermionOperator((Na + Mi), 0.5) op += openfermion.FermionOperator((Ni + Ma), 0.5) elif (form.lower() == 'p-'): op *= 0.5 op += openfermion.FermionOperator((Na + Mi), (- 0.5)) op += openfermion.FermionOperator((Ni + Ma), (- 0.5)) elif (form.lower() == 'g+'): op += openfermion.FermionOperator([], 1.0) op += openfermion.FermionOperator((Na + Mi), (- 1.0)) op += openfermion.FermionOperator((Ni + Ma), (- 1.0)) elif (form.lower() == 'g-'): op += openfermion.FermionOperator([], (- 1.0)) op += openfermion.FermionOperator((Na + Mi), 1.0) op += openfermion.FermionOperator((Ni + Ma), 1.0) elif (form.lower() == 'p0'): op = openfermion.FermionOperator([], 1.0) op += openfermion.FermionOperator((Na + Mi), (- 1.0)) op += openfermion.FermionOperator((Ni + Ma), (- 1.0)) else: raise TequilaException('Unknown generator form {}, supported are G, P+, P-, G+, G- and P0'.format(form)) qop = self.transformation(op) if remove_constant_term: qop.qubit_operator.terms[tuple()] = 0.0 assert qop.is_hermitian() for (k, v) in qop.qubit_operator.terms.items(): qop.qubit_operator.terms[k] = to_float(v) qop = qop.simplify() if (len(qop) == 0): warnings.warn(('Excitation generator is a unit operator.\nNon-standard transformations might not work with general fermionic operators\nindices = ' + str(indices)), category=TequilaWarning) return qop
def make_excitation_gate(self, indices, angle, control=None, assume_real=True, **kwargs): '\n Initialize a fermionic excitation gate defined as\n\n .. math::\n e^{-i\\frac{a}{2} G}\n with generator defines by the indices [(p0,q0),(p1,q1),...]\n .. math::\n G = i(\\prod_{k} a_{p_k}^\\dagger a_{q_k} - h.c.)\n\n Parameters\n ----------\n indices:\n List of tuples that define the generator\n angle:\n Numeric or hashable type or tequila objective\n control:\n List of possible control qubits\n assume_real:\n Assume that the wavefunction will always stay real.\n Will reduce potential gradient costs by a factor of 2\n ' generator = self.make_excitation_generator(indices=indices, remove_constant_term=(control is None)) p0 = self.make_excitation_generator(indices=indices, form='P0', remove_constant_term=(control is None)) return QCircuit.wrap_gate(FermionicGateImpl(angle=angle, generator=generator, p0=p0, transformation=type(self.transformation).__name__.lower(), assume_real=assume_real, control=control, **kwargs))
-3,067,702,008,567,042,000
Initialize a fermionic excitation gate defined as .. math:: e^{-i\frac{a}{2} G} with generator defines by the indices [(p0,q0),(p1,q1),...] .. math:: G = i(\prod_{k} a_{p_k}^\dagger a_{q_k} - h.c.) Parameters ---------- indices: List of tuples that define the generator angle: Numeric or hashable type or tequila objective control: List of possible control qubits assume_real: Assume that the wavefunction will always stay real. Will reduce potential gradient costs by a factor of 2
src/tequila/quantumchemistry/qc_base.py
make_excitation_gate
CopperHu/tequila
python
def make_excitation_gate(self, indices, angle, control=None, assume_real=True, **kwargs): '\n Initialize a fermionic excitation gate defined as\n\n .. math::\n e^{-i\\frac{a}{2} G}\n with generator defines by the indices [(p0,q0),(p1,q1),...]\n .. math::\n G = i(\\prod_{k} a_{p_k}^\\dagger a_{q_k} - h.c.)\n\n Parameters\n ----------\n indices:\n List of tuples that define the generator\n angle:\n Numeric or hashable type or tequila objective\n control:\n List of possible control qubits\n assume_real:\n Assume that the wavefunction will always stay real.\n Will reduce potential gradient costs by a factor of 2\n ' generator = self.make_excitation_generator(indices=indices, remove_constant_term=(control is None)) p0 = self.make_excitation_generator(indices=indices, form='P0', remove_constant_term=(control is None)) return QCircuit.wrap_gate(FermionicGateImpl(angle=angle, generator=generator, p0=p0, transformation=type(self.transformation).__name__.lower(), assume_real=assume_real, control=control, **kwargs))
def make_molecule(self, *args, **kwargs) -> MolecularData: 'Creates a molecule in openfermion format by running psi4 and extracting the data\n Will check for previous outputfiles before running\n Will not recompute if a file was found\n\n Parameters\n ----------\n parameters :\n An instance of ParametersQC, which also holds an instance of ParametersPsi4 via parameters.psi4\n The molecule will be saved in parameters.filename, if this file exists before the call the molecule will be imported from the file\n\n Returns\n -------\n type\n the molecule in openfermion.MolecularData format\n\n ' molecule = MolecularData(**self.parameters.molecular_data_param) do_compute = True try: import os if os.path.exists(self.parameters.filename): molecule.load() do_compute = False except OSError: do_compute = True if do_compute: molecule = self.do_make_molecule(*args, **kwargs) molecule.save() return molecule
-7,852,943,889,117,617,000
Creates a molecule in openfermion format by running psi4 and extracting the data Will check for previous outputfiles before running Will not recompute if a file was found Parameters ---------- parameters : An instance of ParametersQC, which also holds an instance of ParametersPsi4 via parameters.psi4 The molecule will be saved in parameters.filename, if this file exists before the call the molecule will be imported from the file Returns ------- type the molecule in openfermion.MolecularData format
src/tequila/quantumchemistry/qc_base.py
make_molecule
CopperHu/tequila
python
def make_molecule(self, *args, **kwargs) -> MolecularData: 'Creates a molecule in openfermion format by running psi4 and extracting the data\n Will check for previous outputfiles before running\n Will not recompute if a file was found\n\n Parameters\n ----------\n parameters :\n An instance of ParametersQC, which also holds an instance of ParametersPsi4 via parameters.psi4\n The molecule will be saved in parameters.filename, if this file exists before the call the molecule will be imported from the file\n\n Returns\n -------\n type\n the molecule in openfermion.MolecularData format\n\n ' molecule = MolecularData(**self.parameters.molecular_data_param) do_compute = True try: import os if os.path.exists(self.parameters.filename): molecule.load() do_compute = False except OSError: do_compute = True if do_compute: molecule = self.do_make_molecule(*args, **kwargs) molecule.save() return molecule
def do_make_molecule(self, *args, **kwargs): '\n\n Parameters\n ----------\n args\n kwargs\n\n Returns\n -------\n\n ' assert ('one_body_integrals' in kwargs) assert ('two_body_integrals' in kwargs) one_body_integrals = kwargs['one_body_integrals'] two_body_integrals = kwargs['two_body_integrals'] if ('ordering' in kwargs): two_body_integrals = NBodyTensor(two_body_integrals, ordering=kwargs['ordering']) two_body_integrals.reorder(to='openfermion') two_body_integrals = two_body_integrals.elems if ('nuclear_repulsion' in kwargs): nuclear_repulsion = kwargs['nuclear_repulsion'] else: nuclear_repulsion = 0.0 warnings.warn('No nuclear_repulsion given for custom molecule, setting to zero', category=TequilaWarning) if ('n_orbitals' in kwargs): n_orbitals = kwargs['n_orbitals'] else: n_orbitals = one_body_integrals.shape[0] for i in [0, 1, 2, 3]: assert (n_orbitals == two_body_integrals.shape[i]) molecule = MolecularData(**self.parameters.molecular_data_param) molecule.one_body_integrals = one_body_integrals molecule.two_body_integrals = two_body_integrals molecule.nuclear_repulsion = nuclear_repulsion molecule.n_orbitals = n_orbitals if ('n_electrons' in kwargs): molecule.n_electrons = kwargs['n_electrons'] molecule.save() return molecule
6,532,914,810,767,347,000
Parameters ---------- args kwargs Returns -------
src/tequila/quantumchemistry/qc_base.py
do_make_molecule
CopperHu/tequila
python
def do_make_molecule(self, *args, **kwargs): '\n\n Parameters\n ----------\n args\n kwargs\n\n Returns\n -------\n\n ' assert ('one_body_integrals' in kwargs) assert ('two_body_integrals' in kwargs) one_body_integrals = kwargs['one_body_integrals'] two_body_integrals = kwargs['two_body_integrals'] if ('ordering' in kwargs): two_body_integrals = NBodyTensor(two_body_integrals, ordering=kwargs['ordering']) two_body_integrals.reorder(to='openfermion') two_body_integrals = two_body_integrals.elems if ('nuclear_repulsion' in kwargs): nuclear_repulsion = kwargs['nuclear_repulsion'] else: nuclear_repulsion = 0.0 warnings.warn('No nuclear_repulsion given for custom molecule, setting to zero', category=TequilaWarning) if ('n_orbitals' in kwargs): n_orbitals = kwargs['n_orbitals'] else: n_orbitals = one_body_integrals.shape[0] for i in [0, 1, 2, 3]: assert (n_orbitals == two_body_integrals.shape[i]) molecule = MolecularData(**self.parameters.molecular_data_param) molecule.one_body_integrals = one_body_integrals molecule.two_body_integrals = two_body_integrals molecule.nuclear_repulsion = nuclear_repulsion molecule.n_orbitals = n_orbitals if ('n_electrons' in kwargs): molecule.n_electrons = kwargs['n_electrons'] molecule.save() return molecule
def get_integrals(self, two_body_ordering='openfermion'): '\n Returns\n -------\n Tuple with:\n constant part (nuclear_repulsion + possible integrated parts from active-spaces)\n one_body_integrals\n two_body_integrals\n\n ' if ((self.active_space is not None) and (len(self.active_space.frozen_reference_orbitals) > 0)): (c, h1, h2) = self.molecule.get_active_space_integrals(active_indices=self.active_space.active_orbitals, occupied_indices=self.active_space.frozen_reference_orbitals) else: c = 0.0 h1 = self.molecule.one_body_integrals h2 = self.molecule.two_body_integrals c += self.molecule.nuclear_repulsion h2 = NBodyTensor(h2, ordering='openfermion') h2 = h2.reorder(to=two_body_ordering).elems return (c, h1, h2)
-5,854,853,126,287,164,000
Returns ------- Tuple with: constant part (nuclear_repulsion + possible integrated parts from active-spaces) one_body_integrals two_body_integrals
src/tequila/quantumchemistry/qc_base.py
get_integrals
CopperHu/tequila
python
def get_integrals(self, two_body_ordering='openfermion'): '\n Returns\n -------\n Tuple with:\n constant part (nuclear_repulsion + possible integrated parts from active-spaces)\n one_body_integrals\n two_body_integrals\n\n ' if ((self.active_space is not None) and (len(self.active_space.frozen_reference_orbitals) > 0)): (c, h1, h2) = self.molecule.get_active_space_integrals(active_indices=self.active_space.active_orbitals, occupied_indices=self.active_space.frozen_reference_orbitals) else: c = 0.0 h1 = self.molecule.one_body_integrals h2 = self.molecule.two_body_integrals c += self.molecule.nuclear_repulsion h2 = NBodyTensor(h2, ordering='openfermion') h2 = h2.reorder(to=two_body_ordering).elems return (c, h1, h2)
def compute_one_body_integrals(self): ' convenience function ' (c, h1, h2) = self.get_integrals() return h1
5,644,753,562,055,852,000
convenience function
src/tequila/quantumchemistry/qc_base.py
compute_one_body_integrals
CopperHu/tequila
python
def compute_one_body_integrals(self): ' ' (c, h1, h2) = self.get_integrals() return h1
def prepare_reference(self, state=None, *args, **kwargs): '\n\n Returns\n -------\n A tequila circuit object which prepares the reference of this molecule in the chosen transformation\n ' if (state is None): assert ((self.n_electrons % 2) == 0) state = ([0] * (self.n_orbitals * 2)) for i in range(self.n_electrons): state[i] = 1 reference_state = BitString.from_array(self.transformation.map_state(state=state)) U = prepare_product_state(reference_state) U.n_qubits = (self.n_orbitals * 2) return U
5,496,528,263,329,094,000
Returns ------- A tequila circuit object which prepares the reference of this molecule in the chosen transformation
src/tequila/quantumchemistry/qc_base.py
prepare_reference
CopperHu/tequila
python
def prepare_reference(self, state=None, *args, **kwargs): '\n\n Returns\n -------\n A tequila circuit object which prepares the reference of this molecule in the chosen transformation\n ' if (state is None): assert ((self.n_electrons % 2) == 0) state = ([0] * (self.n_orbitals * 2)) for i in range(self.n_electrons): state[i] = 1 reference_state = BitString.from_array(self.transformation.map_state(state=state)) U = prepare_product_state(reference_state) U.n_qubits = (self.n_orbitals * 2) return U
def hcb_to_me(self, U=None): '\n Transform a circuit in the hardcore-boson encoding (HCB)\n to the encoding of this molecule\n HCB is supposed to be encoded on the first n_orbitals qubits\n Parameters\n ----------\n U: HCB circuit (using the alpha qubits)\n Returns\n -------\n\n ' if (U is None): U = QCircuit() consistency = [(x < self.n_orbitals) for x in U.qubits] if (not all(consistency)): warnings.warn('hcb_to_me: given circuit is not defined on the first {} qubits. Is this a HCB circuit?'.format(self.n_orbitals)) alpha_map = {k: self.transformation.up(k) for k in range(self.n_orbitals)} alpha_U = U.map_qubits(qubit_map=alpha_map) UX = self.transformation.hcb_to_me() if (UX is None): raise TequilaException('transformation={} has no hcb_to_me function implemented'.format(self.transformation)) return (alpha_U + UX)
2,084,151,665,806,439,200
Transform a circuit in the hardcore-boson encoding (HCB) to the encoding of this molecule HCB is supposed to be encoded on the first n_orbitals qubits Parameters ---------- U: HCB circuit (using the alpha qubits) Returns -------
src/tequila/quantumchemistry/qc_base.py
hcb_to_me
CopperHu/tequila
python
def hcb_to_me(self, U=None): '\n Transform a circuit in the hardcore-boson encoding (HCB)\n to the encoding of this molecule\n HCB is supposed to be encoded on the first n_orbitals qubits\n Parameters\n ----------\n U: HCB circuit (using the alpha qubits)\n Returns\n -------\n\n ' if (U is None): U = QCircuit() consistency = [(x < self.n_orbitals) for x in U.qubits] if (not all(consistency)): warnings.warn('hcb_to_me: given circuit is not defined on the first {} qubits. Is this a HCB circuit?'.format(self.n_orbitals)) alpha_map = {k: self.transformation.up(k) for k in range(self.n_orbitals)} alpha_U = U.map_qubits(qubit_map=alpha_map) UX = self.transformation.hcb_to_me() if (UX is None): raise TequilaException('transformation={} has no hcb_to_me function implemented'.format(self.transformation)) return (alpha_U + UX)
def get_pair_specific_indices(self, pair_info: str=None, include_singles: bool=True, general_excitations: bool=True) -> list: '\n Assuming a pair-specific model, create a pair-specific index list\n to be used in make_upccgsd_ansatz(indices = ... )\n Excite from a set of references (i) to any pair coming from (i),\n i.e. any (i,j)/(j,i). If general excitations are allowed, also\n allow excitations from pairs to appendant pairs and reference.\n\n Parameters\n ----------\n pair_info\n file or list including information about pair structure\n references single number, pair double\n example: as file: "0,1,11,11,00,10" (hand over file name)\n in file, skip first row assuming some text with information\n as list:[\'0\',\'1`\',\'11\',\'11\',\'00\',\'10\']\n ~> two reference orbitals 0 and 1,\n then two orbitals from pair 11, one from 00, one mixed 10\n include_singles\n include single excitations\n general_excitations\n allow general excitations\n Returns\n -------\n list of indices with pair-specific ansatz\n ' if (pair_info is None): raise TequilaException('Need to provide some pair information.') if isinstance(pair_info, str): pairs = numpy.loadtxt(pair_info, dtype=str, delimiter=',', skiprows=1) elif isinstance(pair_info, list): pairs = pair_info elif (not isinstance(pair_info, list)): raise TequilaException('Pair information needs to be contained in a list or filename.') connect = ([[]] * len(pairs)) generalized = 0 for (idx, p) in enumerate(pairs): if (len(p) == 1): connect[idx] = [i for i in range(len(pairs)) if ((len(pairs[i]) == 2) and (str(idx) in pairs[i]))] elif ((len(p) == 2) and general_excitations): connect[idx] = [i for i in range(len(pairs)) if (((p[0] in pairs[i]) or (p[1] in pairs[i]) or (str(i) in p)) and (not (i == idx)))] elif (len(p) > 2): raise TequilaException('Invalid reference of pair id.') indices = [] for (i, to) in enumerate(connect): for a in to: indices.append((((2 * i), (2 * a)), (((2 * i) + 1), ((2 * a) + 1)))) if include_singles: indices.append(((2 * i), (2 * a))) indices.append((((2 * i) + 1), ((2 * a) + 1))) return indices
2,206,921,487,730,500,600
Assuming a pair-specific model, create a pair-specific index list to be used in make_upccgsd_ansatz(indices = ... ) Excite from a set of references (i) to any pair coming from (i), i.e. any (i,j)/(j,i). If general excitations are allowed, also allow excitations from pairs to appendant pairs and reference. Parameters ---------- pair_info file or list including information about pair structure references single number, pair double example: as file: "0,1,11,11,00,10" (hand over file name) in file, skip first row assuming some text with information as list:['0','1`','11','11','00','10'] ~> two reference orbitals 0 and 1, then two orbitals from pair 11, one from 00, one mixed 10 include_singles include single excitations general_excitations allow general excitations Returns ------- list of indices with pair-specific ansatz
src/tequila/quantumchemistry/qc_base.py
get_pair_specific_indices
CopperHu/tequila
python
def get_pair_specific_indices(self, pair_info: str=None, include_singles: bool=True, general_excitations: bool=True) -> list: '\n Assuming a pair-specific model, create a pair-specific index list\n to be used in make_upccgsd_ansatz(indices = ... )\n Excite from a set of references (i) to any pair coming from (i),\n i.e. any (i,j)/(j,i). If general excitations are allowed, also\n allow excitations from pairs to appendant pairs and reference.\n\n Parameters\n ----------\n pair_info\n file or list including information about pair structure\n references single number, pair double\n example: as file: "0,1,11,11,00,10" (hand over file name)\n in file, skip first row assuming some text with information\n as list:[\'0\',\'1`\',\'11\',\'11\',\'00\',\'10\']\n ~> two reference orbitals 0 and 1,\n then two orbitals from pair 11, one from 00, one mixed 10\n include_singles\n include single excitations\n general_excitations\n allow general excitations\n Returns\n -------\n list of indices with pair-specific ansatz\n ' if (pair_info is None): raise TequilaException('Need to provide some pair information.') if isinstance(pair_info, str): pairs = numpy.loadtxt(pair_info, dtype=str, delimiter=',', skiprows=1) elif isinstance(pair_info, list): pairs = pair_info elif (not isinstance(pair_info, list)): raise TequilaException('Pair information needs to be contained in a list or filename.') connect = ([[]] * len(pairs)) generalized = 0 for (idx, p) in enumerate(pairs): if (len(p) == 1): connect[idx] = [i for i in range(len(pairs)) if ((len(pairs[i]) == 2) and (str(idx) in pairs[i]))] elif ((len(p) == 2) and general_excitations): connect[idx] = [i for i in range(len(pairs)) if (((p[0] in pairs[i]) or (p[1] in pairs[i]) or (str(i) in p)) and (not (i == idx)))] elif (len(p) > 2): raise TequilaException('Invalid reference of pair id.') indices = [] for (i, to) in enumerate(connect): for a in to: indices.append((((2 * i), (2 * a)), (((2 * i) + 1), ((2 * a) + 1)))) if include_singles: indices.append(((2 * i), (2 * a))) indices.append((((2 * i) + 1), ((2 * a) + 1))) return indices
def format_excitation_indices(self, idx): '\n Consistent formatting of excitation indices\n idx = [(p0,q0),(p1,q1),...,(pn,qn)]\n sorted as: p0<p1<pn and pi<qi\n :param idx: list of index tuples describing a single(!) fermionic excitation\n :return: tuple-list of index tuples\n ' idx = [tuple(sorted(x)) for x in idx] idx = sorted(idx, key=(lambda x: x[0])) return tuple(idx)
-1,336,722,734,530,659,300
Consistent formatting of excitation indices idx = [(p0,q0),(p1,q1),...,(pn,qn)] sorted as: p0<p1<pn and pi<qi :param idx: list of index tuples describing a single(!) fermionic excitation :return: tuple-list of index tuples
src/tequila/quantumchemistry/qc_base.py
format_excitation_indices
CopperHu/tequila
python
def format_excitation_indices(self, idx): '\n Consistent formatting of excitation indices\n idx = [(p0,q0),(p1,q1),...,(pn,qn)]\n sorted as: p0<p1<pn and pi<qi\n :param idx: list of index tuples describing a single(!) fermionic excitation\n :return: tuple-list of index tuples\n ' idx = [tuple(sorted(x)) for x in idx] idx = sorted(idx, key=(lambda x: x[0])) return tuple(idx)
def make_upccgsd_ansatz(self, include_reference: bool=True, name: str='UpCCGSD', label: str=None, order: int=None, assume_real: bool=True, hcb_optimization: bool=None, spin_adapt_singles: bool=True, neglect_z=False, *args, **kwargs): '\n UpGCCSD Ansatz similar as described by Lee et. al.\n\n Parameters\n ----------\n include_singles\n include singles excitations. Is overwritten if indices are a string (i.e. indices=UpCCGSD will always include singles, UpCCGD will not)\n include_reference\n include the HF reference state as initial state\n indices\n pass custom defined set of indices from which the ansatz will be created\n List of tuples of tuples spin-indices e.g. [((2*p,2*q),(2*p+1,2*q+1)), ...]\n label\n An additional label that is set with the variables\n default is None and no label will be set: variables names will be\n (x, (p,q)) for x in range(order)\n with a label the variables will be named\n (label, (x, (p,q)))\n order\n Order of the ansatz (default is 1)\n determines how often the ordering gets repeated\n parameters of repeating layers are independent\n assume_real\n assume a real wavefunction (that is always the case if the reference state is real)\n reduces potential gradient costs from 4 to 2\n Returns\n -------\n UpGCCSD ansatz\n ' name = name.upper() if (('A' in name) and (neglect_z is None)): neglect_z = True else: neglect_z = False if (order is None): try: if ('-' in name): order = int(name.split('-')[0]) else: order = 1 except: order = 1 indices = self.make_upccgsd_indices(key=name) have_hcb_trafo = (self.transformation.hcb_to_me() is not None) if (have_hcb_trafo and (hcb_optimization is None)): hcb_optimization = True if ('HCB' in name): hcb_optimization = True if (hcb_optimization and (not have_hcb_trafo) and ('HCB' not in name)): raise TequilaException("use_hcb={} but transformation={} has no 'hcb_to_me' function. Try transformation='ReorderedJordanWigner'".format(hcb_optimization, self.transformation)) if (('S' in name) and ('HCB' in name)): if (('HCB' in name) and ('S' in name)): raise Exception("name={}, Singles can't be realized without mapping back to the standard encoding leave S or HCB out of the name".format(name)) if (not hcb_optimization): U = QCircuit() if include_reference: U = self.prepare_reference() U += self.make_upccgsd_layer(*args, include_singles=('S' in name), indices=indices, assume_real=assume_real, label=(label, 0), spin_adapt_singles=spin_adapt_singles, **kwargs) else: U = QCircuit() if include_reference: U = self.prepare_hardcore_boson_reference() U += self.make_hardcore_boson_upccgd_layer(*args, indices=indices, assume_real=assume_real, label=(label, 0), **kwargs) if ('HCB' not in name): U = self.hcb_to_me(U=U) if ('S' in name): U += self.make_upccgsd_singles(*args, indices=indices, assume_real=assume_real, label=(label, 0), spin_adapt_singles=spin_adapt_singles, neglect_z=neglect_z, **kwargs) for k in range(1, order): U += self.make_upccgsd_layer(include_singles=('S' in name), indices=indices, label=(label, k), spin_adapt_singles=spin_adapt_singles, neglect_z=neglect_z) return U
337,962,731,013,371,260
UpGCCSD Ansatz similar as described by Lee et. al. Parameters ---------- include_singles include singles excitations. Is overwritten if indices are a string (i.e. indices=UpCCGSD will always include singles, UpCCGD will not) include_reference include the HF reference state as initial state indices pass custom defined set of indices from which the ansatz will be created List of tuples of tuples spin-indices e.g. [((2*p,2*q),(2*p+1,2*q+1)), ...] label An additional label that is set with the variables default is None and no label will be set: variables names will be (x, (p,q)) for x in range(order) with a label the variables will be named (label, (x, (p,q))) order Order of the ansatz (default is 1) determines how often the ordering gets repeated parameters of repeating layers are independent assume_real assume a real wavefunction (that is always the case if the reference state is real) reduces potential gradient costs from 4 to 2 Returns ------- UpGCCSD ansatz
src/tequila/quantumchemistry/qc_base.py
make_upccgsd_ansatz
CopperHu/tequila
python
def make_upccgsd_ansatz(self, include_reference: bool=True, name: str='UpCCGSD', label: str=None, order: int=None, assume_real: bool=True, hcb_optimization: bool=None, spin_adapt_singles: bool=True, neglect_z=False, *args, **kwargs): '\n UpGCCSD Ansatz similar as described by Lee et. al.\n\n Parameters\n ----------\n include_singles\n include singles excitations. Is overwritten if indices are a string (i.e. indices=UpCCGSD will always include singles, UpCCGD will not)\n include_reference\n include the HF reference state as initial state\n indices\n pass custom defined set of indices from which the ansatz will be created\n List of tuples of tuples spin-indices e.g. [((2*p,2*q),(2*p+1,2*q+1)), ...]\n label\n An additional label that is set with the variables\n default is None and no label will be set: variables names will be\n (x, (p,q)) for x in range(order)\n with a label the variables will be named\n (label, (x, (p,q)))\n order\n Order of the ansatz (default is 1)\n determines how often the ordering gets repeated\n parameters of repeating layers are independent\n assume_real\n assume a real wavefunction (that is always the case if the reference state is real)\n reduces potential gradient costs from 4 to 2\n Returns\n -------\n UpGCCSD ansatz\n ' name = name.upper() if (('A' in name) and (neglect_z is None)): neglect_z = True else: neglect_z = False if (order is None): try: if ('-' in name): order = int(name.split('-')[0]) else: order = 1 except: order = 1 indices = self.make_upccgsd_indices(key=name) have_hcb_trafo = (self.transformation.hcb_to_me() is not None) if (have_hcb_trafo and (hcb_optimization is None)): hcb_optimization = True if ('HCB' in name): hcb_optimization = True if (hcb_optimization and (not have_hcb_trafo) and ('HCB' not in name)): raise TequilaException("use_hcb={} but transformation={} has no 'hcb_to_me' function. Try transformation='ReorderedJordanWigner'".format(hcb_optimization, self.transformation)) if (('S' in name) and ('HCB' in name)): if (('HCB' in name) and ('S' in name)): raise Exception("name={}, Singles can't be realized without mapping back to the standard encoding leave S or HCB out of the name".format(name)) if (not hcb_optimization): U = QCircuit() if include_reference: U = self.prepare_reference() U += self.make_upccgsd_layer(*args, include_singles=('S' in name), indices=indices, assume_real=assume_real, label=(label, 0), spin_adapt_singles=spin_adapt_singles, **kwargs) else: U = QCircuit() if include_reference: U = self.prepare_hardcore_boson_reference() U += self.make_hardcore_boson_upccgd_layer(*args, indices=indices, assume_real=assume_real, label=(label, 0), **kwargs) if ('HCB' not in name): U = self.hcb_to_me(U=U) if ('S' in name): U += self.make_upccgsd_singles(*args, indices=indices, assume_real=assume_real, label=(label, 0), spin_adapt_singles=spin_adapt_singles, neglect_z=neglect_z, **kwargs) for k in range(1, order): U += self.make_upccgsd_layer(include_singles=('S' in name), indices=indices, label=(label, k), spin_adapt_singles=spin_adapt_singles, neglect_z=neglect_z) return U
def make_uccsd_ansatz(self, trotter_steps: int=1, initial_amplitudes: typing.Union[(str, Amplitudes, ClosedShellAmplitudes)]='mp2', include_reference_ansatz=True, parametrized=True, threshold=1e-08, add_singles=None, *args, **kwargs) -> QCircuit: '\n\n Parameters\n ----------\n initial_amplitudes :\n initial amplitudes given as ManyBodyAmplitudes structure or as string\n where \'mp2\', \'cc2\' or \'ccsd\' are possible initializations\n include_reference_ansatz :\n Also do the reference ansatz (prepare closed-shell Hartree-Fock) (Default value = True)\n parametrized :\n Initialize with variables, otherwise with static numbers (Default value = True)\n trotter_steps: int :\n\n initial_amplitudes: typing.Union[str :\n\n Amplitudes :\n\n ClosedShellAmplitudes] :\n (Default value = "cc2")\n\n Returns\n -------\n type\n Parametrized QCircuit\n\n ' if hasattr(initial_amplitudes, 'lower'): if ((initial_amplitudes.lower() == 'mp2') and (add_singles is None)): add_singles = True elif ((initial_amplitudes is not None) and (add_singles is not None)): warnings.warn('make_uccsd_anstatz: add_singles has no effect when explicit amplitudes are passed down', TequilaWarning) elif (add_singles is None): add_singles = True if ((self.n_electrons % 2) != 0): raise TequilaException('make_uccsd_ansatz currently only for closed shell systems') nocc = (self.n_electrons // 2) nvirt = (self.n_orbitals - nocc) Uref = QCircuit() if include_reference_ansatz: Uref = self.prepare_reference() amplitudes = initial_amplitudes if hasattr(initial_amplitudes, 'lower'): if (initial_amplitudes.lower() == 'mp2'): amplitudes = self.compute_mp2_amplitudes() elif (initial_amplitudes.lower() == 'ccsd'): amplitudes = self.compute_ccsd_amplitudes() else: try: amplitudes = self.compute_amplitudes(method=initial_amplitudes.lower()) except Exception as exc: raise TequilaException("{}\nDon't know how to initialize '{}' amplitudes".format(exc, initial_amplitudes)) if (amplitudes is None): tia = None if add_singles: tia = numpy.zeros(shape=[nocc, nvirt]) amplitudes = ClosedShellAmplitudes(tIjAb=numpy.zeros(shape=[nocc, nocc, nvirt, nvirt]), tIA=tia) closed_shell = isinstance(amplitudes, ClosedShellAmplitudes) indices = {} if (not isinstance(amplitudes, dict)): amplitudes = amplitudes.make_parameter_dictionary(threshold=threshold) amplitudes = dict(sorted(amplitudes.items(), key=(lambda x: numpy.fabs(x[1])), reverse=True)) for (key, t) in amplitudes.items(): assert ((len(key) % 2) == 0) if (not numpy.isclose(t, 0.0, atol=threshold)): if closed_shell: if ((len(key) == 2) and add_singles): angle = (2.0 * t) if parametrized: angle = (2.0 * Variable(name=key)) idx_a = ((2 * key[0]), (2 * key[1])) idx_b = (((2 * key[0]) + 1), ((2 * key[1]) + 1)) indices[idx_a] = angle indices[idx_b] = angle else: assert (len(key) == 4) angle = (2.0 * t) if parametrized: angle = (2.0 * Variable(name=key)) idx_abab = (((2 * key[0]) + 1), ((2 * key[1]) + 1), (2 * key[2]), (2 * key[3])) indices[idx_abab] = angle if ((key[0] != key[2]) and (key[1] != key[3])): idx_aaaa = ((2 * key[0]), (2 * key[1]), (2 * key[2]), (2 * key[3])) idx_bbbb = (((2 * key[0]) + 1), ((2 * key[1]) + 1), ((2 * key[2]) + 1), ((2 * key[3]) + 1)) partner = tuple([key[2], key[1], key[0], key[3]]) anglex = (2.0 * (t - amplitudes[partner])) if parametrized: anglex = (2.0 * (Variable(name=key) - Variable(partner))) indices[idx_aaaa] = anglex indices[idx_bbbb] = anglex else: raise Exception('only closed-shell supported, please assemble yourself .... sorry :-)') UCCSD = QCircuit() factor = (1.0 / trotter_steps) for step in range(trotter_steps): for (idx, angle) in indices.items(): UCCSD += self.make_excitation_gate(indices=idx, angle=(factor * angle)) if (hasattr(initial_amplitudes, 'lower') and (initial_amplitudes.lower() == 'mp2') and parametrized and add_singles): UCCSD += self.make_upccgsd_layer(indices='upccsd', include_singles=True, include_doubles=False) return (Uref + UCCSD)
-7,721,244,416,695,871,000
Parameters ---------- initial_amplitudes : initial amplitudes given as ManyBodyAmplitudes structure or as string where 'mp2', 'cc2' or 'ccsd' are possible initializations include_reference_ansatz : Also do the reference ansatz (prepare closed-shell Hartree-Fock) (Default value = True) parametrized : Initialize with variables, otherwise with static numbers (Default value = True) trotter_steps: int : initial_amplitudes: typing.Union[str : Amplitudes : ClosedShellAmplitudes] : (Default value = "cc2") Returns ------- type Parametrized QCircuit
src/tequila/quantumchemistry/qc_base.py
make_uccsd_ansatz
CopperHu/tequila
python
def make_uccsd_ansatz(self, trotter_steps: int=1, initial_amplitudes: typing.Union[(str, Amplitudes, ClosedShellAmplitudes)]='mp2', include_reference_ansatz=True, parametrized=True, threshold=1e-08, add_singles=None, *args, **kwargs) -> QCircuit: '\n\n Parameters\n ----------\n initial_amplitudes :\n initial amplitudes given as ManyBodyAmplitudes structure or as string\n where \'mp2\', \'cc2\' or \'ccsd\' are possible initializations\n include_reference_ansatz :\n Also do the reference ansatz (prepare closed-shell Hartree-Fock) (Default value = True)\n parametrized :\n Initialize with variables, otherwise with static numbers (Default value = True)\n trotter_steps: int :\n\n initial_amplitudes: typing.Union[str :\n\n Amplitudes :\n\n ClosedShellAmplitudes] :\n (Default value = "cc2")\n\n Returns\n -------\n type\n Parametrized QCircuit\n\n ' if hasattr(initial_amplitudes, 'lower'): if ((initial_amplitudes.lower() == 'mp2') and (add_singles is None)): add_singles = True elif ((initial_amplitudes is not None) and (add_singles is not None)): warnings.warn('make_uccsd_anstatz: add_singles has no effect when explicit amplitudes are passed down', TequilaWarning) elif (add_singles is None): add_singles = True if ((self.n_electrons % 2) != 0): raise TequilaException('make_uccsd_ansatz currently only for closed shell systems') nocc = (self.n_electrons // 2) nvirt = (self.n_orbitals - nocc) Uref = QCircuit() if include_reference_ansatz: Uref = self.prepare_reference() amplitudes = initial_amplitudes if hasattr(initial_amplitudes, 'lower'): if (initial_amplitudes.lower() == 'mp2'): amplitudes = self.compute_mp2_amplitudes() elif (initial_amplitudes.lower() == 'ccsd'): amplitudes = self.compute_ccsd_amplitudes() else: try: amplitudes = self.compute_amplitudes(method=initial_amplitudes.lower()) except Exception as exc: raise TequilaException("{}\nDon't know how to initialize '{}' amplitudes".format(exc, initial_amplitudes)) if (amplitudes is None): tia = None if add_singles: tia = numpy.zeros(shape=[nocc, nvirt]) amplitudes = ClosedShellAmplitudes(tIjAb=numpy.zeros(shape=[nocc, nocc, nvirt, nvirt]), tIA=tia) closed_shell = isinstance(amplitudes, ClosedShellAmplitudes) indices = {} if (not isinstance(amplitudes, dict)): amplitudes = amplitudes.make_parameter_dictionary(threshold=threshold) amplitudes = dict(sorted(amplitudes.items(), key=(lambda x: numpy.fabs(x[1])), reverse=True)) for (key, t) in amplitudes.items(): assert ((len(key) % 2) == 0) if (not numpy.isclose(t, 0.0, atol=threshold)): if closed_shell: if ((len(key) == 2) and add_singles): angle = (2.0 * t) if parametrized: angle = (2.0 * Variable(name=key)) idx_a = ((2 * key[0]), (2 * key[1])) idx_b = (((2 * key[0]) + 1), ((2 * key[1]) + 1)) indices[idx_a] = angle indices[idx_b] = angle else: assert (len(key) == 4) angle = (2.0 * t) if parametrized: angle = (2.0 * Variable(name=key)) idx_abab = (((2 * key[0]) + 1), ((2 * key[1]) + 1), (2 * key[2]), (2 * key[3])) indices[idx_abab] = angle if ((key[0] != key[2]) and (key[1] != key[3])): idx_aaaa = ((2 * key[0]), (2 * key[1]), (2 * key[2]), (2 * key[3])) idx_bbbb = (((2 * key[0]) + 1), ((2 * key[1]) + 1), ((2 * key[2]) + 1), ((2 * key[3]) + 1)) partner = tuple([key[2], key[1], key[0], key[3]]) anglex = (2.0 * (t - amplitudes[partner])) if parametrized: anglex = (2.0 * (Variable(name=key) - Variable(partner))) indices[idx_aaaa] = anglex indices[idx_bbbb] = anglex else: raise Exception('only closed-shell supported, please assemble yourself .... sorry :-)') UCCSD = QCircuit() factor = (1.0 / trotter_steps) for step in range(trotter_steps): for (idx, angle) in indices.items(): UCCSD += self.make_excitation_gate(indices=idx, angle=(factor * angle)) if (hasattr(initial_amplitudes, 'lower') and (initial_amplitudes.lower() == 'mp2') and parametrized and add_singles): UCCSD += self.make_upccgsd_layer(indices='upccsd', include_singles=True, include_doubles=False) return (Uref + UCCSD)
def compute_amplitudes(self, method: str, *args, **kwargs): '\n Compute closed-shell CC amplitudes\n\n Parameters\n ----------\n method :\n coupled-cluster methods like cc2, ccsd, cc3, ccsd(t)\n Success might depend on backend\n got an extra function for MP2\n *args :\n\n **kwargs :\n\n\n Returns\n -------\n\n ' raise TequilaException('compute amplitudes: Needs to be overwritten by backend')
6,440,667,878,847,520,000
Compute closed-shell CC amplitudes Parameters ---------- method : coupled-cluster methods like cc2, ccsd, cc3, ccsd(t) Success might depend on backend got an extra function for MP2 *args : **kwargs : Returns -------
src/tequila/quantumchemistry/qc_base.py
compute_amplitudes
CopperHu/tequila
python
def compute_amplitudes(self, method: str, *args, **kwargs): '\n Compute closed-shell CC amplitudes\n\n Parameters\n ----------\n method :\n coupled-cluster methods like cc2, ccsd, cc3, ccsd(t)\n Success might depend on backend\n got an extra function for MP2\n *args :\n\n **kwargs :\n\n\n Returns\n -------\n\n ' raise TequilaException('compute amplitudes: Needs to be overwritten by backend')
def compute_mp2_amplitudes(self) -> ClosedShellAmplitudes: '\n\n Compute closed-shell mp2 amplitudes\n\n .. math::\n t(a,i,b,j) = 0.25 * g(a,i,b,j)/(e(i) + e(j) -a(i) - b(j) )\n\n :return:\n\n Parameters\n ----------\n\n Returns\n -------\n\n ' g = self.molecule.two_body_integrals fij = self.molecule.orbital_energies nocc = (self.molecule.n_electrons // 2) ei = fij[:nocc] ai = fij[nocc:] abgij = g[nocc:, nocc:, :nocc, :nocc] amplitudes = ((abgij * 1.0) / (((ei.reshape(1, 1, (- 1), 1) + ei.reshape(1, 1, 1, (- 1))) - ai.reshape((- 1), 1, 1, 1)) - ai.reshape(1, (- 1), 1, 1))) E = ((2.0 * numpy.einsum('abij,abij->', amplitudes, abgij)) - numpy.einsum('abji,abij', amplitudes, abgij, optimize='greedy')) self.molecule.mp2_energy = (E + self.molecule.hf_energy) return ClosedShellAmplitudes(tIjAb=numpy.einsum('abij -> ijab', amplitudes, optimize='greedy'))
8,495,409,407,238,118,000
Compute closed-shell mp2 amplitudes .. math:: t(a,i,b,j) = 0.25 * g(a,i,b,j)/(e(i) + e(j) -a(i) - b(j) ) :return: Parameters ---------- Returns -------
src/tequila/quantumchemistry/qc_base.py
compute_mp2_amplitudes
CopperHu/tequila
python
def compute_mp2_amplitudes(self) -> ClosedShellAmplitudes: '\n\n Compute closed-shell mp2 amplitudes\n\n .. math::\n t(a,i,b,j) = 0.25 * g(a,i,b,j)/(e(i) + e(j) -a(i) - b(j) )\n\n :return:\n\n Parameters\n ----------\n\n Returns\n -------\n\n ' g = self.molecule.two_body_integrals fij = self.molecule.orbital_energies nocc = (self.molecule.n_electrons // 2) ei = fij[:nocc] ai = fij[nocc:] abgij = g[nocc:, nocc:, :nocc, :nocc] amplitudes = ((abgij * 1.0) / (((ei.reshape(1, 1, (- 1), 1) + ei.reshape(1, 1, 1, (- 1))) - ai.reshape((- 1), 1, 1, 1)) - ai.reshape(1, (- 1), 1, 1))) E = ((2.0 * numpy.einsum('abij,abij->', amplitudes, abgij)) - numpy.einsum('abji,abij', amplitudes, abgij, optimize='greedy')) self.molecule.mp2_energy = (E + self.molecule.hf_energy) return ClosedShellAmplitudes(tIjAb=numpy.einsum('abij -> ijab', amplitudes, optimize='greedy'))
def compute_cis_amplitudes(self): '\n Compute the CIS amplitudes of the molecule\n ' @dataclass class ResultCIS(): ' ' omegas: typing.List[numbers.Real] amplitudes: typing.List[ClosedShellAmplitudes] def __getitem__(self, item): return (self.omegas[item], self.amplitudes[item]) def __len__(self): return len(self.omegas) g = self.molecule.two_body_integrals fij = self.molecule.orbital_energies nocc = self.n_alpha_electrons nvirt = (self.n_orbitals - nocc) pairs = [] for i in range(nocc): for a in range(nocc, (nocc + nvirt)): pairs.append((a, i)) M = numpy.ndarray(shape=[len(pairs), len(pairs)]) for (xx, x) in enumerate(pairs): eia = (fij[x[0]] - fij[x[1]]) (a, i) = x for (yy, y) in enumerate(pairs): (b, j) = y delta = float((y == x)) gpart = ((2.0 * g[(a, i, b, j)]) - g[(a, i, j, b)]) M[(xx, yy)] = ((eia * delta) + gpart) (omega, xvecs) = numpy.linalg.eigh(M) nex = len(omega) amplitudes = [] for ex in range(nex): t = numpy.ndarray(shape=[nvirt, nocc]) exvec = xvecs[ex] for (xx, x) in enumerate(pairs): (a, i) = x t[((a - nocc), i)] = exvec[xx] amplitudes.append(ClosedShellAmplitudes(tIA=t)) return ResultCIS(omegas=list(omega), amplitudes=amplitudes)
5,713,333,365,143,049,000
Compute the CIS amplitudes of the molecule
src/tequila/quantumchemistry/qc_base.py
compute_cis_amplitudes
CopperHu/tequila
python
def compute_cis_amplitudes(self): '\n \n ' @dataclass class ResultCIS(): ' ' omegas: typing.List[numbers.Real] amplitudes: typing.List[ClosedShellAmplitudes] def __getitem__(self, item): return (self.omegas[item], self.amplitudes[item]) def __len__(self): return len(self.omegas) g = self.molecule.two_body_integrals fij = self.molecule.orbital_energies nocc = self.n_alpha_electrons nvirt = (self.n_orbitals - nocc) pairs = [] for i in range(nocc): for a in range(nocc, (nocc + nvirt)): pairs.append((a, i)) M = numpy.ndarray(shape=[len(pairs), len(pairs)]) for (xx, x) in enumerate(pairs): eia = (fij[x[0]] - fij[x[1]]) (a, i) = x for (yy, y) in enumerate(pairs): (b, j) = y delta = float((y == x)) gpart = ((2.0 * g[(a, i, b, j)]) - g[(a, i, j, b)]) M[(xx, yy)] = ((eia * delta) + gpart) (omega, xvecs) = numpy.linalg.eigh(M) nex = len(omega) amplitudes = [] for ex in range(nex): t = numpy.ndarray(shape=[nvirt, nocc]) exvec = xvecs[ex] for (xx, x) in enumerate(pairs): (a, i) = x t[((a - nocc), i)] = exvec[xx] amplitudes.append(ClosedShellAmplitudes(tIA=t)) return ResultCIS(omegas=list(omega), amplitudes=amplitudes)
@property def rdm1(self): ' \n Returns RMD1 if computed with compute_rdms function before\n ' if (self._rdm1 is not None): return self._rdm1 else: print('1-RDM has not been computed. Return None for 1-RDM.') return None
1,835,887,568,436,279,300
Returns RMD1 if computed with compute_rdms function before
src/tequila/quantumchemistry/qc_base.py
rdm1
CopperHu/tequila
python
@property def rdm1(self): ' \n \n ' if (self._rdm1 is not None): return self._rdm1 else: print('1-RDM has not been computed. Return None for 1-RDM.') return None
@property def rdm2(self): '\n Returns RMD2 if computed with compute_rdms function before\n This is returned in Dirac (physics) notation by default (can be changed in compute_rdms with keyword)!\n ' if (self._rdm2 is not None): return self._rdm2 else: print('2-RDM has not been computed. Return None for 2-RDM.') return None
830,593,727,456,388,500
Returns RMD2 if computed with compute_rdms function before This is returned in Dirac (physics) notation by default (can be changed in compute_rdms with keyword)!
src/tequila/quantumchemistry/qc_base.py
rdm2
CopperHu/tequila
python
@property def rdm2(self): '\n Returns RMD2 if computed with compute_rdms function before\n This is returned in Dirac (physics) notation by default (can be changed in compute_rdms with keyword)!\n ' if (self._rdm2 is not None): return self._rdm2 else: print('2-RDM has not been computed. Return None for 2-RDM.') return None
def compute_rdms(self, U: QCircuit=None, variables: Variables=None, spin_free: bool=True, get_rdm1: bool=True, get_rdm2: bool=True, ordering='dirac'): "\n Computes the one- and two-particle reduced density matrices (rdm1 and rdm2) given\n a unitary U. This method uses the standard ordering in physics as denoted below.\n Note, that the representation of the density matrices depends on the qubit transformation\n used. The Jordan-Wigner encoding corresponds to 'classical' second quantized density\n matrices in the occupation picture.\n\n We only consider real orbitals and thus real-valued RDMs.\n The matrices are set as private members _rdm1, _rdm2 and can be accessed via the properties rdm1, rdm2.\n\n .. math :\n \\text{rdm1: } \\gamma^p_q = \\langle \\psi | a^p a_q | \\psi \\rangle\n = \\langle U 0 | a^p a_q | U 0 \\rangle\n \\text{rdm2: } \\gamma^{pq}_{rs} = \\langle \\psi | a^p a^q a_s a_r | \\psi \\rangle\n = \\langle U 0 | a^p a^q a_s a_r | U 0 \\rangle\n\n Parameters\n ----------\n U :\n Quantum Circuit to achieve the desired state \\psi = U |0\\rangle, non-optional\n variables :\n If U is parametrized, then need to hand over a set of fixed variables\n spin_free :\n Set whether matrices should be spin-free (summation over spin) or defined by spin-orbitals\n get_rdm1, get_rdm2 :\n Set whether either one or both rdm1, rdm2 should be computed. If both are needed at some point,\n it is recommended to compute them at once.\n\n Returns\n -------\n " if (U is None): raise TequilaException('Need to specify a Quantum Circuit.') if (type(self.transformation).__name__ == 'BravyiKitaevFast'): raise TequilaException('The Bravyi-Kitaev-Superfast transformation does not support general FermionOperators yet.') n_SOs = (2 * self.n_orbitals) n_MOs = self.n_orbitals if (U is None): raise TequilaException('Need to specify a Quantum Circuit.') def _get_of_op(operator_tuple): ' Returns operator given by a operator tuple as OpenFermion - Fermion operator ' op = openfermion.FermionOperator(operator_tuple) return op def _get_qop_hermitian(of_operator) -> QubitHamiltonian: ' Returns Hermitian part of Fermion operator as QubitHamiltonian ' qop = self.transformation(of_operator) (real, imag) = qop.split(hermitian=True) if real: return real elif (not real): raise TequilaException('Qubit Hamiltonian does not have a Hermitian part. Operator ={}'.format(of_operator)) def _build_1bdy_operators_spinful() -> list: ' Returns spinful one-body operators as a symmetry-reduced list of QubitHamiltonians ' ops = [] for p in range(n_SOs): for q in range((p + 1)): op_tuple = ((p, 1), (q, 0)) op = _get_of_op(op_tuple) ops += [op] return ops def _build_2bdy_operators_spinful() -> list: ' Returns spinful two-body operators as a symmetry-reduced list of QubitHamiltonians ' ops = [] for p in range(n_SOs): for q in range(p): for r in range(n_SOs): for s in range(r): if (((p * n_SOs) + q) >= ((r * n_SOs) + s)): op_tuple = ((p, 1), (q, 1), (s, 0), (r, 0)) op = _get_of_op(op_tuple) ops += [op] return ops def _build_1bdy_operators_spinfree() -> list: ' Returns spinfree one-body operators as a symmetry-reduced list of QubitHamiltonians ' ops = [] for p in range(n_MOs): for q in range((p + 1)): op_tuple = (((2 * p), 1), ((2 * q), 0)) op = _get_of_op(op_tuple) op_tuple = ((((2 * p) + 1), 1), (((2 * q) + 1), 0)) op += _get_of_op(op_tuple) ops += [op] return ops def _build_2bdy_operators_spinfree() -> list: ' Returns spinfree two-body operators as a symmetry-reduced list of QubitHamiltonians ' ops = [] for (p, q, r, s) in product(range(n_MOs), repeat=4): if ((((p * n_MOs) + q) >= ((r * n_MOs) + s)) and ((p >= q) or (r >= s))): op_tuple = ((((2 * p), 1), ((2 * q), 1), ((2 * s), 0), ((2 * r), 0)) if ((p != q) and (r != s)) else '0.0 []') op = _get_of_op(op_tuple) op_tuple = ((((2 * p), 1), (((2 * q) + 1), 1), (((2 * s) + 1), 0), ((2 * r), 0)) if (((2 * p) != ((2 * q) + 1)) and ((2 * r) != ((2 * s) + 1))) else '0.0 []') op += _get_of_op(op_tuple) op_tuple = (((((2 * p) + 1), 1), ((2 * q), 1), ((2 * s), 0), (((2 * r) + 1), 0)) if ((((2 * p) + 1) != (2 * q)) and (((2 * r) + 1) != (2 * s))) else '0.0 []') op += _get_of_op(op_tuple) op_tuple = (((((2 * p) + 1), 1), (((2 * q) + 1), 1), (((2 * s) + 1), 0), (((2 * r) + 1), 0)) if ((p != q) and (r != s)) else '0.0 []') op += _get_of_op(op_tuple) ops += [op] return ops def _assemble_rdm1(evals) -> numpy.ndarray: '\n Returns spin-ful or spin-free one-particle RDM built by symmetry conditions\n Same symmetry with or without spin, so we can use the same function\n ' N = (n_MOs if spin_free else n_SOs) rdm1 = numpy.zeros([N, N]) ctr: int = 0 for p in range(N): for q in range((p + 1)): rdm1[(p, q)] = evals[ctr] rdm1[(q, p)] = rdm1[(p, q)] ctr += 1 return rdm1 def _assemble_rdm2_spinful(evals) -> numpy.ndarray: ' Returns spin-ful two-particle RDM built by symmetry conditions ' ctr: int = 0 rdm2 = numpy.zeros([n_SOs, n_SOs, n_SOs, n_SOs]) for p in range(n_SOs): for q in range(p): for r in range(n_SOs): for s in range(r): if (((p * n_SOs) + q) >= ((r * n_SOs) + s)): rdm2[(p, q, r, s)] = evals[ctr] rdm2[(r, s, p, q)] = rdm2[(p, q, r, s)] ctr += 1 for p in range(n_SOs): for q in range(p): for r in range(n_SOs): for s in range(r): rdm2[(p, q, s, r)] = ((- 1) * rdm2[(p, q, r, s)]) rdm2[(q, p, r, s)] = ((- 1) * rdm2[(p, q, r, s)]) rdm2[(q, p, s, r)] = rdm2[(p, q, r, s)] return rdm2 def _assemble_rdm2_spinfree(evals) -> numpy.ndarray: ' Returns spin-free two-particle RDM built by symmetry conditions ' ctr: int = 0 rdm2 = numpy.zeros([n_MOs, n_MOs, n_MOs, n_MOs]) for (p, q, r, s) in product(range(n_MOs), repeat=4): if ((((p * n_MOs) + q) >= ((r * n_MOs) + s)) and ((p >= q) or (r >= s))): rdm2[(p, q, r, s)] = evals[ctr] rdm2[(r, s, p, q)] = rdm2[(p, q, r, s)] ctr += 1 for (p, q, r, s) in product(range(n_MOs), repeat=4): if ((p >= q) or (r >= s)): rdm2[(q, p, s, r)] = rdm2[(p, q, r, s)] return rdm2 qops = [] if spin_free: qops += (_build_1bdy_operators_spinfree() if get_rdm1 else []) qops += (_build_2bdy_operators_spinfree() if get_rdm2 else []) else: qops += (_build_1bdy_operators_spinful() if get_rdm1 else []) qops += (_build_2bdy_operators_spinful() if get_rdm2 else []) qops = [_get_qop_hermitian(op) for op in qops] evals = simulate(ExpectationValue(H=qops, U=U, shape=[len(qops)]), variables=variables) def _reset_rdm(rdm): if (rdm is not None): if (spin_free and (rdm.shape[0] != n_MOs)): return None if ((not spin_free) and (rdm.shape[0] != n_SOs)): return None return rdm self._rdm1 = _reset_rdm(self._rdm1) self._rdm2 = _reset_rdm(self._rdm2) if get_rdm1: len_1 = (((n_MOs * (n_MOs + 1)) // 2) if spin_free else ((n_SOs * (n_SOs + 1)) // 2)) else: len_1 = 0 (evals_1, evals_2) = (evals[:len_1], evals[len_1:]) self._rdm1 = (_assemble_rdm1(evals_1) if get_rdm1 else self._rdm1) if spin_free: self._rdm2 = (_assemble_rdm2_spinfree(evals_2) if get_rdm2 else self._rdm2) else: self._rdm2 = (_assemble_rdm2_spinful(evals_2) if get_rdm2 else self._rdm2) if get_rdm2: rdm2 = NBodyTensor(elems=self.rdm2, ordering='dirac') rdm2.reorder(to=ordering) rdm2 = rdm2.elems self._rdm2 = rdm2 if get_rdm1: if get_rdm2: return (self.rdm1, self.rdm2) else: return self.rdm1 elif get_rdm2: return self.rdm2 else: warnings.warn('compute_rdms called with instruction to not compute?', TequilaWarning)
-8,130,753,551,880,289,000
Computes the one- and two-particle reduced density matrices (rdm1 and rdm2) given a unitary U. This method uses the standard ordering in physics as denoted below. Note, that the representation of the density matrices depends on the qubit transformation used. The Jordan-Wigner encoding corresponds to 'classical' second quantized density matrices in the occupation picture. We only consider real orbitals and thus real-valued RDMs. The matrices are set as private members _rdm1, _rdm2 and can be accessed via the properties rdm1, rdm2. .. math : \text{rdm1: } \gamma^p_q = \langle \psi | a^p a_q | \psi \rangle = \langle U 0 | a^p a_q | U 0 \rangle \text{rdm2: } \gamma^{pq}_{rs} = \langle \psi | a^p a^q a_s a_r | \psi \rangle = \langle U 0 | a^p a^q a_s a_r | U 0 \rangle Parameters ---------- U : Quantum Circuit to achieve the desired state \psi = U |0\rangle, non-optional variables : If U is parametrized, then need to hand over a set of fixed variables spin_free : Set whether matrices should be spin-free (summation over spin) or defined by spin-orbitals get_rdm1, get_rdm2 : Set whether either one or both rdm1, rdm2 should be computed. If both are needed at some point, it is recommended to compute them at once. Returns -------
src/tequila/quantumchemistry/qc_base.py
compute_rdms
CopperHu/tequila
python
def compute_rdms(self, U: QCircuit=None, variables: Variables=None, spin_free: bool=True, get_rdm1: bool=True, get_rdm2: bool=True, ordering='dirac'): "\n Computes the one- and two-particle reduced density matrices (rdm1 and rdm2) given\n a unitary U. This method uses the standard ordering in physics as denoted below.\n Note, that the representation of the density matrices depends on the qubit transformation\n used. The Jordan-Wigner encoding corresponds to 'classical' second quantized density\n matrices in the occupation picture.\n\n We only consider real orbitals and thus real-valued RDMs.\n The matrices are set as private members _rdm1, _rdm2 and can be accessed via the properties rdm1, rdm2.\n\n .. math :\n \\text{rdm1: } \\gamma^p_q = \\langle \\psi | a^p a_q | \\psi \\rangle\n = \\langle U 0 | a^p a_q | U 0 \\rangle\n \\text{rdm2: } \\gamma^{pq}_{rs} = \\langle \\psi | a^p a^q a_s a_r | \\psi \\rangle\n = \\langle U 0 | a^p a^q a_s a_r | U 0 \\rangle\n\n Parameters\n ----------\n U :\n Quantum Circuit to achieve the desired state \\psi = U |0\\rangle, non-optional\n variables :\n If U is parametrized, then need to hand over a set of fixed variables\n spin_free :\n Set whether matrices should be spin-free (summation over spin) or defined by spin-orbitals\n get_rdm1, get_rdm2 :\n Set whether either one or both rdm1, rdm2 should be computed. If both are needed at some point,\n it is recommended to compute them at once.\n\n Returns\n -------\n " if (U is None): raise TequilaException('Need to specify a Quantum Circuit.') if (type(self.transformation).__name__ == 'BravyiKitaevFast'): raise TequilaException('The Bravyi-Kitaev-Superfast transformation does not support general FermionOperators yet.') n_SOs = (2 * self.n_orbitals) n_MOs = self.n_orbitals if (U is None): raise TequilaException('Need to specify a Quantum Circuit.') def _get_of_op(operator_tuple): ' Returns operator given by a operator tuple as OpenFermion - Fermion operator ' op = openfermion.FermionOperator(operator_tuple) return op def _get_qop_hermitian(of_operator) -> QubitHamiltonian: ' Returns Hermitian part of Fermion operator as QubitHamiltonian ' qop = self.transformation(of_operator) (real, imag) = qop.split(hermitian=True) if real: return real elif (not real): raise TequilaException('Qubit Hamiltonian does not have a Hermitian part. Operator ={}'.format(of_operator)) def _build_1bdy_operators_spinful() -> list: ' Returns spinful one-body operators as a symmetry-reduced list of QubitHamiltonians ' ops = [] for p in range(n_SOs): for q in range((p + 1)): op_tuple = ((p, 1), (q, 0)) op = _get_of_op(op_tuple) ops += [op] return ops def _build_2bdy_operators_spinful() -> list: ' Returns spinful two-body operators as a symmetry-reduced list of QubitHamiltonians ' ops = [] for p in range(n_SOs): for q in range(p): for r in range(n_SOs): for s in range(r): if (((p * n_SOs) + q) >= ((r * n_SOs) + s)): op_tuple = ((p, 1), (q, 1), (s, 0), (r, 0)) op = _get_of_op(op_tuple) ops += [op] return ops def _build_1bdy_operators_spinfree() -> list: ' Returns spinfree one-body operators as a symmetry-reduced list of QubitHamiltonians ' ops = [] for p in range(n_MOs): for q in range((p + 1)): op_tuple = (((2 * p), 1), ((2 * q), 0)) op = _get_of_op(op_tuple) op_tuple = ((((2 * p) + 1), 1), (((2 * q) + 1), 0)) op += _get_of_op(op_tuple) ops += [op] return ops def _build_2bdy_operators_spinfree() -> list: ' Returns spinfree two-body operators as a symmetry-reduced list of QubitHamiltonians ' ops = [] for (p, q, r, s) in product(range(n_MOs), repeat=4): if ((((p * n_MOs) + q) >= ((r * n_MOs) + s)) and ((p >= q) or (r >= s))): op_tuple = ((((2 * p), 1), ((2 * q), 1), ((2 * s), 0), ((2 * r), 0)) if ((p != q) and (r != s)) else '0.0 []') op = _get_of_op(op_tuple) op_tuple = ((((2 * p), 1), (((2 * q) + 1), 1), (((2 * s) + 1), 0), ((2 * r), 0)) if (((2 * p) != ((2 * q) + 1)) and ((2 * r) != ((2 * s) + 1))) else '0.0 []') op += _get_of_op(op_tuple) op_tuple = (((((2 * p) + 1), 1), ((2 * q), 1), ((2 * s), 0), (((2 * r) + 1), 0)) if ((((2 * p) + 1) != (2 * q)) and (((2 * r) + 1) != (2 * s))) else '0.0 []') op += _get_of_op(op_tuple) op_tuple = (((((2 * p) + 1), 1), (((2 * q) + 1), 1), (((2 * s) + 1), 0), (((2 * r) + 1), 0)) if ((p != q) and (r != s)) else '0.0 []') op += _get_of_op(op_tuple) ops += [op] return ops def _assemble_rdm1(evals) -> numpy.ndarray: '\n Returns spin-ful or spin-free one-particle RDM built by symmetry conditions\n Same symmetry with or without spin, so we can use the same function\n ' N = (n_MOs if spin_free else n_SOs) rdm1 = numpy.zeros([N, N]) ctr: int = 0 for p in range(N): for q in range((p + 1)): rdm1[(p, q)] = evals[ctr] rdm1[(q, p)] = rdm1[(p, q)] ctr += 1 return rdm1 def _assemble_rdm2_spinful(evals) -> numpy.ndarray: ' Returns spin-ful two-particle RDM built by symmetry conditions ' ctr: int = 0 rdm2 = numpy.zeros([n_SOs, n_SOs, n_SOs, n_SOs]) for p in range(n_SOs): for q in range(p): for r in range(n_SOs): for s in range(r): if (((p * n_SOs) + q) >= ((r * n_SOs) + s)): rdm2[(p, q, r, s)] = evals[ctr] rdm2[(r, s, p, q)] = rdm2[(p, q, r, s)] ctr += 1 for p in range(n_SOs): for q in range(p): for r in range(n_SOs): for s in range(r): rdm2[(p, q, s, r)] = ((- 1) * rdm2[(p, q, r, s)]) rdm2[(q, p, r, s)] = ((- 1) * rdm2[(p, q, r, s)]) rdm2[(q, p, s, r)] = rdm2[(p, q, r, s)] return rdm2 def _assemble_rdm2_spinfree(evals) -> numpy.ndarray: ' Returns spin-free two-particle RDM built by symmetry conditions ' ctr: int = 0 rdm2 = numpy.zeros([n_MOs, n_MOs, n_MOs, n_MOs]) for (p, q, r, s) in product(range(n_MOs), repeat=4): if ((((p * n_MOs) + q) >= ((r * n_MOs) + s)) and ((p >= q) or (r >= s))): rdm2[(p, q, r, s)] = evals[ctr] rdm2[(r, s, p, q)] = rdm2[(p, q, r, s)] ctr += 1 for (p, q, r, s) in product(range(n_MOs), repeat=4): if ((p >= q) or (r >= s)): rdm2[(q, p, s, r)] = rdm2[(p, q, r, s)] return rdm2 qops = [] if spin_free: qops += (_build_1bdy_operators_spinfree() if get_rdm1 else []) qops += (_build_2bdy_operators_spinfree() if get_rdm2 else []) else: qops += (_build_1bdy_operators_spinful() if get_rdm1 else []) qops += (_build_2bdy_operators_spinful() if get_rdm2 else []) qops = [_get_qop_hermitian(op) for op in qops] evals = simulate(ExpectationValue(H=qops, U=U, shape=[len(qops)]), variables=variables) def _reset_rdm(rdm): if (rdm is not None): if (spin_free and (rdm.shape[0] != n_MOs)): return None if ((not spin_free) and (rdm.shape[0] != n_SOs)): return None return rdm self._rdm1 = _reset_rdm(self._rdm1) self._rdm2 = _reset_rdm(self._rdm2) if get_rdm1: len_1 = (((n_MOs * (n_MOs + 1)) // 2) if spin_free else ((n_SOs * (n_SOs + 1)) // 2)) else: len_1 = 0 (evals_1, evals_2) = (evals[:len_1], evals[len_1:]) self._rdm1 = (_assemble_rdm1(evals_1) if get_rdm1 else self._rdm1) if spin_free: self._rdm2 = (_assemble_rdm2_spinfree(evals_2) if get_rdm2 else self._rdm2) else: self._rdm2 = (_assemble_rdm2_spinful(evals_2) if get_rdm2 else self._rdm2) if get_rdm2: rdm2 = NBodyTensor(elems=self.rdm2, ordering='dirac') rdm2.reorder(to=ordering) rdm2 = rdm2.elems self._rdm2 = rdm2 if get_rdm1: if get_rdm2: return (self.rdm1, self.rdm2) else: return self.rdm1 elif get_rdm2: return self.rdm2 else: warnings.warn('compute_rdms called with instruction to not compute?', TequilaWarning)
def rdm_spinsum(self, sum_rdm1: bool=True, sum_rdm2: bool=True) -> tuple: '\n Given the spin-ful 1- and 2-particle reduced density matrices, compute the spin-free RDMs by spin summation.\n\n Parameters\n ----------\n sum_rdm1, sum_rdm2 :\n If set to true, perform spin summation on rdm1, rdm2\n\n Returns\n -------\n rdm1_spinsum, rdm2_spinsum :\n The desired spin-free matrices\n ' n_MOs = self.n_orbitals rdm1_spinsum = None rdm2_spinsum = None if sum_rdm1: if (self._rdm1 is None): raise TequilaException('The spin-RDM for the 1-RDM does not exist!') if (self._rdm1.shape[0] != (2 * n_MOs)): raise TequilaException('The existing RDM needs to be in spin-orbital basis, it is already spin-free!') rdm1_spinsum = numpy.zeros([n_MOs, n_MOs]) for p in range(n_MOs): for q in range((p + 1)): rdm1_spinsum[(p, q)] += self._rdm1[((2 * p), (2 * q))] rdm1_spinsum[(p, q)] += self._rdm1[(((2 * p) + 1), ((2 * q) + 1))] for p in range(n_MOs): for q in range(p): rdm1_spinsum[(q, p)] = rdm1_spinsum[(p, q)] if sum_rdm2: if (self._rdm2 is None): raise TequilaException('The spin-RDM for the 2-RDM does not exist!') if (self._rdm2.shape[0] != (2 * n_MOs)): raise TequilaException('The existing RDM needs to be in spin-orbital basis, it is already spin-free!') rdm2_spinsum = numpy.zeros([n_MOs, n_MOs, n_MOs, n_MOs]) for (p, q, r, s) in product(range(n_MOs), repeat=4): rdm2_spinsum[(p, q, r, s)] += self._rdm2[((2 * p), (2 * q), (2 * r), (2 * s))] rdm2_spinsum[(p, q, r, s)] += self._rdm2[(((2 * p) + 1), (2 * q), ((2 * r) + 1), (2 * s))] rdm2_spinsum[(p, q, r, s)] += self._rdm2[((2 * p), ((2 * q) + 1), (2 * r), ((2 * s) + 1))] rdm2_spinsum[(p, q, r, s)] += self._rdm2[(((2 * p) + 1), ((2 * q) + 1), ((2 * r) + 1), ((2 * s) + 1))] return (rdm1_spinsum, rdm2_spinsum)
4,684,720,809,100,469,000
Given the spin-ful 1- and 2-particle reduced density matrices, compute the spin-free RDMs by spin summation. Parameters ---------- sum_rdm1, sum_rdm2 : If set to true, perform spin summation on rdm1, rdm2 Returns ------- rdm1_spinsum, rdm2_spinsum : The desired spin-free matrices
src/tequila/quantumchemistry/qc_base.py
rdm_spinsum
CopperHu/tequila
python
def rdm_spinsum(self, sum_rdm1: bool=True, sum_rdm2: bool=True) -> tuple: '\n Given the spin-ful 1- and 2-particle reduced density matrices, compute the spin-free RDMs by spin summation.\n\n Parameters\n ----------\n sum_rdm1, sum_rdm2 :\n If set to true, perform spin summation on rdm1, rdm2\n\n Returns\n -------\n rdm1_spinsum, rdm2_spinsum :\n The desired spin-free matrices\n ' n_MOs = self.n_orbitals rdm1_spinsum = None rdm2_spinsum = None if sum_rdm1: if (self._rdm1 is None): raise TequilaException('The spin-RDM for the 1-RDM does not exist!') if (self._rdm1.shape[0] != (2 * n_MOs)): raise TequilaException('The existing RDM needs to be in spin-orbital basis, it is already spin-free!') rdm1_spinsum = numpy.zeros([n_MOs, n_MOs]) for p in range(n_MOs): for q in range((p + 1)): rdm1_spinsum[(p, q)] += self._rdm1[((2 * p), (2 * q))] rdm1_spinsum[(p, q)] += self._rdm1[(((2 * p) + 1), ((2 * q) + 1))] for p in range(n_MOs): for q in range(p): rdm1_spinsum[(q, p)] = rdm1_spinsum[(p, q)] if sum_rdm2: if (self._rdm2 is None): raise TequilaException('The spin-RDM for the 2-RDM does not exist!') if (self._rdm2.shape[0] != (2 * n_MOs)): raise TequilaException('The existing RDM needs to be in spin-orbital basis, it is already spin-free!') rdm2_spinsum = numpy.zeros([n_MOs, n_MOs, n_MOs, n_MOs]) for (p, q, r, s) in product(range(n_MOs), repeat=4): rdm2_spinsum[(p, q, r, s)] += self._rdm2[((2 * p), (2 * q), (2 * r), (2 * s))] rdm2_spinsum[(p, q, r, s)] += self._rdm2[(((2 * p) + 1), (2 * q), ((2 * r) + 1), (2 * s))] rdm2_spinsum[(p, q, r, s)] += self._rdm2[((2 * p), ((2 * q) + 1), (2 * r), ((2 * s) + 1))] rdm2_spinsum[(p, q, r, s)] += self._rdm2[(((2 * p) + 1), ((2 * q) + 1), ((2 * r) + 1), ((2 * s) + 1))] return (rdm1_spinsum, rdm2_spinsum)
def perturbative_f12_correction(self, rdm1: numpy.ndarray=None, rdm2: numpy.ndarray=None, gamma: float=1.4, n_ri: int=None, external_info: dict=None, **kwargs) -> float: '\n Computes the spin-free [2]_R12 correction, needing only the 1- and 2-RDM of a reference method\n Requires either 1-RDM, 2-RDM or information to compute them in kwargs\n\n Parameters\n ----------\n rdm1 :\n 1-electron reduced density matrix\n rdm2 :\n 2-electron reduced density matrix\n gamma :\n f12-exponent, for a correlation factor f_12 = -1/gamma * exp[-gamma*r_12]\n n_ri :\n dimensionality of RI-basis; specify only, if want to truncate available RI-basis\n if None, then the maximum available via tensors / basis-set is used\n must not be larger than size of available RI-basis, and not smaller than size of OBS\n for n_ri==dim(OBS), the correction returns zero\n external_info :\n for usage in qc_base, need to provide information where to find one-body tensor f12-tensor <rs|f_12|pq>;\n pass dictionary with {"f12_filename": where to find f12-tensor, "scheme": ordering scheme of tensor}\n kwargs :\n e.g. RDM-information via {"U": QCircuit, "variables": optimal angles}, needs to be passed if rdm1,rdm2 not\n yet computed\n\n Returns\n -------\n the f12 correction for the energy\n ' from .f12_corrections._f12_correction_base import ExplicitCorrelationCorrection correction = ExplicitCorrelationCorrection(mol=self, rdm1=rdm1, rdm2=rdm2, gamma=gamma, n_ri=n_ri, external_info=external_info, **kwargs) return correction.compute()
4,553,724,334,393,502,700
Computes the spin-free [2]_R12 correction, needing only the 1- and 2-RDM of a reference method Requires either 1-RDM, 2-RDM or information to compute them in kwargs Parameters ---------- rdm1 : 1-electron reduced density matrix rdm2 : 2-electron reduced density matrix gamma : f12-exponent, for a correlation factor f_12 = -1/gamma * exp[-gamma*r_12] n_ri : dimensionality of RI-basis; specify only, if want to truncate available RI-basis if None, then the maximum available via tensors / basis-set is used must not be larger than size of available RI-basis, and not smaller than size of OBS for n_ri==dim(OBS), the correction returns zero external_info : for usage in qc_base, need to provide information where to find one-body tensor f12-tensor <rs|f_12|pq>; pass dictionary with {"f12_filename": where to find f12-tensor, "scheme": ordering scheme of tensor} kwargs : e.g. RDM-information via {"U": QCircuit, "variables": optimal angles}, needs to be passed if rdm1,rdm2 not yet computed Returns ------- the f12 correction for the energy
src/tequila/quantumchemistry/qc_base.py
perturbative_f12_correction
CopperHu/tequila
python
def perturbative_f12_correction(self, rdm1: numpy.ndarray=None, rdm2: numpy.ndarray=None, gamma: float=1.4, n_ri: int=None, external_info: dict=None, **kwargs) -> float: '\n Computes the spin-free [2]_R12 correction, needing only the 1- and 2-RDM of a reference method\n Requires either 1-RDM, 2-RDM or information to compute them in kwargs\n\n Parameters\n ----------\n rdm1 :\n 1-electron reduced density matrix\n rdm2 :\n 2-electron reduced density matrix\n gamma :\n f12-exponent, for a correlation factor f_12 = -1/gamma * exp[-gamma*r_12]\n n_ri :\n dimensionality of RI-basis; specify only, if want to truncate available RI-basis\n if None, then the maximum available via tensors / basis-set is used\n must not be larger than size of available RI-basis, and not smaller than size of OBS\n for n_ri==dim(OBS), the correction returns zero\n external_info :\n for usage in qc_base, need to provide information where to find one-body tensor f12-tensor <rs|f_12|pq>;\n pass dictionary with {"f12_filename": where to find f12-tensor, "scheme": ordering scheme of tensor}\n kwargs :\n e.g. RDM-information via {"U": QCircuit, "variables": optimal angles}, needs to be passed if rdm1,rdm2 not\n yet computed\n\n Returns\n -------\n the f12 correction for the energy\n ' from .f12_corrections._f12_correction_base import ExplicitCorrelationCorrection correction = ExplicitCorrelationCorrection(mol=self, rdm1=rdm1, rdm2=rdm2, gamma=gamma, n_ri=n_ri, external_info=external_info, **kwargs) return correction.compute()
def _get_of_op(operator_tuple): ' Returns operator given by a operator tuple as OpenFermion - Fermion operator ' op = openfermion.FermionOperator(operator_tuple) return op
7,108,399,562,124,627,000
Returns operator given by a operator tuple as OpenFermion - Fermion operator
src/tequila/quantumchemistry/qc_base.py
_get_of_op
CopperHu/tequila
python
def _get_of_op(operator_tuple): ' ' op = openfermion.FermionOperator(operator_tuple) return op
def _get_qop_hermitian(of_operator) -> QubitHamiltonian: ' Returns Hermitian part of Fermion operator as QubitHamiltonian ' qop = self.transformation(of_operator) (real, imag) = qop.split(hermitian=True) if real: return real elif (not real): raise TequilaException('Qubit Hamiltonian does not have a Hermitian part. Operator ={}'.format(of_operator))
6,357,291,144,305,196,000
Returns Hermitian part of Fermion operator as QubitHamiltonian
src/tequila/quantumchemistry/qc_base.py
_get_qop_hermitian
CopperHu/tequila
python
def _get_qop_hermitian(of_operator) -> QubitHamiltonian: ' ' qop = self.transformation(of_operator) (real, imag) = qop.split(hermitian=True) if real: return real elif (not real): raise TequilaException('Qubit Hamiltonian does not have a Hermitian part. Operator ={}'.format(of_operator))
def _build_1bdy_operators_spinful() -> list: ' Returns spinful one-body operators as a symmetry-reduced list of QubitHamiltonians ' ops = [] for p in range(n_SOs): for q in range((p + 1)): op_tuple = ((p, 1), (q, 0)) op = _get_of_op(op_tuple) ops += [op] return ops
-4,835,705,876,241,681,000
Returns spinful one-body operators as a symmetry-reduced list of QubitHamiltonians
src/tequila/quantumchemistry/qc_base.py
_build_1bdy_operators_spinful
CopperHu/tequila
python
def _build_1bdy_operators_spinful() -> list: ' ' ops = [] for p in range(n_SOs): for q in range((p + 1)): op_tuple = ((p, 1), (q, 0)) op = _get_of_op(op_tuple) ops += [op] return ops
def _build_2bdy_operators_spinful() -> list: ' Returns spinful two-body operators as a symmetry-reduced list of QubitHamiltonians ' ops = [] for p in range(n_SOs): for q in range(p): for r in range(n_SOs): for s in range(r): if (((p * n_SOs) + q) >= ((r * n_SOs) + s)): op_tuple = ((p, 1), (q, 1), (s, 0), (r, 0)) op = _get_of_op(op_tuple) ops += [op] return ops
-8,522,812,896,792,188,000
Returns spinful two-body operators as a symmetry-reduced list of QubitHamiltonians
src/tequila/quantumchemistry/qc_base.py
_build_2bdy_operators_spinful
CopperHu/tequila
python
def _build_2bdy_operators_spinful() -> list: ' ' ops = [] for p in range(n_SOs): for q in range(p): for r in range(n_SOs): for s in range(r): if (((p * n_SOs) + q) >= ((r * n_SOs) + s)): op_tuple = ((p, 1), (q, 1), (s, 0), (r, 0)) op = _get_of_op(op_tuple) ops += [op] return ops
def _build_1bdy_operators_spinfree() -> list: ' Returns spinfree one-body operators as a symmetry-reduced list of QubitHamiltonians ' ops = [] for p in range(n_MOs): for q in range((p + 1)): op_tuple = (((2 * p), 1), ((2 * q), 0)) op = _get_of_op(op_tuple) op_tuple = ((((2 * p) + 1), 1), (((2 * q) + 1), 0)) op += _get_of_op(op_tuple) ops += [op] return ops
6,888,716,078,207,520,000
Returns spinfree one-body operators as a symmetry-reduced list of QubitHamiltonians
src/tequila/quantumchemistry/qc_base.py
_build_1bdy_operators_spinfree
CopperHu/tequila
python
def _build_1bdy_operators_spinfree() -> list: ' ' ops = [] for p in range(n_MOs): for q in range((p + 1)): op_tuple = (((2 * p), 1), ((2 * q), 0)) op = _get_of_op(op_tuple) op_tuple = ((((2 * p) + 1), 1), (((2 * q) + 1), 0)) op += _get_of_op(op_tuple) ops += [op] return ops
def _build_2bdy_operators_spinfree() -> list: ' Returns spinfree two-body operators as a symmetry-reduced list of QubitHamiltonians ' ops = [] for (p, q, r, s) in product(range(n_MOs), repeat=4): if ((((p * n_MOs) + q) >= ((r * n_MOs) + s)) and ((p >= q) or (r >= s))): op_tuple = ((((2 * p), 1), ((2 * q), 1), ((2 * s), 0), ((2 * r), 0)) if ((p != q) and (r != s)) else '0.0 []') op = _get_of_op(op_tuple) op_tuple = ((((2 * p), 1), (((2 * q) + 1), 1), (((2 * s) + 1), 0), ((2 * r), 0)) if (((2 * p) != ((2 * q) + 1)) and ((2 * r) != ((2 * s) + 1))) else '0.0 []') op += _get_of_op(op_tuple) op_tuple = (((((2 * p) + 1), 1), ((2 * q), 1), ((2 * s), 0), (((2 * r) + 1), 0)) if ((((2 * p) + 1) != (2 * q)) and (((2 * r) + 1) != (2 * s))) else '0.0 []') op += _get_of_op(op_tuple) op_tuple = (((((2 * p) + 1), 1), (((2 * q) + 1), 1), (((2 * s) + 1), 0), (((2 * r) + 1), 0)) if ((p != q) and (r != s)) else '0.0 []') op += _get_of_op(op_tuple) ops += [op] return ops
796,220,979,856,340,700
Returns spinfree two-body operators as a symmetry-reduced list of QubitHamiltonians
src/tequila/quantumchemistry/qc_base.py
_build_2bdy_operators_spinfree
CopperHu/tequila
python
def _build_2bdy_operators_spinfree() -> list: ' ' ops = [] for (p, q, r, s) in product(range(n_MOs), repeat=4): if ((((p * n_MOs) + q) >= ((r * n_MOs) + s)) and ((p >= q) or (r >= s))): op_tuple = ((((2 * p), 1), ((2 * q), 1), ((2 * s), 0), ((2 * r), 0)) if ((p != q) and (r != s)) else '0.0 []') op = _get_of_op(op_tuple) op_tuple = ((((2 * p), 1), (((2 * q) + 1), 1), (((2 * s) + 1), 0), ((2 * r), 0)) if (((2 * p) != ((2 * q) + 1)) and ((2 * r) != ((2 * s) + 1))) else '0.0 []') op += _get_of_op(op_tuple) op_tuple = (((((2 * p) + 1), 1), ((2 * q), 1), ((2 * s), 0), (((2 * r) + 1), 0)) if ((((2 * p) + 1) != (2 * q)) and (((2 * r) + 1) != (2 * s))) else '0.0 []') op += _get_of_op(op_tuple) op_tuple = (((((2 * p) + 1), 1), (((2 * q) + 1), 1), (((2 * s) + 1), 0), (((2 * r) + 1), 0)) if ((p != q) and (r != s)) else '0.0 []') op += _get_of_op(op_tuple) ops += [op] return ops
def _assemble_rdm1(evals) -> numpy.ndarray: '\n Returns spin-ful or spin-free one-particle RDM built by symmetry conditions\n Same symmetry with or without spin, so we can use the same function\n ' N = (n_MOs if spin_free else n_SOs) rdm1 = numpy.zeros([N, N]) ctr: int = 0 for p in range(N): for q in range((p + 1)): rdm1[(p, q)] = evals[ctr] rdm1[(q, p)] = rdm1[(p, q)] ctr += 1 return rdm1
1,946,228,857,425,452,300
Returns spin-ful or spin-free one-particle RDM built by symmetry conditions Same symmetry with or without spin, so we can use the same function
src/tequila/quantumchemistry/qc_base.py
_assemble_rdm1
CopperHu/tequila
python
def _assemble_rdm1(evals) -> numpy.ndarray: '\n Returns spin-ful or spin-free one-particle RDM built by symmetry conditions\n Same symmetry with or without spin, so we can use the same function\n ' N = (n_MOs if spin_free else n_SOs) rdm1 = numpy.zeros([N, N]) ctr: int = 0 for p in range(N): for q in range((p + 1)): rdm1[(p, q)] = evals[ctr] rdm1[(q, p)] = rdm1[(p, q)] ctr += 1 return rdm1
def _assemble_rdm2_spinful(evals) -> numpy.ndarray: ' Returns spin-ful two-particle RDM built by symmetry conditions ' ctr: int = 0 rdm2 = numpy.zeros([n_SOs, n_SOs, n_SOs, n_SOs]) for p in range(n_SOs): for q in range(p): for r in range(n_SOs): for s in range(r): if (((p * n_SOs) + q) >= ((r * n_SOs) + s)): rdm2[(p, q, r, s)] = evals[ctr] rdm2[(r, s, p, q)] = rdm2[(p, q, r, s)] ctr += 1 for p in range(n_SOs): for q in range(p): for r in range(n_SOs): for s in range(r): rdm2[(p, q, s, r)] = ((- 1) * rdm2[(p, q, r, s)]) rdm2[(q, p, r, s)] = ((- 1) * rdm2[(p, q, r, s)]) rdm2[(q, p, s, r)] = rdm2[(p, q, r, s)] return rdm2
-6,612,111,771,052,758,000
Returns spin-ful two-particle RDM built by symmetry conditions
src/tequila/quantumchemistry/qc_base.py
_assemble_rdm2_spinful
CopperHu/tequila
python
def _assemble_rdm2_spinful(evals) -> numpy.ndarray: ' ' ctr: int = 0 rdm2 = numpy.zeros([n_SOs, n_SOs, n_SOs, n_SOs]) for p in range(n_SOs): for q in range(p): for r in range(n_SOs): for s in range(r): if (((p * n_SOs) + q) >= ((r * n_SOs) + s)): rdm2[(p, q, r, s)] = evals[ctr] rdm2[(r, s, p, q)] = rdm2[(p, q, r, s)] ctr += 1 for p in range(n_SOs): for q in range(p): for r in range(n_SOs): for s in range(r): rdm2[(p, q, s, r)] = ((- 1) * rdm2[(p, q, r, s)]) rdm2[(q, p, r, s)] = ((- 1) * rdm2[(p, q, r, s)]) rdm2[(q, p, s, r)] = rdm2[(p, q, r, s)] return rdm2
def _assemble_rdm2_spinfree(evals) -> numpy.ndarray: ' Returns spin-free two-particle RDM built by symmetry conditions ' ctr: int = 0 rdm2 = numpy.zeros([n_MOs, n_MOs, n_MOs, n_MOs]) for (p, q, r, s) in product(range(n_MOs), repeat=4): if ((((p * n_MOs) + q) >= ((r * n_MOs) + s)) and ((p >= q) or (r >= s))): rdm2[(p, q, r, s)] = evals[ctr] rdm2[(r, s, p, q)] = rdm2[(p, q, r, s)] ctr += 1 for (p, q, r, s) in product(range(n_MOs), repeat=4): if ((p >= q) or (r >= s)): rdm2[(q, p, s, r)] = rdm2[(p, q, r, s)] return rdm2
1,758,414,257,986,475,300
Returns spin-free two-particle RDM built by symmetry conditions
src/tequila/quantumchemistry/qc_base.py
_assemble_rdm2_spinfree
CopperHu/tequila
python
def _assemble_rdm2_spinfree(evals) -> numpy.ndarray: ' ' ctr: int = 0 rdm2 = numpy.zeros([n_MOs, n_MOs, n_MOs, n_MOs]) for (p, q, r, s) in product(range(n_MOs), repeat=4): if ((((p * n_MOs) + q) >= ((r * n_MOs) + s)) and ((p >= q) or (r >= s))): rdm2[(p, q, r, s)] = evals[ctr] rdm2[(r, s, p, q)] = rdm2[(p, q, r, s)] ctr += 1 for (p, q, r, s) in product(range(n_MOs), repeat=4): if ((p >= q) or (r >= s)): rdm2[(q, p, s, r)] = rdm2[(p, q, r, s)] return rdm2
def read_rep_cache(repo_dir): 'Return the rep-cache contents as a dict {hash: (rev, index, ...)}.\n ' db_path = os.path.join(repo_dir, 'db', 'rep-cache.db') db1 = svntest.sqlite3.connect(db_path) schema1 = db1.execute('pragma user_version').fetchone()[0] if ((schema1 >= 2) and (svntest.sqlite3.sqlite_version_info < (3, 8, 2))): raise svntest.Failure(("Can't read rep-cache schema %d using old Python-SQLite version %s < (3,8,2)" % (schema1, svntest.sqlite3.sqlite_version_info))) content = {row[0]: row[1:] for row in db1.execute('select * from rep_cache')} return content
-2,334,762,321,693,497,300
Return the rep-cache contents as a dict {hash: (rev, index, ...)}.
subversion/tests/cmdline/svnadmin_tests.py
read_rep_cache
auycro/subversion
python
def read_rep_cache(repo_dir): '\n ' db_path = os.path.join(repo_dir, 'db', 'rep-cache.db') db1 = svntest.sqlite3.connect(db_path) schema1 = db1.execute('pragma user_version').fetchone()[0] if ((schema1 >= 2) and (svntest.sqlite3.sqlite_version_info < (3, 8, 2))): raise svntest.Failure(("Can't read rep-cache schema %d using old Python-SQLite version %s < (3,8,2)" % (schema1, svntest.sqlite3.sqlite_version_info))) content = {row[0]: row[1:] for row in db1.execute('select * from rep_cache')} return content
def check_hotcopy_bdb(src, dst): 'Verify that the SRC BDB repository has been correctly copied to DST.' (exit_code, origout, origerr) = svntest.main.run_svnadmin('dump', src, '--quiet') (exit_code, backout, backerr) = svntest.main.run_svnadmin('dump', dst, '--quiet') if (origerr or backerr or (origout != backout)): raise svntest.Failure
4,106,209,870,099,410,400
Verify that the SRC BDB repository has been correctly copied to DST.
subversion/tests/cmdline/svnadmin_tests.py
check_hotcopy_bdb
auycro/subversion
python
def check_hotcopy_bdb(src, dst): (exit_code, origout, origerr) = svntest.main.run_svnadmin('dump', src, '--quiet') (exit_code, backout, backerr) = svntest.main.run_svnadmin('dump', dst, '--quiet') if (origerr or backerr or (origout != backout)): raise svntest.Failure
def check_hotcopy_fsfs(src, dst): 'Verify that the SRC FSFS repository has been correctly copied to DST.' check_hotcopy_fsfs_fsx(src, dst)
7,227,668,457,595,708,000
Verify that the SRC FSFS repository has been correctly copied to DST.
subversion/tests/cmdline/svnadmin_tests.py
check_hotcopy_fsfs
auycro/subversion
python
def check_hotcopy_fsfs(src, dst): check_hotcopy_fsfs_fsx(src, dst)
def check_hotcopy_fsx(src, dst): 'Verify that the SRC FSX repository has been correctly copied to DST.' check_hotcopy_fsfs_fsx(src, dst)
-8,596,705,677,317,241,000
Verify that the SRC FSX repository has been correctly copied to DST.
subversion/tests/cmdline/svnadmin_tests.py
check_hotcopy_fsx
auycro/subversion
python
def check_hotcopy_fsx(src, dst): check_hotcopy_fsfs_fsx(src, dst)
def get_txns(repo_dir): "Get the txn names using 'svnadmin lstxns'." (exit_code, output_lines, error_lines) = svntest.main.run_svnadmin('lstxns', repo_dir) txns = sorted([output_lines.strip(x) for x in output_lines]) return txns
-3,156,529,327,218,749,400
Get the txn names using 'svnadmin lstxns'.
subversion/tests/cmdline/svnadmin_tests.py
get_txns
auycro/subversion
python
def get_txns(repo_dir): (exit_code, output_lines, error_lines) = svntest.main.run_svnadmin('lstxns', repo_dir) txns = sorted([output_lines.strip(x) for x in output_lines]) return txns
def patch_format(repo_dir, shard_size): 'Rewrite the format of the FSFS or FSX repository REPO_DIR so\n that it would use sharding with SHARDS revisions per shard.' format_path = os.path.join(repo_dir, 'db', 'format') contents = open(format_path, 'rb').read() processed_lines = [] for line in contents.split(b'\n'): if line.startswith(b'layout '): processed_lines.append(('layout sharded %d' % shard_size).encode()) else: processed_lines.append(line) new_contents = b'\n'.join(processed_lines) os.chmod(format_path, svntest.main.S_ALL_RW) with open(format_path, 'wb') as f: f.write(new_contents)
-8,632,408,334,853,087,000
Rewrite the format of the FSFS or FSX repository REPO_DIR so that it would use sharding with SHARDS revisions per shard.
subversion/tests/cmdline/svnadmin_tests.py
patch_format
auycro/subversion
python
def patch_format(repo_dir, shard_size): 'Rewrite the format of the FSFS or FSX repository REPO_DIR so\n that it would use sharding with SHARDS revisions per shard.' format_path = os.path.join(repo_dir, 'db', 'format') contents = open(format_path, 'rb').read() processed_lines = [] for line in contents.split(b'\n'): if line.startswith(b'layout '): processed_lines.append(('layout sharded %d' % shard_size).encode()) else: processed_lines.append(line) new_contents = b'\n'.join(processed_lines) os.chmod(format_path, svntest.main.S_ALL_RW) with open(format_path, 'wb') as f: f.write(new_contents)
def is_sharded(repo_dir): 'Return whether the FSFS repository REPO_DIR is sharded.' format_path = os.path.join(repo_dir, 'db', 'format') contents = open(format_path, 'rb').read() for line in contents.split(b'\n'): if line.startswith(b'layout sharded'): return True return False
2,815,214,373,564,014,000
Return whether the FSFS repository REPO_DIR is sharded.
subversion/tests/cmdline/svnadmin_tests.py
is_sharded
auycro/subversion
python
def is_sharded(repo_dir): format_path = os.path.join(repo_dir, 'db', 'format') contents = open(format_path, 'rb').read() for line in contents.split(b'\n'): if line.startswith(b'layout sharded'): return True return False
def load_and_verify_dumpstream(sbox, expected_stdout, expected_stderr, revs, check_props, dump, *varargs): "Load the array of lines passed in DUMP into the current tests'\n repository and verify the repository content using the array of\n wc.States passed in REVS. If CHECK_PROPS is True, check properties\n of each rev's items. VARARGS are optional arguments passed to the\n 'load' command." dump = svntest.main.ensure_list(dump) (exit_code, output, errput) = svntest.main.run_command_stdin(svntest.main.svnadmin_binary, expected_stderr, 0, True, dump, 'load', '--quiet', sbox.repo_dir, *varargs) if expected_stdout: if (expected_stdout is svntest.verify.AnyOutput): if (len(output) == 0): raise SVNExpectedStdout else: svntest.verify.compare_and_display_lines('Standard output', 'STDOUT:', expected_stdout, output) if expected_stderr: if (expected_stderr is svntest.verify.AnyOutput): if (len(errput) == 0): raise SVNExpectedStderr else: svntest.verify.compare_and_display_lines('Standard error output', 'STDERR:', expected_stderr, errput) return if revs: for rev in range(len(revs)): svntest.actions.run_and_verify_svn(svntest.verify.AnyOutput, [], 'update', ('-r%s' % (rev + 1)), sbox.wc_dir) rev_tree = revs[rev] svntest.actions.verify_disk(sbox.wc_dir, rev_tree, check_props)
3,705,490,436,728,118,300
Load the array of lines passed in DUMP into the current tests' repository and verify the repository content using the array of wc.States passed in REVS. If CHECK_PROPS is True, check properties of each rev's items. VARARGS are optional arguments passed to the 'load' command.
subversion/tests/cmdline/svnadmin_tests.py
load_and_verify_dumpstream
auycro/subversion
python
def load_and_verify_dumpstream(sbox, expected_stdout, expected_stderr, revs, check_props, dump, *varargs): "Load the array of lines passed in DUMP into the current tests'\n repository and verify the repository content using the array of\n wc.States passed in REVS. If CHECK_PROPS is True, check properties\n of each rev's items. VARARGS are optional arguments passed to the\n 'load' command." dump = svntest.main.ensure_list(dump) (exit_code, output, errput) = svntest.main.run_command_stdin(svntest.main.svnadmin_binary, expected_stderr, 0, True, dump, 'load', '--quiet', sbox.repo_dir, *varargs) if expected_stdout: if (expected_stdout is svntest.verify.AnyOutput): if (len(output) == 0): raise SVNExpectedStdout else: svntest.verify.compare_and_display_lines('Standard output', 'STDOUT:', expected_stdout, output) if expected_stderr: if (expected_stderr is svntest.verify.AnyOutput): if (len(errput) == 0): raise SVNExpectedStderr else: svntest.verify.compare_and_display_lines('Standard error output', 'STDERR:', expected_stderr, errput) return if revs: for rev in range(len(revs)): svntest.actions.run_and_verify_svn(svntest.verify.AnyOutput, [], 'update', ('-r%s' % (rev + 1)), sbox.wc_dir) rev_tree = revs[rev] svntest.actions.verify_disk(sbox.wc_dir, rev_tree, check_props)
def load_dumpstream(sbox, dump, *varargs): 'Load dump text without verification.' return load_and_verify_dumpstream(sbox, None, None, None, False, dump, *varargs)
1,622,666,709,462,919,000
Load dump text without verification.
subversion/tests/cmdline/svnadmin_tests.py
load_dumpstream
auycro/subversion
python
def load_dumpstream(sbox, dump, *varargs): return load_and_verify_dumpstream(sbox, None, None, None, False, dump, *varargs)
def repo_format(sbox): ' Return the repository format number for SBOX.' format_file = open(os.path.join(sbox.repo_dir, 'db', 'format')) format = int(format_file.read()[:1]) format_file.close() return format
7,572,120,876,088,850,000
Return the repository format number for SBOX.
subversion/tests/cmdline/svnadmin_tests.py
repo_format
auycro/subversion
python
def repo_format(sbox): ' ' format_file = open(os.path.join(sbox.repo_dir, 'db', 'format')) format = int(format_file.read()[:1]) format_file.close() return format
def set_changed_path_list(sbox, revision, changes): ' Replace the changed paths list in the revision file REVISION in SBOX\n with the text CHANGES.' idx = None fp = open(fsfs_file(sbox.repo_dir, 'revs', str(revision)), 'r+b') contents = fp.read() length = len(contents) if (repo_format(sbox) < 7): header = contents[contents.rfind(b'\n', (length - 64), (length - 1)):] body_len = int(header.split(b' ')[1]) else: footer_length = contents[(length - 1)] if isinstance(footer_length, str): footer_length = ord(footer_length) footer = contents[((length - footer_length) - 1):(length - 1)] l2p_offset = int(footer.split(b' ')[0]) l2p_checksum = footer.split(b' ')[1] p2l_offset = int(footer.split(b' ')[2]) p2l_checksum = footer.split(b' ')[3] idx = FSFS_Index(sbox, revision) (offset, item_len, item_type) = idx.get_item(1) body_len = offset indexes = contents[l2p_offset:((length - footer_length) - 1)] file_len = ((body_len + len(changes)) + 1) p2l_offset += (file_len - l2p_offset) header = ((((((str(file_len).encode() + b' ') + l2p_checksum) + b' ') + str(p2l_offset).encode()) + b' ') + p2l_checksum) header += bytes([len(header)]) header = ((b'\n' + indexes) + header) contents = ((contents[:body_len] + changes) + header) fp.seek(0) fp.write(contents) fp.truncate() fp.close() if (repo_format(sbox) >= 7): idx.modify_item(1, offset, (len(changes) + 1))
2,415,788,640,255,247,000
Replace the changed paths list in the revision file REVISION in SBOX with the text CHANGES.
subversion/tests/cmdline/svnadmin_tests.py
set_changed_path_list
auycro/subversion
python
def set_changed_path_list(sbox, revision, changes): ' Replace the changed paths list in the revision file REVISION in SBOX\n with the text CHANGES.' idx = None fp = open(fsfs_file(sbox.repo_dir, 'revs', str(revision)), 'r+b') contents = fp.read() length = len(contents) if (repo_format(sbox) < 7): header = contents[contents.rfind(b'\n', (length - 64), (length - 1)):] body_len = int(header.split(b' ')[1]) else: footer_length = contents[(length - 1)] if isinstance(footer_length, str): footer_length = ord(footer_length) footer = contents[((length - footer_length) - 1):(length - 1)] l2p_offset = int(footer.split(b' ')[0]) l2p_checksum = footer.split(b' ')[1] p2l_offset = int(footer.split(b' ')[2]) p2l_checksum = footer.split(b' ')[3] idx = FSFS_Index(sbox, revision) (offset, item_len, item_type) = idx.get_item(1) body_len = offset indexes = contents[l2p_offset:((length - footer_length) - 1)] file_len = ((body_len + len(changes)) + 1) p2l_offset += (file_len - l2p_offset) header = ((((((str(file_len).encode() + b' ') + l2p_checksum) + b' ') + str(p2l_offset).encode()) + b' ') + p2l_checksum) header += bytes([len(header)]) header = ((b'\n' + indexes) + header) contents = ((contents[:body_len] + changes) + header) fp.seek(0) fp.write(contents) fp.truncate() fp.close() if (repo_format(sbox) >= 7): idx.modify_item(1, offset, (len(changes) + 1))
def extra_headers(sbox): 'loading of dumpstream with extra headers' sbox.build(empty=True) dumpfile = clean_dumpfile() dumpfile[3:3] = [b'X-Comment-Header: Ignored header normally not in dump stream\n'] load_and_verify_dumpstream(sbox, [], [], dumpfile_revisions, False, dumpfile, '--ignore-uuid')
-3,325,078,735,295,992,000
loading of dumpstream with extra headers
subversion/tests/cmdline/svnadmin_tests.py
extra_headers
auycro/subversion
python
def extra_headers(sbox): sbox.build(empty=True) dumpfile = clean_dumpfile() dumpfile[3:3] = [b'X-Comment-Header: Ignored header normally not in dump stream\n'] load_and_verify_dumpstream(sbox, [], [], dumpfile_revisions, False, dumpfile, '--ignore-uuid')
def extra_blockcontent(sbox): 'load success on oversized Content-length' sbox.build(empty=True) dumpfile = clean_dumpfile() dumpfile[8:9] = [b'Extra-content-length: 10\n', b'Content-length: 108\n\n'] dumpfile[11] = (dumpfile[11][:(- 2)] + b'extra text\n\n\n') load_and_verify_dumpstream(sbox, [], [], dumpfile_revisions, False, dumpfile, '--ignore-uuid')
7,144,138,861,667,878,000
load success on oversized Content-length
subversion/tests/cmdline/svnadmin_tests.py
extra_blockcontent
auycro/subversion
python
def extra_blockcontent(sbox): sbox.build(empty=True) dumpfile = clean_dumpfile() dumpfile[8:9] = [b'Extra-content-length: 10\n', b'Content-length: 108\n\n'] dumpfile[11] = (dumpfile[11][:(- 2)] + b'extra text\n\n\n') load_and_verify_dumpstream(sbox, [], [], dumpfile_revisions, False, dumpfile, '--ignore-uuid')
def inconsistent_headers(sbox): 'load failure on undersized Content-length' sbox.build(empty=True) dumpfile = clean_dumpfile() dumpfile[(- 2)] = b'Content-length: 30\n\n' load_and_verify_dumpstream(sbox, [], svntest.verify.AnyOutput, dumpfile_revisions, False, dumpfile)
3,605,560,593,957,324,000
load failure on undersized Content-length
subversion/tests/cmdline/svnadmin_tests.py
inconsistent_headers
auycro/subversion
python
def inconsistent_headers(sbox): sbox.build(empty=True) dumpfile = clean_dumpfile() dumpfile[(- 2)] = b'Content-length: 30\n\n' load_and_verify_dumpstream(sbox, [], svntest.verify.AnyOutput, dumpfile_revisions, False, dumpfile)
@Issue(2729) def empty_date(sbox): 'preserve date-less revisions in load' sbox.build(empty=True) dumpfile = clean_dumpfile() dumpfile[7:11] = [b'Prop-content-length: 52\n', b'Content-length: 52\n\n', b'K 7\nsvn:log\nV 0\n\nK 10\nsvn:author\nV 4\nerik\nPROPS-END\n\n\n'] load_and_verify_dumpstream(sbox, [], [], dumpfile_revisions, False, dumpfile, '--ignore-uuid') svntest.actions.run_and_verify_svn([], '.*(E195011|E200017).*svn:date', 'propget', '--revprop', '-r1', 'svn:date', sbox.wc_dir)
7,059,030,812,455,790,000
preserve date-less revisions in load
subversion/tests/cmdline/svnadmin_tests.py
empty_date
auycro/subversion
python
@Issue(2729) def empty_date(sbox): sbox.build(empty=True) dumpfile = clean_dumpfile() dumpfile[7:11] = [b'Prop-content-length: 52\n', b'Content-length: 52\n\n', b'K 7\nsvn:log\nV 0\n\nK 10\nsvn:author\nV 4\nerik\nPROPS-END\n\n\n'] load_and_verify_dumpstream(sbox, [], [], dumpfile_revisions, False, dumpfile, '--ignore-uuid') svntest.actions.run_and_verify_svn([], '.*(E195011|E200017).*svn:date', 'propget', '--revprop', '-r1', 'svn:date', sbox.wc_dir)
def dump_copied_dir(sbox): "'svnadmin dump' on copied directory" sbox.build() wc_dir = sbox.wc_dir repo_dir = sbox.repo_dir old_C_path = os.path.join(wc_dir, 'A', 'C') new_C_path = os.path.join(wc_dir, 'A', 'B', 'C') svntest.main.run_svn(None, 'cp', old_C_path, new_C_path) sbox.simple_commit(message='log msg') (exit_code, output, errput) = svntest.main.run_svnadmin('dump', repo_dir) if svntest.verify.compare_and_display_lines("Output of 'svnadmin dump' is unexpected.", 'STDERR', ['* Dumped revision 0.\n', '* Dumped revision 1.\n', '* Dumped revision 2.\n'], errput): raise svntest.Failure
-1,576,102,342,841,974,500
'svnadmin dump' on copied directory
subversion/tests/cmdline/svnadmin_tests.py
dump_copied_dir
auycro/subversion
python
def dump_copied_dir(sbox): sbox.build() wc_dir = sbox.wc_dir repo_dir = sbox.repo_dir old_C_path = os.path.join(wc_dir, 'A', 'C') new_C_path = os.path.join(wc_dir, 'A', 'B', 'C') svntest.main.run_svn(None, 'cp', old_C_path, new_C_path) sbox.simple_commit(message='log msg') (exit_code, output, errput) = svntest.main.run_svnadmin('dump', repo_dir) if svntest.verify.compare_and_display_lines("Output of 'svnadmin dump' is unexpected.", 'STDERR', ['* Dumped revision 0.\n', '* Dumped revision 1.\n', '* Dumped revision 2.\n'], errput): raise svntest.Failure
def dump_move_dir_modify_child(sbox): "'svnadmin dump' on modified child of copied dir" sbox.build() wc_dir = sbox.wc_dir repo_dir = sbox.repo_dir B_path = os.path.join(wc_dir, 'A', 'B') Q_path = os.path.join(wc_dir, 'A', 'Q') svntest.main.run_svn(None, 'cp', B_path, Q_path) svntest.main.file_append(os.path.join(Q_path, 'lambda'), 'hello') sbox.simple_commit(message='log msg') (exit_code, output, errput) = svntest.main.run_svnadmin('dump', repo_dir) svntest.verify.compare_and_display_lines("Output of 'svnadmin dump' is unexpected.", 'STDERR', ['* Dumped revision 0.\n', '* Dumped revision 1.\n', '* Dumped revision 2.\n'], errput) (exit_code, output, errput) = svntest.main.run_svnadmin('dump', '-r', '0:HEAD', repo_dir) svntest.verify.compare_and_display_lines("Output of 'svnadmin dump' is unexpected.", 'STDERR', ['* Dumped revision 0.\n', '* Dumped revision 1.\n', '* Dumped revision 2.\n'], errput)
5,954,414,562,551,596,000
'svnadmin dump' on modified child of copied dir
subversion/tests/cmdline/svnadmin_tests.py
dump_move_dir_modify_child
auycro/subversion
python
def dump_move_dir_modify_child(sbox): sbox.build() wc_dir = sbox.wc_dir repo_dir = sbox.repo_dir B_path = os.path.join(wc_dir, 'A', 'B') Q_path = os.path.join(wc_dir, 'A', 'Q') svntest.main.run_svn(None, 'cp', B_path, Q_path) svntest.main.file_append(os.path.join(Q_path, 'lambda'), 'hello') sbox.simple_commit(message='log msg') (exit_code, output, errput) = svntest.main.run_svnadmin('dump', repo_dir) svntest.verify.compare_and_display_lines("Output of 'svnadmin dump' is unexpected.", 'STDERR', ['* Dumped revision 0.\n', '* Dumped revision 1.\n', '* Dumped revision 2.\n'], errput) (exit_code, output, errput) = svntest.main.run_svnadmin('dump', '-r', '0:HEAD', repo_dir) svntest.verify.compare_and_display_lines("Output of 'svnadmin dump' is unexpected.", 'STDERR', ['* Dumped revision 0.\n', '* Dumped revision 1.\n', '* Dumped revision 2.\n'], errput)
def dump_quiet(sbox): "'svnadmin dump --quiet'" sbox.build(create_wc=False) (exit_code, dump, errput) = svntest.main.run_svnadmin('dump', sbox.repo_dir, '--quiet') svntest.verify.compare_and_display_lines("Output of 'svnadmin dump --quiet' is unexpected.", 'STDERR', [], errput)
4,848,593,199,810,735,000
'svnadmin dump --quiet'
subversion/tests/cmdline/svnadmin_tests.py
dump_quiet
auycro/subversion
python
def dump_quiet(sbox): sbox.build(create_wc=False) (exit_code, dump, errput) = svntest.main.run_svnadmin('dump', sbox.repo_dir, '--quiet') svntest.verify.compare_and_display_lines("Output of is unexpected.", 'STDERR', [], errput)
def hotcopy_dot(sbox): "'svnadmin hotcopy PATH .'" sbox.build() (backup_dir, backup_url) = sbox.add_repo_path('backup') os.mkdir(backup_dir) cwd = os.getcwd() os.chdir(backup_dir) svntest.actions.run_and_verify_svnadmin(None, [], 'hotcopy', os.path.join(cwd, sbox.repo_dir), '.') os.chdir(cwd) if svntest.main.is_fs_type_fsfs(): check_hotcopy_fsfs(sbox.repo_dir, backup_dir) if svntest.main.is_fs_type_bdb(): check_hotcopy_bdb(sbox.repo_dir, backup_dir) if svntest.main.is_fs_type_fsx(): check_hotcopy_fsx(sbox.repo_dir, backup_dir)
-1,891,189,981,001,249,000
'svnadmin hotcopy PATH .'
subversion/tests/cmdline/svnadmin_tests.py
hotcopy_dot
auycro/subversion
python
def hotcopy_dot(sbox): sbox.build() (backup_dir, backup_url) = sbox.add_repo_path('backup') os.mkdir(backup_dir) cwd = os.getcwd() os.chdir(backup_dir) svntest.actions.run_and_verify_svnadmin(None, [], 'hotcopy', os.path.join(cwd, sbox.repo_dir), '.') os.chdir(cwd) if svntest.main.is_fs_type_fsfs(): check_hotcopy_fsfs(sbox.repo_dir, backup_dir) if svntest.main.is_fs_type_bdb(): check_hotcopy_bdb(sbox.repo_dir, backup_dir) if svntest.main.is_fs_type_fsx(): check_hotcopy_fsx(sbox.repo_dir, backup_dir)
@SkipUnless(svntest.main.is_fs_type_bdb) def hotcopy_format(sbox): "'svnadmin hotcopy' checking db/format file" sbox.build() (backup_dir, backup_url) = sbox.add_repo_path('backup') (exit_code, output, errput) = svntest.main.run_svnadmin('hotcopy', sbox.repo_dir, backup_dir) if errput: logger.warn('Error: hotcopy failed') raise svntest.Failure fp = open(os.path.join(sbox.repo_dir, 'db', 'format')) contents1 = fp.read() fp.close() fp2 = open(os.path.join(backup_dir, 'db', 'format')) contents2 = fp2.read() fp2.close() if (contents1 != contents2): logger.warn('Error: db/format file contents do not match after hotcopy') raise svntest.Failure
-7,783,969,956,639,117,000
'svnadmin hotcopy' checking db/format file
subversion/tests/cmdline/svnadmin_tests.py
hotcopy_format
auycro/subversion
python
@SkipUnless(svntest.main.is_fs_type_bdb) def hotcopy_format(sbox): sbox.build() (backup_dir, backup_url) = sbox.add_repo_path('backup') (exit_code, output, errput) = svntest.main.run_svnadmin('hotcopy', sbox.repo_dir, backup_dir) if errput: logger.warn('Error: hotcopy failed') raise svntest.Failure fp = open(os.path.join(sbox.repo_dir, 'db', 'format')) contents1 = fp.read() fp.close() fp2 = open(os.path.join(backup_dir, 'db', 'format')) contents2 = fp2.read() fp2.close() if (contents1 != contents2): logger.warn('Error: db/format file contents do not match after hotcopy') raise svntest.Failure
def setrevprop(sbox): 'setlog, setrevprop, delrevprop; bypass hooks' sbox.build() iota_path = os.path.join(sbox.wc_dir, 'iota') mu_path = sbox.ospath('A/mu') svntest.actions.run_and_verify_svnadmin([], [], 'setlog', sbox.repo_dir, '-r0', '--bypass-hooks', iota_path) svntest.actions.run_and_verify_svnadmin([], svntest.verify.AnyOutput, 'setlog', sbox.repo_dir, '-r0', mu_path) svntest.actions.run_and_verify_svn(["This is the file 'iota'.\n", '\n'], [], 'propget', '--revprop', '-r0', 'svn:log', sbox.wc_dir) foo_path = os.path.join(sbox.wc_dir, 'foo') svntest.main.file_write(foo_path, 'foo') (exit_code, output, errput) = svntest.main.run_svnadmin('setrevprop', sbox.repo_dir, '-r0', 'svn:author', foo_path) if errput: logger.warn("Error: 'setrevprop' failed") raise svntest.Failure svntest.actions.run_and_verify_svn(['foo\n'], [], 'propget', '--revprop', '-r0', 'svn:author', sbox.wc_dir) svntest.actions.run_and_verify_svnadmin([], [], 'delrevprop', '-r0', sbox.repo_dir, 'svn:author') svntest.actions.run_and_verify_svnlook([], '.*E200017.*svn:author.*', 'propget', '--revprop', '-r0', sbox.repo_dir, 'svn:author')
-2,575,452,230,689,988,600
setlog, setrevprop, delrevprop; bypass hooks
subversion/tests/cmdline/svnadmin_tests.py
setrevprop
auycro/subversion
python
def setrevprop(sbox): sbox.build() iota_path = os.path.join(sbox.wc_dir, 'iota') mu_path = sbox.ospath('A/mu') svntest.actions.run_and_verify_svnadmin([], [], 'setlog', sbox.repo_dir, '-r0', '--bypass-hooks', iota_path) svntest.actions.run_and_verify_svnadmin([], svntest.verify.AnyOutput, 'setlog', sbox.repo_dir, '-r0', mu_path) svntest.actions.run_and_verify_svn(["This is the file 'iota'.\n", '\n'], [], 'propget', '--revprop', '-r0', 'svn:log', sbox.wc_dir) foo_path = os.path.join(sbox.wc_dir, 'foo') svntest.main.file_write(foo_path, 'foo') (exit_code, output, errput) = svntest.main.run_svnadmin('setrevprop', sbox.repo_dir, '-r0', 'svn:author', foo_path) if errput: logger.warn("Error: 'setrevprop' failed") raise svntest.Failure svntest.actions.run_and_verify_svn(['foo\n'], [], 'propget', '--revprop', '-r0', 'svn:author', sbox.wc_dir) svntest.actions.run_and_verify_svnadmin([], [], 'delrevprop', '-r0', sbox.repo_dir, 'svn:author') svntest.actions.run_and_verify_svnlook([], '.*E200017.*svn:author.*', 'propget', '--revprop', '-r0', sbox.repo_dir, 'svn:author')
def verify_windows_paths_in_repos(sbox): "verify a repository containing paths like 'c:hi'" sbox.build(create_wc=False) repo_url = sbox.repo_url chi_url = (sbox.repo_url + '/c:hi') svntest.actions.run_and_verify_svn(None, [], 'mkdir', '-m', 'log_msg', chi_url) (exit_code, output, errput) = svntest.main.run_svnadmin('verify', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) if svntest.main.is_fs_log_addressing(): svntest.verify.compare_and_display_lines("Error while running 'svnadmin verify'.", 'STDOUT', ['* Verifying metadata at revision 0 ...\n', '* Verifying repository metadata ...\n', '* Verified revision 0.\n', '* Verified revision 1.\n', '* Verified revision 2.\n'], output) elif (svntest.main.fs_has_rep_sharing() and (not svntest.main.is_fs_type_bdb())): svntest.verify.compare_and_display_lines("Error while running 'svnadmin verify'.", 'STDOUT', ['* Verifying repository metadata ...\n', '* Verified revision 0.\n', '* Verified revision 1.\n', '* Verified revision 2.\n'], output) else: svntest.verify.compare_and_display_lines("Error while running 'svnadmin verify'.", 'STDOUT', ['* Verified revision 0.\n', '* Verified revision 1.\n', '* Verified revision 2.\n'], output)
2,949,465,227,462,650,400
verify a repository containing paths like 'c:hi'
subversion/tests/cmdline/svnadmin_tests.py
verify_windows_paths_in_repos
auycro/subversion
python
def verify_windows_paths_in_repos(sbox): sbox.build(create_wc=False) repo_url = sbox.repo_url chi_url = (sbox.repo_url + '/c:hi') svntest.actions.run_and_verify_svn(None, [], 'mkdir', '-m', 'log_msg', chi_url) (exit_code, output, errput) = svntest.main.run_svnadmin('verify', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) if svntest.main.is_fs_log_addressing(): svntest.verify.compare_and_display_lines("Error while running 'svnadmin verify'.", 'STDOUT', ['* Verifying metadata at revision 0 ...\n', '* Verifying repository metadata ...\n', '* Verified revision 0.\n', '* Verified revision 1.\n', '* Verified revision 2.\n'], output) elif (svntest.main.fs_has_rep_sharing() and (not svntest.main.is_fs_type_bdb())): svntest.verify.compare_and_display_lines("Error while running 'svnadmin verify'.", 'STDOUT', ['* Verifying repository metadata ...\n', '* Verified revision 0.\n', '* Verified revision 1.\n', '* Verified revision 2.\n'], output) else: svntest.verify.compare_and_display_lines("Error while running 'svnadmin verify'.", 'STDOUT', ['* Verified revision 0.\n', '* Verified revision 1.\n', '* Verified revision 2.\n'], output)
@SkipUnless(svntest.main.is_fs_type_fsfs) def verify_incremental_fsfs(sbox): "svnadmin verify detects corruption dump can't" if ((svntest.main.options.fsfs_version is not None) and (svntest.main.options.fsfs_version not in [4, 6])): raise svntest.Skip('Unsupported prepackaged repository version') sbox.build(create_wc=False, minor_version=min(svntest.main.options.server_minor_version, 8)) repo_url = sbox.repo_url E_url = (sbox.repo_url + '/A/B/E') svntest.actions.run_and_verify_svn(None, [], 'mkdir', '-m', 'log_msg', (E_url + '/bravo')) r2 = fsfs_file(sbox.repo_dir, 'revs', '2') if r2.endswith('pack'): raise svntest.Skip("Test doesn't handle packed revisions") fp = open(r2, 'wb') fp.write(b'id: 0-2.0.r2/0\ntype: dir\ncount: 0\ncpath: /A/B/E/bravo\ncopyroot: 0 /\n\nPLAIN\nK 5\nalpha\nV 17\nfile 3-1.0.r1/719\nK 4\nbeta\nV 17\nfile 4-1.0.r1/840\nK 5\nbravo\nV 14\ndir 0-2.0.r2/0\nEND\nENDREP\nid: 2-1.0.r2/181\ntype: dir\npred: 2-1.0.r1/1043\ncount: 1\ntext: 2 69 99 99 f63001f7fddd1842d8891474d0982111\ncpath: /A/B/E\ncopyroot: 0 /\n\nPLAIN\nK 1\nE\nV 16\ndir 2-1.0.r2/181\nK 1\nF\nV 17\ndir 5-1.0.r1/1160\nK 6\nlambda\nV 17\nfile 6-1.0.r1/597\nEND\nENDREP\nid: 1-1.0.r2/424\ntype: dir\npred: 1-1.0.r1/1335\ncount: 1\ntext: 2 316 95 95 bccb66379b4f825dac12b50d80211bae\ncpath: /A/B\ncopyroot: 0 /\n\nPLAIN\nK 1\nB\nV 16\ndir 1-1.0.r2/424\nK 1\nC\nV 17\ndir 7-1.0.r1/1569\nK 1\nD\nV 17\ndir 8-1.0.r1/3061\nK 2\nmu\nV 18\nfile i-1.0.r1/1451\nEND\nENDREP\nid: 0-1.0.r2/692\ntype: dir\npred: 0-1.0.r1/3312\ncount: 1\ntext: 2 558 121 121 c9b5a2d26473a4e28088673dda9df804\ncpath: /A\ncopyroot: 0 /\n\nPLAIN\nK 1\nA\nV 16\ndir 0-1.0.r2/692\nK 4\niota\nV 18\nfile j-1.0.r1/3428\nEND\nENDREP\nid: 0.0.r2/904\ntype: dir\npred: 0.0.r1/3624\ncount: 2\ntext: 2 826 65 65 e44e4151d0d124533338619f082c8c9a\ncpath: /\ncopyroot: 0 /\n\n_0.0.t1-1 add false false /A/B/E/bravo\n\n\n904 1031\n') fp.close() (exit_code, output, errput) = svntest.main.run_svnadmin('verify', '-r2', sbox.repo_dir) svntest.verify.verify_outputs(message=None, actual_stdout=output, actual_stderr=errput, expected_stdout=None, expected_stderr=".*Found malformed header '[^']*' in revision file|.*Missing id field in node-rev.*")
-5,360,502,733,076,162,000
svnadmin verify detects corruption dump can't
subversion/tests/cmdline/svnadmin_tests.py
verify_incremental_fsfs
auycro/subversion
python
@SkipUnless(svntest.main.is_fs_type_fsfs) def verify_incremental_fsfs(sbox): if ((svntest.main.options.fsfs_version is not None) and (svntest.main.options.fsfs_version not in [4, 6])): raise svntest.Skip('Unsupported prepackaged repository version') sbox.build(create_wc=False, minor_version=min(svntest.main.options.server_minor_version, 8)) repo_url = sbox.repo_url E_url = (sbox.repo_url + '/A/B/E') svntest.actions.run_and_verify_svn(None, [], 'mkdir', '-m', 'log_msg', (E_url + '/bravo')) r2 = fsfs_file(sbox.repo_dir, 'revs', '2') if r2.endswith('pack'): raise svntest.Skip("Test doesn't handle packed revisions") fp = open(r2, 'wb') fp.write(b'id: 0-2.0.r2/0\ntype: dir\ncount: 0\ncpath: /A/B/E/bravo\ncopyroot: 0 /\n\nPLAIN\nK 5\nalpha\nV 17\nfile 3-1.0.r1/719\nK 4\nbeta\nV 17\nfile 4-1.0.r1/840\nK 5\nbravo\nV 14\ndir 0-2.0.r2/0\nEND\nENDREP\nid: 2-1.0.r2/181\ntype: dir\npred: 2-1.0.r1/1043\ncount: 1\ntext: 2 69 99 99 f63001f7fddd1842d8891474d0982111\ncpath: /A/B/E\ncopyroot: 0 /\n\nPLAIN\nK 1\nE\nV 16\ndir 2-1.0.r2/181\nK 1\nF\nV 17\ndir 5-1.0.r1/1160\nK 6\nlambda\nV 17\nfile 6-1.0.r1/597\nEND\nENDREP\nid: 1-1.0.r2/424\ntype: dir\npred: 1-1.0.r1/1335\ncount: 1\ntext: 2 316 95 95 bccb66379b4f825dac12b50d80211bae\ncpath: /A/B\ncopyroot: 0 /\n\nPLAIN\nK 1\nB\nV 16\ndir 1-1.0.r2/424\nK 1\nC\nV 17\ndir 7-1.0.r1/1569\nK 1\nD\nV 17\ndir 8-1.0.r1/3061\nK 2\nmu\nV 18\nfile i-1.0.r1/1451\nEND\nENDREP\nid: 0-1.0.r2/692\ntype: dir\npred: 0-1.0.r1/3312\ncount: 1\ntext: 2 558 121 121 c9b5a2d26473a4e28088673dda9df804\ncpath: /A\ncopyroot: 0 /\n\nPLAIN\nK 1\nA\nV 16\ndir 0-1.0.r2/692\nK 4\niota\nV 18\nfile j-1.0.r1/3428\nEND\nENDREP\nid: 0.0.r2/904\ntype: dir\npred: 0.0.r1/3624\ncount: 2\ntext: 2 826 65 65 e44e4151d0d124533338619f082c8c9a\ncpath: /\ncopyroot: 0 /\n\n_0.0.t1-1 add false false /A/B/E/bravo\n\n\n904 1031\n') fp.close() (exit_code, output, errput) = svntest.main.run_svnadmin('verify', '-r2', sbox.repo_dir) svntest.verify.verify_outputs(message=None, actual_stdout=output, actual_stderr=errput, expected_stdout=None, expected_stderr=".*Found malformed header '[^']*' in revision file|.*Missing id field in node-rev.*")
def corrupt_and_recover_db_current(sbox, minor_version=None): 'Build up a MINOR_VERSION sandbox and test different recovery scenarios\n with missing, out-of-date or even corrupt db/current files. Recovery should\n behave the same way with all values of MINOR_VERSION, hence this helper\n containing the common code that allows us to check it.' sbox.build(minor_version=minor_version) current_path = os.path.join(sbox.repo_dir, 'db', 'current') svntest.main.file_append(os.path.join(sbox.wc_dir, 'iota'), 'newer line\n') sbox.simple_commit(message='log msg') svntest.main.file_append(os.path.join(sbox.wc_dir, 'iota'), 'newest line\n') sbox.simple_commit(message='log msg') expected_current_contents = open(current_path).read() os.rename(os.path.join(sbox.repo_dir, 'db', 'current'), os.path.join(sbox.repo_dir, 'db', 'was_current')) (exit_code, output, errput) = svntest.main.run_svnadmin('recover', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) actual_current_contents = open(current_path).read() svntest.verify.compare_and_display_lines('Contents of db/current is unexpected.', 'db/current', expected_current_contents, actual_current_contents) svntest.main.file_write(current_path, '2\n') (exit_code, output, errput) = svntest.main.run_svnadmin('recover', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) actual_current_contents = open(current_path).read() svntest.verify.compare_and_display_lines('Contents of db/current is unexpected.', 'db/current', expected_current_contents, actual_current_contents) svntest.main.file_write(current_path, '1\n') (exit_code, output, errput) = svntest.main.run_svnadmin('recover', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) actual_current_contents = open(current_path).read() svntest.verify.compare_and_display_lines('Contents of db/current is unexpected.', 'db/current', expected_current_contents, actual_current_contents) svntest.main.file_write(current_path, 'fish\n') (exit_code, output, errput) = svntest.main.run_svnadmin('recover', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) actual_current_contents = open(current_path).read() svntest.verify.compare_and_display_lines('Contents of db/current is unexpected.', 'db/current', expected_current_contents, actual_current_contents)
-5,489,307,536,718,855,000
Build up a MINOR_VERSION sandbox and test different recovery scenarios with missing, out-of-date or even corrupt db/current files. Recovery should behave the same way with all values of MINOR_VERSION, hence this helper containing the common code that allows us to check it.
subversion/tests/cmdline/svnadmin_tests.py
corrupt_and_recover_db_current
auycro/subversion
python
def corrupt_and_recover_db_current(sbox, minor_version=None): 'Build up a MINOR_VERSION sandbox and test different recovery scenarios\n with missing, out-of-date or even corrupt db/current files. Recovery should\n behave the same way with all values of MINOR_VERSION, hence this helper\n containing the common code that allows us to check it.' sbox.build(minor_version=minor_version) current_path = os.path.join(sbox.repo_dir, 'db', 'current') svntest.main.file_append(os.path.join(sbox.wc_dir, 'iota'), 'newer line\n') sbox.simple_commit(message='log msg') svntest.main.file_append(os.path.join(sbox.wc_dir, 'iota'), 'newest line\n') sbox.simple_commit(message='log msg') expected_current_contents = open(current_path).read() os.rename(os.path.join(sbox.repo_dir, 'db', 'current'), os.path.join(sbox.repo_dir, 'db', 'was_current')) (exit_code, output, errput) = svntest.main.run_svnadmin('recover', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) actual_current_contents = open(current_path).read() svntest.verify.compare_and_display_lines('Contents of db/current is unexpected.', 'db/current', expected_current_contents, actual_current_contents) svntest.main.file_write(current_path, '2\n') (exit_code, output, errput) = svntest.main.run_svnadmin('recover', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) actual_current_contents = open(current_path).read() svntest.verify.compare_and_display_lines('Contents of db/current is unexpected.', 'db/current', expected_current_contents, actual_current_contents) svntest.main.file_write(current_path, '1\n') (exit_code, output, errput) = svntest.main.run_svnadmin('recover', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) actual_current_contents = open(current_path).read() svntest.verify.compare_and_display_lines('Contents of db/current is unexpected.', 'db/current', expected_current_contents, actual_current_contents) svntest.main.file_write(current_path, 'fish\n') (exit_code, output, errput) = svntest.main.run_svnadmin('recover', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) actual_current_contents = open(current_path).read() svntest.verify.compare_and_display_lines('Contents of db/current is unexpected.', 'db/current', expected_current_contents, actual_current_contents)
@SkipUnless(svntest.main.is_fs_type_fsfs) def fsfs_recover_db_current(sbox): 'fsfs recover db/current' corrupt_and_recover_db_current(sbox)
6,653,498,663,699,317,000
fsfs recover db/current
subversion/tests/cmdline/svnadmin_tests.py
fsfs_recover_db_current
auycro/subversion
python
@SkipUnless(svntest.main.is_fs_type_fsfs) def fsfs_recover_db_current(sbox): corrupt_and_recover_db_current(sbox)
@SkipUnless(svntest.main.is_fs_type_fsfs) def fsfs_recover_old_db_current(sbox): 'fsfs recover db/current --compatible-version=1.3' corrupt_and_recover_db_current(sbox, minor_version=3)
-916,117,988,128,732,800
fsfs recover db/current --compatible-version=1.3
subversion/tests/cmdline/svnadmin_tests.py
fsfs_recover_old_db_current
auycro/subversion
python
@SkipUnless(svntest.main.is_fs_type_fsfs) def fsfs_recover_old_db_current(sbox): corrupt_and_recover_db_current(sbox, minor_version=3)
@Issue(2983) def load_with_parent_dir(sbox): "'svnadmin load --parent-dir' reparents mergeinfo" sbox.build(empty=True) dumpfile_location = os.path.join(os.path.dirname(sys.argv[0]), 'svnadmin_tests_data', 'mergeinfo_included.dump') dumpfile = svntest.actions.load_dumpfile(dumpfile_location) svntest.actions.run_and_verify_svn(['Committing transaction...\n', 'Committed revision 1.\n'], [], 'mkdir', (sbox.repo_url + '/sample'), '-m', 'Create sample dir') load_dumpstream(sbox, dumpfile, '--parent-dir', '/sample') svntest.actions.run_and_verify_svn([(sbox.repo_url + '/sample/branch - /sample/trunk:5-7\n')], [], 'propget', 'svn:mergeinfo', '-R', (sbox.repo_url + '/sample/branch')) svntest.actions.run_and_verify_svn([((sbox.repo_url + '/sample/branch1 - ') + '/sample/branch:6-9\n')], [], 'propget', 'svn:mergeinfo', '-R', (sbox.repo_url + '/sample/branch1')) svntest.actions.run_and_verify_svn(['Committing transaction...\n', 'Committed revision 11.\n'], [], 'mkdir', (sbox.repo_url + '/sample-2'), '-m', 'Create sample-2 dir') load_dumpstream(sbox, dumpfile, '--parent-dir', 'sample-2') svntest.actions.run_and_verify_svn([((sbox.repo_url + '/sample-2/branch - ') + '/sample-2/trunk:15-17\n')], [], 'propget', 'svn:mergeinfo', '-R', (sbox.repo_url + '/sample-2/branch')) svntest.actions.run_and_verify_svn([((sbox.repo_url + '/sample-2/branch1 - ') + '/sample-2/branch:16-19\n')], [], 'propget', 'svn:mergeinfo', '-R', (sbox.repo_url + '/sample-2/branch1'))
4,298,635,654,713,536,500
'svnadmin load --parent-dir' reparents mergeinfo
subversion/tests/cmdline/svnadmin_tests.py
load_with_parent_dir
auycro/subversion
python
@Issue(2983) def load_with_parent_dir(sbox): sbox.build(empty=True) dumpfile_location = os.path.join(os.path.dirname(sys.argv[0]), 'svnadmin_tests_data', 'mergeinfo_included.dump') dumpfile = svntest.actions.load_dumpfile(dumpfile_location) svntest.actions.run_and_verify_svn(['Committing transaction...\n', 'Committed revision 1.\n'], [], 'mkdir', (sbox.repo_url + '/sample'), '-m', 'Create sample dir') load_dumpstream(sbox, dumpfile, '--parent-dir', '/sample') svntest.actions.run_and_verify_svn([(sbox.repo_url + '/sample/branch - /sample/trunk:5-7\n')], [], 'propget', 'svn:mergeinfo', '-R', (sbox.repo_url + '/sample/branch')) svntest.actions.run_and_verify_svn([((sbox.repo_url + '/sample/branch1 - ') + '/sample/branch:6-9\n')], [], 'propget', 'svn:mergeinfo', '-R', (sbox.repo_url + '/sample/branch1')) svntest.actions.run_and_verify_svn(['Committing transaction...\n', 'Committed revision 11.\n'], [], 'mkdir', (sbox.repo_url + '/sample-2'), '-m', 'Create sample-2 dir') load_dumpstream(sbox, dumpfile, '--parent-dir', 'sample-2') svntest.actions.run_and_verify_svn([((sbox.repo_url + '/sample-2/branch - ') + '/sample-2/trunk:15-17\n')], [], 'propget', 'svn:mergeinfo', '-R', (sbox.repo_url + '/sample-2/branch')) svntest.actions.run_and_verify_svn([((sbox.repo_url + '/sample-2/branch1 - ') + '/sample-2/branch:16-19\n')], [], 'propget', 'svn:mergeinfo', '-R', (sbox.repo_url + '/sample-2/branch1'))
def set_uuid(sbox): "test 'svnadmin setuuid'" sbox.build(create_wc=False) (exit_code, output, errput) = svntest.main.run_svnlook('uuid', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) orig_uuid = output[0].rstrip() svntest.actions.run_and_verify_svnadmin(None, '^.*Malformed UUID.*$', 'setuuid', sbox.repo_dir, 'abcdef') svntest.actions.run_and_verify_svnadmin([], None, 'setuuid', sbox.repo_dir) (exit_code, output, errput) = svntest.main.run_svnlook('uuid', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) new_uuid = output[0].rstrip() if (new_uuid == orig_uuid): logger.warn('Error: new UUID matches the original one') raise svntest.Failure svntest.actions.run_and_verify_svnadmin([], None, 'setuuid', sbox.repo_dir, orig_uuid) (exit_code, output, errput) = svntest.main.run_svnlook('uuid', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) new_uuid = output[0].rstrip() if (new_uuid != orig_uuid): logger.warn("Error: new UUID doesn't match the original one") raise svntest.Failure
-8,573,023,354,052,229,000
test 'svnadmin setuuid'
subversion/tests/cmdline/svnadmin_tests.py
set_uuid
auycro/subversion
python
def set_uuid(sbox): sbox.build(create_wc=False) (exit_code, output, errput) = svntest.main.run_svnlook('uuid', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) orig_uuid = output[0].rstrip() svntest.actions.run_and_verify_svnadmin(None, '^.*Malformed UUID.*$', 'setuuid', sbox.repo_dir, 'abcdef') svntest.actions.run_and_verify_svnadmin([], None, 'setuuid', sbox.repo_dir) (exit_code, output, errput) = svntest.main.run_svnlook('uuid', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) new_uuid = output[0].rstrip() if (new_uuid == orig_uuid): logger.warn('Error: new UUID matches the original one') raise svntest.Failure svntest.actions.run_and_verify_svnadmin([], None, 'setuuid', sbox.repo_dir, orig_uuid) (exit_code, output, errput) = svntest.main.run_svnlook('uuid', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) new_uuid = output[0].rstrip() if (new_uuid != orig_uuid): logger.warn("Error: new UUID doesn't match the original one") raise svntest.Failure
@Issue(3020) def reflect_dropped_renumbered_revs(sbox): 'reflect dropped renumbered revs in svn:mergeinfo' sbox.build(empty=True) dumpfile_location = os.path.join(os.path.dirname(sys.argv[0]), 'svndumpfilter_tests_data', 'with_merges.dump') dumpfile = svntest.actions.load_dumpfile(dumpfile_location) svntest.actions.run_and_verify_svn(['Committing transaction...\n', 'Committed revision 1.\n'], [], 'mkdir', (sbox.repo_url + '/toplevel'), '-m', 'Create toplevel dir') load_dumpstream(sbox, dumpfile) load_dumpstream(sbox, dumpfile, '--parent-dir', '/toplevel') url = sbox.repo_url expected_output = svntest.verify.UnorderedOutput([(url + '/trunk - /branch1:5-9\n'), (url + '/toplevel/trunk - /toplevel/branch1:14-18\n')]) svntest.actions.run_and_verify_svn(expected_output, [], 'propget', 'svn:mergeinfo', '-R', sbox.repo_url)
-3,383,642,271,943,255,600
reflect dropped renumbered revs in svn:mergeinfo
subversion/tests/cmdline/svnadmin_tests.py
reflect_dropped_renumbered_revs
auycro/subversion
python
@Issue(3020) def reflect_dropped_renumbered_revs(sbox): sbox.build(empty=True) dumpfile_location = os.path.join(os.path.dirname(sys.argv[0]), 'svndumpfilter_tests_data', 'with_merges.dump') dumpfile = svntest.actions.load_dumpfile(dumpfile_location) svntest.actions.run_and_verify_svn(['Committing transaction...\n', 'Committed revision 1.\n'], [], 'mkdir', (sbox.repo_url + '/toplevel'), '-m', 'Create toplevel dir') load_dumpstream(sbox, dumpfile) load_dumpstream(sbox, dumpfile, '--parent-dir', '/toplevel') url = sbox.repo_url expected_output = svntest.verify.UnorderedOutput([(url + '/trunk - /branch1:5-9\n'), (url + '/toplevel/trunk - /toplevel/branch1:14-18\n')]) svntest.actions.run_and_verify_svn(expected_output, [], 'propget', 'svn:mergeinfo', '-R', sbox.repo_url)
@SkipUnless(svntest.main.is_fs_type_fsfs) @Issue(2992) def fsfs_recover_handle_missing_revs_or_revprops_file(sbox): 'fsfs recovery checks missing revs / revprops files' sbox.build() svntest.main.file_append(os.path.join(sbox.wc_dir, 'iota'), 'newer line\n') sbox.simple_commit(message='log msg') svntest.main.file_append(os.path.join(sbox.wc_dir, 'iota'), 'newest line\n') sbox.simple_commit(message='log msg') rev_3 = fsfs_file(sbox.repo_dir, 'revs', '3') rev_was_3 = (rev_3 + '.was') os.rename(rev_3, rev_was_3) (exit_code, output, errput) = svntest.main.run_svnadmin('recover', sbox.repo_dir) if svntest.verify.verify_outputs("Output of 'svnadmin recover' is unexpected.", None, errput, None, ('.*Expected current rev to be <= %s but found 3' % ((rev_3.endswith('pack') and '[012]') or '2'))): raise svntest.Failure os.rename(rev_was_3, rev_3) revprop_3 = fsfs_file(sbox.repo_dir, 'revprops', '3') revprop_was_3 = (revprop_3 + '.was') os.rename(revprop_3, revprop_was_3) (exit_code, output, errput) = svntest.main.run_svnadmin('recover', sbox.repo_dir) if svntest.verify.verify_outputs("Output of 'svnadmin recover' is unexpected.", None, errput, None, '.*Revision 3 has a revs file but no revprops file'): raise svntest.Failure os.rename(revprop_was_3, revprop_3) os.rename(revprop_3, revprop_was_3) os.mkdir(revprop_3) (exit_code, output, errput) = svntest.main.run_svnadmin('recover', sbox.repo_dir) if svntest.verify.verify_outputs("Output of 'svnadmin recover' is unexpected.", None, errput, None, '.*Revision 3 has a non-file where its revprops file should be.*'): raise svntest.Failure os.rmdir(revprop_3) os.rename(revprop_was_3, revprop_3)
-6,091,200,778,968,647,000
fsfs recovery checks missing revs / revprops files
subversion/tests/cmdline/svnadmin_tests.py
fsfs_recover_handle_missing_revs_or_revprops_file
auycro/subversion
python
@SkipUnless(svntest.main.is_fs_type_fsfs) @Issue(2992) def fsfs_recover_handle_missing_revs_or_revprops_file(sbox): sbox.build() svntest.main.file_append(os.path.join(sbox.wc_dir, 'iota'), 'newer line\n') sbox.simple_commit(message='log msg') svntest.main.file_append(os.path.join(sbox.wc_dir, 'iota'), 'newest line\n') sbox.simple_commit(message='log msg') rev_3 = fsfs_file(sbox.repo_dir, 'revs', '3') rev_was_3 = (rev_3 + '.was') os.rename(rev_3, rev_was_3) (exit_code, output, errput) = svntest.main.run_svnadmin('recover', sbox.repo_dir) if svntest.verify.verify_outputs("Output of 'svnadmin recover' is unexpected.", None, errput, None, ('.*Expected current rev to be <= %s but found 3' % ((rev_3.endswith('pack') and '[012]') or '2'))): raise svntest.Failure os.rename(rev_was_3, rev_3) revprop_3 = fsfs_file(sbox.repo_dir, 'revprops', '3') revprop_was_3 = (revprop_3 + '.was') os.rename(revprop_3, revprop_was_3) (exit_code, output, errput) = svntest.main.run_svnadmin('recover', sbox.repo_dir) if svntest.verify.verify_outputs("Output of 'svnadmin recover' is unexpected.", None, errput, None, '.*Revision 3 has a revs file but no revprops file'): raise svntest.Failure os.rename(revprop_was_3, revprop_3) os.rename(revprop_3, revprop_was_3) os.mkdir(revprop_3) (exit_code, output, errput) = svntest.main.run_svnadmin('recover', sbox.repo_dir) if svntest.verify.verify_outputs("Output of 'svnadmin recover' is unexpected.", None, errput, None, '.*Revision 3 has a non-file where its revprops file should be.*'): raise svntest.Failure os.rmdir(revprop_3) os.rename(revprop_was_3, revprop_3)
@Skip(svntest.main.tests_use_prepackaged_repository) def create_in_repo_subdir(sbox): "'svnadmin create /path/to/repo/subdir'" sbox.build(create_wc=False, empty=True) repo_dir = sbox.repo_dir success = False try: subdir = os.path.join(repo_dir, 'Z') svntest.main.create_repos(subdir) except svntest.main.SVNRepositoryCreateFailure: success = True if (not success): raise svntest.Failure cwd = os.getcwd() success = False try: subdir = os.path.join(repo_dir, 'conf') os.chdir(subdir) svntest.main.create_repos('Z') os.chdir(cwd) except svntest.main.SVNRepositoryCreateFailure: success = True os.chdir(cwd) if (not success): raise svntest.Failure
-2,152,694,088,011,055,000
'svnadmin create /path/to/repo/subdir'
subversion/tests/cmdline/svnadmin_tests.py
create_in_repo_subdir
auycro/subversion
python
@Skip(svntest.main.tests_use_prepackaged_repository) def create_in_repo_subdir(sbox): sbox.build(create_wc=False, empty=True) repo_dir = sbox.repo_dir success = False try: subdir = os.path.join(repo_dir, 'Z') svntest.main.create_repos(subdir) except svntest.main.SVNRepositoryCreateFailure: success = True if (not success): raise svntest.Failure cwd = os.getcwd() success = False try: subdir = os.path.join(repo_dir, 'conf') os.chdir(subdir) svntest.main.create_repos('Z') os.chdir(cwd) except svntest.main.SVNRepositoryCreateFailure: success = True os.chdir(cwd) if (not success): raise svntest.Failure
@SkipUnless(svntest.main.is_fs_type_fsfs) @SkipDumpLoadCrossCheck() def verify_with_invalid_revprops(sbox): 'svnadmin verify detects invalid revprops file' sbox.build(create_wc=False, empty=True) repo_dir = sbox.repo_dir (exit_code, output, errput) = svntest.main.run_svnadmin('verify', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) if svntest.verify.verify_outputs("Output of 'svnadmin verify' is unexpected.", None, output, None, '.*Verified revision 0*'): raise svntest.Failure rp_file = open(os.path.join(repo_dir, 'db', 'revprops', '0', '0'), 'w') rp_file.write('') rp_file.close() (exit_code, output, errput) = svntest.main.run_svnadmin('verify', sbox.repo_dir) if svntest.verify.verify_outputs("Output of 'svnadmin verify' is unexpected.", None, errput, None, '.*svnadmin: E200002:.*'): raise svntest.Failure
-2,633,141,459,617,310,000
svnadmin verify detects invalid revprops file
subversion/tests/cmdline/svnadmin_tests.py
verify_with_invalid_revprops
auycro/subversion
python
@SkipUnless(svntest.main.is_fs_type_fsfs) @SkipDumpLoadCrossCheck() def verify_with_invalid_revprops(sbox): sbox.build(create_wc=False, empty=True) repo_dir = sbox.repo_dir (exit_code, output, errput) = svntest.main.run_svnadmin('verify', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) if svntest.verify.verify_outputs("Output of 'svnadmin verify' is unexpected.", None, output, None, '.*Verified revision 0*'): raise svntest.Failure rp_file = open(os.path.join(repo_dir, 'db', 'revprops', '0', '0'), 'w') rp_file.write() rp_file.close() (exit_code, output, errput) = svntest.main.run_svnadmin('verify', sbox.repo_dir) if svntest.verify.verify_outputs("Output of 'svnadmin verify' is unexpected.", None, errput, None, '.*svnadmin: E200002:.*'): raise svntest.Failure
@Issue(3020) def dont_drop_valid_mergeinfo_during_incremental_loads(sbox): "don't filter mergeinfo revs from incremental dump" sbox.build(empty=True) dumpfile_location = os.path.join(os.path.dirname(sys.argv[0]), 'svnadmin_tests_data', 'mergeinfo_included_full.dump') dumpfile_full = svntest.actions.load_dumpfile(dumpfile_location) load_dumpstream(sbox, dumpfile_full, '--ignore-uuid') url = (sbox.repo_url + '/branches/') expected_output = svntest.verify.UnorderedOutput([(url + 'B1 - /branches/B2:11-12\n'), '/trunk:6,9\n', (url + 'B2 - /trunk:9\n'), (url + 'B1/B/E - /branches/B2/B/E:11-12\n'), '/trunk/B/E:5-6,8-9\n']) svntest.actions.run_and_verify_svn(expected_output, [], 'propget', 'svn:mergeinfo', '-R', sbox.repo_url) dump_file_r1_10 = sbox.get_tempname('r1-10-dump') (exit_code, output, errput) = svntest.main.run_svnadmin('dump', sbox.repo_dir, '-r1:10') dump_fp = open(dump_file_r1_10, 'wb') dump_fp.writelines(output) dump_fp.close() dump_file_r11_13 = sbox.get_tempname('r11-13-dump') (exit_code, output, errput) = svntest.main.run_svnadmin('dump', sbox.repo_dir, '--incremental', '-r11:13') dump_fp = open(dump_file_r11_13, 'wb') dump_fp.writelines(output) dump_fp.close() dump_file_r14_15 = sbox.get_tempname('r14-15-dump') (exit_code, output, errput) = svntest.main.run_svnadmin('dump', sbox.repo_dir, '--incremental', '-r14:15') dump_fp = open(dump_file_r14_15, 'wb') dump_fp.writelines(output) dump_fp.close() sbox.build(empty=True) load_dumpstream(sbox, svntest.actions.load_dumpfile(dump_file_r1_10), '--ignore-uuid') load_dumpstream(sbox, svntest.actions.load_dumpfile(dump_file_r11_13), '--ignore-uuid') load_dumpstream(sbox, svntest.actions.load_dumpfile(dump_file_r14_15), '--ignore-uuid') svntest.actions.run_and_verify_svn(expected_output, [], 'propget', 'svn:mergeinfo', '-R', sbox.repo_url) sbox.build(empty=True) dumpfile_location = os.path.join(os.path.dirname(sys.argv[0]), 'svnadmin_tests_data', 'skeleton_repos.dump') dumpfile_skeleton = svntest.actions.load_dumpfile(dumpfile_location) load_dumpstream(sbox, dumpfile_skeleton, '--ignore-uuid') load_dumpstream(sbox, dumpfile_full, '--parent-dir', 'Projects/Project-X', '--ignore-uuid') url = (sbox.repo_url + '/Projects/Project-X/branches/') expected_output = svntest.verify.UnorderedOutput([(url + 'B1 - /Projects/Project-X/branches/B2:17-18\n'), '/Projects/Project-X/trunk:12,15\n', (url + 'B2 - /Projects/Project-X/trunk:15\n'), (url + 'B1/B/E - /Projects/Project-X/branches/B2/B/E:17-18\n'), '/Projects/Project-X/trunk/B/E:11-12,14-15\n']) svntest.actions.run_and_verify_svn(expected_output, [], 'propget', 'svn:mergeinfo', '-R', sbox.repo_url) sbox.build(empty=True) load_dumpstream(sbox, dumpfile_skeleton, '--ignore-uuid') load_dumpstream(sbox, svntest.actions.load_dumpfile(dump_file_r1_10), '--parent-dir', 'Projects/Project-X', '--ignore-uuid') load_dumpstream(sbox, svntest.actions.load_dumpfile(dump_file_r11_13), '--parent-dir', 'Projects/Project-X', '--ignore-uuid') load_dumpstream(sbox, svntest.actions.load_dumpfile(dump_file_r14_15), '--parent-dir', 'Projects/Project-X', '--ignore-uuid') svntest.actions.run_and_verify_svn(expected_output, [], 'propget', 'svn:mergeinfo', '-R', sbox.repo_url)
2,561,060,232,985,434,600
don't filter mergeinfo revs from incremental dump
subversion/tests/cmdline/svnadmin_tests.py
dont_drop_valid_mergeinfo_during_incremental_loads
auycro/subversion
python
@Issue(3020) def dont_drop_valid_mergeinfo_during_incremental_loads(sbox): sbox.build(empty=True) dumpfile_location = os.path.join(os.path.dirname(sys.argv[0]), 'svnadmin_tests_data', 'mergeinfo_included_full.dump') dumpfile_full = svntest.actions.load_dumpfile(dumpfile_location) load_dumpstream(sbox, dumpfile_full, '--ignore-uuid') url = (sbox.repo_url + '/branches/') expected_output = svntest.verify.UnorderedOutput([(url + 'B1 - /branches/B2:11-12\n'), '/trunk:6,9\n', (url + 'B2 - /trunk:9\n'), (url + 'B1/B/E - /branches/B2/B/E:11-12\n'), '/trunk/B/E:5-6,8-9\n']) svntest.actions.run_and_verify_svn(expected_output, [], 'propget', 'svn:mergeinfo', '-R', sbox.repo_url) dump_file_r1_10 = sbox.get_tempname('r1-10-dump') (exit_code, output, errput) = svntest.main.run_svnadmin('dump', sbox.repo_dir, '-r1:10') dump_fp = open(dump_file_r1_10, 'wb') dump_fp.writelines(output) dump_fp.close() dump_file_r11_13 = sbox.get_tempname('r11-13-dump') (exit_code, output, errput) = svntest.main.run_svnadmin('dump', sbox.repo_dir, '--incremental', '-r11:13') dump_fp = open(dump_file_r11_13, 'wb') dump_fp.writelines(output) dump_fp.close() dump_file_r14_15 = sbox.get_tempname('r14-15-dump') (exit_code, output, errput) = svntest.main.run_svnadmin('dump', sbox.repo_dir, '--incremental', '-r14:15') dump_fp = open(dump_file_r14_15, 'wb') dump_fp.writelines(output) dump_fp.close() sbox.build(empty=True) load_dumpstream(sbox, svntest.actions.load_dumpfile(dump_file_r1_10), '--ignore-uuid') load_dumpstream(sbox, svntest.actions.load_dumpfile(dump_file_r11_13), '--ignore-uuid') load_dumpstream(sbox, svntest.actions.load_dumpfile(dump_file_r14_15), '--ignore-uuid') svntest.actions.run_and_verify_svn(expected_output, [], 'propget', 'svn:mergeinfo', '-R', sbox.repo_url) sbox.build(empty=True) dumpfile_location = os.path.join(os.path.dirname(sys.argv[0]), 'svnadmin_tests_data', 'skeleton_repos.dump') dumpfile_skeleton = svntest.actions.load_dumpfile(dumpfile_location) load_dumpstream(sbox, dumpfile_skeleton, '--ignore-uuid') load_dumpstream(sbox, dumpfile_full, '--parent-dir', 'Projects/Project-X', '--ignore-uuid') url = (sbox.repo_url + '/Projects/Project-X/branches/') expected_output = svntest.verify.UnorderedOutput([(url + 'B1 - /Projects/Project-X/branches/B2:17-18\n'), '/Projects/Project-X/trunk:12,15\n', (url + 'B2 - /Projects/Project-X/trunk:15\n'), (url + 'B1/B/E - /Projects/Project-X/branches/B2/B/E:17-18\n'), '/Projects/Project-X/trunk/B/E:11-12,14-15\n']) svntest.actions.run_and_verify_svn(expected_output, [], 'propget', 'svn:mergeinfo', '-R', sbox.repo_url) sbox.build(empty=True) load_dumpstream(sbox, dumpfile_skeleton, '--ignore-uuid') load_dumpstream(sbox, svntest.actions.load_dumpfile(dump_file_r1_10), '--parent-dir', 'Projects/Project-X', '--ignore-uuid') load_dumpstream(sbox, svntest.actions.load_dumpfile(dump_file_r11_13), '--parent-dir', 'Projects/Project-X', '--ignore-uuid') load_dumpstream(sbox, svntest.actions.load_dumpfile(dump_file_r14_15), '--parent-dir', 'Projects/Project-X', '--ignore-uuid') svntest.actions.run_and_verify_svn(expected_output, [], 'propget', 'svn:mergeinfo', '-R', sbox.repo_url)
@SkipUnless(svntest.main.is_posix_os) @Issue(2591) def hotcopy_symlink(sbox): "'svnadmin hotcopy' replicates symlink" sbox.build(create_wc=False, empty=True) original_repo = sbox.repo_dir (hotcopy_repo, hotcopy_url) = sbox.add_repo_path('hotcopy') svntest.main.safe_rmtree(sbox.wc_dir, 1) os.mkdir(sbox.wc_dir) external_file_path = os.path.join(sbox.wc_dir, 'file') svntest.main.file_write(external_file_path, 'An existing file') external_dir_path = os.path.join(sbox.wc_dir, 'dir') os.mkdir(external_dir_path) external_missing_path = os.path.join(sbox.wc_dir, 'missing') symlinks = [('in_repos_file', 'format'), ('in_repos_dir', 'conf'), ('in_repos_missing', 'missing'), ('external_file', os.path.join('..', '..', '..', external_file_path)), ('external_dir', os.path.join('..', '..', '..', external_dir_path)), ('external_missing', os.path.join('..', '..', '..', external_missing_path))] for (name, target_relpath) in symlinks: target_path = os.path.join(original_repo, target_relpath) target_abspath = os.path.abspath(target_path) symlink_path = os.path.join(original_repo, name) os.symlink(target_relpath, (symlink_path + '_rel')) os.symlink(target_abspath, (symlink_path + '_abs')) svntest.actions.run_and_verify_svnadmin(None, [], 'hotcopy', original_repo, hotcopy_repo) for (name, target_relpath) in symlinks: target_path = os.path.join(original_repo, target_relpath) target_abspath = os.path.abspath(target_path) symlink_path = os.path.join(hotcopy_repo, name) if (os.readlink((symlink_path + '_rel')) != target_relpath): raise svntest.Failure if (os.readlink((symlink_path + '_abs')) != target_abspath): raise svntest.Failure
-5,019,803,570,664,701,000
'svnadmin hotcopy' replicates symlink
subversion/tests/cmdline/svnadmin_tests.py
hotcopy_symlink
auycro/subversion
python
@SkipUnless(svntest.main.is_posix_os) @Issue(2591) def hotcopy_symlink(sbox): sbox.build(create_wc=False, empty=True) original_repo = sbox.repo_dir (hotcopy_repo, hotcopy_url) = sbox.add_repo_path('hotcopy') svntest.main.safe_rmtree(sbox.wc_dir, 1) os.mkdir(sbox.wc_dir) external_file_path = os.path.join(sbox.wc_dir, 'file') svntest.main.file_write(external_file_path, 'An existing file') external_dir_path = os.path.join(sbox.wc_dir, 'dir') os.mkdir(external_dir_path) external_missing_path = os.path.join(sbox.wc_dir, 'missing') symlinks = [('in_repos_file', 'format'), ('in_repos_dir', 'conf'), ('in_repos_missing', 'missing'), ('external_file', os.path.join('..', '..', '..', external_file_path)), ('external_dir', os.path.join('..', '..', '..', external_dir_path)), ('external_missing', os.path.join('..', '..', '..', external_missing_path))] for (name, target_relpath) in symlinks: target_path = os.path.join(original_repo, target_relpath) target_abspath = os.path.abspath(target_path) symlink_path = os.path.join(original_repo, name) os.symlink(target_relpath, (symlink_path + '_rel')) os.symlink(target_abspath, (symlink_path + '_abs')) svntest.actions.run_and_verify_svnadmin(None, [], 'hotcopy', original_repo, hotcopy_repo) for (name, target_relpath) in symlinks: target_path = os.path.join(original_repo, target_relpath) target_abspath = os.path.abspath(target_path) symlink_path = os.path.join(hotcopy_repo, name) if (os.readlink((symlink_path + '_rel')) != target_relpath): raise svntest.Failure if (os.readlink((symlink_path + '_abs')) != target_abspath): raise svntest.Failure
def load_bad_props(sbox): 'svnadmin load with invalid svn: props' dump_str = b'SVN-fs-dump-format-version: 2\n\nUUID: dc40867b-38f6-0310-9f5f-f81aa277e06f\n\nRevision-number: 0\nProp-content-length: 56\nContent-length: 56\n\nK 8\nsvn:date\nV 27\n2005-05-03T19:09:41.129900Z\nPROPS-END\n\nRevision-number: 1\nProp-content-length: 99\nContent-length: 99\n\nK 7\nsvn:log\nV 3\n\n\r\n\nK 10\nsvn:author\nV 2\npl\nK 8\nsvn:date\nV 27\n2005-05-03T19:10:19.975578Z\nPROPS-END\n\nNode-path: file\nNode-kind: file\nNode-action: add\nProp-content-length: 10\nText-content-length: 5\nText-content-md5: e1cbb0c3879af8347246f12c559a86b5\nContent-length: 15\n\nPROPS-END\ntext\n\n\n' sbox.build(empty=True) exp_err = svntest.verify.RegexListOutput(['svnadmin: E125005:.*', 'svnadmin: E125005:.*', 'svnadmin: E125017:.*'], match_all=False) load_and_verify_dumpstream(sbox, [], exp_err, dumpfile_revisions, False, dump_str, '--ignore-uuid') svntest.actions.load_repo(sbox, dump_str=dump_str, bypass_prop_validation=True) svntest.actions.run_and_verify_svn(None, 'svn: E135000: ', 'pg', 'svn:log', '--revprop', '-r1', sbox.repo_url) svntest.actions.load_repo(sbox, dump_str=dump_str, bypass_prop_validation=False, normalize_props=True) (exit_code, output, _) = svntest.main.run_svn(None, 'pg', 'svn:log', '--revprop', '-r1', '--no-newline', sbox.repo_url) svntest.verify.verify_exit_code(None, exit_code, 0) if (output != ['\n', '\n']): raise svntest.Failure(('Unexpected property value %s' % output))
8,739,384,545,327,073,000
svnadmin load with invalid svn: props
subversion/tests/cmdline/svnadmin_tests.py
load_bad_props
auycro/subversion
python
def load_bad_props(sbox): dump_str = b'SVN-fs-dump-format-version: 2\n\nUUID: dc40867b-38f6-0310-9f5f-f81aa277e06f\n\nRevision-number: 0\nProp-content-length: 56\nContent-length: 56\n\nK 8\nsvn:date\nV 27\n2005-05-03T19:09:41.129900Z\nPROPS-END\n\nRevision-number: 1\nProp-content-length: 99\nContent-length: 99\n\nK 7\nsvn:log\nV 3\n\n\r\n\nK 10\nsvn:author\nV 2\npl\nK 8\nsvn:date\nV 27\n2005-05-03T19:10:19.975578Z\nPROPS-END\n\nNode-path: file\nNode-kind: file\nNode-action: add\nProp-content-length: 10\nText-content-length: 5\nText-content-md5: e1cbb0c3879af8347246f12c559a86b5\nContent-length: 15\n\nPROPS-END\ntext\n\n\n' sbox.build(empty=True) exp_err = svntest.verify.RegexListOutput(['svnadmin: E125005:.*', 'svnadmin: E125005:.*', 'svnadmin: E125017:.*'], match_all=False) load_and_verify_dumpstream(sbox, [], exp_err, dumpfile_revisions, False, dump_str, '--ignore-uuid') svntest.actions.load_repo(sbox, dump_str=dump_str, bypass_prop_validation=True) svntest.actions.run_and_verify_svn(None, 'svn: E135000: ', 'pg', 'svn:log', '--revprop', '-r1', sbox.repo_url) svntest.actions.load_repo(sbox, dump_str=dump_str, bypass_prop_validation=False, normalize_props=True) (exit_code, output, _) = svntest.main.run_svn(None, 'pg', 'svn:log', '--revprop', '-r1', '--no-newline', sbox.repo_url) svntest.verify.verify_exit_code(None, exit_code, 0) if (output != ['\n', '\n']): raise svntest.Failure(('Unexpected property value %s' % output))
@SkipUnless(svntest.main.is_fs_type_fsfs) @SkipUnless(svntest.main.server_enforces_UTF8_fspaths_in_verify) def verify_non_utf8_paths(sbox): 'svnadmin verify with non-UTF-8 paths' if ((svntest.main.options.fsfs_version is not None) and (svntest.main.options.fsfs_version not in [4, 6])): raise svntest.Skip('Unsupported prepackaged repository version') dumpfile = clean_dumpfile() sbox.build(empty=True, minor_version=min(svntest.main.options.server_minor_version, 8)) load_and_verify_dumpstream(sbox, [], [], dumpfile_revisions, False, dumpfile, '--ignore-uuid') path1 = os.path.join(sbox.repo_dir, 'db', 'revs', '0', '1') path_new = os.path.join(sbox.repo_dir, 'db', 'revs', '0', '1.new') fp1 = open(path1, 'rb') fp_new = open(path_new, 'wb') for line in fp1.readlines(): if (line == b'A\n'): fp_new.write(b'\xe6\n') elif (line == b'text: 1 340 32 32 a6be7b4cf075fd39e6a99eb69a31232b\n'): fp_new.write(b'text: 1 340 32 32 f2e93e73272cac0f18fccf16f224eb93\n') elif (line == b'text: 1 340 44 32 a6be7b4cf075fd39e6a99eb69a31232b\n'): fp_new.write(b'text: 1 340 44 32 f2e93e73272cac0f18fccf16f224eb93\n') elif (line == b'cpath: /A\n'): fp_new.write(b'cpath: /\xe6\n') elif (line == b'_0.0.t0-0 add-file true true /A\n'): fp_new.write(b'_0.0.t0-0 add-file true true /\xe6\n') else: fp_new.write(line) fp1.close() fp_new.close() os.remove(path1) os.rename(path_new, path1) (exit_code, output, errput) = svntest.main.run_svnadmin('verify', sbox.repo_dir) svntest.verify.verify_outputs("Unexpected error while running 'svnadmin verify'.", [], errput, None, ".*Path '.*' is not in UTF-8.*") expected_stderr = ['* Dumped revision 0.\n', "WARNING 0x0002: E160005: While validating fspath '?\\E6': Path '?\\E6' is not in UTF-8\n", '* Dumped revision 1.\n'] (exit_code, output, errput) = svntest.main.run_svnadmin('dump', sbox.repo_dir) if svntest.verify.compare_and_display_lines("Output of 'svnadmin dump' is unexpected.", 'STDERR', expected_stderr, errput): raise svntest.Failure
560,368,390,026,721,660
svnadmin verify with non-UTF-8 paths
subversion/tests/cmdline/svnadmin_tests.py
verify_non_utf8_paths
auycro/subversion
python
@SkipUnless(svntest.main.is_fs_type_fsfs) @SkipUnless(svntest.main.server_enforces_UTF8_fspaths_in_verify) def verify_non_utf8_paths(sbox): if ((svntest.main.options.fsfs_version is not None) and (svntest.main.options.fsfs_version not in [4, 6])): raise svntest.Skip('Unsupported prepackaged repository version') dumpfile = clean_dumpfile() sbox.build(empty=True, minor_version=min(svntest.main.options.server_minor_version, 8)) load_and_verify_dumpstream(sbox, [], [], dumpfile_revisions, False, dumpfile, '--ignore-uuid') path1 = os.path.join(sbox.repo_dir, 'db', 'revs', '0', '1') path_new = os.path.join(sbox.repo_dir, 'db', 'revs', '0', '1.new') fp1 = open(path1, 'rb') fp_new = open(path_new, 'wb') for line in fp1.readlines(): if (line == b'A\n'): fp_new.write(b'\xe6\n') elif (line == b'text: 1 340 32 32 a6be7b4cf075fd39e6a99eb69a31232b\n'): fp_new.write(b'text: 1 340 32 32 f2e93e73272cac0f18fccf16f224eb93\n') elif (line == b'text: 1 340 44 32 a6be7b4cf075fd39e6a99eb69a31232b\n'): fp_new.write(b'text: 1 340 44 32 f2e93e73272cac0f18fccf16f224eb93\n') elif (line == b'cpath: /A\n'): fp_new.write(b'cpath: /\xe6\n') elif (line == b'_0.0.t0-0 add-file true true /A\n'): fp_new.write(b'_0.0.t0-0 add-file true true /\xe6\n') else: fp_new.write(line) fp1.close() fp_new.close() os.remove(path1) os.rename(path_new, path1) (exit_code, output, errput) = svntest.main.run_svnadmin('verify', sbox.repo_dir) svntest.verify.verify_outputs("Unexpected error while running 'svnadmin verify'.", [], errput, None, ".*Path '.*' is not in UTF-8.*") expected_stderr = ['* Dumped revision 0.\n', "WARNING 0x0002: E160005: While validating fspath '?\\E6': Path '?\\E6' is not in UTF-8\n", '* Dumped revision 1.\n'] (exit_code, output, errput) = svntest.main.run_svnadmin('dump', sbox.repo_dir) if svntest.verify.compare_and_display_lines("Output of 'svnadmin dump' is unexpected.", 'STDERR', expected_stderr, errput): raise svntest.Failure
def test_lslocks_and_rmlocks(sbox): "test 'svnadmin lslocks' and 'svnadmin rmlocks'" sbox.build(create_wc=False) iota_url = (sbox.repo_url + '/iota') lambda_url = (sbox.repo_url + '/A/B/lambda') (exit_code, output, errput) = svntest.main.run_svnadmin('lslocks', sbox.repo_dir) if (exit_code or errput or output): raise svntest.Failure("Error: 'lslocks' failed") expected_output = svntest.verify.UnorderedRegexListOutput(["'.*lambda' locked by user 'jrandom'.\n", "'.*iota' locked by user 'jrandom'.\n"]) svntest.actions.run_and_verify_svn(expected_output, [], 'lock', '-m', 'Locking files', iota_url, lambda_url) def expected_output_list(path): return [('Path: ' + path), 'UUID Token: opaquelocktoken:.*', 'Owner: jrandom', 'Created:.*', 'Expires:.*', 'Comment \\(1 line\\):', 'Locking files', '\n'] (exit_code, output, errput) = svntest.main.run_svnadmin('lslocks', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) svntest.verify.verify_exit_code(None, exit_code, 0) expected_output = svntest.verify.UnorderedRegexListOutput((expected_output_list('/A/B/lambda') + expected_output_list('/iota'))) svntest.verify.compare_and_display_lines('lslocks output mismatch', 'output', expected_output, output) (exit_code, output, errput) = svntest.main.run_svnadmin('lslocks', sbox.repo_dir, 'A') if errput: raise SVNUnexpectedStderr(errput) expected_output = svntest.verify.RegexListOutput(expected_output_list('/A/B/lambda')) svntest.verify.compare_and_display_lines('lslocks output mismatch', 'output', expected_output, output) svntest.verify.verify_exit_code(None, exit_code, 0) (exit_code, output, errput) = svntest.main.run_svnadmin('rmlocks', sbox.repo_dir, 'iota', 'A/B/lambda') expected_output = UnorderedOutput(["Removed lock on '/iota'.\n", "Removed lock on '/A/B/lambda'.\n"]) svntest.verify.verify_outputs("Unexpected output while running 'svnadmin rmlocks'.", output, [], expected_output, None)
3,027,762,593,277,957,600
test 'svnadmin lslocks' and 'svnadmin rmlocks'
subversion/tests/cmdline/svnadmin_tests.py
test_lslocks_and_rmlocks
auycro/subversion
python
def test_lslocks_and_rmlocks(sbox): sbox.build(create_wc=False) iota_url = (sbox.repo_url + '/iota') lambda_url = (sbox.repo_url + '/A/B/lambda') (exit_code, output, errput) = svntest.main.run_svnadmin('lslocks', sbox.repo_dir) if (exit_code or errput or output): raise svntest.Failure("Error: 'lslocks' failed") expected_output = svntest.verify.UnorderedRegexListOutput(["'.*lambda' locked by user 'jrandom'.\n", "'.*iota' locked by user 'jrandom'.\n"]) svntest.actions.run_and_verify_svn(expected_output, [], 'lock', '-m', 'Locking files', iota_url, lambda_url) def expected_output_list(path): return [('Path: ' + path), 'UUID Token: opaquelocktoken:.*', 'Owner: jrandom', 'Created:.*', 'Expires:.*', 'Comment \\(1 line\\):', 'Locking files', '\n'] (exit_code, output, errput) = svntest.main.run_svnadmin('lslocks', sbox.repo_dir) if errput: raise SVNUnexpectedStderr(errput) svntest.verify.verify_exit_code(None, exit_code, 0) expected_output = svntest.verify.UnorderedRegexListOutput((expected_output_list('/A/B/lambda') + expected_output_list('/iota'))) svntest.verify.compare_and_display_lines('lslocks output mismatch', 'output', expected_output, output) (exit_code, output, errput) = svntest.main.run_svnadmin('lslocks', sbox.repo_dir, 'A') if errput: raise SVNUnexpectedStderr(errput) expected_output = svntest.verify.RegexListOutput(expected_output_list('/A/B/lambda')) svntest.verify.compare_and_display_lines('lslocks output mismatch', 'output', expected_output, output) svntest.verify.verify_exit_code(None, exit_code, 0) (exit_code, output, errput) = svntest.main.run_svnadmin('rmlocks', sbox.repo_dir, 'iota', 'A/B/lambda') expected_output = UnorderedOutput(["Removed lock on '/iota'.\n", "Removed lock on '/A/B/lambda'.\n"]) svntest.verify.verify_outputs("Unexpected output while running 'svnadmin rmlocks'.", output, [], expected_output, None)
@Issue(3734) def load_ranges(sbox): "'svnadmin load --revision X:Y'" sbox.build(empty=True) dumpfile_location = os.path.join(os.path.dirname(sys.argv[0]), 'svnadmin_tests_data', 'skeleton_repos.dump') dumplines = svntest.actions.load_dumpfile(dumpfile_location) load_dumpstream(sbox, dumplines, '-r0:2') svntest.actions.run_and_verify_svnlook(['2\n'], None, 'youngest', sbox.repo_dir) load_dumpstream(sbox, dumplines, '-r3:4') svntest.actions.run_and_verify_svnlook(['4\n'], None, 'youngest', sbox.repo_dir) load_dumpstream(sbox, dumplines, '-r5:6') svntest.actions.run_and_verify_svnlook(['6\n'], None, 'youngest', sbox.repo_dir) if (svntest.main.options.server_minor_version < 6): temp = [] for line in dumplines: if (not ('Text-content-sha1:' in line)): temp.append(line) expected_dump = UnorderedOutput(temp) else: expected_dump = UnorderedOutput(dumplines) new_dumpdata = svntest.actions.run_and_verify_dump(sbox.repo_dir) svntest.verify.compare_and_display_lines('Dump files', 'DUMP', expected_dump, new_dumpdata)
-3,604,528,348,858,793,000
'svnadmin load --revision X:Y'
subversion/tests/cmdline/svnadmin_tests.py
load_ranges
auycro/subversion
python
@Issue(3734) def load_ranges(sbox): sbox.build(empty=True) dumpfile_location = os.path.join(os.path.dirname(sys.argv[0]), 'svnadmin_tests_data', 'skeleton_repos.dump') dumplines = svntest.actions.load_dumpfile(dumpfile_location) load_dumpstream(sbox, dumplines, '-r0:2') svntest.actions.run_and_verify_svnlook(['2\n'], None, 'youngest', sbox.repo_dir) load_dumpstream(sbox, dumplines, '-r3:4') svntest.actions.run_and_verify_svnlook(['4\n'], None, 'youngest', sbox.repo_dir) load_dumpstream(sbox, dumplines, '-r5:6') svntest.actions.run_and_verify_svnlook(['6\n'], None, 'youngest', sbox.repo_dir) if (svntest.main.options.server_minor_version < 6): temp = [] for line in dumplines: if (not ('Text-content-sha1:' in line)): temp.append(line) expected_dump = UnorderedOutput(temp) else: expected_dump = UnorderedOutput(dumplines) new_dumpdata = svntest.actions.run_and_verify_dump(sbox.repo_dir) svntest.verify.compare_and_display_lines('Dump files', 'DUMP', expected_dump, new_dumpdata)
@SkipUnless(svntest.main.is_fs_type_fsfs) def hotcopy_incremental(sbox): "'svnadmin hotcopy --incremental PATH .'" sbox.build() (backup_dir, backup_url) = sbox.add_repo_path('backup') os.mkdir(backup_dir) cwd = os.getcwd() for i in [1, 2, 3]: os.chdir(backup_dir) svntest.actions.run_and_verify_svnadmin(None, [], 'hotcopy', '--incremental', os.path.join(cwd, sbox.repo_dir), '.') os.chdir(cwd) check_hotcopy_fsfs(sbox.repo_dir, backup_dir) if (i < 3): sbox.simple_mkdir(('newdir-%i' % i)) sbox.simple_commit()
3,619,880,128,181,488,000
'svnadmin hotcopy --incremental PATH .'
subversion/tests/cmdline/svnadmin_tests.py
hotcopy_incremental
auycro/subversion
python
@SkipUnless(svntest.main.is_fs_type_fsfs) def hotcopy_incremental(sbox): sbox.build() (backup_dir, backup_url) = sbox.add_repo_path('backup') os.mkdir(backup_dir) cwd = os.getcwd() for i in [1, 2, 3]: os.chdir(backup_dir) svntest.actions.run_and_verify_svnadmin(None, [], 'hotcopy', '--incremental', os.path.join(cwd, sbox.repo_dir), '.') os.chdir(cwd) check_hotcopy_fsfs(sbox.repo_dir, backup_dir) if (i < 3): sbox.simple_mkdir(('newdir-%i' % i)) sbox.simple_commit()
@SkipUnless(svntest.main.is_fs_type_fsfs) @SkipUnless(svntest.main.fs_has_pack) def hotcopy_incremental_packed(sbox): "'svnadmin hotcopy --incremental' with packing" sbox.build() patch_format(sbox.repo_dir, shard_size=2) (backup_dir, backup_url) = sbox.add_repo_path('backup') os.mkdir(backup_dir) cwd = os.getcwd() if (not (svntest.main.is_fs_type_fsfs and svntest.main.options.fsfs_packing and (svntest.main.options.fsfs_sharding == 2))): svntest.actions.run_and_verify_svnadmin(['Packing revisions in shard 0...done.\n'], [], 'pack', os.path.join(cwd, sbox.repo_dir)) for i in [1, 2, 3, 4, 5]: os.chdir(backup_dir) svntest.actions.run_and_verify_svnadmin(None, [], 'hotcopy', '--incremental', os.path.join(cwd, sbox.repo_dir), '.') os.chdir(cwd) check_hotcopy_fsfs(sbox.repo_dir, backup_dir) if (i < 5): sbox.simple_mkdir(('newdir-%i' % i)) sbox.simple_commit() if (svntest.main.is_fs_type_fsfs and (not svntest.main.options.fsfs_packing) and (not (i % 2))): expected_output = [('Packing revisions in shard %d...done.\n' % (i / 2))] else: expected_output = [] svntest.actions.run_and_verify_svnadmin(expected_output, [], 'pack', os.path.join(cwd, sbox.repo_dir))
-2,590,107,834,751,945,000
'svnadmin hotcopy --incremental' with packing
subversion/tests/cmdline/svnadmin_tests.py
hotcopy_incremental_packed
auycro/subversion
python
@SkipUnless(svntest.main.is_fs_type_fsfs) @SkipUnless(svntest.main.fs_has_pack) def hotcopy_incremental_packed(sbox): sbox.build() patch_format(sbox.repo_dir, shard_size=2) (backup_dir, backup_url) = sbox.add_repo_path('backup') os.mkdir(backup_dir) cwd = os.getcwd() if (not (svntest.main.is_fs_type_fsfs and svntest.main.options.fsfs_packing and (svntest.main.options.fsfs_sharding == 2))): svntest.actions.run_and_verify_svnadmin(['Packing revisions in shard 0...done.\n'], [], 'pack', os.path.join(cwd, sbox.repo_dir)) for i in [1, 2, 3, 4, 5]: os.chdir(backup_dir) svntest.actions.run_and_verify_svnadmin(None, [], 'hotcopy', '--incremental', os.path.join(cwd, sbox.repo_dir), '.') os.chdir(cwd) check_hotcopy_fsfs(sbox.repo_dir, backup_dir) if (i < 5): sbox.simple_mkdir(('newdir-%i' % i)) sbox.simple_commit() if (svntest.main.is_fs_type_fsfs and (not svntest.main.options.fsfs_packing) and (not (i % 2))): expected_output = [('Packing revisions in shard %d...done.\n' % (i / 2))] else: expected_output = [] svntest.actions.run_and_verify_svnadmin(expected_output, [], 'pack', os.path.join(cwd, sbox.repo_dir))
def locking(sbox): 'svnadmin lock tests' sbox.build(create_wc=False) comment_path = os.path.join(svntest.main.temp_dir, 'comment') svntest.main.file_write(comment_path, 'dummy comment') invalid_comment_path = os.path.join(svntest.main.temp_dir, 'invalid_comment') svntest.main.file_write(invalid_comment_path, 'character \x0c is invalid') expected_error = '.*svnadmin: E130004:.*' svntest.actions.run_and_verify_svnadmin(None, expected_error, 'lock', sbox.repo_dir, 'iota', 'jrandom', invalid_comment_path) expected_output = "'/iota' locked by user 'jrandom'." svntest.actions.run_and_verify_svnadmin(expected_output, None, 'lock', sbox.repo_dir, 'iota', 'jrandom', comment_path, '--bypass-hooks') svntest.actions.run_and_verify_svnadmin(None, None, 'rmlocks', sbox.repo_dir, 'iota') expected_output = "'/iota' locked by user 'jrandom'." svntest.actions.run_and_verify_svnadmin(expected_output, None, 'lock', sbox.repo_dir, 'iota', 'jrandom', comment_path) expected_error = '.*svnadmin: E160035:.*' svntest.actions.run_and_verify_svnadmin(None, expected_error, 'lock', sbox.repo_dir, 'iota', 'jrandom', comment_path) expected_error = '.*svnadmin: E160013:.*' svntest.actions.run_and_verify_svnadmin(None, expected_error, 'lock', sbox.repo_dir, 'non-existent', 'jrandom', comment_path) expected_output = "'/A/D/G/rho' locked by user 'jrandom'." lock_token = 'opaquelocktoken:01234567-89ab-cdef-89ab-cdef01234567' svntest.actions.run_and_verify_svnadmin(expected_output, None, 'lock', sbox.repo_dir, 'A/D/G/rho', 'jrandom', comment_path, lock_token) expected_error = '.*svnadmin: E160040:.*' wrong_lock_token = 'opaquelocktoken:12345670-9ab8-defc-9ab8-def01234567c' svntest.actions.run_and_verify_svnadmin(None, expected_error, 'unlock', sbox.repo_dir, 'A/D/G/rho', 'jrandom', wrong_lock_token) expected_output = "'/A/D/G/rho' unlocked by user 'jrandom'." svntest.actions.run_and_verify_svnadmin(expected_output, None, 'unlock', sbox.repo_dir, 'A/D/G/rho', 'jrandom', lock_token) hook_path = svntest.main.get_pre_lock_hook_path(sbox.repo_dir) svntest.main.create_python_hook_script(hook_path, 'import sys; sys.exit(1)') hook_path = svntest.main.get_pre_unlock_hook_path(sbox.repo_dir) svntest.main.create_python_hook_script(hook_path, 'import sys; sys.exit(1)') expected_error = '.*svnadmin: E165001:.*' svntest.actions.run_and_verify_svnadmin(None, expected_error, 'lock', sbox.repo_dir, 'iota', 'jrandom', comment_path) (exit_code, output, errput) = svntest.main.run_svnadmin('lslocks', sbox.repo_dir, 'iota') iota_token = None for line in output: if line.startswith('UUID Token: opaquelocktoken:'): iota_token = line[12:].rstrip() break if (iota_token is None): raise svntest.Failure("Unable to lookup lock token for 'iota'") expected_error = '.*svnadmin: E165001:.*' svntest.actions.run_and_verify_svnadmin(None, expected_error, 'unlock', sbox.repo_dir, 'iota', 'jrandom', iota_token) expected_output = "'/iota' unlocked by user 'jrandom'." svntest.actions.run_and_verify_svnadmin(expected_output, None, 'unlock', '--bypass-hooks', sbox.repo_dir, 'iota', 'jrandom', iota_token)
-5,838,575,192,461,374,000
svnadmin lock tests
subversion/tests/cmdline/svnadmin_tests.py
locking
auycro/subversion
python
def locking(sbox): sbox.build(create_wc=False) comment_path = os.path.join(svntest.main.temp_dir, 'comment') svntest.main.file_write(comment_path, 'dummy comment') invalid_comment_path = os.path.join(svntest.main.temp_dir, 'invalid_comment') svntest.main.file_write(invalid_comment_path, 'character \x0c is invalid') expected_error = '.*svnadmin: E130004:.*' svntest.actions.run_and_verify_svnadmin(None, expected_error, 'lock', sbox.repo_dir, 'iota', 'jrandom', invalid_comment_path) expected_output = "'/iota' locked by user 'jrandom'." svntest.actions.run_and_verify_svnadmin(expected_output, None, 'lock', sbox.repo_dir, 'iota', 'jrandom', comment_path, '--bypass-hooks') svntest.actions.run_and_verify_svnadmin(None, None, 'rmlocks', sbox.repo_dir, 'iota') expected_output = "'/iota' locked by user 'jrandom'." svntest.actions.run_and_verify_svnadmin(expected_output, None, 'lock', sbox.repo_dir, 'iota', 'jrandom', comment_path) expected_error = '.*svnadmin: E160035:.*' svntest.actions.run_and_verify_svnadmin(None, expected_error, 'lock', sbox.repo_dir, 'iota', 'jrandom', comment_path) expected_error = '.*svnadmin: E160013:.*' svntest.actions.run_and_verify_svnadmin(None, expected_error, 'lock', sbox.repo_dir, 'non-existent', 'jrandom', comment_path) expected_output = "'/A/D/G/rho' locked by user 'jrandom'." lock_token = 'opaquelocktoken:01234567-89ab-cdef-89ab-cdef01234567' svntest.actions.run_and_verify_svnadmin(expected_output, None, 'lock', sbox.repo_dir, 'A/D/G/rho', 'jrandom', comment_path, lock_token) expected_error = '.*svnadmin: E160040:.*' wrong_lock_token = 'opaquelocktoken:12345670-9ab8-defc-9ab8-def01234567c' svntest.actions.run_and_verify_svnadmin(None, expected_error, 'unlock', sbox.repo_dir, 'A/D/G/rho', 'jrandom', wrong_lock_token) expected_output = "'/A/D/G/rho' unlocked by user 'jrandom'." svntest.actions.run_and_verify_svnadmin(expected_output, None, 'unlock', sbox.repo_dir, 'A/D/G/rho', 'jrandom', lock_token) hook_path = svntest.main.get_pre_lock_hook_path(sbox.repo_dir) svntest.main.create_python_hook_script(hook_path, 'import sys; sys.exit(1)') hook_path = svntest.main.get_pre_unlock_hook_path(sbox.repo_dir) svntest.main.create_python_hook_script(hook_path, 'import sys; sys.exit(1)') expected_error = '.*svnadmin: E165001:.*' svntest.actions.run_and_verify_svnadmin(None, expected_error, 'lock', sbox.repo_dir, 'iota', 'jrandom', comment_path) (exit_code, output, errput) = svntest.main.run_svnadmin('lslocks', sbox.repo_dir, 'iota') iota_token = None for line in output: if line.startswith('UUID Token: opaquelocktoken:'): iota_token = line[12:].rstrip() break if (iota_token is None): raise svntest.Failure("Unable to lookup lock token for 'iota'") expected_error = '.*svnadmin: E165001:.*' svntest.actions.run_and_verify_svnadmin(None, expected_error, 'unlock', sbox.repo_dir, 'iota', 'jrandom', iota_token) expected_output = "'/iota' unlocked by user 'jrandom'." svntest.actions.run_and_verify_svnadmin(expected_output, None, 'unlock', '--bypass-hooks', sbox.repo_dir, 'iota', 'jrandom', iota_token)
@SkipUnless(svntest.main.is_threaded_python) @Issue(4129) def mergeinfo_race(sbox): 'concurrent mergeinfo commits invalidate pred-count' sbox.build() wc_dir = sbox.wc_dir wc2_dir = sbox.add_wc_path('2') svntest.main.run_svn(None, 'checkout', '-q', sbox.repo_url, wc2_dir) svntest.main.run_svn(None, 'mkdir', sbox.ospath('d1', wc_dir)) svntest.main.run_svn(None, 'mkdir', sbox.ospath('d2', wc2_dir)) svntest.main.run_svn(None, 'ps', 'svn:mergeinfo', '/P:42', sbox.ospath('A', wc_dir)) svntest.main.run_svn(None, 'ps', 'svn:mergeinfo', '/Q:42', sbox.ospath('iota', wc2_dir)) def makethread(some_wc_dir): def worker(): svntest.main.run_svn(None, 'commit', '-mm', some_wc_dir) return worker t1 = threading.Thread(None, makethread(wc_dir)) t2 = threading.Thread(None, makethread(wc2_dir)) t1.start() t2.start() t1.join() t2.join() if (svntest.actions.run_and_parse_info(sbox.repo_url)[0]['Revision'] != '3'): raise svntest.Failure('one or both commits failed')
5,069,601,437,167,270,000
concurrent mergeinfo commits invalidate pred-count
subversion/tests/cmdline/svnadmin_tests.py
mergeinfo_race
auycro/subversion
python
@SkipUnless(svntest.main.is_threaded_python) @Issue(4129) def mergeinfo_race(sbox): sbox.build() wc_dir = sbox.wc_dir wc2_dir = sbox.add_wc_path('2') svntest.main.run_svn(None, 'checkout', '-q', sbox.repo_url, wc2_dir) svntest.main.run_svn(None, 'mkdir', sbox.ospath('d1', wc_dir)) svntest.main.run_svn(None, 'mkdir', sbox.ospath('d2', wc2_dir)) svntest.main.run_svn(None, 'ps', 'svn:mergeinfo', '/P:42', sbox.ospath('A', wc_dir)) svntest.main.run_svn(None, 'ps', 'svn:mergeinfo', '/Q:42', sbox.ospath('iota', wc2_dir)) def makethread(some_wc_dir): def worker(): svntest.main.run_svn(None, 'commit', '-mm', some_wc_dir) return worker t1 = threading.Thread(None, makethread(wc_dir)) t2 = threading.Thread(None, makethread(wc2_dir)) t1.start() t2.start() t1.join() t2.join() if (svntest.actions.run_and_parse_info(sbox.repo_url)[0]['Revision'] != '3'): raise svntest.Failure('one or both commits failed')