code stringlengths 1 18.2k |
|---|
def diamondTabularFormatToDicts(filename, fieldNames=None): """ Read DIAMOND tabular (--outfmt 6) output and convert lines to dictionaries. @param filename: Either a C{str} file name or an open file pointer. @param fieldNames: A C{list} or C{tuple} of C{str} DIAMOND field names. Run 'diamond -help' to see the full list... |
> 1: raise ValueError( 'fieldNames contains duplicated names: %s.' % (', '.join(sorted(x[0] for x in c.most_common() if x[1] > 1)))) def identity(x): return x convertFunc = DIAMOND_FIELD_CONVERTER.get with as_handle(filename) as fp: for count, line in enumerate(fp, start=1): result = {} line = line[:-1] values = line.s... |
def records(self): """ Parse the DIAMOND output and yield records. This will be used to read original DIAMOND output (either from stdin or from a file) to turn the DIAMOND results into Python dictionaries that will then be stored in our JSON format. @return: A generator that produces C{dict}s containing 'alignments' an... |
output generated before # that. So those values will be None when reading # DIAMOND output without those fields, but that's much # better than no longer being able to read that data. if six.PY2: error = 'need more than 13 values to unpack' else: error = ( 'not enough values to unpack (expected 15, ' 'got 13)') if str(e... |
qtitle: # We have already started accumulating alignments for this # query. if stitle not in subjectsSeen: # We have not seen this subject before, so this is a # new alignment. subjectsSeen.add(stitle) alignment = { 'hsps': [hsp], 'length': int(slen), 'title': stitle, } record['alignments'].append(alignment) else: # We... |
Yield the last record, if any. if record: yield record |
def saveAsJSON(self, fp, writeBytes=False): """ Write the records out as JSON. The first JSON object saved contains information about the DIAMOND algorithm. @param fp: A C{str} file pointer to write to. @param writeBytes: If C{True}, the JSON will be written out as bytes (not strings). This is required when we are writ... |
def _dictToAlignments(self, diamondDict, read): """ Take a dict (made by DiamondTabularFormatReader.records) and convert it to a list of alignments. @param diamondDict: A C{dict}, from records(). @param read: A C{Read} instance, containing the read that DIAMOND used to create this record. @return: A C{list} of L{dark.a... |
None for those JSON files, # but that's much better than no longer being able to # read all that data. identicalCount=diamondHsp.get('identicalCount'), positiveCount=diamondHsp.get('positiveCount')) alignment.addHsp(hsp) return alignments |
def object_as_dict(obj): """Turn an SQLAlchemy model into a dict of field names and values. Based on https://stackoverflow.com/a/37350445/1579058 """ return {c.key: getattr(obj, c.key) for c in inspect(obj).mapper.column_attrs} |
def fetch_object(self, model_id): """Fetch the model by its ID.""" pk_field_instance = getattr(self.object_class, self.pk_field) qs = self.object_class.query.filter(pk_field_instance == model_id) model = qs.one_or_none() if not model: raise ReferenceNotFoundError return model |
def bytecount(rst, clk, rx_vld, rx_sop, rx_eop, rx_dat, rx_mty, count, MAX_BYTES=1500 ): """ Counts bytes in a stream of packetised data rx_vld - (i) valid data rx_sop - (i) start of packet rx_eop - (i) end of packet rx_dat - (i) data rx_mty - (i) empty bits when rx_eop count - (o) byte count MAX_BYTES - a limit: maxim... |
-rx_mty if (rx_sop==1): count_s.next = x else: count_s.next = count_s + x @always_comb def out_comb(): count.next = count_s return instances() |
def checksum(rst, clk, rx_vld, rx_sop, rx_eop, rx_dat, rx_mty, chksum, sum16=None, sumN=None, init_sum=None, MAX_BYTES=1500): """ Calculates checksum on a stream of packetised data rx_vld - (i) valid data rx_sop - (i) start of packet rx_eop - (i) end of packet rx_dat - (i) data rx_mty - (i) empty bits when rx_eop init_... |
""" DATA_WIDTH = len(rx_dat) assert DATA_WIDTH%16==0, "checksum: expects len(rx_dat)=16*x, but len(tx_dat)={}".format(DATA_WIDTH) NUM_BYTES = DATA_WIDTH // 8 NUM_WORDS = DATA_WIDTH // 16 SUM_WIDTH = 16 + int(ceil(log(MAX_BYTES/2,2))) + 1 SUM16_WIDTH = 16 + int(ceil(log(NUM_WORDS,2))) + 1 if (init_sum != None): assert l... |
= int(init_sum) else: s = int(sumN_reg) for w in range(NUM_WORDS): s += mdata16[w] sumN_reg.next = s @always_comb def _passN(): sumN.next = sumN_reg if chksum!=None or sum16!=None: sum16_reg = Signal(intbv(0)[SUM16_WIDTH:]) @always_seq(clk.posedge, reset=rst) def _accu16(): ''' Accumulate 16 bit words''' if (rx_vld): s... |
def get_argument_parser(): """Function to obtain the argument parser. Returns ------- A fully configured `argparse.ArgumentParser` object. Notes ----- This function is used by the `sphinx-argparse` extension for sphinx. """ file_mv = cli.file_mv desc = 'Extracts gene-level expression data from StringTie output.' parser... |
def main(args=None): """Extracts gene-level expression data from StringTie output. Parameters ---------- args: argparse.Namespace object, optional The argument values. If not specified, the values will be obtained by parsing the command line arguments using the `argparse` module. Returns ------- int Exit code (0 if no ... |
reader = csv.reader(fh, dialect='excel-tab') for l in reader: if l[0][0] == '#': continue assert len(l) == 9 if l[2] != 'transcript': continue attr = parse_attributes(l[8]) try: ref_gene = attr['ref_gene_name'] except KeyError: continue else: # entry has a "ref_gene_name" attribute try: g = stringtie_genes[attr['gene_i... |
0 with open(stringtie_file) as fh: reader = csv.reader(fh, dialect='excel-tab') for l in reader: if l[0][0] == '#': # skip header continue assert len(l) == 9 if l[2] != 'transcript': # skip exon lines continue attr = parse_attributes(l[8]) f = float(attr['FPKM']) try: g = attr['ref_gene_name'] except KeyError: if no_no... |
ValueError: fpkm_unknown_gene_name += f logger.warning('Unknown gene name: "%s".', g) continue t = float(attr['TPM']) fpkm[idx] += f tpm[idx] += t # ignored_fpkm = None if no_novel_transcripts: ignored_fpkm = fpkm_novel_trans + fpkm_unknown_gene_name else: ignored_fpkm = fpkm_novel_gene + fpkm_ambig + fpkm_unknown_gene... |
open(output_file, 'w') as ofh: writer = csv.writer(ofh, dialect='excel-tab', lineterminator=os.linesep, quoting=csv.QUOTE_NONE) for i, g in enumerate(genes): writer.writerow([g] + ['%.5f' % e for e in E[i, :]]) return 0 |
def init_ixe(logger, host, port=4555, rsa_id=None): """ Connect to Tcl Server and Create IxExplorer object. :param logger: python logger object :param host: host (IxTclServer) IP address :param port: Tcl Server port :param rsa_id: full path to RSA ID file for Linux based IxVM :return: IXE object """ return IxeApp(logge... |
def connect(self, user=None): """ Connect to host. :param user: if user - login session. """ self.api._tcl_handler.connect() if user: self.session.login(user) |
def add(self, chassis): """ add chassis. :param chassis: chassis IP address. """ self.chassis_chain[chassis] = IxeChassis(self.session, chassis, len(self.chassis_chain) + 1) self.chassis_chain[chassis].connect() |
def reserve_ports(self, ports_locations, force=False, clear=True, phy_mode=IxePhyMode.ignore): """ Reserve ports and reset factory defaults. :param ports_locations: list of ports ports_locations <ip, card, port> to reserve :param force: True - take forcefully, False - fail if port is reserved by other user :param clear... |
def wait_for_up(self, timeout=16, ports=None): """ Wait until ports reach up state. :param timeout: seconds to wait. :param ports: list of ports to wait for. :return: """ port_list = [] for port in ports: port_list.append(self.set_ports_list(port)) t_end = time.time() + timeout ports_not_in_up = [] ports_in_up = [] whi... |
def clear_all_stats(self, *ports): """ Clear all statistic counters (port, streams and packet groups) on list of ports. :param ports: list of ports to clear. """ port_list = self.set_ports_list(*ports) self.api.call_rc('ixClearStats {}'.format(port_list)) self.api.call_rc('ixClearPacketGroups {}'.format(port_list)) |
def start_transmit(self, blocking=False, start_packet_groups=True, *ports): """ Start transmit on ports. :param blocking: True - wait for traffic end, False - return after traffic start. :param start_packet_groups: True - clear time stamps and start collecting packet groups stats, False - don't. :param ports: list of p... |
def start_packet_groups(self, clear_time_stamps=True, *ports): """ Start packet groups on ports. :param clear_time_stamps: True - clear time stamps, False - don't. :param ports: list of ports to start traffic on, if empty start on all ports. """ port_list = self.set_ports_list(*ports) if clear_time_stamps: self.api.cal... |
def stop_transmit(self, *ports): """ Stop traffic on ports. :param ports: list of ports to stop traffic on, if empty start on all ports. """ port_list = self.set_ports_list(*ports) self.api.call_rc('ixStopTransmit {}'.format(port_list)) time.sleep(0.2) |
def wait_transmit(self, *ports): """ Wait for traffic end on ports. :param ports: list of ports to wait for, if empty wait for all ports. """ port_list = self.set_ports_list(*ports) self.api.call_rc('ixCheckTransmitDone {}'.format(port_list)) |
def start_capture(self, *ports): """ Start capture on ports. :param ports: list of ports to start capture on, if empty start on all ports. """ IxeCapture.current_object = None IxeCaptureBuffer.current_object = None if not ports: ports = self.ports.values() for port in ports: port.captureBuffer = None port_list = self.s... |
def stop_capture(self, cap_file_name=None, cap_file_format=IxeCapFileFormat.mem, *ports): """ Stop capture on ports. :param cap_file_name: prefix for the capture file name. Capture files for each port are saved as individual pcap file named 'prefix' + 'URI'.pcap. :param cap_file_format: exported file format :param port... |
def get_cap_files(self, *ports): """ :param ports: list of ports to get capture files names for. :return: dictionary (port, capture file) """ cap_files = {} for port in ports: if port.cap_file_name: with open(port.cap_file_name) as f: cap_files[port] = f.read().splitlines() else: cap_files[port] = None return cap_files |
def set_stream_stats(self, rx_ports=None, tx_ports=None, start_offset=40, sequence_checking=True, data_integrity=True, timestamp=True): """ Set TX ports and RX streams for stream statistics. :param ports: list of ports to set RX pgs. If empty set for all ports. :type ports: list[ixexplorer.ixe_port.IxePort] :param tx_p... |
8 if sequence_checking: sequenceNumberOffset = next_offset next_offset += 4 if data_integrity: di_signatureOffset = next_offset for port in rx_ports: modes = [] modes.append(IxeReceiveMode.widePacketGroup) port.packetGroup.groupIdOffset = groupIdOffset port.packetGroup.signatureOffset = signatureOffset if sequence_chec... |
def set_prbs(self, rx_ports=None, tx_ports=None): """ Set TX ports and RX streams for stream statistics. :param ports: list of ports to set RX PRBS. If empty set for all ports. :type ports: list[ixexplorer.ixe_port.IxePort] :param tx_ports: list of streams to set TX PRBS. If empty set for all streams. :type tx_ports: d... |
def chr22XY(c): """force to name from 1..22, 23, 24, X, Y, M to in chr1..chr22, chrX, chrY, chrM str or ints accepted >>> chr22XY('1') 'chr1' >>> chr22XY(1) 'chr1' >>> chr22XY('chr1') 'chr1' >>> chr22XY(23) 'chrX' >>> chr22XY(24) 'chrY' >>> chr22XY("X") 'chrX' >>> chr22XY("23") 'chrX' >>> chr22XY("M") 'chrM' """ c = st... |
def infer_namespace(ac): """Infer the single namespace of the given accession This function is convenience wrapper around infer_namespaces(). Returns: * None if no namespaces are inferred * The (single) namespace if only one namespace is inferred * Raises an exception if more than one namespace is inferred >>> infer_na... |
def infer_namespaces(ac): """infer possible namespaces of given accession based on syntax Always returns a list, possibly empty >>> infer_namespaces("ENST00000530893.6") ['ensembl'] >>> infer_namespaces("ENST00000530893") ['ensembl'] >>> infer_namespaces("ENSQ00000530893") [] >>> infer_namespaces("NM_01234") ['refseq']... |
def _add(self, other): """Add a interval to the underlying IntervalSet data store. This does not perform any tests as we assume that any requirements have already been checked and that this function is being called by an internal function such as union(), intersection() or add(). :param other: An Interval to add to thi... |
def intersection(self, other): """Returns a new IntervalSet which represents the intersection of each of the intervals in this IntervalSet with each of the intervals in the other IntervalSet. :param other: An IntervalSet to intersect with this one. """ # if self or other is empty the intersection will be empty result =... |
def union(self, other): """Returns a new IntervalSet which represents the union of each of the intervals in this IntervalSet with each of the intervals in the other IntervalSet :param other: An IntervalSet to union with this one. """ result = IntervalSet() for el in self: result.add(el) for el in other: result.add(el) ... |
def add(self, other): """ Add an Interval to the IntervalSet by taking the union of the given Interval object with the existing Interval objects in self. This has no effect if the Interval is already represented. :param other: an Interval to add to this IntervalSet. """ if other.empty(): return to_add = set() for inter... |
def difference(self, other): """ Subtract an Interval or IntervalSet from the intervals in the set. """ intervals = other if isinstance(other, IntervalSet) else IntervalSet((other,)) result = IntervalSet() for left in self: for right in intervals: left = left - right if isinstance(left, IntervalSet): for interval in le... |
def send_notification(self, subject="", message="", sender="", source=None, actions=None): """ Sends a notification. Blocks as long as necessary. :param subject: The subject. :type subject: str :param message: The message. :type message: str :param sender: The sender. :type sender: str :param source: The source of the ... |
def randomBinaryField(self): """ Return random bytes format. """ lst = [ b"hello world", b"this is bytes", b"awesome django", b"djipsum is awesome", b"\x00\x01\x02\x03\x04\x05\x06\x07", b"\x0b\x0c\x0e\x0f" ] return self.randomize(lst) |
def randomCharField(self, model_class, field_name): """ Checking if `field_name` has choices. Then, returning random value from it. Result of: `available_choices` [ ('project', 'I wanna to talk about project'), ('feedback', 'I want to report a bugs or give feedback'), ('hello', 'I just want to say hello') ] """ try: av... |
def randomCommaSeparatedIntegerField(self): """ Return the unique integers in the string such as below: '6,1,7' or '4,5,1,3,2' or '2,7,9,3,5,4,1' or '3,9,2,8,7,1,5,4,6' """ randint = lambda max: ",".join( [str(x) for x in random.sample(range(1, 10), max)] ) lst = [ randint(3), randint(5), randint(7), randint(9) ] retur... |
def randomDecimalField(self, model_class, field_name): """ Validate if the field has a `max_digits` and `decimal_places` And generating the unique decimal number. """ decimal_field = model_class._meta.get_field(field_name) max_digits = None decimal_places = None if decimal_field.max_digits is not None: max_digits = dec... |
def randomSlugField(self): """ Return the unique slug by generating the uuid4 to fix the duplicate slug (unique=True) """ lst = [ "sample-slug-{}".format(uuid.uuid4().hex), "awesome-djipsum-{}".format(uuid.uuid4().hex), "unique-slug-{}".format(uuid.uuid4().hex) ] return self.randomize(lst) |
def randomUUIDField(self): """ Return the unique uuid from uuid1, uuid3, uuid4, or uuid5. """ uuid1 = uuid.uuid1().hex uuid3 = uuid.uuid3( uuid.NAMESPACE_URL, self.randomize(['python', 'django', 'awesome']) ).hex uuid4 = uuid.uuid4().hex uuid5 = uuid.uuid5( uuid.NAMESPACE_DNS, self.randomize(['python', 'django', 'aweso... |
def getOrCreateForeignKey(self, model_class, field_name): """ Return related random object to set as ForeignKey. """ # Getting related object type # Eg: <django.db.models.fields.related.ForeignKey: test_ForeignKey> instance = getattr(model_class, field_name).field # Getting the model name by instance to find/create fir... |
def create_validated_fields(self): """ To generate lorem ipsum by validated fields for the model. """ model_class = self.model_class fields = self.fields maximum = self.maximum objects = [] for n in range(maximum): data_dict = {} for field in fields: def default_assign(func): data_dict[field['field_name']] = func def s... |
elif field['field_type'] == 'EmailField': # self.randomEmailField() string_assign(self.randomEmailField()) elif field['field_type'] == 'FileField': # self.randomFileField() string_assign(self.randomFileField()) elif field['field_type'] == 'FloatField': # 1.92, 0.0, 5.0, or else. default_assign(float(("%.2f" % float(ran... |
string_assign(str(datetime.datetime.now().date())) elif field['field_type'] == 'URLField': # self.randomURLField() string_assign(self.randomURLField()) elif field['field_type'] == 'UUIDField': # self.randomUUIDField() string_assign(self.randomUUIDField()) elif field['field_type'] == 'ForeignKey': # self.getOrCreateFore... |
has minimum objects to be choice. if len(random_decission) <= 2: random_decission = [self.randomize(ids_m2m)] related_objects = [ rel_obj for rel_obj in objects_m2m if rel_obj.pk in random_decission ] # adding the `ManyToManyField` instance_m2m.add(*related_objects) try: obj.save_m2m() except: obj.save() objects.append... |
def get_flash_region(self, offset, length): """ Retrieves the contents of a region of flash from the watch. This only works on watches running non-release firmware. Raises :exc:`.GetBytesError` on failure. :return: The retrieved data :rtype: bytes """ return self._get(GetBytesFlashRequest(offset=offset, length=length)) |
def grab_image(self): """ Takes a screenshot. Blocks until completion, or raises a :exc:`.ScreenshotError` on failure. While this method is executing, "progress" events will periodically be emitted with the following signature: :: (downloaded_so_far, total_size) :return: A list of bytearrays in RGB8 format, where each ... |
def trade_day(dt, cal='US'): """ Latest trading day w.r.t given dt Args: dt: date of reference cal: trading calendar Returns: pd.Timestamp: last trading day Examples: >>> trade_day('2018-12-25').strftime('%Y-%m-%d') '2018-12-24' """ from xone import calendar dt = pd.Timestamp(dt).date() return calendar.trading_dates(st... |
def cur_time(typ='date', tz=DEFAULT_TZ, trading=True, cal='US'): """ Current time Args: typ: one of ['date', 'time', 'time_path', 'raw', ''] tz: timezone trading: check if current date is trading day cal: trading calendar Returns: relevant current time or date Examples: >>> cur_dt = pd.Timestamp('now') >>> cur_time(typ... |
def align_data(*args): """ Resample and aligh data for defined frequency Args: *args: DataFrame of data to be aligned Returns: pd.DataFrame: aligned data with renamed columns Examples: >>> start = '2018-09-10T10:10:00' >>> tz = 'Australia/Sydney' >>> idx = pd.date_range(start=start, periods=6, freq='min').tz_localize(t... |
2018-09-10 10:12:00+10:00 70.85 4908 2018-09-10 10:13:00+10:00 70.79 2002 2018-09-10 10:14:00+10:00 70.79 9170 2018-09-10 10:15:00+10:00 70.79 9791 >>> align_data(d1, d2) price_1 volume_1 price_2 volume_2 2018-09-10 10:10:00+10:00 31.08 10166 70.81 4749 2018-09-10 10:11:00+10:00 31.10 69981 70.78 6762 2018-09-10 10:12:... |
def cat_data(data_kw): """ Concatenate data with ticker as sub column index Args: data_kw: key = ticker, value = pd.DataFrame Returns: pd.DataFrame Examples: >>> start = '2018-09-10T10:10:00' >>> tz = 'Australia/Sydney' >>> idx = pd.date_range(start=start, periods=6, freq='min').tz_localize(tz) >>> close_1 = [31.08, 31... |
AU price 31.08 31.10 volume 10,166.00 69,981.00 RIO AU price 70.81 70.78 volume 4,749.00 6,762.00 """ if len(data_kw) == 0: return pd.DataFrame() return pd.DataFrame(pd.concat([ data.assign(ticker=ticker).set_index('ticker', append=True) .unstack('ticker').swaplevel(0, 1, axis=1) for ticker, data in data_kw.items() ], ... |
def to_frame(data_list, exc_cols=None, **kwargs): """ Dict in Python 3.6 keeps insertion order, but cannot be relied upon This method is to keep column names in order In Python 3.7 this method is redundant Args: data_list: list of dict exc_cols: exclude columns Returns: pd.DataFrame Example: >>> d_list = [ ... dict(sid... |
def spline_curve(x, y, step, val_min=0, val_max=None, kind='quadratic', **kwargs): """ Fit spline curve for given x, y values Args: x: x-values y: y-values step: step size for interpolation val_min: minimum value of result val_max: maximum value of result kind: for scipy.interpolate.interp1d Specifies the kind of inter... |
spline_curve(x=x, y=y, step=.5, val_min=3, val_max=18, fill_value='extrapolate') >>> r.round(2).index.tolist() [1.0, 1.5, 2.0, 2.5, 3.0] >>> r.round(2).tolist() [3.0, 4.05, 7.39, 12.73, 18.0] >>> y_df = pd.DataFrame(dict(a=[np.exp(1), np.exp(2), np.exp(3)], b=[2, 3, 4])) >>> r_df = spline_curve(x=x, y=y_df, step=.5, va... |
def format_float(digit=0, is_pct=False): """ Number display format for pandas Args: digit: number of digits to keep if negative, add one space in front of positive pct is_pct: % display Returns: lambda function to format floats Examples: >>> format_float(0)(1e5) '100,000' >>> format_float(1)(1e5) '100,000.0' >>> format... |
def inst_repr(instance, fmt='str', public_only=True): """ Generate class instance signature from its __dict__ From python 3.6 dict is ordered and order of attributes will be preserved automatically Args: instance: class instance fmt: ['json', 'str'] public_only: if display public members only Returns: str: string or js... |
elif fmt == 'str': return to_str(inst_dict, public_only=public_only) return '' |
def concat_expr(operator, conditions): """ Concatenate `conditions` with `operator` and wrap it by (). It returns a string in a list or empty list, if `conditions` is empty. """ expr = " {0} ".format(operator).join(conditions) return ["({0})".format(expr)] if expr else [] |
def join(self, source, op='LEFT JOIN', on=''): """ Join `source`. >>> sc = SQLConstructor('main', ['c1', 'c2']) >>> sc.join('sub', 'JOIN', 'main.id = sub.id') >>> (sql, params, keys) = sc.compile() >>> sql 'SELECT c1, c2 FROM main JOIN sub ON main.id = sub.id' It is possible to pass another `SQLConstructor` as a source... |
source: >>> params ['abc', 111] Note that `subsc.compile` is called when `sc.join(subsc, ...)` is called. Therefore, calling `subsc.add_<predicate>` does not effect `sc`. :type source: str or SQLConstructor :arg source: table :type op: str :arg op: operation (e.g., 'JOIN') :type on: str :arg on: on clause. `source` ("r... |
def compile(self): """ Compile SQL and return 3-tuple ``(sql, params, keys)``. Example usage:: (sql, params, keys) = sc.compile() for row in cursor.execute(sql, params): record = dict(zip(keys, row)) """ params = self.column_params + self.join_params + self.params if self.limit and self.limit >= 0: self.sql_limit = 'LI... |
def add_and_matches(self, matcher, lhs, params, numq=1, flatten=None): """ Add AND conditions to match to `params`. :type matcher: str or callable :arg matcher: if `str`, `matcher.format` is used. :type lhs: str :arg lhs: the first argument to `matcher`. :type params: list :arg params: each element should be able to fe... |
def add_matches(self, matcher, lhs, match_params=[], include_params=[], exclude_params=[], numq=1, flatten=None): """ Quick way to call `add_or_matches` and `add_and_matches`. """ matcher = adapt_matcher(matcher) notmatcher = negate(matcher) self.add_and_matches(matcher, lhs, match_params, numq, flatten) self.add_or_ma... |
def uniquify_by(self, column, chooser=None, aggregate='MAX'): """ Group by `column` and run `aggregate` function on `chooser` column. """ self.group_by.append(column) if chooser: i = self.columns.index(chooser) self.columns[i] = '{0}({1})'.format(aggregate, self.columns[i]) |
def move_where_clause_to_column(self, column='condition', key=None): """ Move whole WHERE clause to a column named `column`. """ if self.conditions: expr = " AND ".join(self.conditions) params = self.params self.params = [] self.conditions = [] else: expr = '1' params = [] self.add_column('({0}) AS {1}'.format(expr, co... |
def remove_axis_junk(ax, which=['right', 'top']): '''remove upper and right axis''' for loc, spine in ax.spines.items(): if loc in which: spine.set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') |
def plot_signal_sum(ax, z, fname='LFPsum.h5', unit='mV', ylabels=True, scalebar=True, vlimround=None, T=[0, 1000], color='k', label=''): ''' on axes plot the signal contributions args: :: ax : matplotlib.axes.AxesSubplot object z : np.ndarray T : list, [tstart, tstop], which timeinterval ylims : list, set range of yaxi... |
vlimround = 2.**np.round(np.log2(vlim)) yticklabels=[] yticks = [] colors = [color]*data.shape[0] for i, z in enumerate(z): if i == 0: ax.plot(tvec[slica], data[i, slica] * 100 / vlimround + z, color=colors[i], rasterized=False, label=label, clip_on=False) else: ax.plot(tvec[slica], data[i, slica] * 100 / vlimround + z... |
def plot_population(ax, populationParams, electrodeParams, layerBoundaries, aspect='equal', isometricangle=np.pi/12, X=['EX', 'IN'], markers=['^', 'o'], colors=['r', 'b'], layers = ['upper', 'lower'], title='positions'): ''' Plot the geometry of the column model, optionally with somatic locations and optionally with re... |
ax.xaxis.set_ticks([]) ax.yaxis.set_ticks([]) #contact points ax.plot(electrodeParams['x'], electrodeParams['z'], '.', marker='o', markersize=5, color='k', zorder=0) #outline of electrode x_0 = np.array(electrodeParams['r_z'])[1, 1:-1] z_0 = np.array(electrodeParams['r_z'])[0, 1:-1] x = np.r_[x_0[-1], x_0[::-1], -x_0[1... |
clip_on=False) #plot a horizontal radius scalebar ax.plot([0, r], [z_0.min()]*2, 'k', lw=2, zorder=0, clip_on=False) ax.text(r / 2., z_0.min()-100, 'r = %i $\mu$m' % int(r), ha='center') #plot a vertical depth scalebar ax.plot([-r]*2, [z_0.min()+50, z_0.min()-50], 'k', lw=2, zorder=0, clip_on=False) ax.text(-r, z_0.min... |
def normalize(x): '''normalize x to have mean 0 and unity standard deviation''' x = x.astype(float) x -= x.mean() return x / float(x.std()) |
def plot_correlation(z_vec, x0, x1, ax, lag=20., title='firing_rate vs LFP'): ''' mls on axes plot the correlation between x0 and x1 args: :: x0 : first dataset x1 : second dataset - e.g., the multichannel LFP ax : matplotlib.axes.AxesSubplot object title : text to be used as current axis object title ''' zvec = np.r_[... |
ax.set_ylim(z-100, 100) axis = ax.axis() ax.vlines(0, axis[2], axis[3], 'r', 'dotted') ax.yaxis.set_ticks(yticks) ax.yaxis.set_ticklabels(yticklabels) ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') # Create a scaling bar ax.plot([lag, lag], [0, 100], lw=2, color='k', clip_on=False) ax.text(la... |
def _PrPz(r0, z0, r1, z1, r2, z2, r3, z3): """ Intersection point for infinite lines. Parameters ---------- r0 : float z0 : float r1 : float z1 : float r2 : float z2 : float r3 : float z3 : float Returns ---------- Pr : float Pz : float hit : bool """ Pr = ((r0*z1 - z0*r1)*(r2 - r3) - (r0 - r1)*(r2*z3 - r3*z2)) / \ ((r... |
and Pz >= z0 and Pz <= z1: hit = True elif Pr >= r0 and Pr <= r1 and Pz <= z0 and Pz >= z1: hit = True elif Pr <= r0 and Pr >= r1 and Pz <= z0 and Pz >= z1: hit = True else: hit = False return [Pr, Pz, hit] |
def true_lam_csd(cell, dr=100, z=None): """ Return CSD from membrane currents as function along the coordinates of the electrode along z-axis. Parameters ---------- cell : `LFPy.cell.Cell` or `LFPy.cell.TemplateCell` object. Cell. dr : float Radius of the cylindrical CSD volume. z : numpy.ndarray Z-coordinates of elect... |
dr cc1 = r_end < dr ii = aa0 & bb0 & cc0 # startpoint inside volume jj = aa1 & bb1 & cc1 # endpoint inside volume for j in range(cell.zstart.size): # Calc fraction of source being inside control volume from 0-1 # both start and endpoint in volume if ii[j] and jj[j]: CSD[i,] = CSD[i, ] + cell.imem[j, ] / volume # Startp... |
z3 = [z[i]-dz/2, z[i]+dz/2, z[i]+dz/2] r3 = [dr, dr, dr] P = [] for k in range(3): P.append(_PrPz(r0, z0, r1, z1, r2[k], z2[k], r3[k], z3[k])) if P[k][2]: vL2 = (P[k][0] - r0)**2 + (P[k][1] -z0)**2 frac = np.sqrt(vL2 / L2) CSD[i,] = CSD[i, ] + frac * cell.imem[j, ] / volume # Endpoint in volume: elif jj[j] and not ii[j... |
[] for k in range(3): P.append(_PrPz(r0, z0, r1, z1, r2[k], z2[k], r3[k], z3[k])) if P[k][2]: vL2 = (r1 - P[k][0])**2 + (z1 - P[k][1])**2 frac = np.sqrt(vL2 / L2) CSD[i,] = CSD[i, ] + frac * cell.imem[j, ] / volume else: pass return CSD |
def search_run(output, **kwds): """ Search command history. """ from .config import ConfigStore from .database import DataBase from .query import expand_query, preprocess_kwds cfstore = ConfigStore() kwds = expand_query(cfstore.get_config(), kwds) format = get_formatter(**kwds) fmtkeys = formatter_keys(format) candidat... |
def fig_intro(params, ana_params, T=[800, 1000], fraction=0.05, rasterized=False): '''set up plot for introduction''' ana_params.set_PLOS_2column_fig_style(ratio=0.5) #load spike as database networkSim = CachedNetwork(**params.networkSimParams) if analysis_params.bw: networkSim.colors = phlp.get_colors(len(networkSim.X... |
va='bottom', fontweight='normal') phlp.annotate_subplot(ax2, ncols=4, nrows=1, letter='C', linear_offset=0.065) #LFP traces in all channels ax3 = fig.add_subplot(gs[:, 3], frameon=True) phlp.remove_axis_junk(ax3) plot_signal_sum(ax3, params, fname=os.path.join(params.savefolder, 'LFPsum.h5'), unit='mV', vlimround=0.8, ... |
def index_record(self, json_path): """ Import `json_path` and remove it if :attr:`keep_json` is false. """ self.logger.debug('Indexing record: %s', json_path) json_path = os.path.abspath(json_path) self.check_path(json_path, '`json_path`') with open(json_path) as fp: try: dct = json.load(fp) except ValueError: warnings... |
def find_record_files(self): """ Yield paths to record files. """ for (root, _, files) in os.walk(self.record_path): for f in (f for f in files if f.endswith('.json')): yield os.path.join(root, f) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.