Processes a single patient for ``two_antidepressant_episodes()`` (q.v.).

    Implements the key algorithm.
425349
def two_antidepressant_episodes_single_patient(
        patient_id: str,
        patient_drug_date_df: DataFrame,
        patient_colname: str = DEFAULT_SOURCE_PATIENT_COLNAME,
        drug_colname: str = DEFAULT_SOURCE_DRUG_COLNAME,
        date_colname: str = DEFAULT_SOURCE_DATE_COLNAME,
        course_length_days: int = DEFAULT_ANTIDEPRESSANT_COURSE_LENGTH_DAYS,
        expect_response_by_days: int = DEFAULT_EXPECT_RESPONSE_BY_DAYS,
        symptom_assessment_time_days: int = DEFAULT_SYMPTOM_ASSESSMENT_TIME_DAYS,  # noqa
        first_episode_only: bool = True) -> Optional[DataFrame]:
    
    log.debug("Running two_antidepressant_episodes_single_patient() for "
              "patient {!r}".format(patient_id))
    all_episodes_for_patient = _get_blank_two_antidep_episodes_result()
    flush_stdout_stderr()
    # Get column details from source data
    sourcecolnum_drug = patient_drug_date_df.columns.get_loc(drug_colname)
    sourcecolnum_date = patient_drug_date_df.columns.get_loc(date_colname)

    # -------------------------------------------------------------------------
    # Get data for this patient
    # -------------------------------------------------------------------------
    # ... this is pretty quick (e.g. 4ms for 1150 rows
    patient_mask = patient_drug_date_df[patient_colname].values == patient_id
    tp = patient_drug_date_df[patient_mask]  # type: DataFrame

    # -------------------------------------------------------------------------
    # Sort by date, then drug.
    # ... arbitrary drug name order to make the output stable
    # -------------------------------------------------------------------------
    # ... this is about 2ms for small lists; probably not limiting
    # ... seems slower if "inplace=True" is used.
    tp = tp.sort_values(by=[date_colname, drug_colname], ascending=True)

    # log.critical("{!r}", tp)

    nrows_all = len(tp)  # https://stackoverflow.com/questions/15943769/
    if nrows_all < 4:  # need A, A, B, B; so minimum #rows is 4
        return None
    end_date = tp.iat[nrows_all - 1, sourcecolnum_date]  # date of last row

    # -------------------------------------------------------------------------
    # Get antidepressants, in the order they appear
    # -------------------------------------------------------------------------
    for first_b_rownum in range(1, nrows_all):
        # ... skip rows 0 and 1, because a drug can't be the second (B) drug
        #     unless there are two mentions of A beforehand.
        # ... modified 2019-04-01 from range(2, nrows_all) to
        #     range(1, nrows_all) because we now support A ending on the same
        #     day that B starts (so first possible "first B" row is the second
        #     row, row 1)
        # ---------------------------------------------------------------------
        # Check candidate B drug
        # ---------------------------------------------------------------------
        antidepressant_b_name = tp.iat[first_b_rownum, sourcecolnum_drug]
        antidepressant_b_first_mention = tp.iat[first_b_rownum,
                                                sourcecolnum_date]
        earliest_possible_b_second_mention = (
            antidepressant_b_first_mention +
            timedelta_days(course_length_days - 1)
        )
        if earliest_possible_b_second_mention > end_date:
            # Impossible for this to be a B course.
            # Logically unnecessary test, but improves efficiency by skipping
            # the slice operation that follows.
            continue  # try another B
        b_second_mentions = tp[
            (tp[drug_colname] == antidepressant_b_name) &  # same drug
            (tp[date_colname] >= earliest_possible_b_second_mention)
        ]
        if len(b_second_mentions) == 0:
            # No second mention of antidepressant_b_name
            continue  # try another B
        # We only care about the earliest qualifying (completion-of-course)
        # B second mention.
        antidepressant_b_second_mention = b_second_mentions.iat[
            0, sourcecolnum_date]
        # ... this statement could be moved to after the A loop, but that
        #     would sacrifice clarity.

        # ---------------------------------------------------------------------
        # Now find preceding A drug
        # ---------------------------------------------------------------------
        preceding_other_antidepressants = tp[
            (tp[drug_colname] != antidepressant_b_name) &
            # ... A is a different drug to B

            # Changed 2019-04-01: WAS THIS:
            #     (tp[date_colname] < antidepressant_b_first_mention)
            #     # ... A is mentioned before B starts
            # CHANGED TO THIS:
            (tp[date_colname] <= antidepressant_b_first_mention)
            # ... A is mentioned before B starts or on the same day
        ]
        nrows_a = len(preceding_other_antidepressants)
        if nrows_a < 2:  # need at least two mentions of A
            # No candidates for A
            continue  # try another B
        # preceding_other_antidepressants remains date-sorted (ascending)
        found_valid_a = False
        antidepressant_a_name = NaN
        antidepressant_a_first_mention = NaN
        antidepressant_a_second_mention = NaN
        for first_a_rownum in range(nrows_a - 1):
            # skip the last row, as that's impossible (the first mention of
            # A cannot be the last row since there must be two mentions of A)
            antidepressant_a_name = tp.iat[first_a_rownum, sourcecolnum_drug]
            antidepressant_a_first_mention = tp.iat[first_a_rownum,
                                                    sourcecolnum_date]
            earliest_possible_a_second_mention = (
                antidepressant_a_first_mention +
                timedelta_days(course_length_days - 1)
            )

            # 2019-04-01: CHANGED FROM:
            #     if (earliest_possible_a_second_mention >=
            #             antidepressant_b_first_mention):
            # TO:
            if (earliest_possible_a_second_mention >
                    antidepressant_b_first_mention):
                # Impossible to squeeze in the second A mention before B.
                # Logically unnecessary test, but improves efficiency by
                # skipping the slice operation that follows.
                continue  # try another A
            a_second_mentions = tp[
                (tp[drug_colname] == antidepressant_a_name) &
                # ... same drug
                (tp[date_colname] >= earliest_possible_a_second_mention)
                # ... mentioned late enough after its first mention
            ]
            if len(a_second_mentions) == 0:
                # No second mention of antidepressant_a_name
                continue  # try another A
            # We pick the first possible completion-of-course A second
            # mention:
            antidepressant_a_second_mention = a_second_mentions.iat[
                0, sourcecolnum_date]
            # Make sure B is not mentioned within the A range
            mentions_of_b_within_a_range = tp[
                (tp[drug_colname] == antidepressant_b_name) &
                (tp[date_colname] >= antidepressant_a_first_mention) &

                # 2019-04-01: CHANGED FROM:
                #    (tp[date_colname] <= antidepressant_a_second_mention)
                # TO:
                (tp[date_colname] < antidepressant_a_second_mention)
            ]
            if len(mentions_of_b_within_a_range) > 0:
                # Nope, chuck out this combination.
                continue  # try another A
            found_valid_a = True
            break
        if not found_valid_a:
            continue  # try another B

        # ---------------------------------------------------------------------
        # OK; here we have found a combination that we like.
        # Add it to the results.
        # ---------------------------------------------------------------------
        # https://stackoverflow.com/questions/19365513/how-to-add-an-extra-row-to-a-pandas-dataframe/19368360  # noqa
        # http://pandas.pydata.org/pandas-docs/stable/indexing.html#setting-with-enlargement  # noqa

        expect_response_by_date = (
            antidepressant_b_first_mention + timedelta_days(
                expect_response_by_days)
        )
        end_of_symptom_period = (
            antidepressant_b_first_mention + timedelta_days(
                expect_response_by_days + symptom_assessment_time_days - 1)
        )
        result = _get_generic_two_antidep_episodes_result((
            patient_id,
            antidepressant_a_name,
            antidepressant_a_first_mention,
            antidepressant_a_second_mention,
            antidepressant_b_name,
            antidepressant_b_first_mention,
            antidepressant_b_second_mention,
            expect_response_by_date,
            end_of_symptom_period
        ))
        # We only care about the first episode per patient that matches, so:
        if first_episode_only:
            return result
        else:
            all_episodes_for_patient = all_episodes_for_patient.append(result)

    if len(all_episodes_for_patient) == 0:
        return None  # nothing found
    return all_episodes_for_patient
257040
def finalize_episode(self, params):
        
        total_reward = sum(self.intermediate_rewards)
        self.total_rewards.append(total_reward)
        self.params.append(params)
        self.intermediate_rewards = []
1285435
def _add_variant_sameas_relationships(self, patient_var_map, rs_map):
        
        model = Model(self.graph)
        for patient in patient_var_map:
            for variant_id, variant in patient_var_map[patient].items():
                variant_bnode = self.make_id("{0}".format(variant_id), "_")
                build = variant['build']
                chromosome = variant['chromosome']
                position = variant['position']
                reference_allele = variant['reference_allele']
                variant_allele = variant['variant_allele']
                if build and chromosome and position\
                        and reference_allele and variant_allele:
                    if re.fullmatch(r'[ATCG]', reference_allele)\
                            and re.fullmatch(r'[ATCG]', variant_allele):
                        # variation is snp
                        rs_id = self._get_rs_id(variant, rs_map, 'snp')
                        if rs_id:
                            dbsnp_curie = 'dbSNP:rs{0}'.format(rs_id)
                            model.addSameIndividual(variant_bnode, dbsnp_curie)

                    elif re.fullmatch(r'\-', reference_allele)\
                            or re.fullmatch(r'\-', variant_allele):
                        rs_id = self._get_rs_id(variant, rs_map, 'indel')
                        if rs_id is not None:
                            dbsnp_curie = 'dbSNP:rs{0}'.format(rs_id)
                            model.addSameIndividual(variant_bnode, dbsnp_curie)
                    else:
                        rs_id = self.\
                            _get_rs_id(variant, rs_map, 'indel')
                        if rs_id is not None:
                            dbsnp_curie = 'dbSNP:rs{0}'.format(rs_id)
                            model.addSameIndividual(variant_bnode, dbsnp_curie)
        return
1047942
def set_scf_algorithm_and_iterations(self, algorithm="diis",
                                         iterations=50):
        
        available_algorithms = {"diis", "dm", "diis_dm", "diis_gdm", "gdm",
                                "rca", "rca_diis", "roothaan"}
        if algorithm.lower() not in available_algorithms:
            raise ValueError("Algorithm " + algorithm +
                             " is not available in QChem")
        self.params["rem"]["scf_algorithm"] = algorithm.lower()
        self.params["rem"]["max_scf_cycles"] = iterations
99792
def record_treatment!(experiment, treatment, object)
      redis.sadd(subjects_key(experiment, treatment), generate_identifier(object))
    end
115465
def process_paper_helper(model_name, pmid, start_time_local):
    """"""
    try:
        if not aws_available:
            rp, txt_format = process_paper(model_name, pmid)
        else:
            rp, txt_format = process_paper_aws(pmid, start_time_local)
    except:
        logger.exception('uncaught exception while processing %s', pmid)
        return None, None

    return rp, txt_format
553093
private void ProcessNextStep() {

        switch (iSelectionStep) {

            case SELECT_SOURCE_CATALOG :
            case SELECT_DEST_CATALOG :
                if (CatalogToSelect()) {
                    fMain.show();

                    return;
                }
                break;

            case SELECT_DEST_SCHEMA :
            case SELECT_SOURCE_SCHEMA :
                if (SchemaToSelect()) {
                    fMain.show();

                    return;
                }
                break;

            case SELECT_SOURCE_TABLES :
                if (iTransferMode == TRFM_TRANSFER) {
                    bStart.setLabel("Start Transfer");
                } else if (iTransferMode == TRFM_DUMP) {
                    bStart.setLabel("Start Dump");
                } else if (iTransferMode == TRFM_RESTORE) {
                    bStart.setLabel("Start Restore");
                }

                bStart.invalidate();
                bStart.setEnabled(false);
                lTable.setMultipleMode(false);
                RefreshMainDisplay();
                break;

            default :
                break;
        }
    }
497220
def _process_queue(self):
        '''
        
        '''
        if len(self._queue):
            args, kwargs = self._queue.popleft()
            self.publish(*args, **kwargs)
425543
public void process() {
		solver.solve(Y,X);

		double a = X.data[0];
		double b = X.data[1];
		double c = X.data[2];
		double d = X.data[3];
		double e = X.data[4];

		double bottom = 4*a*c - b*b;
		deltaX = (b*e - 2*d*c)/bottom;
		deltaY = (b*d - 2*a*e)/bottom;
	}
1234564
def assess(self, cases=None):
        
        if cases is None:
            cases = product(range(2), repeat=self.dimension)
        
        misses = 0
        ordered = [[0]*(self.dimension-i) + [1]*i for i in range(self.dimension+1)]
        for sequence in cases:
            sequence = list(sequence)
            self.sort(sequence)
            misses += (sequence != ordered[sum(sequence)])
        return misses
675900
def run_one_iteration(parameters, score)
	  	self.run_one_mating_iteration(parameters, score) if @currently_mating == true
	    @current = {:parameters => parameters, :score => score}
	    # update best score?
	    self.update_best?
	    # push new parameter set into generation
	    @currently_mating = @generation_handler.add_new_individual(@current)
	    if @currently_mating == true
	    	# begin mating process
	    	# empty current population
	    	@generation_handler.population_array = []
	    	selected_to_mate = @mating_handler.select_mating_population(@generation_handler.archive_array)
	    	self.get_children_to_score(selected_to_mate)
	    	@children_to_score.pop[:parameters]
	    else
	    	# get next parameter set to score
	    	self.random_parameter_set
	    end
	  end
16150
def _postprocess(self):
        
        # validate series ISBN
        self._POST["P0601010__a"] = self._validate_isbn(
            self._POST["P0601010__a"],
            accept_blank=True
        )
        if self._POST["P0601010__a"] != "":
            self._POST["P0601010__b"] = "soubor : " + self._POST["P0601010__a"]

        # validate ISBN of the book
        self._POST["P0501010__a"] = self._validate_isbn(
            self._POST["P0501010__a"],
            accept_blank=False
        )
        self._POST["P1601ISB__a"] = self._POST["P0501010__a"]
815984
def multi_p_run(tot_num, _func, worker, params, n_process):
    
    from multiprocessing import Process, Queue
    out_q = Queue()
    procs = []

    split_num = split_seq(list(range(0, tot_num)), n_process)

    print(tot_num, ">>", split_num)

    split_len = len(split_num)
    if n_process > split_len:
        n_process = split_len

    for i in range(n_process):
        _p = Process(target=_func,
                     args=(worker, split_num[i][0], split_num[i][1],
                           params, out_q))
        _p.daemon = True
        procs.append(_p)
        _p.start()

    try:
        result = []
        for i in range(n_process):
            result.append(out_q.get())
        for i in procs:
            i.join()
    except KeyboardInterrupt:
        print('Killing all the children in the pool.')
        for i in procs:
            i.terminate()
            i.join()
        return -1

    while not out_q.empty():
        print(out_q.get(block=False))

    return result
428434
def run(align_bams, items, ref_file, assoc_files, region=None, out_file=None):
    
    paired = vcfutils.get_paired_bams(align_bams, items)
    assert paired and not paired.normal_bam, ("smCounter2 supports tumor-only variant calling: %s" %
                                              (",".join([dd.get_sample_name(d) for d in items])))
    vrs = bedutils.population_variant_regions(items)
    target = shared.subset_variant_regions(vrs, region,
                                            out_file, items=items, do_merge=True)
    out_file = out_file.replace(".vcf.gz", ".vcf")
    out_prefix = utils.splitext_plus(os.path.basename(out_file))[0]
    if not utils.file_exists(out_file) and not utils.file_exists(out_file + ".gz"):
        with file_transaction(paired.tumor_data, out_file) as tx_out_file:
            cmd = ["smCounter2", "--runPath", os.path.dirname(tx_out_file),
                   "--outPrefix", out_prefix,
                   "--bedTarget", target, "--refGenome", ref_file,
                   "--bamFile", paired.tumor_bam, "--bamType", "consensus",
                   "--nCPU", dd.get_num_cores(paired.tumor_data)]
            do.run(cmd, "smcounter2 variant calling")
            for fname in glob.glob(os.path.join(os.path.dirname(tx_out_file), "*.smCounter*")):
                shutil.move(fname, os.path.join(os.path.dirname(out_file), os.path.basename(fname)))
            utils.symlink_plus(os.path.join(os.path.dirname(out_file),
                                            "%s.smCounter.cut.vcf" % out_prefix),
                               out_file)
    return vcfutils.bgzip_and_index(out_file, paired.tumor_data["config"], remove_orig=False,
                                    prep_cmd="sed 's#FORMAT\t%s#FORMAT\t%s#' | %s" %
                                    (out_prefix, dd.get_sample_name(paired.tumor_data),
                                     vcfutils.add_contig_to_header_cl(dd.get_ref_file(paired.tumor_data), out_file)))
1301719
def execute(self):
        
        if not hasattr(self, 'riskinputs'):  # in the reportwriter
            return
        res = Starmap.apply(
            self.core_task.__func__,
            (self.riskinputs, self.riskmodel, self.param, self.monitor()),
            concurrent_tasks=self.oqparam.concurrent_tasks or 1,
            weight=get_weight
        ).reduce(self.combine)
        return res
1071664
private static PharmacophoreQuery processPharmacophoreElement(Element e, HashMap<String, String> global)
            throws CDKException {
        PharmacophoreQuery ret = new PharmacophoreQuery();
        ret.setProperty("description", e.getAttributeValue("description"));
        ret.setTitle(e.getAttributeValue("name"));

        // first get any local group definitions
        HashMap<String, String> local = getGroupDefinitions(e);

        // now lets look at the constraints
        Elements children = e.getChildElements();
        for (int i = 0; i < children.size(); i++) {
            Element child = children.get(i);
            if (child.getQualifiedName().equals("distanceConstraint")) {
                processDistanceConstraint(child, local, global, ret);
            } else if (child.getQualifiedName().equals("angleConstraint")) {
                processAngleConstraint(child, local, global, ret);
            }
        }
        return ret;
    }
453198
@Override public void processMiniBatch(long seed, double[] responses, double[] offsets, int n) {
    assert(_training);
    if (_localmodel.get_params()._reproducible) {
      seed += _localmodel.get_processed_global(); //avoid periodicity
    } else {
      seed = _dropout_rng.nextLong(); // non-reproducible case - make a fast & good random number
    }
    fpropMiniBatch(seed, _neurons, _localmodel, _localmodel.get_params()._elastic_averaging ? _sharedmodel : null, _training, responses, offsets, n);
    bpropMiniBatch(_neurons, n);
  }