def add_audio_content(self, stream_no, a_filter_extra): self._result.append( self._bodya[0].format( stream_no=stream_no, bodyident=np.base_repr(self._numbody, 36), a_filter_extra=a_filter_extra + "," if a_filter_extra else "")) self._fconcat.ia.append(self._bodya[1].format( bodyident=np.base_repr(self._numbody, 36))) self._numbody += 1 return self
def add_video_content(self, stream_no, v_filter_extra): self._result.append( self._bodyv[0].format( stream_no=stream_no, bodyident=np.base_repr(self._numbody, 36), v_filter_extra=v_filter_extra + "," if v_filter_extra else "")) self._fconcat.iv.append(self._bodyv[1].format( bodyident=np.base_repr(self._numbody, 36))) self._numbody += 1 return self
def add_audio_gap(self, duration): if duration <= 0: return self self._result.append( self._tmpl_gapa[0].format( gapno=np.base_repr(self._gapno, 36), duration=duration)) self._fconcat.ia.append(self._tmpl_gapa[1].format( gapno=np.base_repr(self._gapno, 36))) self._gapno += 1 return self
def indexToState(ind, hspace): """ return # of phonons and binary repr of state """ maxphonons = hspace.maxphonons levels = hspace.levels nuions = hspace.nuions # phonon number phonon = ind % (maxphonons+1) def unpackdigits(numstr): ''' like np.unpackbits, but for base 10 ''' numarr = [] for c in numstr: numarr.append(float(c)) return np.array(numarr) # state can be expressed in binary indstate = (ind - phonon) / (maxphonons+1) # statestr is a string like |SS,0> # statenum is an array of 0,1,2's statestr = np.base_repr(indstate, base=levels).zfill(nuions) statenum = unpackdigits(statestr) statestr = statestr.replace('0', 'D').replace('1', 'S').replace('2', 'A') statestr = statestr + ',' + str(phonon) return phonon, statenum, statestr
def doProblem(): sum = 0 for i in range(1,1000000): if IfPalindromic(str(i)): if IfPalindromic(numpy.base_repr(i)): sum += i return sum
def get_id(self): """ A unique id to identify the specific instance of the model Guaranteed to probably be different for two different sets of params """ return base_repr(hash(tuple(sorted(self.__dict__.items()))), 36).lower()[-6:]
def base_repr(number, base=2, padding=0): # NOQA (needed to avoid redefinition of `number`) """Return a string representation of a number in the given base system. .. seealso:: :func:`numpy.base_repr` """ return _numpy.base_repr(number, base, padding)
def id_gen(): a = uuid.uuid4().int while (len(str(a)) > 6): z = int(len(str(a)) / 2) - 1 b = int(str(a)[0:z]) c = int(str(a)[z:-1]) a = b ^ c return (np.base_repr(a, 36).lower())
def gen_jamcoins(n, length): jamcoins = [] i = int("1" + ("0" * (length - 2)) + "1", 2) while len(jamcoins) < n: if is_jamcoin(i): jamcoins.append(numpy.base_repr(i)) i += 2 return jamcoins
def inc_string(s): ns = [base26[ord(y) - 97] for y in s] sn = ''.join(ns) i = int(sn, 26) + 1 isn = base_repr(i, 26).lower() ins = [letters[base26.index(y)] for y in isn] pw = ''.join(ins) return pw
def gen_vander_corupt_seq_3(n): phi_3 = [] phi_3.append(0) for i in range(1, n + 1): ternary = np.base_repr(i, base=3) num = calc3(ternary) phi_3.append(num) return phi_3
def base_ints(q, m): ''' Returns a matrix where row 'i' is the base-q representation of i, for i from 0 to q ** m - 1. Covers the functionality of binary_ints when n = 2, but binary_ints is faster for that case. ''' get_row = lambda i: np.array( [int(j) for j in np.base_repr(i, base=q).zfill(m)]) return np.vstack((get_row(i) for i in range(q**m)))
def int_to_kmer(num): intermediate = numpy.base_repr(num, base=4) kmer = "" for c in intermediate: kmer += translation_table[c] return kmer
def build_rule_set(self, rule, base, systemSize): Length = pow(base, systemSize) ruleSet = list(map(int, list(np.base_repr(rule, base)))) extraLength = Length - len(ruleSet) zeroList = [0] * extraLength ruleSet = zeroList + ruleSet #print(ruleSet) return ruleSet
def test_get_psf_path(): """Test that the get_psf_path method of the yaml_generator.SimInput class is working as expected. """ # Make an instance of the SimInput class input_xml = os.path.join(__location__, 'test_data', 'NIRCam', '1144-OTE-10.xml') pointing_file = os.path.join(__location__, 'test_data', 'NIRCam', '1144-OTE-10.pointing') yam = SimInput(input_xml, pointing_file, offline=True) # Fake the activity IDs and instrument n_activities = 101 act_ids = [np.base_repr(i, 36).zfill(2) for i in range(n_activities)] yam.info = {} yam.info['act_id'] = act_ids yam.info['Instrument'] = ['NIRCam'] * n_activities # Test for a default path paths_out = yam.get_psf_path() assert len(paths_out) == n_activities,\ 'Default PSF path not properly provided.' assert 'nircam/gridded_psf_library' in paths_out[0],\ 'Default PSF path not properly provided.' np.testing.assert_array_equal( paths_out, paths_out[0], err_msg='Default PSF path not properly defined.') # Test for a single path yam.psf_paths = __location__ paths_out = yam.get_psf_path() assert paths_out == [__location__] * n_activities,\ 'Single PSF path not properly assigned.' # Test for a list of paths of incorrect length with pytest.raises(ValueError) as e: yam.psf_paths = [__location__] * 99 yam.get_psf_path() assert 'Please provide the psf_paths in the form of a list of strings ' \ 'with a length equal to the number of activities in the APT ' \ 'program (101), not equal to 99.' in e, \ 'Failed to reject psf_path of incorrect length.' # Test for a list of paths of correct length list_101_paths = [__location__] * 50 + [os.path.dirname(__location__)] * 51 yam.psf_paths = list_101_paths paths_out = yam.get_psf_path() assert paths_out == sorted(list_101_paths),\ 'List of PSF paths not properly assigned.' # Test for a completely invalid path with pytest.raises(TypeError) as e: yam.psf_paths = 3.054 yam.get_psf_path() assert 'Please provide the psf_paths in the form of a list or ' \ 'string, not float' in e, \ 'Failed to reject psf_path of incorrect type.'
def get_final_state(self, reduce_to_basis=None, ignore_global_phase=True, tol=1e-6, normalize=True): """Get the final state of the simulation. Keyword Args: reduce_to_basis (str, default=None): Reduces the full state vector to the given basis ("ground-rydberg" or "digital"), if the population of the states to be ignored is negligible. ignore_global_phase (bool, default=True): If True, changes the final state's global phase such that the largest term (in absolute value) is real. tol (float, default=1e-6): Maximum allowed population of each eliminated state. normalize (bool, default=True): Whether to normalize the reduced state. Returns: qutip.Qobj: The resulting final state. Raises: TypeError: If trying to reduce to a basis that would eliminate states with significant occupation probabilites. """ final_state = self._states[-1].copy() if ignore_global_phase: full = final_state.full() global_ph = float(np.angle(full[np.argmax(np.abs(full))])) final_state *= np.exp(-1j * global_ph) if self._dim != 3: if reduce_to_basis not in [None, self._basis_name]: raise TypeError( f"Can't reduce a system in {self._basis_name}" + f" to the {reduce_to_basis} basis.") elif reduce_to_basis is not None: if reduce_to_basis == "ground-rydberg": ex_state = "2" elif reduce_to_basis == "digital": ex_state = "0" else: raise ValueError( "'reduce_to_basis' must be 'ground-rydberg' " + f"or 'digital', not '{reduce_to_basis}'.") ex_inds = [ i for i in range(3**self._size) if ex_state in np.base_repr(i, base=3).zfill(self._size) ] ex_probs = np.abs(final_state.extract_states(ex_inds).full())**2 if not np.all(np.isclose(ex_probs, 0, atol=tol)): raise TypeError( "Can't reduce to chosen basis because the population of a " "state to eliminate is above the allowed tolerance.") final_state = final_state.eliminate_states(ex_inds, normalize=normalize) return final_state.tidyup()
def DividedByBase(pot:int): if pot == 0: return '' potStr = n.base_repr(pot,base) if potStr.endswith('0'): potStr = potStr[:-1] else: potStr = potStr[:-1] + '.' + potStr[-1] return potStr
def format_value(value, base): if value < -256 or value > 255: return "OVF" value = np.uint8(value) if base == 2: v = np.binary_repr(value, width=8) else: v = np.base_repr(value, base) return format_message(v, base)
def test_leading(n, k): regex_str = aut.get_regex(n, k) regex = re.compile(regex_str) n_str = np.base_repr(n, k) n_str = "000" + n_str if my_match(n_str, regex): raise Exception("leading zero test for " + str(n) + " failed")
def translation_generator(self): """ a function to handle the translation during lattice transformation """ modulo=round(np.linalg.det(self.R[:3,:3])) inv_rotation=np.array(self.inv_R[:3,:3])*modulo subgroup_basis_vectors=(np.round(inv_rotation.transpose()).astype(int)%modulo).tolist() # remove the [0,0,0] vectors translations=[x for x in subgroup_basis_vectors if x!=[0,0,0]] #find the independent vectors if len(translations)==0: independent_vectors=[[0,0,0]] elif len(translations)==1: independent_vectors=translations elif len(translations)==2: norm=round(np.linalg.norm(translations[0])*np.linalg.norm(translations[1])) inner_product=np.inner(translations[0],translations[1]) difference=norm-inner_product if difference==0.: independent_vectors=[translations[0]] else: independent_vectors=translations else: norms=np.round([np.linalg.norm(translations[i])*np.linalg.norm(translations[j]) for i in range(2) for j in range(i+1,3)]) inner_products=np.array([np.inner(translations[i],translations[j]) for i in range(2) for j in range(i+1,3)]) differences=inner_products-norms independent_vectors=[translations[0]] if differences[0]!=0. and differences[1]==0.: independent_vectors.append(translations[1]) elif differences[0]==0. and differences[1]!=0.: independent_vectors.append(translations[2]) elif differences[0]!=0. and differences[1]!=0. and differences[2]!=0.: independent_vectors.append(translations[1]) independent_vectors.append(translations[2]) elif differences[0]!=0. and differences[1]!=0. and differences[2]==0.: independent_vectors.append(translations[1]) #generate all possible combinations of the independent vectors l=len(independent_vectors) independent_vectors=np.array(independent_vectors) possible_combos=[] final_translation_list=[] for i in range(self.index**l): possible_combos.append(np.base_repr(i,self.index,padding=l)[-l:]) for combo in possible_combos: combo=np.array([int(x) for x in combo]) vector=np.array([0.,0.,0.]) for i,scalar in enumerate(combo): vector+=scalar*independent_vectors[i] vector=(vector%modulo/modulo).tolist() if vector not in final_translation_list: final_translation_list.append(vector) return final_translation_list
def index_to_structure(self, index): """Given an integer and target length, encode into structure.""" structure = np.zeros(self.length, dtype=np.int32) tokens = [ int(token, base=len(self.vocab)) for token in np.base_repr(index, base=len(self.vocab)) ] structure[-len(tokens):] = tokens return structure
def integer_to_quaternary(integer): """ This function ... :param integer: :return: """ from numpy import base_repr return base_repr(integer, 4)
def to_base_n(x, base, len): """ Returns array representing x in the given base, with the fixed length """ padding = len - int(np.log(x) / np.log(base)) - 1 if x > 0 else len tmp = np.base_repr(x, base=base, padding=padding) tmp = np.array([int(u) for u in tmp]) return tmp
def enumerateStrings(alphabet, n): """ Given: A collection of at most 10 symbols defining an ordered alphabet, and a positive integer n (n≤10). Return: All strings of length n that can be formed from the alphabet, ordered lexicographically. """ base = len(alphabet.keys()) enumeration = [('{0:0'+str(n)+'d}').format(int(np.base_repr(i, base))) for i in range(base**n)] return(enumeration)
def convert_binary_seq(s): ret = '' for i in range((len(s) + 4) // 5): v = 0 for j in range(5): if i * 5 + j < len(s) and s[i * 5 + j] == 1: v += (2 ** (4 - j)) ret += np.base_repr(v, 32).lower() return ret
def writer(fastq1_out, side_car_out, fastq2_out=None, data_queue=None, max_qname_len=__max_qname_len__): """Write templates to file :param fastq1_out: Name of FASTQ1 :param side_car_out: Name of side car file for long qnames :param fastq2_out: If paired end, name of FASTQ2 :param data_queue: multiprocessing queue :param max_qname_len: Send qnames longer than this to the overflow file The data format is as follows: ( idx, - if this is None then we create an index afresh sample_name, chrom, copy, ( (strand, pos, cigar, (v1,v2,...), MD, seq, qual) ... [repeated as for as many reads in this template] ) ) :return: """ t0 = time.time() cnt = -1 fastq_l, side_car_fp = [open(fastq1_out, 'w')], open(side_car_out, 'w') if fastq2_out is not None: fastq_l += [open(fastq2_out, 'w')] for cnt, template in enumerate(iter(data_queue.get, __process_stop_code__)): # @index|sn|chrom:copy| qname = '@{}|{}|{}:{}|'.format(template[0] or base_repr(cnt, 36), *template[1:4]) # strand:pos:cigar:v1,v2,...:MD|strand:pos:cigar:v1,v2,...:MD* qname += '|'.join( '{}:{}:{}:{}:{}'.format(*r[:3], str(r[3])[1:-1].replace(' ', ''), r[4]) for r in template[4]) + '*' if len(qname) > max_qname_len: side_car_fp.write(qname + '\n') qname = qname[:max_qname_len] for fp, r in zip(fastq_l, template[4]): fp.write('{}\n{}\n+\n{}\n'.format(qname, r[5], r[6])) for fp in fastq_l: fp.close() t1 = time.time() logger.debug( 'Writer finished: {} templates in {:0.2f}s ({:0.2f} t/s)'.format( cnt + 1, t1 - t0, (cnt + 1) / (t1 - t0)))
def alpha_numeric_number_generator(previous=''): length = len(previous) new = int(previous, 36) + 1 new = numpy.base_repr(new, 36) if len(new) != length: diff = length - len(new) zero = ['0' for _ in range(0, diff)] new = ''.join(zero) + new return new
def test_powers(self): signal = constant_op.constant(np.squeeze(self.powers[0, :, :]), dtype=dtypes.int64) reconstruction = reconstruction_ops.overlap_and_add( signal, self.frame_hop) output = self.evaluate(reconstruction) string_output = [np.base_repr(x, self.bases[0]) for x in output] self.assertEqual(string_output, self.expected_string)
def getEnv(n): a = np.base_repr(n,base = 3) array = [] string = str(a) for i in range(9-len(string)): array.append(0) for c in string: array.append(int(c)) return array
def coordinates_from_distance(self, d): d_str = np.base_repr(d, 3).zfill(2 * self.order) drgc_str = self._rgc(d_str) xrgc_str = drgc_str[1::2] yrgc_str = drgc_str[0::2] x_str = self._rgc(xrgc_str) y_str = self._rgc(yrgc_str) x = int(x_str, 3) y = int(y_str, 3) return x, y
def key_generator(entity): status = "ok" if entity == "User": initial = "USER" if User.objects.count() == 0: counter = str('0000') else: last_row = User.objects.values().last() prev_day = str(last_row['user_id']).split("_")[0][0:4] prev_counter = str(last_row['user_id']).split("_")[2][0:4] new_counter = int(prev_counter, 36) + 1 counter = base_repr(new_counter, 36).zfill(4) if counter == '10000': status = "exceeded" if prev_day != date_generator(): counter = str('0000') elif entity == "Vendor": initial = "VNDR" if Vendor.objects.count() == 0: counter = str('0000') else: last_row = Vendor.objects.values().last() prev_day = str(last_row['vendor_id']).split("_")[0][0:4] prev_counter = str(last_row['vendor_id']).split("_")[2][0:4] new_counter = int(prev_counter, 36) + 1 counter = base_repr(new_counter, 36).zfill(4) if counter == '10000': status = "exceeded" if prev_day != date_generator(): counter = str('0000') else: status = "Invalid Entity" if status == "Invalid Entity": return "Invalid Entity" elif status == "exceeded": return "Limit Exceeded" else: date = date_generator() key = date + "_" + initial + "_" + counter return key
def generar_paquetes(n1, n2): moves = np.zeros([n2, 2]) rng = np.random.default_rng() for i in range(n2): moves[i, :] = rng.choice(n1, size=2, replace=False) colores = [] for i in range(n2): color = np.base_repr(np.random.choice(16777215), base=16) colores.append('#{:0>6}'.format(color)) return moves, colores
def genroots(): for i in range(1,100): if is_p(i): yield i x = 3 while x < 10**24: ys = np.base_repr(x,3) yield np.int(ys+ys[:-1][::-1]) yield np.int(ys+ys[::-1]) x += 1
def convertLabel(self, line, type): ''' convertLabel function convert labels in the instruction to binary values Returns String ''' try: lineIndex = int(self.content.index(list(line))) labelIndex = None calculatedIndex = None if type == 'I': for index, label in self.contentLabels: if label == line[3]: labelIndex = index calculatedIndex = labelIndex - lineIndex - 1 return self.convertSignedBinary(str(calculatedIndex), 16) elif type == 'J': for index, label in self.contentLabels: if label == line[1]: labelIndex = index calculatedProgramMemoryLocation = self.programMemoryLocation[ 2:] calculatedProgramMemoryLocation = int( calculatedProgramMemoryLocation, 16) calculatedIndex = calculatedProgramMemoryLocation + 4 * labelIndex calculatedIndex = np.base_repr(calculatedIndex, base=2) calculatedIndex = np.base_repr(int(calculatedIndex, 2), base=2, padding=32 - len(calculatedIndex)) calculatedIndex = calculatedIndex[4:-2] return calculatedIndex else: return '0' except: return False
def createGeneSeqLarge(n): assert (n < 4**6) listNum = list(np.base_repr(n, base=4)) listNum = np.array([int(num) for num in listNum]) while len(listNum) < 6: listNum = np.pad(listNum, (1, 0), 'constant', constant_values=(0, 0)) geneSeq = np.zeros((6, 4, 50)) for i in range(6): geneSeq[i, listNum[i]] = np.ones(50) return geneSeq
def enumerateStrings(alphabet, n): """ Given: A collection of at most 10 symbols defining an ordered alphabet, and a positive integer n (n≤10). Return: All strings of length n that can be formed from the alphabet, ordered lexicographically. """ base = len(alphabet.keys()) enumeration = [('{0:0' + str(n) + 'd}').format(int(np.base_repr(i, base))) for i in range(base**n)] return (enumeration)
def generate_key(): num = 1 while True: num = int((10**11) * np.random.rand()) #print(num) num = np.base_repr(num, base=16) #print(num) if is_unique_key(num): break return num
def datetime32(): """ 時刻情報を元に衝突しにくい名前を自動で生成する(base_repr使用版) [out] 生成された名前 """ now = datetime.today() exec_time1 = int(now.strftime('%y%m%d')) exec_time2 = int(now.strftime('%H%M%S')) return np.base_repr(exec_time1 * exec_time2, 32).lower()
def decimal_converter(Number, state=2): states = 8 if state == 3: states = 9 Converted = str(np.base_repr(Number, state)) Converted_length = len(Converted) if Converted_length != states: padding = states - Converted_length Converted = '0' * padding + Converted return Converted
def test_powers(self): signal = constant_op.constant(np.squeeze(self.powers[0, :, :]), dtype=dtypes.int64) reconstruction = reconstruction_ops.overlap_and_add(signal, self.frame_hop) with self.session(use_gpu=True) as sess: output = sess.run(reconstruction) string_output = [np.base_repr(x, self.bases[0]) for x in output] self.assertEqual(string_output, self.expected_string)
def convert_to_carr_vert(im_arr, w=32, h=88, thresh=50): ''' converts a PIL image np array to a C byte array Parameters ---------- im_arr : PIL numpy array of an image image data to convert. w : width, int, optional width of the images, autodetected. The default is 32. h : height, int, optional height of the images, autodetected. The default is 88. Returns ------- output_str : TYPE DESCRIPTION. ''' data = im_arr.flatten() output_str = "" output_index = 0 screenheight = h screenwidth = w k = 0 for p in range(0, int(np.ceil(screenheight) / 8)): for x in range(0, screenwidth): byteIndex = 7 number = 0 for y in range(7, -1, -1): index = ((p * 8) + y) * (screenwidth * 4) + x * 4 avg = (data[index] + data[index + 1] + data[index + 2]) / 3 if avg > thresh: number += np.power(2, byteIndex) byteIndex -= 1 byteset = np.base_repr(number, base=16) while len(byteset) < 2: byteset = '0' + byteset byteset = '0x' + byteset if k != 0: output_str = (output_str + ', ' + byteset) else: output_str = byteset k += 1 output_index += 1 return output_str
def p148bf(n,base=7): t=time.clock() sum7=0 for i in range(n): sum7+=np.prod([int(x)+1 for x in str(np.base_repr(i,base))]) print(n,sum7,time.clock()-t) return sum7 #to see number odd numbers mod n) in first m rows #sum([sum([nCk(y,x)%n!=0 for x in range(y+1)]) for y in range(m)])
def p148(n,base=7): t=time.clock() s=str(np.base_repr(n,base)) m=sum([x for x in range(1,base+1)]) bsum=0 smult=1 for i in range(len(s)): if i>0: smult*=(int(s[i-1])+1) bsum+=m**(len(s)-i-1)*smult*sum([x for x in range(int(s[i])+1)]) print(bsum,time.clock()-t)
def enumerateStrings(alphabet, n): """ Given: A collection of at most 12 symbols defining an ordered alphabet, and a positive integer n (n≤4). Return: All strings of length at most n that can be formed from the alphabet, ordered lexicographically. """ base = len(alphabet.keys()) enumeration = list() for i in range(0,n+1): enumeration += [('{0:0'+str(i)+'x}').format(int(np.base_repr(j, base),16)) for j in range(base**n)] enumeration = sorted(list(set(enumeration))) return(enumeration)
def test_batch(self): signal = constant_op.constant(self.powers, dtype=dtypes.int64) reconstruction = reconstruction_ops.overlap_and_add(signal, self.frame_hop) with self.session(use_gpu=True) as sess: output = sess.run(reconstruction) accumulator = True for i in range(self.batch_size): string_output = [np.base_repr(x, self.bases[i]) for x in output[i, :]] accumulator = accumulator and (string_output == self.expected_string) self.assertTrue(accumulator)
def get_next_curve_key(curve_key): """ expects a string like: 21032 expressing level and fold_index >>> fold_index_key = "21033" >>> next_fold_index_key = get_next_curve_key(fold_index_key) >>> next_fold_index_key '21100' """ format = "%%0%dd"%len(curve_key) return format%int(np.base_repr(int(curve_key,4)+1,4))
def test_one_element_batch(self): input_matrix = np.squeeze(self.powers[0, :, :]) input_matrix = input_matrix[np.newaxis, :, :].astype(float) signal = constant_op.constant(input_matrix, dtype=dtypes.float32) reconstruction = reconstruction_ops.overlap_and_add(signal, self.frame_hop) with self.session(use_gpu=True) as sess: output = sess.run(reconstruction) string_output = [np.base_repr(int(x), self.bases[0]) for x in np.squeeze(output)] self.assertEqual(output.shape, (1, 9)) self.assertEqual(string_output, self.expected_string)
def _direct_computation(self, u, v): # keep track of the best parameters max_states = np.zeros(self.samples) # ...and values max_obj = -1e16 num_combs = self.S**len(self.V) # this is the number of combinations # print('There are {0} combinations for {1} samples and {2} states.'.format(num_combs, self.samples, self.S)) # partition function values part_value = 0.0 # partition function Z value part_grad = np.zeros(v.size) # partition function Z gradient y = self.labels.reshape((self.labels.size, 1)) u = u.reshape((u.size, 1)) v = v.reshape((v.size, 1)) # test every single combination opt_list = [] for i in range(num_combs): comb = np.base_repr(i, base=self.S) # convert current id of combinations to string of states states = np.zeros(self.samples, dtype=np.int8) for s in range(len(comb)): states[s] = np.int(comb[len(comb)-s-1]) phis, psi = self.get_joint_feature_maps(latent=states) # get the corresponding crf feature map # map inference and objective functions obj_crf = -v.T.dot(psi) obj_rr = y - u.T.dot(phis[:, self.label_inds]).T obj_rr = 0.5 * np.sum(obj_rr*obj_rr) map_obj = -(self.reg_theta*obj_rr + (1.-self.reg_theta)*obj_crf) # partition function and gradient part_value += np.exp(-obj_crf) part_grad += psi*np.exp(-obj_crf) if np.abs(map_obj-max_obj) < 1e-12: opt_list.append(states) elif map_obj > max_obj: max_obj = map_obj max_states = states max_psi = psi opt_list = [max_states] print opt_list return max_obj, max_states, max_psi, np.float64(np.log(part_value)), part_grad.reshape((part_grad.size))
def writer(fastq1_out, side_car_out, fastq2_out=None, data_queue=None, max_qname_len=__max_qname_len__): """Write templates to file :param fastq1_out: Name of FASTQ1 :param side_car_out: Name of side car file for long qnames :param fastq2_out: If paired end, name of FASTQ2 :param data_queue: multiprocessing queue :param max_qname_len: Send qnames longer than this to the overflow file The data format is as follows: ( idx, - if this is None then we create an index afresh sample_name, chrom, copy, ( (strand, pos, cigar, (v1,v2,...), MD, seq, qual) ... [repeated as for as many reads in this template] ) ) :return: """ t0 = time.time() cnt = -1 fastq_l, side_car_fp = [open(fastq1_out, 'w')], open(side_car_out, 'w') if fastq2_out is not None: fastq_l += [open(fastq2_out, 'w')] for cnt, template in enumerate(iter(data_queue.get, __process_stop_code__)): # @index|sn|chrom:copy| qname = '@{}|{}|{}:{}|'.format(template[0] or base_repr(cnt, 36), *template[1:4]) # strand:pos:cigar:v1,v2,...:MD|strand:pos:cigar:v1,v2,...:MD* qname += '|'.join('{}:{}:{}:{}:{}'.format(*r[:3], str(r[3])[1:-1].replace(' ', ''), r[4]) for r in template[4]) + '*' if len(qname) > max_qname_len: side_car_fp.write(qname + '\n') qname = qname[:max_qname_len] for fp, r in zip(fastq_l, template[4]): fp.write('{}\n{}\n+\n{}\n'.format(qname, r[5], r[6])) for fp in fastq_l: fp.close() t1 = time.time() logger.debug('Writer finished: {} templates in {:0.2f}s ({:0.2f} t/s)'.format(cnt + 1, t1 - t0, (cnt + 1) / (t1 - t0)))
def get_primitive_polynomial(p, m): """Find a primitive polynomial of GF(p^m).""" # Based on algorithm at: # http://www.seanerikoconnor.freeservers.com/Mathematics/AbstractAlgebra/PrimitivePolynomials/theory.html # Generate all p**m possible coefficients for coeff_idx in range(p**m, p**(m + 1)): # Calculate all coefficients base p # (Note that base_repr returns numbers with the least significant nit in the last column.) coeffs = [int(aux_str) for aux_str in base_repr(coeff_idx, p)] coeffs = coeffs[::-1] if is_primitive_polynomial(coeffs, p, m): return coeffs # If no primitve polynomial is found, return the empty set return []
def cantor(x): xb3 = np.base_repr(x, 3) # print(xb3) string = str(xb3) chars = [] count = 1 for ch in string: if str(ch) == str(1): chars.append(str(1)) break else: chars.append(str(ch)) count += 1 # print(count) for i in range(0, len(string) - count): chars.append(str(0)) # print(chars) chars2 = [] for i in range(len(chars)): if chars[i] == str(2): chars2.append(1) if chars[i] == str(1): chars2.append(1) if chars[i] == str(0): chars2.append(0) # print(chars2) result = ft.reduce(lambda a, b: a + str(b), chars2, '') # print(result) result2 = int(result, 2) # print(result2) return result2
def survey_begin(): """Base url start the survey for user with key c""" c = request.args.get('c') params = dict(DEFAULT_PARAMS) post_links = [] sub = subreddits[key_data[c]['index']] for id, data in post_link_data[sub].items(): num = base_repr(int(id), 36) link = "https://reddit.com/r/" + sub + "/comments/" + num post_links.append((link, data)) params.update({ "c": c, "subreddit": subreddits[key_data[c]['index']], "id": key_data[c]['index'], "nmore": key_data[c]['npages'], "percent": 0, "post_links": post_links }) return render_template('poll.html.jinja2', **params)
def get_max_extreme(G,D,N): """Calculate the array d_hat such that:: d_hat = max(G*DN_extreme), where DN_extreme are the vertices of the set D^N. This is used to describe the polytope:: L*x <= M - G*d_hat. Calculating d_hat is equivalen to taking the intersection of the polytopes:: L*x <= M - G*d_i for every possible d_i in the set of extreme points to D^N. @param G: The matrix to maximize with respect to @param D: Polytope describing the disturbance set @param N: Horizon length @return: d_hat: Array describing the maximum possible effect from the disturbance """ D_extreme = pc.extreme(D) nv = D_extreme.shape[0] dim = D_extreme.shape[1] DN_extreme = np.zeros([dim*N, nv**N]) for i in xrange(nv**N): # Last N digits are indices we want! ind = np.base_repr(i, base=nv, padding=N) for j in xrange(N): DN_extreme[range(j*dim,(j+1)*dim),i] = D_extreme[int(ind[-j-1]),:] d_hat = np.amax(np.dot(G,DN_extreme), axis=1) return d_hat.reshape(d_hat.size,1)
def poll(id): """The polling storage method for user with key c and for sequence id """ params = dict(DEFAULT_PARAMS) key = request.args.get('c') allparams = request.args.items() subreddit = subreddits[id] for param in allparams: if param[0] == 'c' or param[0] == 'subreddit': continue else: query_db("insert into link_value values(?,?,?,?)", [key, param[0], param[1], datetime.utcnow()]) if id + 1 >= key_data[key]['npages'] + key_data[key]['index']: params.update({ "participant": key_data[key]['participant'] }) return render_template('finish.html.jinja2', **params) else: sub = subreddits[id + 1] post_links = [] for num, data in post_link_data[sub].items(): num = base_repr(int(num), 36) link = "https://reddit.com/r/" + sub + "/comments/" + num post_links.append((link, data)) params.update({ "c": key, "subreddit": subreddits[id + 1], "id": id + 1, "nmore": key_data[key]['npages'] - (id - key_data[key]['index'] + 1), "percent": float(id - key_data[key]['index'] + 1) / key_data[key]['npages'] * 100, "post_links": post_links }) return render_template('poll.html.jinja2', **params)
def get_board_from_id(self, bid): """ Given a unique board ID, return the associated board array. The board ID is a base-10 number, that when converted to a base-3 number repro- duces the board configuration. Args: bid: The board ID to evaluate. Returns: board: A numpy array containing the associated board configuration. """ # convert the decimal bid into a base 3 number, represented as a string flat_board_string = np.base_repr(bid, base=3) strlen = len(flat_board_string) fboard = np.zeros(self.NROW * self.NCOL, dtype=int) for i in range(strlen): fboard[i] = flat_board_string[strlen - 1 - i] board = np.reshape(np.flipud(fboard), (self.NROW, self.NCOL)) return board
def binary(): print '###########################' print '#' print '# 二进制处理' print '#' print '###########################' x = np.array([[[1,0,1], [0,1,0]], [[1,1,0], [0,0,1]]]) print '二进制字符串表示:', np.binary_repr(-3, width=4) print '自定义进制字符串表示:', np.base_repr(7, base=5, padding=3) print '二进制打包为整型:', np.packbits(x, axis=-1) print '整型解包为二进制:', np.unpackbits(np.array(b[0], dtype=np.uint8).reshape(8, -1), axis=1) print '左位移:', np.left_shift(5, 2) print '右位移:', np.right_shift(5, 2) # 求反的参数必须为unit8类型的数组 print '求反:', np.invert(np.array([13], dtype=np.uint8)) print '求异或:', np.bitwise_xor(13, 17) print '求或:', np.bitwise_or(13, 16) print '求与:', np.bitwise_and(13, 17)
""" Created Nov 19, 2012 Author: Spencer Lyon Project Euler Problem 36 """ import numpy as np from time import time start_time = time() the_sum = 0 for i in xrange(1, 1000000): si = str(i) if si == si[::-1]: b2i = np.base_repr(i) if b2i == b2i[::-1]: the_sum += i print 'The answer is: ', the_sum running_time = time() elapsed_time = running_time - start_time print 'Total Execution time is ', elapsed_time, 'seconds'
def x1(self): return numpy.base_repr(random.randint(16777216,16777216*2-1),36).lower()
def newInteger(self, n): """ :type n: int :rtype: int """ return int(numpy.base_repr(n, 9))